Completed
Push — master ( f63129...3a8a63 )
by Sergey
03:49
created

Request::getDefaultHttpHeaders()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace seregazhuk\PinterestBot\Api;
4
5
use seregazhuk\PinterestBot\Helpers\UrlHelper;
6
use seregazhuk\PinterestBot\Helpers\CsrfHelper;
7
use seregazhuk\PinterestBot\Contracts\HttpInterface;
8
use seregazhuk\PinterestBot\Contracts\RequestInterface;
9
10
/**
11
 * Class Request
12
 *
13
 * @package Pinterest
14
 * @property resource $ch
15
 * @property bool     $loggedIn
16
 * @property string   $userAgent
17
 * @property string   $csrfToken
18
 * @property string   $cookieJar
19
 */
20
class Request implements RequestInterface
21
{
22
    const INTEREST_ENTITY_ID = 'interest_id';
23
    const BOARD_ENTITY_ID = 'board_id';
24
    const COOKIE_NAME = 'pinterest_cookie';
25
    const PINNER_ENTITY_ID = 'user_id';
26
27
    protected $userAgent = 'Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0';
28
    /**
29
     * @var HttpInterface
30
     */
31
    protected $http;
32
    protected $loggedIn;
33
    protected $cookieJar;
34
    protected $options;
35
36
    public $csrfToken = "";
37
38
    /**
39
     * Common headers needed for every query
40
     *
41
     * @var array
42
     */
43
    protected $requestHeaders = [
44
        'Accept: application/json, text/javascript, */*; q=0.01',
45
        'Accept-Language: en-US,en;q=0.5',
46
        'DNT: 1',
47
        'Host: nl.pinterest.com',
48
        'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
49
        'X-Pinterest-AppState: active',
50
        'X-NEW-APP: 1',
51
        'X-APP-VERSION: 04cf8cc',
52
        'X-Requested-With: XMLHttpRequest',
53
    ];
54
55
    /**
56
     * @param HttpInterface $http
57
     * @param string|null $userAgent
58
     */
59
    public function __construct(HttpInterface $http, $userAgent = null)
60
    {
61
        $this->http = $http;
62
        if ($userAgent !== null) {
63
            $this->userAgent = $userAgent;
64
        }
65
        $this->cookieJar = self::COOKIE_NAME;
66
    }
67
68
    /**
69
     * Executes api call for follow or unfollow user
70
     *
71
     * @param int    $entityId
72
     * @param string $entityName
73
     * @param string $url
74
     * @return array
75
     */
76
    public function followMethodCall($entityId, $entityName, $url)
77
    {
78
        $dataJson = [
79
            "options" => [
80
                $entityName => $entityId,
81
            ],
82
            "context" => [],
83
        ];
84
85
        if ($entityName == self::INTEREST_ENTITY_ID) {
86
            $dataJson["options"]["interest_list"] = "favorited";
87
        }
88
89
        $post = ["data" => json_encode($dataJson, JSON_FORCE_OBJECT)];
90
        $postString = UrlHelper::buildRequestString($post);
91
92
        return $this->exec($url, $postString);
93
    }
94
95
    /**
96
     * Checks if bot is logged in
97
     *
98
     * @throws \LogicException if is not logged in
99
     * @return bool
100
     */
101
    public function checkLoggedIn()
102
    {
103
        if ( ! $this->loggedIn) {
104
            throw new \LogicException("You must log in before.");
105
        }
106
107
        return true;
108
    }
109
110
    /**
111
     * Executes request to Pinterest API
112
     *
113
     * @param string $resourceUrl
114
     * @param string $postString
115
     * @return array
116
     */
117
    public function exec($resourceUrl, $postString = "")
118
    {
119
        $url = UrlHelper::buildApiUrl($resourceUrl);
120
        $res = $this->http->init($url)->setOptions($this->makeHttpOptions($postString))->execute();
121
122
        $this->http->close();
123
        return json_decode($res, true);
124
    }
125
126
    /**
127
     * Adds necessary curl options for query
128
     *
129
     * @param string $postString POST query string
130
     * @return array
131
     */
132
    protected function makeHttpOptions($postString = "")
133
    {
134
        $options = $this->getDefaultHttpOptions();
135
136
        if ($this->csrfToken == CsrfHelper::DEFAULT_TOKEN) {
137
            $options = $this->addDefaultCsrfInfo($options);
138
        }
139
140
        if ( ! empty($postString)) {
141
            $options[CURLOPT_POST] = true;
142
            $options[CURLOPT_POSTFIELDS] = $postString;
143
        }
144
145
        return $options;
146
    }
147
148
    /**
149
     * Clear token information
150
     * @return $this
151
     */
152
    public function clearToken()
153
    {
154
        $this->csrfToken = CsrfHelper::DEFAULT_TOKEN;
155
156
        return $this;
157
    }
158
159
    /**
160
     * Mark api as logged
161
     *
162
     * @return $this
163
     */
164
    public function setLoggedIn()
165
    {
166
        $this->csrfToken = CsrfHelper::getTokenFromFile($this->cookieJar);
167
        if ( ! empty($this->csrfToken)) {
168
            $this->loggedIn = true;
169
        }
170
171
        return $this;
172
    }
173
174
    /**
175
     * Get log status
176
     *
177
     * @return bool
178
     */
179
    public function isLoggedIn()
180
    {
181
        return $this->loggedIn;
182
    }
183
184
    /**
185
     * @param array|object $data
186
     * @param string|null  $sourceUrl
187
     * @param array        $bookmarks
188
     * @return array
189
     */
190
    public static function createRequestData($data = [], $sourceUrl = '/', $bookmarks = [])
191
    {
192
        if (empty($data)) {
193
            $data = self::createEmptyRequestData();
194
        }
195
196
        if ( ! empty($bookmarks)) {
197
            $data["options"]["bookmarks"] = $bookmarks;
198
        }
199
200
        $data["context"] = new \stdClass();
201
202
        return [
203
            "source_url" => $sourceUrl,
204
            "data"       => json_encode($data),
205
        ];
206
    }
207
208
    /**
209
     * @return array
210
     */
211
    protected static function createEmptyRequestData()
212
    {
213
        return array('options' => []);
214
    }
215
216
    /**
217
     * @return array
218
     */
219
    protected function getDefaultHttpOptions()
220
    {
221
        return [
222
            CURLOPT_USERAGENT      => $this->userAgent,
223
            CURLOPT_RETURNTRANSFER => true,
224
            CURLOPT_SSL_VERIFYPEER => false,
225
            CURLOPT_FOLLOWLOCATION => true,
226
            CURLOPT_ENCODING       => 'gzip,deflate',
227
            CURLOPT_HTTPHEADER     => $this->getDefaultHttpHeaders(),
228
            CURLOPT_REFERER        => UrlHelper::URL_BASE,
229
            CURLOPT_COOKIEFILE     => $this->cookieJar,
230
            CURLOPT_COOKIEJAR      => $this->cookieJar,
231
        ];
232
    }
233
234
    /**
235
     * @return array
236
     */
237
    protected function getDefaultHttpHeaders()
238
    {
239
        return array_merge($this->requestHeaders, ['X-CSRFToken: '.$this->csrfToken]);
240
    }
241
242
    /**
243
     * @param array $options
244
     * @return mixed
245
     */
246
    protected function addDefaultCsrfInfo($options)
247
    {
248
        $options[CURLOPT_REFERER] = UrlHelper::URL_BASE;
249
        $options[CURLOPT_HTTPHEADER][] = CsrfHelper::getDefaultCookie();
250
251
        return $options;
252
    }
253
}
254