فهرست منبع

Allow send push notification to mobile-messaging project - refs #7402

Angel Fernando Quiroz Campos 9 سال پیش
والد
کامیت
23dba3b5a0

+ 4 - 1
main/inc/lib/notification.lib.php

@@ -314,17 +314,20 @@ class Notification extends Model
                 }
 
                 // Saving the notification to be sent some day.
+                $content = cut($content, $this->max_content_length);
                 $params = array(
                     'sent_at' => $sendDate,
                     'dest_user_id' => $user_id,
                     'dest_mail' => $userInfo['email'],
                     'title' => $title,
-                    'content' => cut($content, $this->max_content_length),
+                    'content' => $content,
                     'send_freq' => $userSetting
                 );
 
                 $this->save($params);
             }
+
+            MessagesWebService::sendPushNotification($user_list, $title, $content);
         }
     }
 

+ 103 - 0
main/inc/lib/webservices/MessagesWebService.class.php

@@ -9,6 +9,7 @@
 class MessagesWebService extends WebService
 {
     const SERVICE_NAME = 'MsgREST';
+    const EXTRA_FIELD_GCM_REGISTRATION = 'gcm_registration_id';
 
     /**
      * Generate the api key for a user
@@ -124,4 +125,106 @@ class MessagesWebService extends WebService
 
         return $messages;
     }
+
+    /**
+     * Create the user extra field
+     */
+    public static function init()
+    {
+        $extraField = new ExtraField('user');
+        $fieldInfo = $extraField->get_handler_field_info_by_field_variable(self::EXTRA_FIELD_GCM_REGISTRATION);
+
+        if (empty($fieldInfo)) {
+            $extraField->save([
+                'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
+                'field_type' => ExtraField::FIELD_TYPE_TEXT,
+                'display_text' => self::EXTRA_FIELD_GCM_REGISTRATION
+            ]);
+        }
+    }
+
+    /**
+     * Register the GCM Registration ID for a user
+     * @param Chamilo\UserBundle\Entity\User $user The user
+     * @param string $registrationId The token registration id from GCM
+     * @return int The id after insert or the number of affected rows after update. Otherwhise return false
+     */
+    public static function setGcmRegistrationId(Chamilo\UserBundle\Entity\User $user, $registrationId)
+    {
+        $registrationId = Security::remove_XSS($registrationId);
+        $extraFieldValue = new ExtraFieldValue('user');
+
+        return $extraFieldValue->save([
+            'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
+            'value' => $registrationId,
+            'item_id' => $user->getId()
+        ]);
+    }
+
+    /**
+     * Send the push notifications to MobileMessaging app
+     * @param array $userIds The IDs of users who will be notified
+     * @param string $title The notification title
+     * @param string $content The notification content
+     * @return int The number of success notifications. Otherwise returns false
+     */
+    public static function sendPushNotification(array $userIds, $title, $content)
+    {
+        if (api_get_configuration_value('messaging_allow_send_push_notification') !== 'true') {
+            return false;
+        }
+
+        $gdcApiKey = api_get_configuration_value('messaging_gdc_api_key');
+
+        if ($gdcApiKey === false) {
+            return false;
+        }
+
+        $content = str_replace(['<br>', '<br/>', '<br />'], "\n", $content);
+        $content = strip_tags($content);
+        $content = html_entity_decode($content, ENT_QUOTES);
+
+        $gcmRegistrationIds = [];
+
+        foreach ($userIds as $userId) {
+            $extraFieldValue = new ExtraFieldValue('user');
+            $valueInfo = $extraFieldValue->get_values_by_handler_and_field_variable(
+                $userId,
+                self::EXTRA_FIELD_GCM_REGISTRATION
+            );
+
+            if (empty($valueInfo)) {
+                continue;
+            }
+
+            $gcmRegistrationIds[] = $valueInfo['value'];
+        }
+
+        $headers = [
+            'Authorization: key=' . $gdcApiKey,
+            'Content-Type: application/json'
+        ];
+
+        $fields = json_encode([
+            'registration_ids' => $gcmRegistrationIds,
+            'data' => [
+                'title' => $title,
+                'message' => $content
+            ]
+        ]);
+
+        $ch = curl_init();
+        curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send');
+        curl_setopt($ch, CURLOPT_POST, true);
+        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
+        $result = curl_exec($ch);
+        curl_close($ch);
+
+        $decodedResult = json_decode($result);
+
+        return $decodedResult->success;
+    }
 }

+ 8 - 0
main/install/configuration.dist.php

@@ -230,3 +230,11 @@ $_configuration['system_stable'] = NEW_VERSION_STABLE;
 //$_configuration['document_manage_deleted_files'] = false;
 // Hide tabs in the main/session/index.php page
 //$_configuration['session_hide_tab_list'] = array();
+// Show invisible exercise in LP list
+//$_configuration['show_invisible_exercise_in_lp_list'] = false;
+//Allow send a push notification when an email are sent
+//$_configuration['messaging_allow_send_push_notification'] = 'true';
+//Project number in the Google Developer Console
+//$_configuration['messaging_gdc_project_number'] = '';
+//Api Key in the Google Developer Console
+//$_configuration['messaging_gdc_api_key'] = '';

+ 18 - 2
main/webservices/rest.php

@@ -15,18 +15,22 @@ $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 'nothing';
 $username = isset($_POST['username']) ? Security::remove_XSS($_POST['username']) : null;
 $apiKey = isset($_POST['api_key']) ? Security::remove_XSS($_POST['api_key']) : null;
 
+$em = Database::getManager();
+
 switch ($action) {
     case 'loginNewMessages':
         $password = isset($_POST['password']) ? Security::remove_XSS($_POST['password']) : null;
 
         if (MessagesWebService::isValidUser($username, $password)) {
-            $webService = new MessagesWebService();
+            MessagesWebService::init();
 
+            $webService = new MessagesWebService();
             $apiKey = $webService->getApiKey($username);
 
             $json = array(
                 'status' => true,
-                'apiKey' => $apiKey
+                'apiKey' => $apiKey,
+                'gcmSenderId' => api_get_configuration_value('messaging_gdc_project_number'),
             );
         } else {
             $json = array(
@@ -72,6 +76,18 @@ switch ($action) {
             );
         }
         break;
+    case 'setGcmRegistrationId':
+        if (!MessagesWebService::isValidApiKey($username, $apiKey)) {
+            $json = ['status' => false];
+            break;
+        }
+
+        $user = $em->getRepository('ChamiloUserBundle:User')->findOneBy(['username' => $username]);
+
+        MessagesWebService::setGcmRegistrationId($user, $_POST['registration_id']);
+
+        $json = ['status' => true];
+        break;
     default:
 }