[ Index ]

PHP Cross Reference of Moodle 1.9.3 [Build 15-Oct-2008]

title

Body

[close]

/enrol/mnet/ -> enrol.php (source)

   1  <?php
   2  // The following flags are set in the configuration
   3  // $config->allow_allcourses:       expose all courses to external enrolment
   4  // $config->allowed_categories:     serialised array of courses allowed
   5  // $config->allowed_courses:        serialised array of courses allowed
   6  
   7  class enrolment_plugin_mnet {
   8  
   9      /// Override the base config_form() function
  10      function config_form($frm) {
  11          global $CFG;
  12  
  13         $vars = array('enrol_mnet_allow_allcourses',
  14                       'enrol_mnet_allowed_categories',
  15                       'enrol_mnet_allowed_courses');
  16  
  17          foreach ($vars as $var) {
  18              if (!isset($frm->$var)) {
  19                  $frm->$var = '';
  20              }
  21          }
  22  
  23          $mnethosts = $this->list_remote_servers();
  24  
  25          include ("$CFG->dirroot/enrol/mnet/config.html");
  26      }
  27  
  28  
  29      /// Override the base process_config() function
  30      function process_config($config) {
  31  
  32          if (!isset($config->enrol_mnet_allow_allcourses)) {
  33              $config->enrol_mnet_allow_allcourses = false;
  34          }
  35          set_config('enrol_mnet_allow_allcourses', $config->enrol_mnet_allow_allcourses);
  36  
  37          if (!isset($config->enrol_mnet_allowed_categories)) {
  38              $config->enrol_mnet_allowed_categories = '';
  39          }
  40          set_config('enrol_mnet_allowed_categories', $config->enrol_mnet_allowed_categories);
  41  
  42          if (!isset($config->enrol_mnet_allowed_courses)) {
  43              $config->enrol_mnet_allowed_courses = '';
  44          }
  45          set_config('enrol_mnet_allowed_courses', $config->enrol_mnet_allowed_courses);
  46  
  47          return true;
  48  
  49      }
  50  
  51      /// Override the get_access_icons() function
  52      function get_access_icons($course) {
  53      }
  54  
  55      /**
  56       * Override the base cron() function
  57       */
  58      //function cron() {
  59      //
  60      //} // end of cron()
  61  
  62  
  63  
  64      /***
  65       *** MNET functions
  66       ***
  67       ***/
  68      function mnet_publishes() {
  69          
  70          $enrol = array();
  71          $enrol['name']        = 'mnet_enrol'; // Name & Description go in lang file
  72          $enrol['apiversion']  = 1;
  73          $enrol['methods']     = array('available_courses','user_enrolments', 'enrol_user', 'unenrol_user', 'course_enrolments' );
  74  
  75          return array($enrol);
  76      }
  77  
  78      /**
  79      * Does Foo
  80      *
  81      * @param string $username   The username
  82      * @param int    $mnethostid The id of the remote mnethost
  83      * @return bool              Whether the user can login from the remote host
  84      */
  85      function available_courses() {
  86          global $CFG;
  87  
  88          if (!empty($CFG->enrol_mnet_allow_allcourses)) {
  89  
  90              $query =
  91              "SELECT
  92                  co.id          AS remoteid,
  93                  ca.id          AS cat_id,
  94                  ca.name        AS cat_name,
  95                  ca.description AS cat_description,
  96                  co.sortorder,
  97                  co.fullname,
  98                  co.shortname,
  99                  co.idnumber,
 100                  co.summary,
 101                  co.startdate,
 102                  co.cost,
 103                  co.currency,
 104                  co.defaultrole AS defaultroleid,
 105                  r.name         AS defaultrolename 
 106              FROM
 107                  {$CFG->prefix}course_categories ca
 108              JOIN
 109                  {$CFG->prefix}course co ON
 110                  ca.id = co.category
 111              LEFT JOIN
 112                  {$CFG->prefix}role r ON
 113                  r.id = co.defaultrole
 114              WHERE
 115                  co.visible = '1' AND
 116                  co.enrollable = '1'
 117              ORDER BY
 118                  sortorder ASC
 119                  ";
 120  
 121              return get_records_sql($query);
 122  
 123          } elseif (!empty($CFG->enrol_mnet_allowed_categories)) {
 124  
 125              $cats = preg_split('/\s*,\s*/', $CFG->enrol_mnet_allowed_categories);
 126              for ($n=0;$n < count($cats); $n++) {
 127                  $cats[$n] = " ca.path LIKE '%/" . (int)$cats[$n] . "/%' ";
 128              }
 129              $cats = join(' OR ', $cats);
 130  
 131              $query =
 132              "SELECT
 133                  id, name
 134              FROM
 135                  {$CFG->prefix}course_categories ca
 136              WHERE
 137                  ca.id IN ({$CFG->enrol_mnet_allowed_categories})
 138                  OR ( $cats )
 139              ORDER BY
 140                  path ASC,
 141                  depth ASC
 142                  ";
 143              unset($cats);
 144  
 145              $rs = get_records_sql($query);
 146  
 147              if (!empty($rs)) {
 148                  $cats = array_keys($rs);
 149              }
 150              $where = ' AND ( ca.id IN (' . join(',', $cats) . ') ';
 151  
 152  
 153              if (!empty($CFG->enrol_mnet_allowed_courses)) {
 154                  $where .=  " OR co.id in ('{$CFG->enrol_mnet_allowed_courses}') ";
 155              }
 156  
 157              $where .= ')';
 158  
 159              $query =
 160              "SELECT
 161                  co.id as remoteid,
 162                  ca.id as cat_id,
 163                  ca.name as cat_name,
 164                  ca.description as cat_description,
 165                  co.sortorder,
 166                  co.fullname,
 167                  co.shortname,
 168                  co.idnumber,
 169                  co.summary,
 170                  co.startdate,
 171                  co.cost,
 172                  co.currency,
 173                  co.defaultrole as defaultroleid,
 174                  r.name
 175              FROM
 176                  {$CFG->prefix}course_categories ca
 177              JOIN
 178                  {$CFG->prefix}course co ON
 179                  ca.id = co.category
 180              LEFT JOIN
 181                  {$CFG->prefix}role r ON
 182                  r.id = co.defaultrole
 183              WHERE
 184                  co.visible = '1' AND
 185                  co.enrollable = '1' $where
 186              ORDER BY
 187                  sortorder ASC
 188                  ";
 189  
 190              return get_records_sql($query);
 191  
 192          } elseif (!empty($CFG->enrol_mnet_allowed_courses)) {
 193  
 194              $query =
 195                  "SELECT
 196                      co.id as remoteid,
 197                      ca.id as cat_id,
 198                      ca.name as cat_name,
 199                      ca.description as cat_description,
 200                      co.sortorder,
 201                      co.fullname,
 202                      co.shortname,
 203                      co.idnumber,
 204                      co.summary,
 205                      co.startdate,
 206                      co.cost,
 207                      co.currency,
 208                      co.defaultrole as defaultroleid,
 209                      r.name
 210                  FROM
 211                      {$CFG->prefix}course_categories ca
 212                  JOIN
 213                      {$CFG->prefix}course co ON
 214                      ca.id = co.category
 215                  LEFT JOIN
 216                      {$CFG->prefix}role r ON
 217                      r.id = co.defaultrole
 218                  WHERE
 219                      co.visible = '1' AND
 220                      co.enrollable = '1' AND
 221                      co.id in ({$CFG->enrol_mnet_allowed_courses})
 222                  ORDER BY
 223                      sortorder ASC
 224                      ";
 225  
 226              return get_records_sql($query);
 227  
 228          }
 229  
 230          return array();
 231      }
 232  
 233      /**
 234       * 
 235       */
 236      function user_enrolments($userid) {
 237          return array();
 238      }
 239  
 240      /**
 241       * Get a list of users from the client server who are enrolled in a course
 242       *
 243       * @param   int     $courseid   The Course ID
 244       * @param   string  $roles      Comma-separated list of role shortnames
 245       * @return  array               Array of usernames who are homed on the 
 246       *                              client machine
 247       */
 248      function course_enrolments($courseid, $roles = '') {
 249          global $MNET_REMOTE_CLIENT, $CFG;
 250  
 251          if (! $course = get_record('course', 'id', $courseid) ) {
 252              return 'no course';
 253              //error("That's an invalid course id");
 254          }
 255  
 256          $context = get_context_instance(CONTEXT_COURSE, $courseid);
 257  
 258          $sql = "
 259                  SELECT
 260                      u.id,
 261                      u.username,
 262                      a.enrol,
 263                      a.timemodified,
 264                      r.name,
 265                      r.shortname
 266                  FROM
 267                      {$CFG->prefix}role_assignments a,
 268                      {$CFG->prefix}role r,
 269                      {$CFG->prefix}user u
 270                  WHERE
 271                      a.contextid = '{$context->id}' AND
 272                      a.roleid = r.id AND
 273                      a.userid = u.id AND
 274                      u.mnethostid = '{$MNET_REMOTE_CLIENT->id}'
 275                      ";
 276  
 277          if(!empty($roles)) {
 278              // $default_role = get_default_course_role($course); ???
 279              $sql .= " AND
 280                      a.roleid in ('".str_replace(',',  "', '",  $roles)."')";
 281          } 
 282  
 283          $enrolments = get_records_sql($sql);
 284  
 285          $returnarray = array();
 286          foreach($enrolments as $user) {
 287              $returnarray[$user->username] = array('enrol' => $user->enrol, 
 288                                                    'timemodified' => $user->timemodified, 
 289                                                    'shortname' => $user->shortname, 
 290                                                    'name' => $user->name);
 291          }
 292          return $returnarray;
 293      }
 294  
 295      /**
 296      * Enrols user to course with the default role
 297      *
 298      * @param string $username   The username of the remote use
 299      * @param int    $courseid   The id of the local course
 300      * @return bool              Whether the enrolment has been successful
 301      */
 302      function enrol_user($user, $courseid) {
 303          global $MNET, $MNET_REMOTE_CLIENT;
 304  
 305          $userrecord = get_record('user','username',addslashes($user['username']), 'mnethostid',$MNET_REMOTE_CLIENT->id);
 306  
 307          if ($userrecord == false) {
 308              // We should at least be checking that we allow the remote
 309              // site to create users
 310              // TODO: more rigour here thanks!
 311              $userrecord = new stdClass();
 312              $userrecord->username   = addslashes($user['username']);
 313              $userrecord->email      = addslashes($user['email']);
 314              $userrecord->firstname  = addslashes($user['firstname']);
 315              $userrecord->lastname   = addslashes($user['lastname']);
 316              $userrecord->mnethostid = $MNET_REMOTE_CLIENT->id;
 317  
 318              if ($userrecord->id = insert_record('user', $userrecord)) {
 319                  $userrecord = get_record('user','id', $userrecord->id);
 320              } else {
 321                  // TODO: Error out
 322                  return false;
 323              }
 324          }
 325  
 326          if (! $course = get_record('course', 'id', $courseid) ) {
 327              // TODO: Error out
 328              return false;
 329          }
 330  
 331          $courses = $this->available_courses();
 332  
 333          if (!empty($courses[$courseid])) {
 334              if (enrol_into_course($course, $userrecord, 'mnet')) {
 335                  return true;
 336              }
 337          }
 338          return false;
 339      }
 340  
 341      /**
 342      * Unenrol a user from a course
 343      *
 344      * @param string $username   The username
 345      * @param int    $courseid   The id of the local course
 346      * @return bool              Whether the user can login from the remote host
 347      */
 348      function unenrol_user($username, $courseid) {
 349          global $MNET_REMOTE_CLIENT;
 350  
 351          $userrecord = get_record('user', 'username', addslashes($username), 'mnethostid', $MNET_REMOTE_CLIENT->id);
 352  
 353          if ($userrecord == false) {
 354              return false;
 355              // TODO: Error out
 356          }
 357  
 358          if (! $course = get_record('course', 'id', $courseid) ) {
 359              return false;
 360              // TODO: Error out
 361          }
 362  
 363          if (! $context = get_context_instance(CONTEXT_COURSE, $course->id)) {
 364              return false;
 365              // TODO: Error out (Invalid context)
 366          }
 367  
 368          // Are we a *real* user or the shady MNET Daemon?
 369          // require_capability('moodle/role:assign', $context, NULL, false);
 370  
 371          if (!role_unassign(0, $userrecord->id, 0, $context->id)) {
 372              error("An error occurred while trying to unenrol that person.");
 373          }
 374  
 375          return true;
 376      }
 377  
 378      /***
 379       *** Client RPC behaviour
 380       ***
 381       ***
 382       ***/
 383  
 384      /**
 385      * Lists remote servers we use 'enrol' services from.
 386      *
 387      * @return array
 388      */
 389      function list_remote_servers() {
 390          global $CFG;
 391  
 392          $sql = "
 393              SELECT DISTINCT 
 394                  h.id, 
 395                  h.name
 396              FROM 
 397                  {$CFG->prefix}mnet_host h,
 398                  {$CFG->prefix}mnet_host2service h2s,
 399                  {$CFG->prefix}mnet_service s
 400              WHERE
 401                  h.id          = h2s.hostid   AND
 402                  h2s.serviceid = s.id         AND
 403                  s.name        = 'mnet_enrol' AND
 404                  h2s.subscribe = 1";
 405  
 406          $res = get_records_sql($sql);
 407          if (is_array($res)) {
 408              return $res;
 409          } else {
 410              return array();
 411          }
 412      }
 413  
 414      /**
 415      * Does Foo
 416      *
 417      * @param int    $mnethostid The id of the remote mnethost
 418      * @return array              Whether the user can login from the remote host
 419      */
 420      function fetch_remote_courses($mnethostid) {
 421          global $CFG;
 422          global $USER;
 423          global $MNET;
 424          require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
 425  
 426          // get the Service Provider info
 427          $mnet_sp = new mnet_peer();
 428          $mnet_sp->set_id($mnethostid);
 429  
 430          // set up the RPC request
 431          $mnetrequest = new mnet_xmlrpc_client();
 432          $mnetrequest->set_method('enrol/mnet/enrol.php/available_courses');
 433  
 434          // Initialise $message
 435          $message = '';
 436  
 437          // TODO: cache for a while (10 minutes?)
 438  
 439          // Thunderbirds are go! Do RPC call and store response
 440          if ($mnetrequest->send($mnet_sp) === true) {
 441              $courses = $mnetrequest->response;
 442  
 443              // get the cached courses key'd on remote id - only need remoteid and id fields
 444              $cachedcourses = get_records('mnet_enrol_course',
 445                                           'hostid', $mnethostid,
 446                                           'remoteid', 'remoteid, id' );
 447  
 448              // Update cache and transform $courses into objects
 449              // in-place for the benefit of our caller...
 450              for ($n=0;$n<count($courses);$n++) {
 451  
 452                  $course = &$courses[$n];
 453  
 454                  // add/update cached data in mnet_enrol_courses
 455                  // sanitise data 
 456                  $course = (object)$course;
 457                  $course->remoteid        = (int)$course->remoteid;
 458                  $course->hostid          = $mnethostid;
 459                  $course->cat_id          = (int)$course->cat_id;
 460                  $course->sortorder       = (int)$course->sortorder ;
 461                  $course->startdate       = (int)$course->startdate;
 462                  $course->cost            = (int)$course->cost;
 463                  $course->defaultroleid   = (int)$course->defaultroleid;
 464  
 465                  // sanitise strings for DB NOTE - these are not sane
 466                  // for printing, so we'll use a different object
 467                  $dbcourse = clone($course);
 468                  $dbcourse->cat_name        = addslashes($dbcourse->cat_name);
 469                  $dbcourse->cat_description = addslashes($dbcourse->cat_description);
 470                  $dbcourse->fullname        = addslashes($dbcourse->fullname);
 471                  $dbcourse->shortname       = addslashes($dbcourse->shortname);
 472                  $dbcourse->idnumber        = addslashes($dbcourse->idnumber);
 473                  $dbcourse->summary         = addslashes($dbcourse->summary);
 474                  $dbcourse->currency        = addslashes($dbcourse->currency);
 475                  $dbcourse->defaultrolename = addslashes($dbcourse->defaultrolename);
 476  
 477                  // insert or update
 478                  if (empty($cachedcourses[$course->remoteid])) {
 479                      $course->id = insert_record('mnet_enrol_course', $dbcourse);
 480                  } else {
 481                      $course->id = $cachedcourses[$course->remoteid]->id;
 482                      $cachedcourses[$course->remoteid]->seen=true;
 483                      update_record('mnet_enrol_course', $dbcourse);
 484                  }
 485                  // free tmp obj
 486                  unset($dbcourse);
 487              }
 488  
 489              // prune stale data from cache
 490              if (!empty($cachedcourses)) {
 491                  $stale = array();
 492                  foreach ($cachedcourses as $id => $cc) {
 493                      // TODO: maybe set a deleted flag instead
 494                      if (empty($cc->seen)) {
 495                          $stale[] = $cc->id;
 496                      }
 497                  }
 498                  if (!empty($stale)) {
 499                      delete_records_select('mnet_enrol_course', 'id IN ('.join(',',$stale).')');
 500                  }
 501              }
 502  
 503              return $courses;
 504          } else {
 505              foreach ($mnetrequest->error as $errormessage) {
 506                  list($code, $errormessage) = array_map('trim',explode(':', $errormessage, 2));
 507                  $message .= "ERROR $code:<br/>$errormessage<br/>";
 508              }
 509              error("RPC enrol/mnet/available_courses:<br/>$message");
 510          }
 511          return false;
 512      }
 513  
 514      /**
 515      * Does Foo
 516      *
 517      * @param int    $mnethostid The id of the remote mnethost
 518      * @return array              Whether the user can login from the remote host
 519      */
 520      function req_enrol_user($userid, $courseid) {
 521          global $CFG;
 522          global $USER;
 523          global $MNET;
 524          require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
 525  
 526          // Prepare a basic user record
 527          // in case the remote host doesn't have it
 528          $user = get_record('user', 'id', $userid, '','','','', 'username, email, firstname, lastname');
 529          $user = (array)$user;
 530  
 531          $course = get_record('mnet_enrol_course', 'id', $courseid);
 532  
 533          // get the Service Provider info
 534          $mnet_sp = new mnet_peer();
 535          $mnet_sp->set_id($course->hostid);
 536  
 537          // set up the RPC request
 538          $mnetrequest = new mnet_xmlrpc_client();
 539          $mnetrequest->set_method('enrol/mnet/enrol.php/enrol_user');
 540          $mnetrequest->add_param($user);
 541          $mnetrequest->add_param($course->remoteid);
 542  
 543          // Thunderbirds are go! Do RPC call and store response
 544          if ($mnetrequest->send($mnet_sp) === true) {
 545              if ($mnetrequest->response == true) {
 546                  // now store it in the mnet_enrol_assignments table
 547                  $assignment = new StdClass;
 548                  $assignment->userid = $userid;
 549                  $assignment->hostid = $course->hostid;
 550                  $assignment->courseid = $course->id;
 551                  $assignment->enroltype = 'mnet';
 552                  // TODO: other fields
 553                  if (insert_record('mnet_enrol_assignments', $assignment)) {
 554                      return true;
 555                  }
 556              }
 557          }
 558  
 559          return false;
 560      }
 561  
 562      /**
 563      * Does Foo
 564      *
 565      * @param int    $mnethostid The id of the remote mnethost
 566      * @return array              Whether the user can login from the remote host
 567      */
 568      function req_unenrol_user($userid, $courseid) {
 569          global $CFG;
 570          global $USER;
 571          global $MNET;
 572          require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
 573  
 574          // in case the remote host doesn't have it
 575          $username = get_field('user', 'username', 'id', $userid);
 576  
 577          $course = get_record('mnet_enrol_course', 'id', $courseid);
 578  
 579          // get the Service Provider info
 580          $mnet_sp = new mnet_peer();
 581          $mnet_sp->set_id($course->hostid);
 582  
 583          // set up the RPC request
 584          $mnetrequest = new mnet_xmlrpc_client();
 585          $mnetrequest->set_method('enrol/mnet/enrol.php/unenrol_user');
 586          $mnetrequest->add_param($username);
 587          $mnetrequest->add_param($course->remoteid);
 588  
 589          // TODO - prevent removal of enrolments that are not of
 590          // type mnet...
 591  
 592  
 593          // Thunderbirds are go! Do RPC call and store response
 594          if ($mnetrequest->send($mnet_sp) === true) {
 595              if ($mnetrequest->response == true) {
 596                  // remove enrolment cached in mnet_enrol_assignments
 597                  delete_records_select('mnet_enrol_assignments',
 598                                        "userid={$userid} AND courseid={$course->id}");
 599  
 600                  return true;
 601              }
 602          }
 603          return false;
 604      }
 605  
 606  } // end of class
 607  
 608  ?>


Generated: Wed Jan 14 11:33:29 2009 Cross-referenced by PHPXref 0.7