Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Airnotifier message processor to send messages to the APNS provider: airnotfier. (https://github.com/dcai/airnotifier)
  19   *
  20   * @package    message_airnotifier
  21   * @category   external
  22   * @copyright  2012 Jerome Mouneyrac <jerome@moodle.com>
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   * @since Moodle 2.7
  25   */
  26  
  27  require_once($CFG->dirroot . '/message/output/lib.php');
  28  
  29  /**
  30   * Message processor class
  31   *
  32   * @package   message_airnotifier
  33   * @copyright 2012 Jerome Mouneyrac
  34   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  35   */
  36  class message_output_airnotifier extends message_output {
  37  
  38      /**
  39       * Processes the message and sends a notification via airnotifier
  40       *
  41       * @param stdClass $eventdata the event data submitted by the message sender plus $eventdata->savedmessageid
  42       * @return true if ok, false if error
  43       */
  44      public function send_message($eventdata) {
  45          global $CFG, $DB;
  46          require_once($CFG->libdir . '/filelib.php');
  47  
  48          if (!empty($CFG->noemailever)) {
  49              // Hidden setting for development sites, set in config.php if needed.
  50              debugging('$CFG->noemailever active, no airnotifier message sent.', DEBUG_MINIMAL);
  51              return true;
  52          }
  53  
  54          // Skip any messaging suspended and deleted users.
  55          if ($eventdata->userto->auth === 'nologin' or
  56              $eventdata->userto->suspended or
  57              $eventdata->userto->deleted) {
  58              return true;
  59          }
  60  
  61          // If username is empty we try to retrieve it, since it's required to generate the siteid.
  62          if (empty($eventdata->userto->username)) {
  63              $eventdata->userto->username = $DB->get_field('user', 'username', array('id' => $eventdata->userto->id));
  64          }
  65  
  66          // Site id, to map with Moodle Mobile stored sites.
  67          $siteid = md5($CFG->wwwroot . $eventdata->userto->username);
  68  
  69          // Airnotifier can handle custom requests using processors (that are Airnotifier plugins).
  70          // In the extra parameter we indicate which processor to use and also additional data to be handled by the processor.
  71          // Here we clone the eventdata object because will be deleting/adding attributes.
  72          $extra = clone $eventdata;
  73  
  74          // Delete attributes that may content private information.
  75          if (!empty($eventdata->userfrom)) {
  76              $extra->userfromid = $eventdata->userfrom->id;
  77              $extra->userfromfullname = fullname($eventdata->userfrom);
  78              unset($extra->userfrom);
  79          }
  80          $extra->usertoid = $eventdata->userto->id;
  81          unset($extra->userto);
  82  
  83          $extra->processor       = 'moodle';
  84          $extra->site            = $siteid;
  85          $extra->date            = (!empty($eventdata->timecreated)) ? $eventdata->timecreated : time();
  86          $extra->notification    = (!empty($eventdata->notification)) ? 1 : 0;
  87          $encryptnotifications = get_config('message_airnotifier', 'encryptnotifications') == 1;
  88          $encryptprocessing = get_config('message_airnotifier', 'encryptprocessing');
  89  
  90          // Site name.
  91          $site = get_site();
  92          $extra->sitefullname = clean_param(format_string($site->fullname), PARAM_NOTAGS);
  93          $extra->siteshortname = clean_param(format_string($site->shortname), PARAM_NOTAGS);
  94  
  95          // Clean HTML and ony allow data not to be ignored by Airnotifier to reduce the payload size.
  96          if (empty($extra->smallmessage)) {
  97              $extra->smallmessage = $extra->fullmessage;
  98          }
  99          $extra->smallmessage = clean_param($extra->smallmessage, PARAM_NOTAGS);
 100          unset($extra->fullmessage);
 101          unset($extra->fullmessagehtml);
 102          unset($extra->fullmessageformat);
 103          unset($extra->fullmessagetrust);
 104  
 105          // Send wwwroot to airnotifier.
 106          $extra->wwwroot = $CFG->wwwroot;
 107  
 108          // We are sending to message to all devices.
 109          $airnotifiermanager = new message_airnotifier_manager();
 110          $devicetokens = $airnotifiermanager->get_user_devices($CFG->airnotifiermobileappname, $eventdata->userto->id);
 111          $skipsend = $encryptnotifications && $encryptprocessing == message_airnotifier_manager::ENCRYPT_UNSUPPORTED_NOT_SEND;
 112          $encryptionavailable = \core\encryption::is_sodium_installed();
 113  
 114          foreach ($devicetokens as $devicetoken) {
 115              if (!$devicetoken->enable) {
 116                  continue;
 117              }
 118  
 119              // Check if we should skip sending the notification.
 120              if ($skipsend) {
 121                  // If encryption is not available, do not send notifications.
 122                  if (!$encryptionavailable || ($encryptnotifications && empty($devicetoken->publickey))) {
 123                      continue;
 124                  }
 125              }
 126  
 127              // Sending the message to the device.
 128              $serverurl = $CFG->airnotifierurl . ':' . $CFG->airnotifierport . '/api/v2/push/';
 129              $header = array('Accept: application/json', 'X-AN-APP-NAME: ' . $CFG->airnotifierappname,
 130                  'X-AN-APP-KEY: ' . $CFG->airnotifieraccesskey);
 131              $curl = new curl;
 132              // Push notifications are supposed to be instant, do not wait to long blocking the execution.
 133              $curl->setopt(array('CURLOPT_TIMEOUT' => 2, 'CURLOPT_CONNECTTIMEOUT' => 2));
 134              $curl->setHeader($header);
 135  
 136              // Clone the data to avoid modifying the original.
 137              $deviceextra = clone $extra;
 138  
 139              $deviceextra->encrypted = $encryptnotifications;
 140              $deviceextra = $this->encrypt_payload($deviceextra, $devicetoken);
 141  
 142              // We use Firebase to deliver all Push Notifications, and for all device types.
 143              // Firebase has a 4KB payload limit.
 144              // https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
 145              // If the message is over that limit we remove unneeded fields and replace the title with a simple message.
 146              if (\core_text::strlen(json_encode($deviceextra), '8bit') > 4000) {
 147                  $deviceextra->smallmessage = get_string('view_notification', 'message_airnotifier');
 148              }
 149  
 150              $params = array(
 151                  'device'    => $devicetoken->platform,
 152                  'token'     => $devicetoken->pushid,
 153                  'extra'     => $deviceextra
 154              );
 155              if ($deviceextra->encrypted) {
 156                  // Setting alert to null makes air notifier send the notification as a data payload,
 157                  // this forces Android phones to call the app onMessageReceived function to decrypt the notification.
 158                  // Otherwise notifications are created by the Android system and will not be decrypted.
 159                  $params['alert'] = null;
 160              }
 161  
 162              // JSON POST raw body request.
 163              $resp = $curl->post($serverurl, json_encode($params));
 164          }
 165  
 166          return true;
 167      }
 168  
 169      /**
 170       * Encrypt the notification payload.
 171       *
 172       * @param stdClass $payload The notification payload.
 173       * @param stdClass $devicetoken The device token record
 174       * @return stdClass
 175       */
 176      protected function encrypt_payload(stdClass $payload, stdClass $devicetoken): stdClass {
 177          if (empty($payload->encrypted)) {
 178              return $payload;
 179          }
 180  
 181          if (empty($devicetoken->publickey) || !\core\encryption::is_sodium_installed()) {
 182              $payload->encrypted = false;
 183              return $payload;
 184          }
 185  
 186          $publickey = sodium_base642bin($devicetoken->publickey, SODIUM_BASE64_VARIANT_ORIGINAL);
 187          $fields = [
 188              'userfromfullname',
 189              'userfromid',
 190              'sitefullname',
 191              'smallmessage',
 192              'subject',
 193              'contexturl',
 194          ];
 195          foreach ($fields as $field) {
 196              if (!isset($payload->$field)) {
 197                  continue;
 198              }
 199              $payload->$field = sodium_bin2base64(sodium_crypto_box_seal(
 200                  $payload->$field,
 201                  $publickey
 202              ), SODIUM_BASE64_VARIANT_ORIGINAL);
 203          }
 204  
 205          // Remove extra fields which may contain personal data.
 206          // They cannot be encrypted otherwise we would go over the 4KB payload size limit.
 207          unset($payload->usertoid);
 208          unset($payload->replyto);
 209          unset($payload->replytoname);
 210          unset($payload->siteshortname);
 211          unset($payload->customdata);
 212          unset($payload->contexturlname);
 213          unset($payload->replytoname);
 214          unset($payload->attachment);
 215          unset($payload->attachname);
 216  
 217          return $payload;
 218      }
 219  
 220      /**
 221       * Creates necessary fields in the messaging config form.
 222       *
 223       * @param array $preferences An array of user preferences
 224       */
 225      public function config_form($preferences) {
 226          global $CFG, $OUTPUT, $USER, $PAGE;
 227  
 228          $systemcontext = context_system::instance();
 229          if (!has_capability('message/airnotifier:managedevice', $systemcontext)) {
 230              return get_string('nopermissiontomanagedevices', 'message_airnotifier');
 231          }
 232  
 233          if (!$this->is_system_configured()) {
 234              return get_string('notconfigured', 'message_airnotifier');
 235          } else {
 236  
 237              $airnotifiermanager = new message_airnotifier_manager();
 238              $devicetokens = $airnotifiermanager->get_user_devices($CFG->airnotifiermobileappname, $USER->id);
 239  
 240              if (!empty($devicetokens)) {
 241                  $output = '';
 242  
 243                  foreach ($devicetokens as $devicetoken) {
 244  
 245                      if ($devicetoken->enable) {
 246                          $hideshowiconname = 't/hide';
 247                          $dimmed = '';
 248                      } else {
 249                          $hideshowiconname = 't/show';
 250                          $dimmed = 'dimmed_text';
 251                      }
 252  
 253                      $hideshowicon = $OUTPUT->pix_icon($hideshowiconname, get_string('showhide', 'message_airnotifier'));
 254                      $name = "{$devicetoken->name} {$devicetoken->model} {$devicetoken->platform} {$devicetoken->version}";
 255  
 256                      $output .= html_writer::start_tag('li', array('id' => $devicetoken->id,
 257                                                                      'class' => 'airnotifierdevice ' . $dimmed)) . "\n";
 258                      $output .= html_writer::label($name, 'deviceid-' . $devicetoken->id, array('class' => 'devicelabel ')) . ' ' .
 259                          html_writer::link('#', $hideshowicon, array('class' => 'hidedevice', 'alt' => 'show/hide')) . "\n";
 260                      $output .= html_writer::end_tag('li') . "\n";
 261                  }
 262  
 263                  // Include the AJAX script to automatically trigger the action.
 264                  $airnotifiermanager->include_device_ajax();
 265  
 266                  $output = html_writer::tag('ul', $output, array('class' => 'list-unstyled unstyled',
 267                      'id' => 'airnotifierdevices'));
 268              } else {
 269                  $output = get_string('nodevices', 'message_airnotifier');
 270              }
 271              return $output;
 272          }
 273      }
 274  
 275      /**
 276       * Parses the submitted form data and saves it into preferences array.
 277       *
 278       * @param stdClass $form preferences form class
 279       * @param array $preferences preferences array
 280       */
 281      public function process_form($form, &$preferences) {
 282          return true;
 283      }
 284  
 285      /**
 286       * Loads the config data from database to put on the form during initial form display
 287       *
 288       * @param array $preferences preferences array
 289       * @param int $userid the user id
 290       */
 291      public function load_data(&$preferences, $userid) {
 292          return true;
 293      }
 294  
 295      /**
 296       * Tests whether the airnotifier settings have been configured
 297       * @return boolean true if airnotifier is configured
 298       */
 299      public function is_system_configured() {
 300          $airnotifiermanager = new message_airnotifier_manager();
 301          return $airnotifiermanager->is_system_configured();
 302      }
 303  }