Completed
Branch master (b53644)
by Pierre-Henry
33:47
created

app/system/modules/connect/inc/class/Facebook.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * @title          Facebook Authentication Class
4
 *
5
 * @author         Pierre-Henry Soria <[email protected]>
6
 * @copyright      (c) 2012-2017, Pierre-Henry Soria. All Rights Reserved.
7
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
8
 * @package        PH7 / App / System / Module / Connect / Inc / Class
9
 * @version        2.0
10
 */
11
namespace PH7;
12
defined('PH7') or exit('Restricted access');
13
14
use
0 ignored issues
show
There must be a single space after the USE keyword
Loading history...
15
PH7\Framework\File\Import,
16
PH7\Framework\Date\CDateTime,
17
PH7\Framework\Config\Config,
18
PH7\Framework\Mvc\Model\DbConfig,
19
PH7\Framework\Ip\Ip,
20
PH7\Framework\File\File,
21
PH7\Framework\Util\Various,
22
PH7\Framework\Geo\Ip\Geo,
23
PH7\Framework\Error\CException\PH7Exception,
24
Facebook\Facebook as FB,
25
Facebook\FacebookResponse,
26
Facebook\Helpers\FacebookRedirectLoginHelper,
27
Facebook\GraphNodes\GraphUser,
28
Facebook\GraphNodes\GraphLocation,
29
Facebook\Exceptions\FacebookSDKException,
30
Facebook\Exceptions\FacebookResponseException,
31
PH7\Framework\Mvc\Router\Uri;
32
33
class Facebook extends Api implements IApi
34
{
35
36
    const GRAPH_URL = 'https://graph.facebook.com/';
37
38
    private $oProfile, $oLocation, $sAvatarFile, $sUsername, $iProfileId, $aUserInfo;
39
40
    private $aPermissions = [
41
        'email',
42
        'user_birthday',
43
        'user_relationships',
44
        'user_relationship_details',
45
        'user_hometown',
46
        'user_location',
47
        'user_about_me',
48
        'user_likes',
49
        'user_website'
50
    ];
51
52
    /**
53
     * @return void
54
     */
55
    public function __construct()
56
    {
57
        parent::__construct();
58
59
        $oFb = new FB([
60
            'app_id' => Config::getInstance()->values['module.api']['facebook.id'],
61
            'app_secret' => Config::getInstance()->values['module.api']['facebook.secret_key'],
62
            'default_graph_version' => 'v2.7',
63
        ]);
64
65
        $oHelper = $oFb->getRedirectLoginHelper();
66
67
        try {
68
            $sAccessToken = $oHelper->getAccessToken();
69
        } catch(FacebookSDKException $oE) {
70
            PH7Exception::launch($oE);
71
        }
72
73
        if (empty($sAccessToken)) {
74
            // First off, set the login URL
75
            $this->setLoginUrl($oHelper);
76
            return; // Stop method
77
        }
78
79
        // Set the FB access token for the app
80
        $oFb->setDefaultAccessToken($sAccessToken);
81
82
        try {
83
            $oResponse = $oFb->get('/me');
84
            $this->initClassAttrs($oResponse);
85
        } catch(FacebookResponseException $oE) {
86
            PH7Exception::launch($oE);
87
        }
88
89
90
        // If we have GraphUser object
91
        if (!empty($this->oProfile)) {
92
            // User info is ok? Here we will be connect the user and/or adding the login and registering routines...
93
            $oUserModel = new UserCoreModel;
94
95
            if (!$iId = $oUserModel->getId($this->oProfile->getEmail())) {
96
                // Add User if it does not exist in our database
97
                $this->add($oUserModel);
98
99
                // Add User Avatar
100
                $this->setAvatar($this->oProfile->getId());
101
102
                $this->oDesign->setFlashMsg( t('You have now been registered! %0%', (new Registration)->sendMail($this->aUserInfo, true)->getMsg()) );
103
                $this->sUrl = Uri::get('connect','main','register');
104
            } else {
105
                // Login
106
                $this->setLogin($iId, $oUserModel);
107
                $this->sUrl = Uri::get('connect','main','home');
108
            }
109
110
            unset($oUserModel);
111
        } else {
112
            // For testing purposes, if there was an error, let's kill the script
113
            $this->oDesign->setFlashMsg(t('Oops! An error has occurred. Please try again later.'));
114
            $this->sUrl = Uri::get('connect','main','index');
115
        }
116
117
        unset($oFb);
118
    }
119
120
    /**
121
     * @param \PH7\UserCoreModel $oUserModel
122
     * @return void
123
     */
124
    public function add(UserCoreModel $oUserModel)
125
    {
126
        $oUser = new UserCore;
127
        $sBirthDate = !empty($this->oProfile->getBirthday()) ? $this->oProfile->getBirthday() : date('m/d/Y', strtotime('-30 year'));
128
        $sSex = $this->checkGender($this->oProfile->getGender());
129
        $sMatchSex = $oUser->getMatchSex($sSex);
130
        $this->sUsername = $oUser->findUsername($this->oProfile->getId(), $this->oProfile->getFirstName(), $this->oProfile->getLastName());
131
        unset($oUser);
132
133
        $this->aUserInfo = [
134
            'email' => $this->oProfile->getEmail(),
135
            'username' => $this->sUsername,
136
            'password' => Various::genRndWord(8,30),
137
            'first_name' => $this->oProfile->getFirstName(),
138
            'last_name' => $this->oProfile->getLastName(),
139
            'middle_name' => $this->oProfile->getMiddleName(),
140
            'sex' => $sSex,
141
            'match_sex' => array($sMatchSex),
142
            'birth_date' => (new CDateTime)->get($sBirthDate)->date('Y-m-d'),
143
            'country' => Geo::getCountryCode(),
144
            'city' =>  !empty($this->oLocation->getCity()) ? $this->oLocation->getCity() : Geo::getCity(),
145
            'state' => !empty($this->oLocation->getState()) ? $this->oLocation->getState() : Geo::getState(),
146
            'zip_code' => !empty($this->oLocation->getZip()) ? $this->oLocation->getZip() : Geo::getZipCode(),
147
            'description' => $this->oProfile->getDescription(),
148
            'social_network_site' => $oProfie->getLink(),
149
            'ip' => Ip::get(),
150
            'prefix_salt' => Various::genRnd(),
151
            'suffix_salt' => Various::genRnd(),
152
            'hash_validation' => Various::genRnd(),
153
            'is_active' => DbConfig::getSetting('userActivationType')
154
        ];
155
156
        $this->iProfileId = $oUserModel->add($this->aUserInfo);
157
    }
158
159
    /**
160
     * Set Avatar.
161
     *
162
     * @param string $sUserId FB user ID.
163
     * @return void
164
     */
165
    public function setAvatar($sUserId)
166
    {
167
        $this->sAvatarFile = $this->getAvatar(static::GRAPH_URL . $sUserId . '/picture?type=large');
168
169
         if ($this->sAvatarFile) {
170
             $iApproved = (DbConfig::getSetting('avatarManualApproval') == 0) ? '1' : '0';
171
             (new UserCore)->setAvatar($this->iProfileId, $this->sUsername, $this->sAvatarFile, $iApproved);
172
         }
173
174
         // Remove the temporary avatar
175
         (new File)->deleteFile($this->sAvatarFile);
176
    }
177
178
    /**
179
     * Set the FB Login URL.
180
     *
181
     * @param \Facebook\Helpers\FacebookRedirectLoginHelper $oHelper
182
     * @return void
183
     */
184
    protected function setLoginUrl(FacebookRedirectLoginHelper $oHelper)
185
    {
186
187
        $this->sUrl = $oHelper->getLoginUrl(Uri::get('connect','main','home'), $this->aPermissions);
188
    }
189
190
    private function initClassAttrs(FacebookResponse $oResponse)
191
    {
192
        $this->oProfile = $oResponse->getGraphObject(GraphUser::className());
193
        $this->oLocation = $oResponse->getGraphObject(GraphLocation::className());
194
    }
195
}
196