File size: 6,857 Bytes
d2897cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php

namespace Mautic\PluginBundle\Helper;

use Mautic\PluginBundle\Integration\UnifiedIntegrationInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Portions modified from https://code.google.com/p/simple-php-oauth/.
 */
class oAuthHelper
{
    private $clientId;

    private $clientSecret;

    private $accessToken;

    private $accessTokenSecret;

    private $callback;

    private $settings;

    public function __construct(
        UnifiedIntegrationInterface $integration,
        private ?Request $request = null,
        $settings = []
    ) {
        $clientId                = $integration->getClientIdKey();
        $clientSecret            = $integration->getClientSecretKey();
        $keys                    = $integration->getDecryptedApiKeys();
        $this->clientId          = $keys[$clientId] ?? null;
        $this->clientSecret      = $keys[$clientSecret] ?? null;
        $authToken               = $integration->getAuthTokenKey();
        $this->accessToken       = $keys[$authToken] ?? '';
        $this->accessTokenSecret = $settings['token_secret'] ?? '';
        $this->callback          = $integration->getAuthCallbackUrl();
        $this->settings          = $settings;
    }

    public function getAuthorizationHeader($url, $parameters, $method): array
    {
        // Get standard OAuth headers
        $headers = $this->getOauthHeaders();

        if (!empty($this->settings['include_verifier']) && $this->request && $this->request->query->has('oauth_verifier')) {
            $headers['oauth_verifier'] = $this->request->query->get('oauth_verifier');
        }

        if (!empty($this->settings['query'])) {
            // Include query in the base string if appended
            $parameters = array_merge($parameters, $this->settings['query']);
        }

        if (!empty($this->settings['double_encode_basestring_parameters'])) {
            // Parameters must be encoded before going through buildBaseString
            array_walk($parameters, function (&$val, $key, $oauth): void {
                $val = $oauth->encode($val);
            }, $this);
        }

        $signature = array_merge($headers, $parameters);

        $base_info                  = $this->buildBaseString($url, $method, $signature);
        $composite_key              = $this->getCompositeKey();
        $headers['oauth_signature'] = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));

        return [$this->buildAuthorizationHeader($headers), 'Expect:'];
    }

    /**
     * Get composite key for OAuth 1 signature signing.
     */
    private function getCompositeKey(): string
    {
        if (strlen($this->accessTokenSecret) > 0) {
            $composite_key = $this->encode($this->clientSecret).'&'.$this->encode($this->accessTokenSecret);
        } else {
            $composite_key = $this->encode($this->clientSecret).'&';
        }

        return $composite_key;
    }

    /**
     * Get OAuth 1.0 Headers.
     */
    private function getOauthHeaders(): array
    {
        $oauth = [
            'oauth_consumer_key'     => $this->clientId,
            'oauth_nonce'            => $this->generateNonce(),
            'oauth_signature_method' => 'HMAC-SHA1',
            'oauth_timestamp'        => time(),
            'oauth_version'          => '1.0',
        ];

        if (empty($this->settings['authorize_session']) && !empty($this->accessToken)) {
            $oauth['oauth_token'] = $this->accessToken;
        } elseif (!empty($this->settings['request_token'])) {
            // OAuth1.a access_token request that requires the retrieved request_token to be appended
            $oauth['oauth_token'] = $this->settings['request_token'];
        }

        if (!empty($this->settings['append_callback']) && !empty($this->callback)) {
            $oauth['oauth_callback'] = urlencode($this->callback);
        }

        return $oauth;
    }

    /**
     * Build base string for OAuth 1 signature signing.
     */
    private function buildBaseString($baseURI, $method, $params): string
    {
        $r = $this->normalizeParameters($params);

        return $method.'&'.$this->encode($baseURI).'&'.$this->encode($r);
    }

    /**
     * Build header for OAuth 1 authorization.
     */
    private function buildAuthorizationHeader($oauth): string
    {
        $r      = 'Authorization: OAuth ';
        $values = $this->normalizeParameters($oauth, true, true);

        return $r.implode(', ', $values);
    }

    /**
     * Normalize parameters.
     *
     * @param bool $encode
     * @param bool $returnarray
     *
     * @return string|array<string,string>
     */
    private function normalizeParameters($parameters, $encode = false, $returnarray = false, $normalized = [], $key = '')
    {
        // Sort by key
        ksort($parameters);

        foreach ($parameters as $k => $v) {
            if (is_array($v)) {
                $normalized = $this->normalizeParameters($v, $encode, true, $normalized, $k);
            } else {
                if ($key) {
                    // Multidimensional array; using foo=baz&foo=bar rather than foo[bar]=baz&foo[baz]=bar as this is
                    // what the server expects when creating the signature
                    $k = $key;
                }
                if ($encode) {
                    $normalized[] = $this->encode($k).'="'.$this->encode($v).'"';
                } else {
                    $normalized[] = $k.'='.$v;
                }
            }
        }

        return $returnarray ? $normalized : implode('&', $normalized);
    }

    /**
     * Returns an encoded string according to the RFC3986.
     */
    public function encode($string): string
    {
        return str_replace('%7E', '~', rawurlencode($string));
    }

    /**
     * OAuth1.0 nonce generator.
     *
     * @param int $bits
     */
    private function generateNonce($bits = 64): string
    {
        $result          = '';
        $accumulatedBits = 0;
        $random          = mt_getrandmax();
        for ($totalBits = 0; 0 != $random; $random >>= 1) {
            ++$totalBits;
        }
        $usableBits = intval($totalBits / 8) * 8;

        while ($accumulatedBits < $bits) {
            $bitsToAdd = min($totalBits - $usableBits, $bits - $accumulatedBits);
            if (0 != $bitsToAdd % 4) {
                // add bits in whole increments of 4
                $bitsToAdd += 4 - $bitsToAdd % 4;
            }

            // isolate leftmost $bits_to_add from mt_rand() result
            $moreBits = mt_rand() & ((1 << $bitsToAdd) - 1);

            // format as hex (this will be safe)
            $format_string = '%0'.($bitsToAdd / 4).'x';
            $result .= sprintf($format_string, $moreBits);
            $accumulatedBits += $bitsToAdd;
        }

        return $result;
    }
}