Completed
Pull Request — master (#186)
by Sergey
05:07
created

User::deactivate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 2
1
<?php
2
3
namespace seregazhuk\PinterestBot\Api\Providers;
4
5
use LogicException;
6
use seregazhuk\PinterestBot\Api\Response;
7
use seregazhuk\PinterestBot\Api\Traits\UploadsImages;
8
use seregazhuk\PinterestBot\Helpers\UrlBuilder;
9
10
class User extends Provider
11
{
12
    use UploadsImages;
13
14
    /**
15
     * @var array
16
     */
17
    protected $loginRequiredFor = [
18
        'profile',
19
        'convertToBusiness',
20
        'changePassword',
21
        'isBanned',
22
        'deactivate',
23
        'getUserName'
24
    ];
25
26
    const REGISTRATION_COMPLETE_EXPERIENCE_ID = '11:10105';
27
    const ACCOUNT_TYPE_OTHER = 'other';
28
29
    /**
30
     * Updates or returns user profile info. Gets associative array as a param. Available keys of array are:
31
     * 'last_name', 'first_name', 'username', 'about', 'location' and 'website_url'.
32
     * You can also change user avatar by passing 'profile_image'.
33
     *
34
     * @param array $userInfo If empty returns current user profile.
35
     *
36
     * @return bool|array
37
     */
38
    public function profile($userInfo = [])
39
    {
40
        if(empty($userInfo)) {
41
            return $this->execGetRequest([], UrlBuilder::RESOURCE_GET_USER_SETTINGS);
42
        }
43
44
        if (isset($userInfo['profile_image'])) {
45
            $userInfo['profile_image_url'] = $this->upload($userInfo['profile_image']);
46
        }
47
48
        return $this->execPostRequest($userInfo, UrlBuilder::RESOURCE_UPDATE_USER_SETTINGS);
49
    }
50
51
    /**
52
     * Register a new user.
53
     *
54
     * @param string $email
55
     * @param string $password
56
     * @param string $name
57
     * @param string $country
58
     * @param int $age
59
     *
60
     * @return bool
61
     */
62
    public function register($email, $password, $name, $country = 'GB', $age = 18)
63
    {
64
        $data = [
65
            "age"        => $age,
66
            "email"      => $email,
67
            "password"   => $password,
68
            "country"    => $country,
69
            "first_name" => $name,
70
            "container"  => "home_page"
71
        ];
72
73
        return $this->makeRegisterCall($data);
74
    }
75
76
    /**
77
     * Register a new business account.
78
     *
79
     * @param string $email
80
     * @param string $password
81
     * @param string $businessName
82
     * @param string $website
83
     * @return bool|mixed
84
     */
85
    public function registerBusiness($email, $password, $businessName, $website = '')
86
    {
87
        $data = [
88
            "email"         => $email,
89
            "password"      => $password,
90
            "website_url"   => $website,
91
            "business_name" => $businessName,
92
            "account_type"  => self::ACCOUNT_TYPE_OTHER,
93
        ];
94
95
        return $this->makeRegisterCall($data);
96
    }
97
98
    /**
99
     * Convert your account to a business one.
100
     *
101
     * @param string $businessName
102
     * @param string $websiteUrl
103
     *
104
     * @return bool
105
     */
106
    public function convertToBusiness($businessName, $websiteUrl = '')
107
    {
108
        $data = [
109
            'business_name' => $businessName,
110
            'website_url'   => $websiteUrl,
111
            'account_type'  => self::ACCOUNT_TYPE_OTHER,
112
        ];
113
114
        return $this->execPostRequest($data, UrlBuilder::RESOURCE_CONVERT_TO_BUSINESS);
115
    }
116
117
    /**
118
     * Login as pinner.
119
     *
120
     * @param string $username
121
     * @param string $password
122
     *
123
     * @param bool $autoLogin
124
     * @return bool
125
     */
126
    public function login($username, $password, $autoLogin = true)
127
    {
128
        if ($this->request->isLoggedIn()) return true;
129
130
        $this->checkCredentials($username, $password);
131
132
        // Trying to load previously saved cookies from last login
133
        // session for this username.
134
        if($autoLogin && $this->request->autoLogin($username)) {
135
            return true;
136
        }
137
138
        return $this->processLogin($username, $password);
139
    }
140
141
    public function logout()
142
    {
143
        $this->request->logout();
144
    }
145
146
    /**
147
     * @return bool
148
     */
149
    public function isLoggedIn()
150
    {
151
        return $this->request->isLoggedIn();
152
    }
153
154
    /**
155
     * Checks if current user is banned
156
     *
157
     * @return bool
158
     */
159
    public function isBanned()
160
    {
161
        $profile = $this->profile();
162
163
       return isset($profile['is_write_banned']) ?
164
           (bool)$profile['is_write_banned'] :
165
           false;
166
    }
167
168
    /**
169
     * Returns current user username
170
     *
171
     * @return string
172
     */
173
    public function getUserName()
174
    {
175
        $profile = $this->profile();
176
177
        return isset($profile['username']) ? $profile['username'] : '';
178
    }
179
180
    /**
181
     * @param string $oldPassword
182
     * @param string $newPassword
183
     * @return bool
184
     */
185
    public function changePassword($oldPassword, $newPassword)
186
    {
187
        $request = [
188
            'old_password'         => $oldPassword,
189
            'new_password'         => $newPassword,
190
            'new_password_confirm' => $newPassword,
191
        ];
192
193
        return $this->execPostRequest($request, UrlBuilder::RESOURCE_CHANGE_PASSWORD);
194
    }
195
196
    /**
197
     * Deactivates your account.
198
     *
199
     * @param string $reason
200
     * @param string $explanation
201
     * @return bool
202
     */
203
    public function deactivate($reason = 'other', $explanation = '')
204
    {
205
        $profile = $this->profile();
206
207
        if(!isset($profile['id'])) return false;
208
209
        $request = [
210
            'user_id'     => $profile['id'],
211
            'reason'      => $reason,
212
            'explanation' => $explanation,
213
        ];
214
215
        return $this->execPostRequest($request, UrlBuilder::RESOURCE_DEACTIVATE_ACCOUNT);
216
    }
217
218
    /**
219
     * Validates password and login.
220
     *
221
     * @param string $username
222
     * @param string $password
223
     */
224
    protected function checkCredentials($username, $password)
225
    {
226
        if (!$username || !$password) {
227
            throw new LogicException('You must set username and password to login.');
228
        }
229
    }
230
231
    /**
232
     * @return bool
233
     */
234
    protected function completeRegistration()
235
    {
236
        $this->request->setTokenFromCookies();
237
238
        return $this->execPostRequest(
239
                ['placed_experience_id' => self::REGISTRATION_COMPLETE_EXPERIENCE_ID],
240
                UrlBuilder::RESOURCE_REGISTRATION_COMPLETE
241
            );
242
    }
243
244
    /**
245
     * @param array $data
246
     * @return bool|mixed
247
     */
248
    protected function makeRegisterCall($data)
249
    {
250
        $this->visitMainPage();
251
        $this->request->setTokenFromCookies();
252
253
        if (!$this->execPostRequest($data, UrlBuilder::RESOURCE_CREATE_REGISTER)) {
254
            return false;
255
        }
256
257
        return $this->completeRegistration();
258
    }
259
260
    /**
261
     * @param string $username
262
     * @param string $password
263
     * @return bool
264
     */
265
    protected function processLogin($username, $password)
266
    {
267
        $this->request->clearToken();
268
269
        $credentials = [
270
            'username_or_email' => $username,
271
            'password'          => $password,
272
        ];
273
274
        $response = $this->execPostRequest($credentials, UrlBuilder::RESOURCE_LOGIN, true);
275
        if ($response->hasErrors()) {
276
            return false;
277
        }
278
279
        $this->request->login();
280
281
        return true;
282
    }
283
284
    /**
285
     * Ask for password reset link in email
286
     *
287
     * @param string $user Username or user mail
288
     * @return bool
289
     */
290
    public function sendPasswordResetLink($user)
291
    {
292
        $request = ['username_or_email' => $user];
293
294
        return $this->execPostRequest($request, UrlBuilder::RESOURCE_RESET_PASSWORD_SEND_LINK);
295
    }
296
297
    /**
298
     * Set a new password by link from reset password email
299
     *
300
     * @param $link
301
     * @param string $newPassword
302
     * @return bool|Response
303
     */
304
    public function resetPassword($link, $newPassword)
305
    {
306
        // Visit link to get current reset token, username and token expiration
307
        $this->execGetRequest([], $link);
308
        $this->request->clearToken();
309
310
        $passwordResetUrl = $this->request->getHttpClient()->getCurrentUrl();
311
312
        $urlData = parse_url($passwordResetUrl);
313
        $username = trim(str_replace('/pw/', '', $urlData['path']), '/');
314
315
        $query = [];
316
        parse_str($urlData['query'], $query);
317
318
319
        return $this->execPostRequest([
320
                'username'             => $username,
321
                'new_password'         => $newPassword,
322
                'new_password_confirm' => $newPassword,
323
                'token'                => $query['t'],
324
                'expiration'           => $query['e'],
325
            ], UrlBuilder::RESOURCE_RESET_PASSWORD_UPDATE, true);
326
    }
327
328
329
    public function visitMainPage()
330
    {
331
        $this->execGetRequest([], '');
332
    }
333
}
334