Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

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