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 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   * External functions
  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  defined('MOODLE_INTERNAL') || die;
  28  
  29  require_once("$CFG->libdir/externallib.php");
  30  
  31  /**
  32   * External API for airnotifier web services
  33   *
  34   * @package    message_airnotifier
  35   * @category   external
  36   * @copyright  2012 Jerome Mouneyrac <jerome@moodle.com>
  37   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  38   * @since Moodle 2.7
  39   */
  40  class message_airnotifier_external extends external_api {
  41  
  42      /**
  43       * Returns description of method parameters
  44       *
  45       * @since Moodle 2.7
  46       */
  47      public static function is_system_configured_parameters() {
  48          return new external_function_parameters(
  49                  array()
  50          );
  51      }
  52  
  53      /**
  54       * Tests whether the airnotifier settings have been configured
  55       *
  56       * @since Moodle 2.7
  57       */
  58      public static function is_system_configured() {
  59          global $DB;
  60  
  61          // First, check if the plugin is disabled.
  62          $processor = $DB->get_record('message_processors', array('name' => 'airnotifier'), '*', MUST_EXIST);
  63          if (!$processor->enabled) {
  64              return 0;
  65          }
  66  
  67          // Then, check if the plugin is completly configured.
  68          $manager = new message_airnotifier_manager();
  69          return (int) $manager->is_system_configured();
  70      }
  71  
  72      /**
  73       * Returns description of method result value
  74       *
  75       * @return external_single_structure
  76       * @since Moodle 2.7
  77       */
  78      public static function is_system_configured_returns() {
  79          return new external_value( PARAM_INT, '0 if the system is not configured, 1 otherwise');
  80      }
  81  
  82      /**
  83       * Returns description of method parameters
  84       *
  85       * @since Moodle 2.7
  86       */
  87      public static function are_notification_preferences_configured_parameters() {
  88          return new external_function_parameters(
  89                  array(
  90                      'userids' => new external_multiple_structure(new external_value(PARAM_INT, 'user ID')),
  91                  )
  92          );
  93      }
  94  
  95      /**
  96       * Check if the users have notification preferences configured for the airnotifier plugin
  97       *
  98       * @param array $userids Array of user ids
  99       * @since Moodle 2.7
 100       */
 101      public static function are_notification_preferences_configured($userids) {
 102          global $CFG, $USER, $DB;
 103  
 104          require_once($CFG->dirroot . '/message/lib.php');
 105          $params = self::validate_parameters(self::are_notification_preferences_configured_parameters(),
 106                  array('userids' => $userids));
 107  
 108          list($sqluserids, $params) = $DB->get_in_or_equal($params['userids'], SQL_PARAMS_NAMED);
 109          $uselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
 110          $ujoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
 111          $params['contextlevel'] = CONTEXT_USER;
 112          $usersql = "SELECT u.* $uselect
 113                        FROM {user} u $ujoin
 114                       WHERE u.id $sqluserids";
 115          $users = $DB->get_recordset_sql($usersql, $params);
 116  
 117          $result = array(
 118              'users' => [],
 119              'warnings' => []
 120          );
 121          $hasuserupdatecap = has_capability('moodle/user:update', context_system::instance());
 122          foreach ($users as $user) {
 123  
 124              $currentuser = ($user->id == $USER->id);
 125  
 126              if ($currentuser or $hasuserupdatecap) {
 127  
 128                  if (!empty($user->deleted)) {
 129                      $warning = [];
 130                      $warning['item'] = 'user';
 131                      $warning['itemid'] = $user->id;
 132                      $warning['warningcode'] = '1';
 133                      $warning['message'] = "User $user->id was deleted";
 134                      $result['warnings'][] = $warning;
 135                      continue;
 136                  }
 137  
 138                  $preferences = [];
 139                  $preferences['userid'] = $user->id;
 140                  $preferences['configured'] = 0;
 141  
 142                  // Now we get for all the providers and all the states
 143                  // the user preferences to check if at least one is enabled for airnotifier plugin.
 144                  $providers = message_get_providers_for_user($user->id);
 145                  $configured = false;
 146  
 147                  foreach ($providers as $provider) {
 148                      if ($configured) {
 149                          break;
 150                      }
 151  
 152                      $prefstocheck = [];
 153                      $prefname = 'message_provider_'.$provider->component.'_'.$provider->name.'_enabled';
 154  
 155                      // First get forced settings.
 156                      if ($forcedpref = get_config('message', $prefname)) {
 157                          $prefstocheck = array_merge($prefstocheck, explode(',', $forcedpref));
 158                      }
 159  
 160                      // Then get user settings.
 161                      if ($userpref = get_user_preferences($prefname, '', $user->id)) {
 162                          $prefstocheck = array_merge($prefstocheck, explode(',', $userpref));
 163                      }
 164  
 165                      if (in_array('airnotifier', $prefstocheck)) {
 166                          $preferences['configured'] = 1;
 167                          $configured = true;
 168                          break;
 169                      }
 170                  }
 171  
 172                  $result['users'][] = $preferences;
 173              } else if (!$hasuserupdatecap) {
 174                  $warning = [];
 175                  $warning['item'] = 'user';
 176                  $warning['itemid'] = $user->id;
 177                  $warning['warningcode'] = '2';
 178                  $warning['message'] = "You don't have permissions for view user $user->id preferences";
 179                  $result['warnings'][] = $warning;
 180              }
 181  
 182          }
 183          $users->close();
 184  
 185          return $result;
 186      }
 187  
 188      /**
 189       * Returns description of method result value
 190       *
 191       * @return external_single_structure
 192       * @since Moodle 2.7
 193       */
 194      public static function are_notification_preferences_configured_returns() {
 195          return new external_single_structure(
 196              array(
 197                  'users' => new external_multiple_structure(
 198                      new external_single_structure(
 199                          array (
 200                              'userid'     => new external_value(PARAM_INT, 'userid id'),
 201                              'configured' => new external_value(PARAM_INT,
 202                                  '1 if the user preferences have been configured and 0 if not')
 203                          )
 204                      ),
 205                      'list of preferences by user'),
 206                  'warnings' => new external_warnings()
 207              )
 208          );
 209      }
 210  
 211      /**
 212       * Returns description of method parameters
 213       *
 214       * @since Moodle 3.2
 215       */
 216      public static function get_user_devices_parameters() {
 217          return new external_function_parameters(
 218              array(
 219                  'appid' => new external_value(PARAM_NOTAGS, 'App unique id (usually a reversed domain)'),
 220                  'userid' => new external_value(PARAM_INT, 'User id, 0 for current user', VALUE_DEFAULT, 0)
 221              )
 222          );
 223      }
 224  
 225      /**
 226       * Return the list of mobile devices that are registered in Moodle for the given user.
 227       *
 228       * @param  string  $appid  app unique id (usually a reversed domain)
 229       * @param  integer $userid the user id, 0 for current user
 230       * @return array warnings and devices
 231       * @throws moodle_exception
 232       * @since Moodle 3.2
 233       */
 234      public static function get_user_devices($appid, $userid = 0) {
 235          global $USER;
 236  
 237          $params = self::validate_parameters(
 238              self::get_user_devices_parameters(),
 239              array(
 240                  'appid' => $appid,
 241                  'userid' => $userid,
 242              )
 243          );
 244  
 245          $context = context_system::instance();
 246          self::validate_context($context);
 247  
 248          if (empty($params['userid'])) {
 249              $user = $USER;
 250          } else {
 251              $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
 252              core_user::require_active_user($user);
 253              // Allow only admins to retrieve other users devices.
 254              if ($user->id != $USER->id) {
 255                  require_capability('moodle/site:config', $context);
 256              }
 257          }
 258  
 259          $warnings = array();
 260          $devices = array();
 261          // Check if mobile notifications are enabled.
 262          if (!self::is_system_configured()) {
 263              $warnings[] = array(
 264                  'item' => 'user',
 265                  'itemid' => $user->id,
 266                  'warningcode' => 'systemnotconfigured',
 267                  'message' => 'Mobile notifications are not configured'
 268              );
 269          } else {
 270              // We catch exceptions here because get_user_devices may try to connect to Airnotifier.
 271              try {
 272                  $manager = new message_airnotifier_manager();
 273                  $devices = $manager->get_user_devices($appid, $user->id);
 274              } catch (Exception $e) {
 275                  $warnings[] = array(
 276                      'item' => 'user',
 277                      'itemid' => $user->id,
 278                      'warningcode' => 'errorgettingdevices',
 279                      'message' => $e->getMessage()
 280                  );
 281              }
 282          }
 283  
 284          return array(
 285              'devices' => $devices,
 286              'warnings' => $warnings
 287          );
 288      }
 289  
 290      /**
 291       * Returns description of method result value
 292       *
 293       * @return external_single_structure
 294       * @since Moodle 3.2
 295       */
 296      public static function get_user_devices_returns() {
 297          return new external_single_structure(
 298              array(
 299                  'devices' => new external_multiple_structure(
 300                      new external_single_structure(
 301                          array (
 302                              'id' => new external_value(PARAM_INT, 'Device id (in the message_airnotifier table)'),
 303                              'appid' => new external_value(PARAM_NOTAGS, 'The app id, something like com.moodle.moodlemobile'),
 304                              'name' => new external_value(PARAM_NOTAGS, 'The device name, \'occam\' or \'iPhone\' etc.'),
 305                              'model' => new external_value(PARAM_NOTAGS, 'The device model \'Nexus4\' or \'iPad1,1\' etc.'),
 306                              'platform' => new external_value(PARAM_NOTAGS, 'The device platform \'iOS\' or \'Android\' etc.'),
 307                              'version' => new external_value(PARAM_NOTAGS, 'The device version \'6.1.2\' or \'4.2.2\' etc.'),
 308                              'pushid' => new external_value(PARAM_RAW, 'The device PUSH token/key/identifier/registration id'),
 309                              'uuid' => new external_value(PARAM_RAW, 'The device UUID'),
 310                              'enable' => new external_value(PARAM_INT, 'Whether the device is enabled or not'),
 311                              'timecreated' => new external_value(PARAM_INT, 'Time created'),
 312                              'timemodified' => new external_value(PARAM_INT, 'Time modified'),
 313                          )
 314                      ),
 315                      'List of devices'
 316                  ),
 317                  'warnings' => new external_warnings()
 318              )
 319          );
 320      }
 321  
 322      /**
 323       * Returns description of method parameters
 324       *
 325       * @since Moodle 3.2
 326       */
 327      public static function enable_device_parameters() {
 328          return new external_function_parameters(
 329              array(
 330                  'deviceid' => new external_value(PARAM_INT, 'The device id'),
 331                  'enable' => new external_value(PARAM_BOOL, 'True for enable the device, false otherwise')
 332              )
 333          );
 334      }
 335  
 336      /**
 337       * Enables or disables a registered user device so it can receive Push notifications
 338       *
 339       * @param  integer $deviceid the device id
 340       * @param  bool $enable whether to enable the device
 341       * @return array warnings and success status
 342       * @throws moodle_exception
 343       * @since Moodle 3.2
 344       */
 345      public static function enable_device($deviceid, $enable) {
 346          global $USER;
 347  
 348          $params = self::validate_parameters(
 349              self::enable_device_parameters(),
 350              array(
 351                  'deviceid' => $deviceid,
 352                  'enable' => $enable,
 353              )
 354          );
 355  
 356          $context = context_system::instance();
 357          self::validate_context($context);
 358          require_capability('message/airnotifier:managedevice', $context);
 359  
 360          if (!message_airnotifier_manager::enable_device($params['deviceid'], $params['enable'])) {
 361              throw new moodle_exception('unknowndevice', 'message_airnotifier');
 362          }
 363  
 364          return array(
 365              'success' => true,
 366              'warnings' => array()
 367          );
 368      }
 369  
 370      /**
 371       * Returns description of method result value
 372       *
 373       * @return external_single_structure
 374       * @since Moodle 3.2
 375       */
 376      public static function enable_device_returns() {
 377          return new external_single_structure(
 378              array(
 379                  'success' => new external_value(PARAM_BOOL, 'True if success'),
 380                  'warnings' => new external_warnings()
 381              )
 382          );
 383      }
 384  }