Completed
Pull Request — master (#60)
by Sergey
04:54 queued 01:12
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
     * Executes request to Pinterest API
97
     *
98
     * @param string $resourceUrl
99
     * @param string $postString
100
     * @return array
101
     */
102
    public function exec($resourceUrl, $postString = "")
103
    {
104
        $url = UrlHelper::buildApiUrl($resourceUrl);
105
        $this->makeHttpOptions($postString);
106
        $res = $this->http->execute($url, $this->options);
107
        return json_decode($res, true);
108
    }
109
110
    /**
111
     * Adds necessary curl options for query
112
     *
113
     * @param string $postString POST query string
114
     * @return $this
115
     */
116
    protected function makeHttpOptions($postString = "")
117
    {
118
        $this->setDefaultHttpOptions();
119
120
        if ($this->csrfToken == CsrfHelper::DEFAULT_TOKEN) {
121
            $this->options = $this->addDefaultCsrfInfo($this->options);
122
        }
123
124
        if ( ! empty($postString)) {
125
            $this->options[CURLOPT_POST] = true;
126
            $this->options[CURLOPT_POSTFIELDS] = $postString;
127
        }
128
129
        return $this;
130
    }
131
132
    /**
133
     * Clear token information
134
     * @return $this
135
     */
136
    public function clearToken()
137
    {
138
        $this->csrfToken = CsrfHelper::DEFAULT_TOKEN;
139
140
        return $this;
141
    }
142
143
    /**
144
     * Mark api as logged
145
     *
146
     * @return $this
147
     */
148
    public function setLoggedIn()
149
    {
150
        $this->csrfToken = CsrfHelper::getTokenFromFile($this->cookieJar);
151
        if ( ! empty($this->csrfToken)) {
152
            $this->loggedIn = true;
153
        }
154
155
        return $this;
156
    }
157
158
    /**
159
     * Get log status
160
     *
161
     * @return bool
162
     */
163
    public function isLoggedIn()
164
    {
165
        return $this->loggedIn;
166
    }
167
168
    /**
169
     * Create request string
170
     *
171
     * @param array $data
172
     * @param string $sourceUrl
173
     * @param array $bookmarks
174
     * @return string
175
     */
176
    public static function createQuery(array $data = [], $sourceUrl = '/', $bookmarks = [])
177
    {
178
        $request = Request::createRequestData($data, $sourceUrl, $bookmarks);
179
180
        return UrlHelper::buildRequestString($request);
181
    }
182
183
    /**
184
     * @param array|object $data
185
     * @param string|null  $sourceUrl
186
     * @param array        $bookmarks
187
     * @return array
188
     */
189
    public static function createRequestData(array $data = [], $sourceUrl = '/', $bookmarks = [])
190
    {
191
        if (empty($data)) {
192
            $data = self::createEmptyRequestData();
193
        }
194
195
        if ( ! empty($bookmarks)) {
196
            $data["options"]["bookmarks"] = $bookmarks;
197
        }
198
199
        $data["context"] = new \stdClass();
200
201
        return [
202
            "source_url" => $sourceUrl,
203
            "data"       => json_encode($data),
204
        ];
205
    }
206
207
    /**
208
     * @return array
209
     */
210
    protected static function createEmptyRequestData()
211
    {
212
        return array('options' => []);
213
    }
214
215
    /**
216
     * @return array
217
     */
218
    protected function setDefaultHttpOptions()
219
    {
220
        $this->options = [
221
            CURLOPT_USERAGENT      => $this->userAgent,
222
            CURLOPT_RETURNTRANSFER => true,
223
            CURLOPT_SSL_VERIFYPEER => false,
224
            CURLOPT_FOLLOWLOCATION => true,
225
            CURLOPT_ENCODING       => 'gzip,deflate',
226
            CURLOPT_HTTPHEADER     => $this->getDefaultHttpHeaders(),
227
            CURLOPT_REFERER        => UrlHelper::URL_BASE,
228
            CURLOPT_COOKIEFILE     => $this->cookieJar,
229
            CURLOPT_COOKIEJAR      => $this->cookieJar,
230
        ];
231
    }
232
233
    /**
234
     * @return array
235
     */
236
    protected function getDefaultHttpHeaders()
237
    {
238
        return array_merge($this->requestHeaders, ['X-CSRFToken: '.$this->csrfToken]);
239
    }
240
241
    /**
242
     * @param array $options
243
     * @return mixed
244
     */
245
    protected function addDefaultCsrfInfo($options)
246
    {
247
        $options[CURLOPT_REFERER] = UrlHelper::URL_BASE;
248
        $options[CURLOPT_HTTPHEADER][] = CsrfHelper::getDefaultCookie();
249
250
        return $options;
251
    }
252
}
253