Test Setup Failed
Push — master ( a33163...7b535f )
by Yannick
316:04 queued 252:40
created

MessagesWebService::countNewMessages()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 2
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class for manage the messages web service
6
 * @author Angel Fernando Quiroz Campos <[email protected]>
7
 * @package chamilo.webservices.messages
8
 */
9
class MessagesWebService extends WebService
10
{
11
    const SERVICE_NAME = 'MsgREST';
12
    /**
13
     * @var string EXTRA_FIELD_GCM_REGISTRATION Variable name of the user extra field.
14
     * Necessary for register the registration token from the Google Cloud Messaging
15
     */
16
    const EXTRA_FIELD_GCM_REGISTRATION = 'gcm_registration_id';
17
18
    /**
19
     * Generate the api key for a user
20
     * @param int $userId The user id
21
     * @return string The api key
22
     */
23
    public function generateApiKey($userId)
24
    {
25
        $apiKey = UserManager::get_api_keys($userId, self::SERVICE_NAME);
26
27
        if (empty($apiKey)) {
28
            UserManager::add_api_key($userId, self::SERVICE_NAME);
29
30
            $apiKey = UserManager::get_api_keys($userId, self::SERVICE_NAME);
31
        }
32
33
        return current($apiKey);
34
    }
35
36
    /**
37
     * Get the user api key
38
     * @param string $username The user name
39
     * @return string The api key
40
     */
41
    public function getApiKey($username)
42
    {
43
        $userInfo = api_get_user_info_from_username($username);
44
        $userId = $userInfo['user_id'];
45
46
        if ($this->apiKey !== null) {
47
            return $this->apiKey;
48
        } else {
49
            $this->apiKey = $this->generateApiKey($userId);
50
51
            return $this->apiKey;
52
        }
53
    }
54
55
    /**
56
     * Check if the api is valid for a user
57
     * @param string $username The username
58
     * @param string $apiKeyToValidate The api key
59
     * @return boolean Whether the api belongs to the user return true. Otherwise return false
60
     */
61
    public static function isValidApiKey($username, $apiKeyToValidate)
62
    {
63
        $userInfo = api_get_user_info_from_username($username);
64
        $userId = $userInfo['user_id'];
65
66
        $apiKeys = UserManager::get_api_keys($userId, self::SERVICE_NAME);
67
68
        if (!empty($apiKeys)) {
69
            $apiKey = current($apiKeys);
70
71
            if ($apiKey == $apiKeyToValidate) {
72
                return true;
73
            }
74
        }
75
76
        return false;
77
    }
78
79
    /**
80
     * Get the count of new messages for a user
81
     * @param string $username The username
82
     * @param int $lastId The id of the last received message
83
     * @return int The count fo new messages
84
     */
85
    public function countNewMessages($username, $lastId = 0)
86
    {
87
        $userInfo = api_get_user_info_from_username($username);
88
        $userId = $userInfo['user_id'];
89
90
        return MessageManager::countMessagesFromLastReceivedMessage($userId, $lastId);
91
    }
92
93
    /**
94
     * Get the list of new messages for a user
95
     * @param string $username The username
96
     * @param int $lastId The id of the last received message
97
     * @return array the new message list
98
     */
99
    public function getNewMessages($username, $lastId = 0)
100
    {
101
        $messages = array();
102
103
        $userInfo = api_get_user_info_from_username($username);
104
        $userId = $userInfo['user_id'];
105
106
        $lastMessages = MessageManager::getMessagesFromLastReceivedMessage($userId, $lastId);
107
108
        foreach ($lastMessages as $message) {
0 ignored issues
show
Bug introduced by
The expression $lastMessages of type integer|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
109
            $hasAttachments = MessageManager::hasAttachments($message['id']);
110
111
            $messages[] = array(
112
                'id' => $message['id'],
113
                'title' => $message['title'],
114
                'sender' => array(
115
                    'id' => $message['user_id'],
116
                    'lastname' => $message['lastname'],
117
                    'firstname' => $message['firstname'],
118
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
119
                ),
120
                'sendDate' => $message['send_date'],
121
                'content' => $message['content'],
122
                'hasAttachments' => $hasAttachments,
123
                'platform' => array(
124
                    'website' => api_get_path(WEB_PATH),
125
                    'messagingTool' => api_get_path(WEB_PATH) . 'main/messages/inbox.php'
126
                )
127
            );
128
        }
129
130
        return $messages;
131
    }
132
133
    /**
134
     * Create the user extra field
135
     */
136
    public static function init()
137
    {
138
        $extraField = new ExtraField('user');
139
        $fieldInfo = $extraField->get_handler_field_info_by_field_variable(self::EXTRA_FIELD_GCM_REGISTRATION);
140
141
        if (empty($fieldInfo)) {
142
            $extraField->save([
143
                'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
144
                'field_type' => ExtraField::FIELD_TYPE_TEXT,
145
                'display_text' => self::EXTRA_FIELD_GCM_REGISTRATION
146
            ]);
147
        }
148
    }
149
150
    /**
151
     * Register the Registration ID (token) obtained from Google Cloud Messaging for a user
152
     * @param Chamilo\UserBundle\Entity\User $user The user
153
     * @param string $registrationId The token registration id from Google Cloud Messaging
154
     * @return int The id after insert or the number of affected rows after update. Otherwhise return false
155
     */
156
    public static function setGcmRegistrationId(Chamilo\UserBundle\Entity\User $user, $registrationId)
157
    {
158
        $registrationId = Security::remove_XSS($registrationId);
159
        $extraFieldValue = new ExtraFieldValue('user');
160
161
        return $extraFieldValue->save([
162
            'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
163
            'value' => $registrationId,
164
            'item_id' => $user->getId()
165
        ]);
166
    }
167
168
    /**
169
     * Send the push notifications to MobileMessaging app
170
     * @param array $userIds The IDs of users who will be notified
171
     * @param string $title The notification title
172
     * @param string $content The notification content
173
     * @return int The number of success notifications. Otherwise returns false
174
     */
175
    public static function sendPushNotification(array $userIds, $title, $content)
176
    {
177
        if (api_get_setting('webservice.messaging_allow_send_push_notification') !== 'true') {
178
            return false;
179
        }
180
181
        $gdcApiKey = api_get_setting('webservice.messaging_gdc_api_key');
182
183
        if ($gdcApiKey === false) {
184
            return false;
185
        }
186
187
        $content = str_replace(['<br>', '<br/>', '<br />'], "\n", $content);
188
        $content = strip_tags($content);
189
        $content = html_entity_decode($content, ENT_QUOTES);
190
191
        $gcmRegistrationIds = [];
192
193
        foreach ($userIds as $userId) {
194
            $extraFieldValue = new ExtraFieldValue('user');
195
            $valueInfo = $extraFieldValue->get_values_by_handler_and_field_variable(
196
                $userId,
197
                self::EXTRA_FIELD_GCM_REGISTRATION
198
            );
199
200
            if (empty($valueInfo)) {
201
                continue;
202
            }
203
204
            $gcmRegistrationIds[] = $valueInfo['value'];
205
        }
206
207
        $headers = [
208
            'Authorization: key=' . $gdcApiKey,
209
            'Content-Type: application/json'
210
        ];
211
212
        $fields = json_encode([
213
            'registration_ids' => $gcmRegistrationIds,
214
            'data' => [
215
                'title' => $title,
216
                'message' => $content
217
            ]
218
        ]);
219
220
        $ch = curl_init();
221
        curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send');
222
        curl_setopt($ch, CURLOPT_POST, true);
223
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
224
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
225
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
226
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
227
        $result = curl_exec($ch);
228
        curl_close($ch);
229
230
        $decodedResult = json_decode($result);
231
232
        return $decodedResult->success;
233
    }
234
}
235