Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.

Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 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   * Class for Moodle Mobile tools.
  19   *
  20   * @package    tool_mobile
  21   * @copyright  2016 Juan Leyva
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   * @since      Moodle 3.1
  24   */
  25  namespace tool_mobile;
  26  
  27  use core_component;
  28  use core_plugin_manager;
  29  use context_system;
  30  use moodle_url;
  31  use moodle_exception;
  32  use lang_string;
  33  use curl;
  34  use core_qrcode;
  35  use stdClass;
  36  
  37  /**
  38   * API exposed by tool_mobile, to be used mostly by external functions and the plugin settings.
  39   *
  40   * @copyright  2016 Juan Leyva
  41   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  42   * @since      Moodle 3.1
  43   */
  44  class api {
  45  
  46      /** @var int to identify the login via app. */
  47      const LOGIN_VIA_APP = 1;
  48      /** @var int to identify the login via browser. */
  49      const LOGIN_VIA_BROWSER = 2;
  50      /** @var int to identify the login via an embedded browser. */
  51      const LOGIN_VIA_EMBEDDED_BROWSER = 3;
  52      /** @var int seconds an auto-login key will expire. */
  53      const LOGIN_KEY_TTL = 60;
  54      /** @var string URL of the Moodle Apps Portal */
  55      const MOODLE_APPS_PORTAL_URL = 'https://apps.moodle.com';
  56      /** @var int default value in seconds a QR login key will expire. */
  57      const LOGIN_QR_KEY_TTL = 600;
  58      /** @var int QR code disabled value */
  59      const QR_CODE_DISABLED = 0;
  60      /** @var int QR code type URL value */
  61      const QR_CODE_URL = 1;
  62      /** @var int QR code type login value */
  63      const QR_CODE_LOGIN = 2;
  64      /** @var string Default Android app id */
  65      const DEFAULT_ANDROID_APP_ID = 'com.moodle.moodlemobile';
  66      /** @var string Default iOS app id */
  67      const DEFAULT_IOS_APP_ID = '633359593';
  68  
  69      /**
  70       * Returns a list of Moodle plugins supporting the mobile app.
  71       *
  72       * @return array an array of objects containing the plugin information
  73       */
  74      public static function get_plugins_supporting_mobile() {
  75          global $CFG;
  76          require_once($CFG->libdir . '/adminlib.php');
  77  
  78          $cachekey = 'mobileplugins';
  79          if (!isloggedin()) {
  80              $cachekey = 'authmobileplugins';    // Use a different cache for not logged users.
  81          }
  82  
  83          // Check if we can return this from cache.
  84          $cache = \cache::make('tool_mobile', 'plugininfo');
  85          $pluginsinfo = $cache->get($cachekey);
  86          if ($pluginsinfo !== false) {
  87              return (array)$pluginsinfo;
  88          }
  89  
  90          $pluginsinfo = [];
  91          // For not logged users return only auth plugins.
  92          // This is to avoid anyone (not being a registered user) to obtain and download all the site remote add-ons.
  93          if (!isloggedin()) {
  94              $plugintypes = array('auth' => $CFG->dirroot.'/auth');
  95          } else {
  96              $plugintypes = core_component::get_plugin_types();
  97          }
  98  
  99          foreach ($plugintypes as $plugintype => $unused) {
 100              // We need to include files here.
 101              $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, 'db' . DIRECTORY_SEPARATOR . 'mobile.php');
 102              foreach ($pluginswithfile as $plugin => $notused) {
 103                  $path = core_component::get_plugin_directory($plugintype, $plugin);
 104                  $component = $plugintype . '_' . $plugin;
 105                  $version = get_component_version($component);
 106  
 107                  require("$path/db/mobile.php");
 108                  foreach ($addons as $addonname => $addoninfo) {
 109  
 110                      // Add handlers (for site add-ons).
 111                      $handlers = !empty($addoninfo['handlers']) ? $addoninfo['handlers'] : array();
 112                      $handlers = json_encode($handlers); // JSON formatted, since it is a complex structure that may vary over time.
 113  
 114                      // Now language strings used by the app.
 115                      $lang = array();
 116                      if (!empty($addoninfo['lang'])) {
 117                          $stringmanager = get_string_manager();
 118                          $langs = $stringmanager->get_list_of_translations(true);
 119                          foreach ($langs as $langid => $langname) {
 120                              foreach ($addoninfo['lang'] as $stringinfo) {
 121                                  $lang[$langid][$stringinfo[0]] =
 122                                      $stringmanager->get_string($stringinfo[0], $stringinfo[1], null, $langid);
 123                              }
 124                          }
 125                      }
 126                      $lang = json_encode($lang);
 127  
 128                      $plugininfo = array(
 129                          'component' => $component,
 130                          'version' => $version,
 131                          'addon' => $addonname,
 132                          'dependencies' => !empty($addoninfo['dependencies']) ? $addoninfo['dependencies'] : array(),
 133                          'fileurl' => '',
 134                          'filehash' => '',
 135                          'filesize' => 0,
 136                          'handlers' => $handlers,
 137                          'lang' => $lang,
 138                      );
 139  
 140                      // All the mobile packages must be under the plugin mobile directory.
 141                      $package = $path . '/mobile/' . $addonname . '.zip';
 142                      if (file_exists($package)) {
 143                          $plugininfo['fileurl'] = $CFG->wwwroot . '' . str_replace($CFG->dirroot, '', $package);
 144                          $plugininfo['filehash'] = sha1_file($package);
 145                          $plugininfo['filesize'] = filesize($package);
 146                      }
 147                      $pluginsinfo[] = $plugininfo;
 148                  }
 149              }
 150          }
 151  
 152          $cache->set($cachekey, $pluginsinfo);
 153  
 154          return $pluginsinfo;
 155      }
 156  
 157      /**
 158       * Returns a list of the site public settings, those not requiring authentication.
 159       *
 160       * @return array with the settings and warnings
 161       */
 162      public static function get_public_config() {
 163          global $CFG, $SITE, $PAGE, $OUTPUT;
 164          require_once($CFG->libdir . '/authlib.php');
 165  
 166          $context = context_system::instance();
 167          // We need this to make work the format text functions.
 168          $PAGE->set_context($context);
 169  
 170          list($authinstructions, $notusedformat) = external_format_text($CFG->auth_instructions, FORMAT_MOODLE, $context->id);
 171          list($maintenancemessage, $notusedformat) = external_format_text($CFG->maintenance_message, FORMAT_MOODLE, $context->id);
 172          $settings = array(
 173              'wwwroot' => $CFG->wwwroot,
 174              'httpswwwroot' => $CFG->wwwroot,
 175              'sitename' => external_format_string($SITE->fullname, $context->id, true),
 176              'guestlogin' => $CFG->guestloginbutton,
 177              'rememberusername' => $CFG->rememberusername,
 178              'authloginviaemail' => $CFG->authloginviaemail,
 179              'registerauth' => $CFG->registerauth,
 180              'forgottenpasswordurl' => clean_param($CFG->forgottenpasswordurl, PARAM_URL), // We may expect a mailto: here.
 181              'authinstructions' => $authinstructions,
 182              'authnoneenabled' => (int) is_enabled_auth('none'),
 183              'enablewebservices' => $CFG->enablewebservices,
 184              'enablemobilewebservice' => $CFG->enablemobilewebservice,
 185              'maintenanceenabled' => $CFG->maintenance_enabled,
 186              'maintenancemessage' => $maintenancemessage,
 187              'mobilecssurl' => !empty($CFG->mobilecssurl) ? $CFG->mobilecssurl : '',
 188              'tool_mobile_disabledfeatures' => get_config('tool_mobile', 'disabledfeatures'),
 189              'country' => clean_param($CFG->country, PARAM_NOTAGS),
 190              'agedigitalconsentverification' => \core_auth\digital_consent::is_age_digital_consent_verification_enabled(),
 191              'autolang' => $CFG->autolang,
 192              'lang' => clean_param($CFG->lang, PARAM_LANG),  // Avoid breaking WS because of incorrect package langs.
 193              'langmenu' => $CFG->langmenu,
 194              'langlist' => $CFG->langlist,
 195              'locale' => $CFG->locale,
 196              'tool_mobile_minimumversion' => get_config('tool_mobile', 'minimumversion'),
 197              'tool_mobile_iosappid' => get_config('tool_mobile', 'iosappid'),
 198              'tool_mobile_androidappid' => get_config('tool_mobile', 'androidappid'),
 199              'tool_mobile_setuplink' => clean_param(get_config('tool_mobile', 'setuplink'), PARAM_URL),
 200              'tool_mobile_qrcodetype' => clean_param(get_config('tool_mobile', 'qrcodetype'), PARAM_INT),
 201              'supportpage' => clean_param($CFG->supportpage, PARAM_URL),
 202          );
 203  
 204          $typeoflogin = get_config('tool_mobile', 'typeoflogin');
 205          // Not found, edge case.
 206          if ($typeoflogin === false) {
 207              $typeoflogin = self::LOGIN_VIA_APP; // Defaults to via app.
 208          }
 209          $settings['typeoflogin'] = $typeoflogin;
 210  
 211          // Check if the user can sign-up to return the launch URL in that case.
 212          $cansignup = signup_is_enabled();
 213  
 214          $url = new moodle_url("/$CFG->admin/tool/mobile/launch.php");
 215          $settings['launchurl'] = $url->out(false);
 216  
 217          // Check that we are receiving a moodle_url object, themes can override get_logo_url and may return incorrect values.
 218          if (($logourl = $OUTPUT->get_logo_url()) && $logourl instanceof moodle_url) {
 219              $settings['logourl'] = clean_param($logourl->out(false), PARAM_URL);
 220          }
 221          if (($compactlogourl = $OUTPUT->get_compact_logo_url()) && $compactlogourl instanceof moodle_url) {
 222              $settings['compactlogourl'] = clean_param($compactlogourl->out(false), PARAM_URL);
 223          }
 224  
 225          // Identity providers.
 226          $authsequence = get_enabled_auth_plugins();
 227          $identityproviders = \auth_plugin_base::get_identity_providers($authsequence);
 228          $identityprovidersdata = \auth_plugin_base::prepare_identity_providers_for_output($identityproviders, $OUTPUT);
 229          if (!empty($identityprovidersdata)) {
 230              $settings['identityproviders'] = $identityprovidersdata;
 231              // Clean URLs to avoid breaking Web Services.
 232              // We can't do it in prepare_identity_providers_for_output() because it may break the web output.
 233              foreach ($settings['identityproviders'] as &$ip) {
 234                  $ip['url'] = (!empty($ip['url'])) ? clean_param($ip['url'], PARAM_URL) : '';
 235                  $ip['iconurl'] = (!empty($ip['iconurl'])) ? clean_param($ip['iconurl'], PARAM_URL) : '';
 236              }
 237          }
 238  
 239          // If age is verified, return also the admin contact details.
 240          if ($settings['agedigitalconsentverification']) {
 241              $settings['supportname'] = clean_param($CFG->supportname, PARAM_NOTAGS);
 242              $settings['supportemail'] = clean_param($CFG->supportemail, PARAM_EMAIL);
 243          }
 244  
 245          return $settings;
 246      }
 247  
 248      /**
 249       * Returns a list of site configurations, filtering by section.
 250       *
 251       * @param  string $section section name
 252       * @return stdClass object containing the settings
 253       */
 254      public static function get_config($section) {
 255          global $CFG, $SITE;
 256  
 257          $settings = new \stdClass;
 258          $context = context_system::instance();
 259          $isadmin = has_capability('moodle/site:config', $context);
 260  
 261          if (empty($section) or $section == 'frontpagesettings') {
 262              require_once($CFG->dirroot . '/course/format/lib.php');
 263              // First settings that anyone can deduce.
 264              $settings->fullname = external_format_string($SITE->fullname, $context->id);
 265              $settings->shortname = external_format_string($SITE->shortname, $context->id);
 266  
 267              // Return to a var instead of directly to $settings object because of differences between
 268              // list() in php5 and php7. {@link http://php.net/manual/en/function.list.php}
 269              $formattedsummary = external_format_text($SITE->summary, $SITE->summaryformat,
 270                                                                                          $context->id);
 271              $settings->summary = $formattedsummary[0];
 272              $settings->summaryformat = $formattedsummary[1];
 273              $settings->frontpage = $CFG->frontpage;
 274              $settings->frontpageloggedin = $CFG->frontpageloggedin;
 275              $settings->maxcategorydepth = $CFG->maxcategorydepth;
 276              $settings->frontpagecourselimit = $CFG->frontpagecourselimit;
 277              $settings->numsections = course_get_format($SITE)->get_last_section_number();
 278              $settings->newsitems = $SITE->newsitems;
 279              $settings->commentsperpage = $CFG->commentsperpage;
 280  
 281              // Now, admin settings.
 282              if ($isadmin) {
 283                  $settings->defaultfrontpageroleid = $CFG->defaultfrontpageroleid;
 284              }
 285          }
 286  
 287          if (empty($section) or $section == 'sitepolicies') {
 288              $manager = new \core_privacy\local\sitepolicy\manager();
 289              $settings->sitepolicy = ($sitepolicy = $manager->get_embed_url()) ? $sitepolicy->out(false) : '';
 290              $settings->sitepolicyhandler = $CFG->sitepolicyhandler;
 291              $settings->disableuserimages = $CFG->disableuserimages;
 292          }
 293  
 294          if (empty($section) or $section == 'gradessettings') {
 295              require_once($CFG->dirroot . '/user/lib.php');
 296              $settings->mygradesurl = user_mygrades_url();
 297              // The previous function may return moodle_url instances or plain string URLs.
 298              if ($settings->mygradesurl instanceof moodle_url) {
 299                  $settings->mygradesurl = $settings->mygradesurl->out(false);
 300              }
 301          }
 302  
 303          if (empty($section) or $section == 'mobileapp') {
 304              $settings->tool_mobile_forcelogout = get_config('tool_mobile', 'forcelogout');
 305              $settings->tool_mobile_customlangstrings = get_config('tool_mobile', 'customlangstrings');
 306              $settings->tool_mobile_disabledfeatures = get_config('tool_mobile', 'disabledfeatures');
 307              $settings->tool_mobile_filetypeexclusionlist = get_config('tool_mobile', 'filetypeexclusionlist');
 308              $settings->tool_mobile_custommenuitems = get_config('tool_mobile', 'custommenuitems');
 309              $settings->tool_mobile_apppolicy = get_config('tool_mobile', 'apppolicy');
 310              // This setting could be not set in some edge cases such as bad upgrade.
 311              $mintimereq = get_config('tool_mobile', 'autologinmintimebetweenreq');
 312              $mintimereq = empty($mintimereq) ? 6 * MINSECS : $mintimereq;
 313              $settings->tool_mobile_autologinmintimebetweenreq = $mintimereq;
 314          }
 315  
 316          if (empty($section) or $section == 'calendar') {
 317              $settings->calendartype = $CFG->calendartype;
 318              $settings->calendar_site_timeformat = $CFG->calendar_site_timeformat;
 319              $settings->calendar_startwday = $CFG->calendar_startwday;
 320              $settings->calendar_adminseesall = $CFG->calendar_adminseesall;
 321              $settings->calendar_lookahead = $CFG->calendar_lookahead;
 322              $settings->calendar_maxevents = $CFG->calendar_maxevents;
 323          }
 324  
 325          if (empty($section) or $section == 'coursecolors') {
 326              $colornumbers = range(1, 10);
 327              foreach ($colornumbers as $number) {
 328                  $settings->{'core_admin_coursecolor' . $number} = get_config('core_admin', 'coursecolor' . $number);
 329              }
 330          }
 331  
 332          if (empty($section) or $section == 'supportcontact') {
 333              $settings->supportname = $CFG->supportname;
 334              $settings->supportemail = $CFG->supportemail ?? null;
 335              $settings->supportpage = $CFG->supportpage;
 336          }
 337  
 338          if (empty($section) || $section === 'graceperiodsettings') {
 339              $settings->coursegraceperiodafter = $CFG->coursegraceperiodafter;
 340              $settings->coursegraceperiodbefore = $CFG->coursegraceperiodbefore;
 341          }
 342  
 343          if (empty($section) || $section === 'navigation') {
 344              $settings->enabledashboard = $CFG->enabledashboard;
 345          }
 346  
 347          return $settings;
 348      }
 349  
 350      /*
 351       * Check if all the required conditions are met to allow the auto-login process continue.
 352       *
 353       * @param  int $userid  current user id
 354       * @since Moodle 3.2
 355       * @throws moodle_exception
 356       */
 357      public static function check_autologin_prerequisites($userid) {
 358          global $CFG;
 359  
 360          if (!$CFG->enablewebservices or !$CFG->enablemobilewebservice) {
 361              throw new moodle_exception('enablewsdescription', 'webservice');
 362          }
 363  
 364          if (!is_https()) {
 365              throw new moodle_exception('httpsrequired', 'tool_mobile');
 366          }
 367  
 368          if (has_capability('moodle/site:config', context_system::instance(), $userid) or is_siteadmin($userid)) {
 369              throw new moodle_exception('autologinnotallowedtoadmins', 'tool_mobile');
 370          }
 371      }
 372  
 373      /**
 374       * Creates an auto-login key for the current user, this key is restricted by time and ip address.
 375       * This key is used for automatically login the user in the site when the Moodle app opens the site in a mobile browser.
 376       *
 377       * @return string the key
 378       * @since Moodle 3.2
 379       */
 380      public static function get_autologin_key() {
 381          global $USER;
 382          // Delete previous keys.
 383          delete_user_key('tool_mobile', $USER->id);
 384  
 385          // Create a new key.
 386          $iprestriction = getremoteaddr();
 387          $validuntil = time() + self::LOGIN_KEY_TTL;
 388          return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
 389      }
 390  
 391      /**
 392       * Creates a QR login key for the current user, this key is restricted by time and ip address.
 393       * This key is used for automatically login the user in the site when the user scans a QR code in the Moodle app.
 394       *
 395       * @param  stdClass $mobilesettings  mobile app plugin settings
 396       * @return string the key
 397       * @since Moodle 3.9
 398       */
 399      public static function get_qrlogin_key(stdClass $mobilesettings) {
 400          global $USER;
 401          // Delete previous keys.
 402          delete_user_key('tool_mobile', $USER->id);
 403  
 404          // Create a new key.
 405          $iprestriction = getremoteaddr(null);
 406          $qrkeyttl = !empty($mobilesettings->qrkeyttl) ? $mobilesettings->qrkeyttl : self::LOGIN_QR_KEY_TTL;
 407          $validuntil = time() + $qrkeyttl;
 408          return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
 409      }
 410  
 411      /**
 412       * Get a list of the Mobile app features.
 413       *
 414       * @return array array with the features grouped by theirs ubication in the app.
 415       * @since Moodle 3.3
 416       */
 417      public static function get_features_list() {
 418          global $CFG;
 419          require_once($CFG->libdir . '/authlib.php');
 420  
 421          $general = new lang_string('general');
 422          $mainmenu = new lang_string('mainmenu', 'tool_mobile');
 423          $course = new lang_string('course');
 424          $modules = new lang_string('managemodules');
 425          $blocks = new lang_string('blocks');
 426          $useraccount = new lang_string('useraccount');
 427          $participants = new lang_string('participants');
 428          $files = new lang_string('files');
 429          $remoteaddons = new lang_string('remoteaddons', 'tool_mobile');
 430          $identityproviders = new lang_string('oauth2identityproviders', 'tool_mobile');
 431  
 432          $availablemods = core_plugin_manager::instance()->get_plugins_of_type('mod');
 433          $coursemodules = array();
 434          $appsupportedmodules = array(
 435              'assign', 'bigbluebuttonbn', 'book', 'chat', 'choice', 'data', 'feedback', 'folder', 'forum', 'glossary', 'h5pactivity',
 436              'imscp', 'label', 'lesson', 'lti', 'page', 'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki', 'workshop');
 437  
 438          foreach ($availablemods as $mod) {
 439              if (in_array($mod->name, $appsupportedmodules)) {
 440                  $coursemodules['$mmCourseDelegate_mmaMod' . ucfirst($mod->name)] = $mod->displayname;
 441              }
 442          }
 443          asort($coursemodules);
 444  
 445          $remoteaddonslist = array();
 446          $mobileplugins = self::get_plugins_supporting_mobile();
 447          foreach ($mobileplugins as $plugin) {
 448              $displayname = core_plugin_manager::instance()->plugin_name($plugin['component']) . " - " . $plugin['addon'];
 449              $remoteaddonslist['sitePlugin_' . $plugin['component'] . '_' . $plugin['addon']] = $displayname;
 450  
 451          }
 452  
 453          // Display blocks.
 454          $availableblocks = core_plugin_manager::instance()->get_plugins_of_type('block');
 455          $courseblocks = array();
 456          $appsupportedblocks = array(
 457              'activity_modules' => 'CoreBlockDelegate_AddonBlockActivityModules',
 458              'activity_results' => 'CoreBlockDelegate_AddonBlockActivityResults',
 459              'site_main_menu' => 'CoreBlockDelegate_AddonBlockSiteMainMenu',
 460              'myoverview' => 'CoreBlockDelegate_AddonBlockMyOverview',
 461              'course_list' => 'CoreBlockDelegate_AddonBlockCourseList',
 462              'timeline' => 'CoreBlockDelegate_AddonBlockTimeline',
 463              'recentlyaccessedcourses' => 'CoreBlockDelegate_AddonBlockRecentlyAccessedCourses',
 464              'starredcourses' => 'CoreBlockDelegate_AddonBlockStarredCourses',
 465              'recentlyaccesseditems' => 'CoreBlockDelegate_AddonBlockRecentlyAccessedItems',
 466              'badges' => 'CoreBlockDelegate_AddonBlockBadges',
 467              'blog_menu' => 'CoreBlockDelegate_AddonBlockBlogMenu',
 468              'blog_recent' => 'CoreBlockDelegate_AddonBlockBlogRecent',
 469              'blog_tags' => 'CoreBlockDelegate_AddonBlockBlogTags',
 470              'calendar_month' => 'CoreBlockDelegate_AddonBlockCalendarMonth',
 471              'calendar_upcoming' => 'CoreBlockDelegate_AddonBlockCalendarUpcoming',
 472              'comments' => 'CoreBlockDelegate_AddonBlockComments',
 473              'completionstatus' => 'CoreBlockDelegate_AddonBlockCompletionStatus',
 474              'feedback' => 'CoreBlockDelegate_AddonBlockFeedback',
 475              'glossary_random' => 'CoreBlockDelegate_AddonBlockGlossaryRandom',
 476              'html' => 'CoreBlockDelegate_AddonBlockHtml',
 477              'lp' => 'CoreBlockDelegate_AddonBlockLp',
 478              'news_items' => 'CoreBlockDelegate_AddonBlockNewsItems',
 479              'online_users' => 'CoreBlockDelegate_AddonBlockOnlineUsers',
 480              'private_files' => 'CoreBlockDelegate_AddonBlockPrivateFiles',
 481              'recent_activity' => 'CoreBlockDelegate_AddonBlockRecentActivity',
 482              'rss_client' => 'CoreBlockDelegate_AddonBlockRssClient',
 483              'selfcompletion' => 'CoreBlockDelegate_AddonBlockSelfCompletion',
 484              'tags' => 'CoreBlockDelegate_AddonBlockTags',
 485          );
 486  
 487          foreach ($availableblocks as $block) {
 488              if (isset($appsupportedblocks[$block->name])) {
 489                  $courseblocks[$appsupportedblocks[$block->name]] = $block->displayname;
 490              }
 491          }
 492          asort($courseblocks);
 493  
 494          $features = array(
 495              "$general" => array(
 496                  'NoDelegate_CoreOffline' => new lang_string('offlineuse', 'tool_mobile'),
 497                  'NoDelegate_SiteBlocks' => new lang_string('blocks'),
 498                  'NoDelegate_CoreComments' => new lang_string('comments'),
 499                  'NoDelegate_CoreRating' => new lang_string('ratings', 'rating'),
 500                  'NoDelegate_CoreTag' => new lang_string('tags'),
 501                  '$mmLoginEmailSignup' => new lang_string('startsignup'),
 502                  'NoDelegate_ForgottenPassword' => new lang_string('forgotten'),
 503                  'NoDelegate_ResponsiveMainMenuItems' => new lang_string('responsivemainmenuitems', 'tool_mobile'),
 504                  'NoDelegate_H5POffline' => new lang_string('h5poffline', 'tool_mobile'),
 505                  'NoDelegate_DarkMode' => new lang_string('darkmode', 'tool_mobile'),
 506                  'CoreFilterDelegate' => new lang_string('type_filter_plural', 'plugin'),
 507                  'CoreReportBuilderDelegate' => new lang_string('reportbuilder', 'core_reportbuilder'),
 508              ),
 509              "$mainmenu" => array(
 510                  '$mmSideMenuDelegate_mmaFrontpage' => new lang_string('sitehome'),
 511                  'CoreMainMenuDelegate_CoreCoursesDashboard' => new lang_string('myhome'),
 512                  '$mmSideMenuDelegate_mmCourses' => new lang_string('mycourses'),
 513                  '$mmSideMenuDelegate_mmaMessages' => new lang_string('messages', 'message'),
 514                  '$mmSideMenuDelegate_mmaNotifications' => new lang_string('notifications', 'message'),
 515                  '$mmSideMenuDelegate_mmaCalendar' => new lang_string('calendar', 'calendar'),
 516                  'CoreMainMenuDelegate_AddonBlog' => new lang_string('blog', 'blog'),
 517                  'CoreMainMenuDelegate_CoreTag' => new lang_string('tags'),
 518                  'CoreMainMenuDelegate_QrReader' => new lang_string('scanqrcode', 'tool_mobile'),
 519              ),
 520              "$useraccount" => array(
 521                  '$mmSideMenuDelegate_mmaGrades' => new lang_string('grades', 'grades'),
 522                  '$mmSideMenuDelegate_mmaFiles' => new lang_string('files'),
 523                  'CoreUserDelegate_AddonBadges:account' => new lang_string('badges', 'badges'),
 524                  'CoreUserDelegate_AddonBlog:account' => new lang_string('blog', 'blog'),
 525                  '$mmSideMenuDelegate_mmaCompetency' => new lang_string('myplans', 'tool_lp'),
 526                  'NoDelegate_SwitchAccount' => new lang_string('switchaccount', 'tool_mobile'),
 527              ),
 528              "$course" => array(
 529                  '$mmCoursesDelegate_mmaParticipants' => new lang_string('participants'),
 530                  '$mmCoursesDelegate_mmaGrades' => new lang_string('grades', 'grades'),
 531                  '$mmCoursesDelegate_mmaCompetency' => new lang_string('competencies', 'competency'),
 532                  '$mmCoursesDelegate_mmaNotes' => new lang_string('notes', 'notes'),
 533                  '$mmCoursesDelegate_mmaCourseCompletion' => new lang_string('coursecompletion', 'completion'),
 534                  'NoDelegate_CourseBlocks' => new lang_string('blocks'),
 535                  'CoreCourseOptionsDelegate_AddonBlog' => new lang_string('blog', 'blog'),
 536                  '$mmCoursesDelegate_search' => new lang_string('search'),
 537                  'NoDelegate_CoreCourseDownload' => new lang_string('downloadcourse', 'tool_mobile'),
 538                  'NoDelegate_CoreCoursesDownload' => new lang_string('downloadcourses', 'tool_mobile'),
 539              ),
 540              "$participants" => array(
 541                  '$mmUserDelegate_mmaGrades:viewGrades' => new lang_string('grades', 'grades'),
 542                  '$mmUserDelegate_mmaCourseCompletion:viewCompletion' => new lang_string('coursecompletion', 'completion'),
 543                  '$mmUserDelegate_mmaBadges' => new lang_string('badges', 'badges'),
 544                  '$mmUserDelegate_mmaNotes:addNote' => new lang_string('notes', 'notes'),
 545                  'CoreUserDelegate_AddonBlog:blogs' => new lang_string('blog', 'blog'),
 546                  '$mmUserDelegate_mmaCompetency:learningPlan' => new lang_string('competencies', 'competency'),
 547                  '$mmUserDelegate_mmaMessages:sendMessage' => new lang_string('sendmessage', 'message'),
 548                  '$mmUserDelegate_picture' => new lang_string('userpic'),
 549              ),
 550              "$files" => array(
 551                  'files_privatefiles' => new lang_string('privatefiles'),
 552                  'files_sitefiles' => new lang_string('sitefiles'),
 553                  'files_upload' => new lang_string('upload'),
 554              ),
 555              "$modules" => $coursemodules,
 556              "$blocks" => $courseblocks,
 557          );
 558  
 559          if (!empty($remoteaddonslist)) {
 560              $features["$remoteaddons"] = $remoteaddonslist;
 561          }
 562  
 563          if (!empty($availablemods['lti'])) {
 564              $ltidisplayname = $availablemods['lti']->displayname;
 565              $features["$ltidisplayname"]['CoreCourseModuleDelegate_AddonModLti:launchViaSite'] =
 566                  new lang_string('launchviasiteinbrowser', 'tool_mobile');
 567          }
 568  
 569          // Display OAuth 2 identity providers.
 570          if (is_enabled_auth('oauth2')) {
 571              $identityproviderslist = array();
 572              $idps = \auth_plugin_base::get_identity_providers(['oauth2']);
 573  
 574              foreach ($idps as $idp) {
 575                  // Only add identity providers that have an ID.
 576                  $id = isset($idp['url']) ? $idp['url']->get_param('id') : null;
 577                  if ($id != null) {
 578                      $identityproviderslist['NoDelegate_IdentityProvider_' . $id] = $idp['name'];
 579                  }
 580              }
 581  
 582              if (!empty($identityproviderslist)) {
 583                  $features["$identityproviders"] = array();
 584  
 585                  if (count($identityproviderslist) > 1) {
 586                      // Include an option to disable them all.
 587                      $features["$identityproviders"]['NoDelegate_IdentityProviders'] = new lang_string('all');
 588                  }
 589  
 590                  $features["$identityproviders"] = array_merge($features["$identityproviders"], $identityproviderslist);
 591              }
 592          }
 593  
 594          return $features;
 595      }
 596  
 597      /**
 598       * This function check the current site for potential configuration issues that may prevent the mobile app to work.
 599       *
 600       * @return array list of potential issues
 601       * @since  Moodle 3.4
 602       */
 603      public static function get_potential_config_issues() {
 604          global $CFG;
 605          require_once($CFG->dirroot . "/lib/filelib.php");
 606          require_once($CFG->dirroot . '/message/lib.php');
 607  
 608          $warnings = array();
 609  
 610          if (is_https()) {
 611              $curl = new curl();
 612              // Return certificate information and verify the certificate.
 613              $curl->setopt(array('CURLOPT_CERTINFO' => 1, 'CURLOPT_SSL_VERIFYPEER' => true));
 614              // Check https using a page not redirecting or returning exceptions.
 615              $curl->head("$CFG->wwwroot/$CFG->admin/tool/mobile/mobile.webmanifest.php");
 616              $info = $curl->get_info();
 617  
 618              // Check the certificate is not self-signed or has an untrusted-root.
 619              // This may be weak in some scenarios (when the curl SSL verifier is outdated).
 620              if (empty($info['http_code']) || empty($info['certinfo'])) {
 621                  $warnings[] = ['selfsignedoruntrustedcertificatewarning', 'tool_mobile'];
 622              } else {
 623                  $timenow = time();
 624                  $infokeys = array_keys($info['certinfo']);
 625                  $lastkey = end($infokeys);
 626  
 627                  if (count($info['certinfo']) == 1) {
 628                      // This will work in a normal browser because it will complete the chain, but not in a mobile app.
 629                      $warnings[] = ['invalidcertificatechainwarning', 'tool_mobile'];
 630                  }
 631  
 632                  foreach ($info['certinfo'] as $key => $cert) {
 633                      // Convert to lower case the keys, some OS/curl implementations differ.
 634                      $cert = array_change_key_case($cert, CASE_LOWER);
 635  
 636                      // Due to a bug in certain curl/openssl versions the signature algorithm isn't always correctly parsed.
 637                      // See https://github.com/curl/curl/issues/3706 for reference.
 638                      if (!array_key_exists('signature algorithm', $cert)) {
 639                          // The malformed field that does contain the algorithm we're looking for looks like the following:
 640                          // <WHITESPACE>Signature Algorithm: <ALGORITHM><CRLF><ALGORITHM>.
 641                          preg_match('/\s+Signature Algorithm: (?<algorithm>[^\s]+)/', $cert['public key algorithm'], $matches);
 642  
 643                          $signaturealgorithm = $matches['algorithm'] ?? '';
 644                      } else {
 645                          $signaturealgorithm = $cert['signature algorithm'];
 646                      }
 647  
 648                      // Check if the signature algorithm is weak (Android won't work with SHA-1).
 649                      if ($key != $lastkey &&
 650                              ($signaturealgorithm == 'sha1WithRSAEncryption' || $signaturealgorithm == 'sha1WithRSA')) {
 651                          $warnings['insecurealgorithmwarning'] = ['insecurealgorithmwarning', 'tool_mobile'];
 652                      }
 653                      // Check certificate start date.
 654                      if (strtotime($cert['start date']) > $timenow) {
 655                          $warnings['invalidcertificatestartdatewarning'] = ['invalidcertificatestartdatewarning', 'tool_mobile'];
 656                      }
 657                      // Check certificate end date.
 658                      if (strtotime($cert['expire date']) < $timenow) {
 659                          $warnings['invalidcertificateexpiredatewarning'] = ['invalidcertificateexpiredatewarning', 'tool_mobile'];
 660                      }
 661                  }
 662              }
 663          } else {
 664              // Warning for non https sites.
 665              $warnings[] = ['nohttpsformobilewarning', 'admin'];
 666          }
 667  
 668          // Check ADOdb debug enabled.
 669          if (get_config('auth_db', 'debugauthdb') || get_config('enrol_database', 'debugdb')) {
 670              $warnings[] = ['adodbdebugwarning', 'tool_mobile'];
 671          }
 672          // Check display errors on.
 673          if (!empty($CFG->debugdisplay)) {
 674              $warnings[] = ['displayerrorswarning', 'tool_mobile'];
 675          }
 676          // Check mobile notifications.
 677          $processors = get_message_processors();
 678          $enabled = false;
 679          foreach ($processors as $processor => $status) {
 680              if ($processor == 'airnotifier' && $status->enabled) {
 681                  $enabled = true;
 682              }
 683          }
 684          if (!$enabled) {
 685              $warnings[] = ['mobilenotificationsdisabledwarning', 'tool_mobile'];
 686          }
 687  
 688          return $warnings;
 689      }
 690  
 691      /**
 692       * Generates a QR code with the site URL or for automatic login from the mobile app.
 693       *
 694       * @param  stdClass $mobilesettings tool_mobile settings
 695       * @return string base64 data image contents, null if qr disabled
 696       */
 697      public static function generate_login_qrcode(stdClass $mobilesettings) {
 698          global $CFG, $USER;
 699  
 700          if ($mobilesettings->qrcodetype == static::QR_CODE_DISABLED) {
 701              return null;
 702          }
 703  
 704          $urlscheme = !empty($mobilesettings->forcedurlscheme) ? $mobilesettings->forcedurlscheme : 'moodlemobile';
 705          $data = $urlscheme . '://' . $CFG->wwwroot;
 706  
 707          if ($mobilesettings->qrcodetype == static::QR_CODE_LOGIN) {
 708              $qrloginkey = static::get_qrlogin_key($mobilesettings);
 709              $data .= '?qrlogin=' . $qrloginkey . '&userid=' . $USER->id;
 710          }
 711  
 712          $qrcode = new core_qrcode($data);
 713          $imagedata = 'data:image/png;base64,' . base64_encode($qrcode->getBarcodePngData(5, 5));
 714  
 715          return $imagedata;
 716      }
 717  
 718      /**
 719       * Gets Moodle app plan subscription information for the current site as it is returned by the Apps Portal.
 720       *
 721       * @return array Subscription information
 722       */
 723      public static function get_subscription_information() : ?array {
 724          global $CFG;
 725  
 726          // Use session cache to prevent multiple requests.
 727          $cache = \cache::make('tool_mobile', 'subscriptiondata');
 728          $subscriptiondata = $cache->get(0);
 729          if ($subscriptiondata !== false) {
 730              return $subscriptiondata;
 731          }
 732  
 733          $mobilesettings = get_config('tool_mobile');
 734  
 735          // To validate that the requests come from this site we need to send some private information that only is known by the
 736          // Moodle Apps portal or the Sites registration database.
 737          $credentials = [];
 738  
 739          if (!empty($CFG->airnotifieraccesskey)) {
 740              $credentials[] = ['type' => 'airnotifieraccesskey', 'value' => $CFG->airnotifieraccesskey];
 741          }
 742          if (\core\hub\registration::is_registered()) {
 743              $credentials[] = ['type' => 'siteid', 'value' => $CFG->siteidentifier];
 744          }
 745          // Generate a hash key for validating that the request is coming from this site via WS.
 746          $key = complex_random_string(32);
 747          $sitesubscriptionkey = json_encode(['validuntil' => time() + 10 * MINSECS, 'key' => $key]);
 748          set_config('sitesubscriptionkey', $sitesubscriptionkey, 'tool_mobile');
 749          $credentials[] = ['type' => 'sitesubscriptionkey', 'value' => $key];
 750  
 751          // Parameters for the WebService returning site information.
 752          $androidappid = empty($mobilesettings->androidappid) ? static::DEFAULT_ANDROID_APP_ID : $mobilesettings->androidappid;
 753          $iosappid = empty($mobilesettings->iosappid) ? static::DEFAULT_IOS_APP_ID : $mobilesettings->iosappid;
 754          $fnparams = (object) [
 755              'siteurl' => $CFG->wwwroot,
 756              'appids' => [$androidappid, $iosappid],
 757              'credentials' => $credentials,
 758          ];
 759          // Prepare the arguments for a request to the AJAX nologin endpoint.
 760          $args = [
 761              (object) [
 762                  'index' => 0,
 763                  'methodname' => 'local_apps_get_site_info',
 764                  'args' => $fnparams,
 765              ]
 766          ];
 767  
 768          // Ask the Moodle Apps Portal for the subscription information.
 769          $curl = new curl();
 770          $curl->setopt(array('CURLOPT_TIMEOUT' => 10, 'CURLOPT_CONNECTTIMEOUT' => 10));
 771  
 772          $serverurl = static::MOODLE_APPS_PORTAL_URL . "/lib/ajax/service-nologin.php";
 773          $query = 'args=' . urlencode(json_encode($args));
 774          $wsresponse = @json_decode($curl->post($serverurl, $query), true);
 775  
 776          $info = $curl->get_info();
 777          if ($curlerrno = $curl->get_errno()) {
 778              // CURL connection error.
 779              debugging("Unexpected response from the Moodle Apps Portal server, CURL error number: $curlerrno");
 780              return null;
 781          } else if ($info['http_code'] != 200) {
 782              // Unexpected error from server.
 783              debugging('Unexpected response from the Moodle Apps Portal server, HTTP code:' . $info['httpcode']);
 784              return null;
 785          } else if (!empty($wsresponse[0]['error'])) {
 786              // Unexpected error from Moodle Apps Portal.
 787              debugging('Unexpected response from the Moodle Apps Portal server:' . json_encode($wsresponse[0]));
 788              return null;
 789          } else if (empty($wsresponse[0]['data'])) {
 790              debugging('Unexpected response from the Moodle Apps Portal server:' . json_encode($wsresponse));
 791              return null;
 792          }
 793  
 794          $cache->set(0, $wsresponse[0]['data']);
 795  
 796          return $wsresponse[0]['data'];
 797      }
 798  }