Passed
Pull Request — develop (#52)
by Peter
04:27
created

Tiqr_Message_FCM::getGoogleAccessToken()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 9
ccs 0
cts 9
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * This file is part of the tiqr project.
4
 *
5
 * The tiqr project aims to provide an open implementation for
6
 * authentication using mobile devices. It was initiated by
7
 * SURFnet and developed by Egeniq.
8
 *
9
 * More information: http://www.tiqr.org
10
 *
11
 * @author Joost van Dijk <[email protected]>
12
 *
13
 * @package tiqr
14
 *
15
 * @license New BSD License - See LICENSE file for details.
16
 *
17
 * @copyright (C) 2010-2015 SURFnet BV
18
 */
19
20
/**
21
 * Android Cloud To Device Messaging message.
22
 * @author peter
23
 */
24
class Tiqr_Message_FCM extends Tiqr_Message_Abstract
25
{
26
    /**
27
     * Send message.
28
     *
29
     * @throws Tiqr_Message_Exception_AuthFailure
30
     * @throws Tiqr_Message_Exception_SendFailure
31
     */
32
    public function send()
33
    {
34
        $options = $this->getOptions();
35
        $apiKey = $options['firebase.apikey'];
36
37
        $translatedAddress = $this->getAddress();
38
        $alertText = $this->getText();
39
        $url = $this->getCustomProperty('challenge');
40
41
        $this->_sendFirebase($translatedAddress, $alertText, $url, $apiKey);
42
    }
43
44
    /**
45
     * @throws \Google\Exception
46
     */
47
    private function getGoogleAccessToken(){
48
        $options = $this->getOptions();
49
        $credentialsFilePath = $options['credentialsFile'];
50
        $client = new \Google_Client();
51
        $client->setAuthConfig($credentialsFilePath);
52
        $client->addScope('https://www.googleapis.com/auth/firebase.messaging');
53
        $client->fetchAccessTokenWithAssertion();
54
        $token = $client->getAccessToken();
55
        return $token['access_token'];
56
    }
57
58
    /**
59
     * Send a message to a device using the firebase API key.
60
     *
61
     * @param $deviceToken string device ID
62
     * @param $alert string alert message
63
     * @param $challenge string tiqr challenge url
64
     * @param $apiKey string api key for firebase
65
     * @param $retry boolean is this a 2nd attempt
66
     * @throws Tiqr_Message_Exception_SendFailure
67
     * @throws \Google\Exception
68
     */
69
    private function _sendFirebase($deviceToken, $alert, $challenge, $apiKey, $retry=false)
70
    {
71
        $options = $this->getOptions();
72
        $apiurl = 'https://fcm.googleapis.com/v1/projects/'.$options['fcm.projectId'].'/messages:send';   //replace "your-project-id" with...your project ID
73
74
        $fields = [
75
            'message' => [
76
                'token' => $deviceToken,
77
                'data' => [
78
                    'challenge' => $challenge,
79
                    'text'      => $alert,
80
                ],
81
                "android" => [
82
                    "ttl" => "300s",
83
                ],
84
            ],
85
        ];
86
87
        $headers = array(
88
            'Authorization: Bearer ' . $this->getGoogleAccessToken(),
89
            'Content-Type: application/json',
90
        );
91
92
        $ch = curl_init();
93
        curl_setopt($ch, CURLOPT_URL, $apiurl);
94
        curl_setopt($ch, CURLOPT_POST, true);
95
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
96
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
97
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
98
        $result = curl_exec($ch);
99
        $errors = curl_error($ch);
100
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
101
        $remoteip = curl_getinfo($ch,CURLINFO_PRIMARY_IP);
102
        curl_close($ch);
103
104
        if ($result === false) {
105
            throw new Tiqr_Message_Exception_SendFailure("Server unavailable", true);
106
        }
107
108
        if (!empty($errors)) {
109
            throw new Tiqr_Message_Exception_SendFailure("Http error occurred: ". $errors, true);
110
        }
111
112
        // Wait and retry once in case of a 502 Bad Gateway error
113
        if ($statusCode === 502 && !($retry)) {
114
          sleep(2);
115
          $this->_sendFirebase($deviceToken, $alert, $challenge, $apiKey, true);
116
          return;
117
        }
118
119
        if ($statusCode !== 200) {
120
            throw new Tiqr_Message_Exception_SendFailure(sprintf('Invalid status code : %s. Server : %s. Response : "%s".', $statusCode, $remoteip, $result), true);
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type true; however, parameter $values of sprintf() does only seem to accept double|integer|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

120
            throw new Tiqr_Message_Exception_SendFailure(sprintf('Invalid status code : %s. Server : %s. Response : "%s".', $statusCode, $remoteip, /** @scrutinizer ignore-type */ $result), true);
Loading history...
121
        }
122
123
        // handle errors, ignoring registration_id's
124
        $response = json_decode($result, true);
0 ignored issues
show
Bug introduced by
It seems like $result can also be of type true; however, parameter $json of json_decode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

124
        $response = json_decode(/** @scrutinizer ignore-type */ $result, true);
Loading history...
125
        foreach ($response['results'] as $k => $v) {
126
            if (isset($v['error'])) {
127
                throw new Tiqr_Message_Exception_SendFailure("Error in FCM response: " . $v['error'], true);
128
            }
129
        }
130
    }
131
}
132