Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.
   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  namespace communication_matrix;
  18  
  19  /**
  20   * class matrix_user_manager to handle specific actions.
  21   *
  22   * @package    communication_matrix
  23   * @copyright  2023 Stevani Andolo <stevani.andolo@moodle.com>
  24   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  25   */
  26  class matrix_user_manager {
  27      /**
  28       * Gets matrix user id from moodle.
  29       *
  30       * @param int $userid Moodle user id
  31       * @return string|null
  32       */
  33      public static function get_matrixid_from_moodle(
  34          int $userid,
  35      ): ?string {
  36          self::load_requirements();
  37          $field = profile_user_record($userid);
  38          $matrixprofilefield = get_config('communication_matrix', 'matrixuserid_field');
  39  
  40          if ($matrixprofilefield === false) {
  41              return null;
  42          }
  43  
  44          return $field->{$matrixprofilefield} ?? null;
  45      }
  46  
  47      /**
  48       * Get a qualified matrix user id based on a Moodle username.
  49       *
  50       * @param string $username The moodle username to turn into a Matrix username
  51       * @return string
  52       */
  53      public static function get_formatted_matrix_userid(
  54          string $username,
  55      ): string {
  56          $username = preg_replace('/[@#$%^&*()+{}|<>?!,]/i', '.', $username);
  57          $username = ltrim(rtrim($username, '.'), '.');
  58  
  59          $homeserver = self::get_formatted_matrix_home_server();
  60  
  61          return "@{$username}:{$homeserver}";
  62      }
  63  
  64      /**
  65       * Add user's Matrix user id.
  66       *
  67       * @param int $userid Moodle user id
  68       * @param string $matrixuserid Matrix user id
  69       */
  70      public static function set_matrix_userid_in_moodle(
  71          int $userid,
  72          string $matrixuserid,
  73      ): void {
  74          $matrixprofilefield = self::get_profile_field_name();
  75          $field = profile_get_custom_field_data_by_shortname($matrixprofilefield);
  76  
  77          if ($field === null) {
  78              return;
  79          }
  80          $userinfodata = (object) [
  81              'id' => $userid,
  82              'data' => $matrixuserid,
  83              'fieldid' => $field->id,
  84              "profile_field_{$matrixprofilefield}" => $matrixuserid,
  85          ];
  86          profile_save_data($userinfodata);
  87      }
  88  
  89      /**
  90       * Sets home server for user matrix id
  91       *
  92       * @return string
  93       */
  94      public static function get_formatted_matrix_home_server(): string {
  95          $homeserver = get_config('communication_matrix', 'matrixhomeserverurl');
  96          if ($homeserver === false) {
  97              throw new \moodle_exception('Unknown matrix homeserver url');
  98          }
  99  
 100          $homeserver = parse_url($homeserver)['host'];
 101  
 102          if (str_starts_with($homeserver, 'www.')) {
 103              $homeserver = str_replace('www.', '', $homeserver);
 104          }
 105  
 106          return $homeserver;
 107      }
 108  
 109      /**
 110       * Insert "Communication" category and "matrixuserid" field.
 111       *
 112       * @return string
 113       */
 114      public static function create_matrix_user_profile_fields(): string {
 115          global $CFG, $DB;
 116  
 117          require_once($CFG->dirroot . '/user/profile/definelib.php');
 118          require_once($CFG->dirroot . '/user/profile/field/text/define.class.php');
 119  
 120          // Check if communication category exists.
 121          $categoryname = get_string('communication', 'core_communication');
 122          $category = $DB->count_records('user_info_category', ['name' => $categoryname]);
 123  
 124          if ($category < 1) {
 125              $data = new \stdClass();
 126              $data->sortorder = $DB->count_records('user_info_category') + 1;
 127              $data->name = $categoryname;
 128              $data->id = $DB->insert_record('user_info_category', $data);
 129  
 130              $createdcategory = $DB->get_record('user_info_category', ['id' => $data->id]);
 131              $categoryid = $createdcategory->id;
 132              \core\event\user_info_category_created::create_from_category($createdcategory)->trigger();
 133          } else {
 134              $category = $DB->get_record('user_info_category', ['name' => $categoryname]);
 135              $categoryid = $category->id;
 136          }
 137  
 138          set_config('communication_category_field', $categoryname, 'core_communication');
 139  
 140          // Check if matrixuserid exists in user_info_field table.
 141          $matrixuserid = $DB->count_records('user_info_field', [
 142              'shortname' => 'matrixuserid',
 143              'categoryid' => $categoryid,
 144          ]);
 145  
 146          if ($matrixuserid < 1) {
 147              $profileclass = new \profile_define_text();
 148  
 149              $data = (object) [
 150                  'shortname' => 'matrixuserid',
 151                  'name' => get_string('matrixuserid', 'communication_matrix'),
 152                  'datatype' => 'text',
 153                  'categoryid' => $categoryid,
 154                  'forceunique' => 1,
 155                  'visible' => 0,
 156                  'locked' => 1,
 157                  'param1' => 30,
 158                  'param2' => 2048,
 159              ];
 160  
 161              $profileclass->define_save($data);
 162              set_config('matrixuserid_field', 'matrixuserid', 'communication_matrix');
 163              return 'matrixuserid';
 164          }
 165      }
 166  
 167      /**
 168       * Get the profile field name, creating the profiel field if it does not exist.
 169       *
 170       * @return string
 171       */
 172      protected static function get_profile_field_name(): string {
 173          self::load_requirements();
 174          $matrixprofilefield = get_config('communication_matrix', 'matrixuserid_field');
 175          if ($matrixprofilefield === false) {
 176              $matrixprofilefield = self::create_matrix_user_profile_fields();
 177          }
 178  
 179          return $matrixprofilefield;
 180      }
 181  
 182      /**
 183       * Load requirements for profile field management.
 184       *
 185       * This is just a helper to keep loading legacy files isolated.
 186       */
 187      protected static function load_requirements(): void {
 188          global $CFG;
 189  
 190          require_once("{$CFG->dirroot}/user/profile/lib.php");
 191      }
 192  }