示例#1
0
 public function setUp()
 {
     $this->resetAfterTest();
     // Set this user as the admin.
     $this->setAdminUser();
     $this->task = new dummy_sync_members_task();
     $generator = $this->getDataGenerator();
     $course = $generator->create_course();
     $tooldata = ['courseid' => $course->id, 'membersyncmode' => helper::MEMBER_SYNC_ENROL_AND_UNENROL, 'membersync' => 1];
     $tool = $generator->create_lti_tool((object) $tooldata);
     $this->tool = helper::get_lti_tool($tool->id);
     $dataconnector = $this->task->get_dataconnector();
     $this->consumer = new ToolConsumer('Consumer1Key', $dataconnector);
     $this->consumer->name = 'Consumer1';
     $this->consumer->secret = 'Consumer1Secret';
     $this->consumer->save();
     $toolprovider = new tool_provider($this->tool->id);
     $toolprovider->consumer = $this->consumer;
     $toolprovider->map_tool_to_consumer();
     $imageurl = $this->getExternalTestFileUrl('test.jpg');
     $count = 10;
     $this->members = [];
     for ($i = 1; $i <= $count; $i++) {
         $user = new User();
         $user->firstname = 'Firstname' . $i;
         $user->lastname = 'Lastname' . $i;
         $user->ltiUserId = 'user' . $i;
         // Set user image values for some users.
         if ($i % 3 == 0) {
             $user->image = $imageurl;
         }
         $this->members[] = $user;
     }
     $this->context = Context::fromConsumer($this->consumer, 'testlticontextid');
     $this->context->save();
     $this->resourcelink = ResourceLink::fromContext($this->context, 'testresourcelinkid');
     $this->resourcelink->save();
 }
示例#2
0
$toolid = null;
$token = null;
$filearguments = get_file_argument();
$arguments = explode('/', trim($filearguments, '/'));
if (count($arguments) >= 2) {
    // Can put cartridge.xml at the end, or anything really.
    list($toolid, $token) = $arguments;
}
$toolid = optional_param('id', $toolid, PARAM_INT);
$token = optional_param('token', $token, PARAM_ALPHANUM);
// Only show the cartridge if the token parameter is correct.
// If we do not compare with a shared secret, someone could very easily
// guess an id for the enrolment.
if (!\enrol_lti\helper::verify_tool_token($toolid, $token)) {
    throw new \moodle_exception('incorrecttoken', 'enrol_lti');
}
$tool = \enrol_lti\helper::get_lti_tool($toolid);
if (!is_enabled_auth('lti')) {
    print_error('pluginnotenabled', 'auth', '', get_string('pluginname', 'auth_lti'));
} else {
    if (!enrol_is_enabled('lti')) {
        print_error('enrolisdisabled', 'enrol_lti');
    } else {
        if ($tool->status != ENROL_INSTANCE_ENABLED) {
            print_error('enrolisdisabled', 'enrol_lti');
        } else {
            header('Content-Type: text/xml; charset=utf-8');
            echo \enrol_lti\helper::create_cartridge($toolid);
        }
    }
}
示例#3
0
                    $ltiplugin->update_status($instance, ENROL_INSTANCE_DISABLED);
                    redirect($PAGE->url);
                }
            }
        } else {
            if ($action === 'enable') {
                if ($ltiplugin->can_hide_show_instance($instance)) {
                    if ($instance->status != ENROL_INSTANCE_ENABLED) {
                        $ltiplugin->update_status($instance, ENROL_INSTANCE_ENABLED);
                        redirect($PAGE->url);
                    }
                }
            }
        }
    }
}
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('toolsprovided', 'enrol_lti'));
echo "<p>" . get_string('toolsprovided_help', 'enrol_lti') . "</p>";
if (\enrol_lti\helper::count_lti_tools(array('courseid' => $courseid)) > 0) {
    $table = new \enrol_lti\manage_table($courseid);
    $table->define_baseurl($pageurl);
    $table->out(50, false);
} else {
    $notify = new \core\output\notification(get_string('notoolsprovided', 'enrol_lti'), \core\output\notification::NOTIFY_WARNING);
    echo $OUTPUT->render($notify);
}
if ($ltiplugin->can_add_instance($course->id)) {
    echo $OUTPUT->single_button(new moodle_url('/enrol/editinstance.php', array('type' => 'lti', 'courseid' => $course->id, 'returnurl' => new moodle_url('/enrol/lti/index.php', array('courseid' => $course->id)))), get_string('add'));
}
echo $OUTPUT->footer();
示例#4
0
 /**
  * Performs the synchronisation of members.
  *
  * @return bool|void
  */
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuth.php';
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuthBody.php';
     // Check if the authentication plugin is disabled.
     if (!is_enabled_auth('lti')) {
         mtrace('Skipping task - ' . get_string('pluginnotenabled', 'auth', get_string('pluginname', 'auth_lti')));
         return true;
     }
     // Check if the enrolment plugin is disabled - isn't really necessary as the task should not run if
     // the plugin is disabled, but there is no harm in making sure core hasn't done something wrong.
     if (!enrol_is_enabled('lti')) {
         mtrace('Skipping task - ' . get_string('enrolisdisabled', 'enrol_lti'));
         return true;
     }
     // Get all the enabled tools.
     if ($tools = \enrol_lti\helper::get_lti_tools(array('status' => ENROL_INSTANCE_ENABLED, 'membersync' => 1))) {
         $ltiplugin = enrol_get_plugin('lti');
         $consumers = array();
         $currentusers = array();
         $userphotos = array();
         foreach ($tools as $tool) {
             mtrace("Starting - Member sync for shared tool '{$tool->id}' for the course '{$tool->courseid}'.");
             // Variables to keep track of information to display later.
             $usercount = 0;
             $enrolcount = 0;
             $unenrolcount = 0;
             // We check for all the users - users can access the same tool from different consumers.
             if ($ltiusers = $DB->get_records('enrol_lti_users', array('toolid' => $tool->id), 'lastaccess DESC')) {
                 foreach ($ltiusers as $ltiuser) {
                     $mtracecontent = "for the user '{$ltiuser->userid}' in the tool '{$tool->id}' for the course " . "'{$tool->courseid}'";
                     $usercount++;
                     // Check if we do not have a membershipsurl - this can happen if the sync process has an unexpected error.
                     if (!$ltiuser->membershipsurl) {
                         mtrace("Skipping - Empty membershipsurl {$mtracecontent}.");
                         continue;
                     }
                     // Check if we do not have a membershipsid - this can happen if the sync process has an unexpected error.
                     if (!$ltiuser->membershipsid) {
                         mtrace("Skipping - Empty membershipsid {$mtracecontent}.");
                         continue;
                     }
                     $consumer = sha1($ltiuser->membershipsurl . ':' . $ltiuser->membershipsid . ':' . $ltiuser->consumerkey . ':' . $ltiuser->consumersecret);
                     if (in_array($consumer, $consumers)) {
                         // We have already synchronised with this consumer.
                         continue;
                     }
                     $consumers[] = $consumer;
                     $params = array('lti_message_type' => self::LTI_MESSAGE_TYPE, 'id' => $ltiuser->membershipsid, 'lti_version' => self::LTI_VERSION);
                     mtrace("Calling memberships url '{$ltiuser->membershipsurl}' with body '" . json_encode($params) . "'");
                     try {
                         $response = sendOAuthParamsPOST('POST', $ltiuser->membershipsurl, $ltiuser->consumerkey, $ltiuser->consumersecret, 'application/x-www-form-urlencoded', $params);
                     } catch (\Exception $e) {
                         mtrace("Skipping - No response received {$mtracecontent} from '{$ltiuser->membershipsurl}'");
                         mtrace($e->getMessage());
                         continue;
                     }
                     // Check the response from the consumer.
                     $data = new \SimpleXMLElement($response);
                     // Check if we did not receive a valid response.
                     if (empty($data->statusinfo)) {
                         mtrace("Skipping - Bad response received {$mtracecontent} from '{$ltiuser->membershipsurl}'");
                         mtrace('Skipping - Error parsing the XML received \'' . substr($response, 0, 125) . '\' ... (Displaying only 125 chars)');
                         continue;
                     }
                     // Check if we did not receive a valid response.
                     if (strpos(strtolower($data->statusinfo->codemajor), 'success') === false) {
                         mtrace('Skipping - Error received from the remote system: ' . $data->statusinfo->codemajor . ' ' . $data->statusinfo->severity . ' ' . $data->statusinfo->codeminor);
                         continue;
                     }
                     $members = $data->memberships->member;
                     mtrace(count($members) . ' members received.');
                     foreach ($members as $member) {
                         // Set the user data.
                         $user = new \stdClass();
                         $user->username = \enrol_lti\helper::create_username($ltiuser->consumerkey, $member->user_id);
                         $user->firstname = \core_user::clean_field($member->person_name_given, 'firstname');
                         $user->lastname = \core_user::clean_field($member->person_name_family, 'lastname');
                         $user->email = \core_user::clean_field($member->person_contact_email_primary, 'email');
                         // Get the user data from the LTI consumer.
                         $user = \enrol_lti\helper::assign_user_tool_data($tool, $user);
                         if (!($dbuser = $DB->get_record('user', array('username' => $user->username, 'deleted' => 0)))) {
                             if ($tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_AND_UNENROL || $tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_NEW) {
                                 // If the email was stripped/not set then fill it with a default one. This
                                 // stops the user from being redirected to edit their profile page.
                                 if (empty($user->email)) {
                                     $user->email = $user->username . "@example.com";
                                 }
                                 $user->auth = 'lti';
                                 $user->id = user_create_user($user);
                                 // Add the information to the necessary arrays.
                                 $currentusers[] = $user->id;
                                 $userphotos[$user->id] = $member->user_image;
                             }
                         } else {
                             // If email is empty remove it, so we don't update the user with an empty email.
                             if (empty($user->email)) {
                                 unset($user->email);
                             }
                             $user->id = $dbuser->id;
                             user_update_user($user);
                             // Add the information to the necessary arrays.
                             $currentusers[] = $user->id;
                             $userphotos[$user->id] = $member->user_image;
                         }
                         if ($tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_AND_UNENROL || $tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_NEW) {
                             // Enrol the user in the course.
                             \enrol_lti\helper::enrol_user($tool, $user->id);
                         }
                     }
                 }
                 // Now we check if we have to unenrol users who were not listed.
                 if ($tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_ENROL_AND_UNENROL || $tool->membersyncmode == \enrol_lti\helper::MEMBER_SYNC_UNENROL_MISSING) {
                     // Go through the users and check if any were never listed, if so, remove them.
                     foreach ($ltiusers as $ltiuser) {
                         if (!in_array($ltiuser->userid, $currentusers)) {
                             $instance = new \stdClass();
                             $instance->id = $tool->enrolid;
                             $instance->courseid = $tool->courseid;
                             $instance->enrol = 'lti';
                             $ltiplugin->unenrol_user($instance, $ltiuser->id);
                         }
                     }
                 }
             }
             mtrace("Completed - Synced members for tool '{$tool->id}' in the course '{$tool->courseid}'. " . "Processed {$usercount} users; enrolled {$enrolcount} members; unenrolled {$unenrolcount} members.");
             mtrace("");
         }
         // Sync the user profile photos.
         mtrace("Started - Syncing user profile images.");
         $counter = 0;
         if (!empty($userphotos)) {
             foreach ($userphotos as $userid => $url) {
                 if ($url) {
                     $result = \enrol_lti\helper::update_user_profile_image($userid, $url);
                     if ($result === \enrol_lti\helper::PROFILE_IMAGE_UPDATE_SUCCESSFUL) {
                         $counter++;
                         mtrace("Profile image succesfully downloaded and created for user '{$userid}' from {$url}.");
                     } else {
                         mtrace($result);
                     }
                 }
             }
         }
         mtrace("Completed - Synced {$counter} profile images.");
     }
 }
示例#5
0
 /**
  * Performs the synchronisation of grades.
  *
  * @return bool|void
  */
 public function execute()
 {
     global $DB, $CFG;
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuth.php';
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuthBody.php';
     require_once $CFG->dirroot . '/lib/completionlib.php';
     require_once $CFG->libdir . '/gradelib.php';
     require_once $CFG->dirroot . '/grade/querylib.php';
     // Check if the authentication plugin is disabled.
     if (!is_enabled_auth('lti')) {
         mtrace('Skipping task - ' . get_string('pluginnotenabled', 'auth', get_string('pluginname', 'auth_lti')));
         return true;
     }
     // Check if the enrolment plugin is disabled - isn't really necessary as the task should not run if
     // the plugin is disabled, but there is no harm in making sure core hasn't done something wrong.
     if (!enrol_is_enabled('lti')) {
         mtrace('Skipping task - ' . get_string('enrolisdisabled', 'enrol_lti'));
         return true;
     }
     // Get all the enabled tools.
     if ($tools = \enrol_lti\helper::get_lti_tools(array('status' => ENROL_INSTANCE_ENABLED, 'gradesync' => 1))) {
         foreach ($tools as $tool) {
             mtrace("Starting - Grade sync for shared tool '{$tool->id}' for the course '{$tool->courseid}'.");
             // Variables to keep track of information to display later.
             $usercount = 0;
             $sendcount = 0;
             // We check for all the users - users can access the same tool from different consumers.
             if ($ltiusers = $DB->get_records('enrol_lti_users', array('toolid' => $tool->id), 'lastaccess DESC')) {
                 $completion = new \completion_info(get_course($tool->courseid));
                 foreach ($ltiusers as $ltiuser) {
                     $mtracecontent = "for the user '{$ltiuser->userid}' in the tool '{$tool->id}' for the course " . "'{$tool->courseid}'";
                     $usercount = $usercount + 1;
                     // Check if we do not have a serviceurl - this can happen if the sync process has an unexpected error.
                     if (empty($ltiuser->serviceurl)) {
                         mtrace("Skipping - Empty serviceurl {$mtracecontent}.");
                         continue;
                     }
                     // Check if we do not have a sourceid - this can happen if the sync process has an unexpected error.
                     if (empty($ltiuser->sourceid)) {
                         mtrace("Skipping - Empty sourceid {$mtracecontent}.");
                         continue;
                     }
                     // Need a valid context to continue.
                     if (!($context = \context::instance_by_id($tool->contextid))) {
                         mtrace("Failed - Invalid contextid '{$tool->contextid}' for the tool '{$tool->id}'.");
                         continue;
                     }
                     // Ok, let's get the grade.
                     $grade = false;
                     if ($context->contextlevel == CONTEXT_COURSE) {
                         // Check if the user did not completed the course when it was required.
                         if ($tool->gradesynccompletion && !$completion->is_course_complete($ltiuser->userid)) {
                             mtrace("Skipping - Course not completed {$mtracecontent}.");
                             continue;
                         }
                         // Get the grade.
                         if ($grade = grade_get_course_grade($ltiuser->userid, $tool->courseid)) {
                             $grademax = floatval($grade->item->grademax);
                             $grade = $grade->grade;
                         }
                     } else {
                         if ($context->contextlevel == CONTEXT_MODULE) {
                             $cm = get_coursemodule_from_id(false, $context->instanceid, 0, false, MUST_EXIST);
                             if ($tool->gradesynccompletion) {
                                 $data = $completion->get_data($cm, false, $ltiuser->userid);
                                 if ($data->completionstate != COMPLETION_COMPLETE_PASS && $data->completionstate != COMPLETION_COMPLETE) {
                                     mtrace("Skipping - Activity not completed {$mtracecontent}.");
                                     continue;
                                 }
                             }
                             $grades = grade_get_grades($cm->course, 'mod', $cm->modname, $cm->instance, $ltiuser->userid);
                             if (!empty($grades->items[0]->grades)) {
                                 $grade = reset($grades->items[0]->grades);
                                 if (!empty($grade->item)) {
                                     $grademax = floatval($grade->item->grademax);
                                 } else {
                                     $grademax = floatval($grades->items[0]->grademax);
                                 }
                                 $grade = $grade->grade;
                             }
                         }
                     }
                     if ($grade === false || $grade === null || strlen($grade) < 1) {
                         mtrace("Skipping - Invalid grade {$mtracecontent}.");
                         continue;
                     }
                     // No need to be dividing by zero.
                     if (empty($grademax)) {
                         mtrace("Skipping - Invalid grade {$mtracecontent}.");
                         continue;
                     }
                     // This can happen if the sync process has an unexpected error.
                     if ($grade == $ltiuser->lastgrade) {
                         mtrace("Not sent - The grade {$mtracecontent} was not sent as the grades are the same.");
                         continue;
                     }
                     // Sync with the external system.
                     $floatgrade = $grade / $grademax;
                     $body = \enrol_lti\helper::create_service_body($ltiuser->sourceid, $floatgrade);
                     try {
                         $response = sendOAuthBodyPOST('POST', $ltiuser->serviceurl, $ltiuser->consumerkey, $ltiuser->consumersecret, 'application/xml', $body);
                     } catch (\Exception $e) {
                         mtrace("Failed - The grade '{$floatgrade}' {$mtracecontent} failed to send.");
                         mtrace($e->getMessage());
                         continue;
                     }
                     if (strpos(strtolower($response), 'success') !== false) {
                         $DB->set_field('enrol_lti_users', 'lastgrade', intval($grade), array('id' => $ltiuser->id));
                         mtrace("Success - The grade '{$floatgrade}' {$mtracecontent} was sent.");
                         $sendcount = $sendcount + 1;
                     } else {
                         mtrace("Failed - The grade '{$floatgrade}' {$mtracecontent} failed to send.");
                     }
                 }
             }
             mtrace("Completed - Synced grades for tool '{$tool->id}' in the course '{$tool->courseid}'. " . "Processed {$usercount} users; sent {$sendcount} grades.");
             mtrace("");
         }
     }
 }
示例#6
0
文件: tool.php 项目: sirromas/lms
         $urltogo = new moodle_url('/mod/' . $cm->modname . '/view.php', array('id' => $cm->id));
         // If we are a student in the course module context we do not want to display blocks.
         if (!$isinstructor) {
             // Force the page layout.
             $SESSION->forcepagelayout = 'embedded';
         } else {
             // May still be set from previous session, so unset it.
             unset($SESSION->forcepagelayout);
         }
     } else {
         print_error('invalidcontext');
         exit;
     }
 }
 // Enrol the user in the course with no role.
 $result = \enrol_lti\helper::enrol_user($tool, $user->id);
 // Display an error, if there is one.
 if ($result !== \enrol_lti\helper::ENROLMENT_SUCCESSFUL) {
     print_error($result, 'enrol_lti');
     exit;
 }
 // Give the user the role in the given context.
 $roleid = $isinstructor ? $tool->roleinstructor : $tool->rolelearner;
 role_assign($roleid, $user->id, $tool->contextid);
 // Login user.
 $sourceid = !empty($ltirequest->info['lis_result_sourcedid']) ? $ltirequest->info['lis_result_sourcedid'] : '';
 $serviceurl = !empty($ltirequest->info['lis_outcome_service_url']) ? $ltirequest->info['lis_outcome_service_url'] : '';
 // Check if we have recorded this user before.
 if ($userlog = $DB->get_record('enrol_lti_users', array('toolid' => $tool->id, 'userid' => $user->id))) {
     if ($userlog->sourceid != $sourceid) {
         $userlog->sourceid = $sourceid;
示例#7
0
 /**
  * Query the reader. Store results in the object for use by build_table.
  *
  * @param int $pagesize size of page for paginated displayed table.
  * @param bool $useinitialsbar do you want to use the initials bar.
  */
 public function query_db($pagesize, $useinitialsbar = true)
 {
     $total = \enrol_lti\helper::count_lti_tools(array('courseid' => $this->courseid));
     $this->pagesize($pagesize, $total);
     $tools = \enrol_lti\helper::get_lti_tools(array('courseid' => $this->courseid), $this->get_page_start(), $this->get_page_size());
     $this->rawdata = $tools;
     // Set initial bars.
     if ($useinitialsbar) {
         $this->initialbars($total > $pagesize);
     }
 }
示例#8
0
 /**
  * Performs synchronisation of user profile images.
  */
 protected function sync_profile_images()
 {
     $counter = 0;
     foreach ($this->userphotos as $userid => $url) {
         if ($url) {
             $result = helper::update_user_profile_image($userid, $url);
             if ($result === helper::PROFILE_IMAGE_UPDATE_SUCCESSFUL) {
                 $counter++;
                 mtrace("Profile image succesfully downloaded and created for user '{$userid}' from {$url}.");
             } else {
                 mtrace($result);
             }
         }
     }
     return $counter;
 }
示例#9
0
文件: tool.php 项目: dg711/moodle
/**
 * The main entry point for the external system.
 *
 * @package    enrol_lti
 * @copyright  2016 Mark Nelson <*****@*****.**>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require_once __DIR__ . '/../../config.php';
$toolid = required_param('id', PARAM_INT);
$PAGE->set_context(context_system::instance());
$url = new moodle_url('/enrol/lti/tool.php');
$PAGE->set_url($url);
$PAGE->set_pagelayout('popup');
$PAGE->set_title(get_string('opentool', 'enrol_lti'));
// Get the tool.
$tool = \enrol_lti\helper::get_lti_tool($toolid);
// Check if the authentication plugin is disabled.
if (!is_enabled_auth('lti')) {
    print_error('pluginnotenabled', 'auth', '', get_string('pluginname', 'auth_lti'));
    exit;
}
// Check if the enrolment plugin is disabled.
if (!enrol_is_enabled('lti')) {
    print_error('enrolisdisabled', 'enrol_lti');
    exit;
}
// Check if the enrolment instance is disabled.
if ($tool->status != ENROL_INSTANCE_ENABLED) {
    print_error('enrolisdisabled', 'enrol_lti');
    exit;
}
示例#10
0
 /**
  * Test create cartridge.
  */
 public function test_create_cartridge()
 {
     global $CFG;
     $course1 = $this->getDataGenerator()->create_course();
     $data = new stdClass();
     $data->courseid = $course1->id;
     $tool1 = $this->create_tool($data);
     $cartridge = \enrol_lti\helper::create_cartridge($tool1->id);
     $this->assertContains('<blti:title>Test LTI</blti:title>', $cartridge);
     $this->assertContains("<blti:icon>{$CFG->wwwroot}/theme/image.php/_s/clean/theme/1/favicon</blti:icon>", $cartridge);
     $this->assertContains("<blti:launch_url>{$CFG->wwwroot}/enrol/lti/tool.php?id={$tool1->id}</blti:launch_url>", $cartridge);
 }
示例#11
0
 /**
  * Override onLaunch with tool logic.
  * @return void
  */
 protected function onLaunch()
 {
     global $DB, $SESSION, $CFG;
     // Check for valid consumer.
     if (empty($this->consumer) || $this->dataConnector->loadToolConsumer($this->consumer) === false) {
         $this->ok = false;
         $this->message = get_string('invalidtoolconsumer', 'enrol_lti');
         return;
     }
     $url = helper::get_launch_url($this->tool->id);
     // If a tool proxy has been stored for the current consumer trying to access a tool,
     // check that the tool is being launched from the correct url.
     $correctlaunchurl = false;
     if (!empty($this->consumer->toolProxy)) {
         $proxy = json_decode($this->consumer->toolProxy);
         $handlers = $proxy->tool_profile->resource_handler;
         foreach ($handlers as $handler) {
             foreach ($handler->message as $message) {
                 $handlerurl = new moodle_url($message->path);
                 $fullpath = $handlerurl->out(false);
                 if ($message->message_type == "basic-lti-launch-request" && $fullpath == $url) {
                     $correctlaunchurl = true;
                     break 2;
                 }
             }
         }
     } else {
         if ($this->tool->secret == $this->consumer->secret) {
             // Test if the LTI1 secret for this tool is being used. Then we know the correct tool is being launched.
             $correctlaunchurl = true;
         }
     }
     if (!$correctlaunchurl) {
         $this->ok = false;
         $this->message = get_string('invalidrequest', 'enrol_lti');
         return;
     }
     // Before we do anything check that the context is valid.
     $tool = $this->tool;
     $context = context::instance_by_id($tool->contextid);
     // Set the user data.
     $user = new stdClass();
     $user->username = helper::create_username($this->consumer->getKey(), $this->user->ltiUserId);
     if (!empty($this->user->firstname)) {
         $user->firstname = $this->user->firstname;
     } else {
         $user->firstname = $this->user->getRecordId();
     }
     if (!empty($this->user->lastname)) {
         $user->lastname = $this->user->lastname;
     } else {
         $user->lastname = $this->tool->contextid;
     }
     $user->email = core_user::clean_field($this->user->email, 'email');
     // Get the user data from the LTI consumer.
     $user = helper::assign_user_tool_data($tool, $user);
     // Check if the user exists.
     if (!($dbuser = $DB->get_record('user', ['username' => $user->username, 'deleted' => 0]))) {
         // If the email was stripped/not set then fill it with a default one. This
         // stops the user from being redirected to edit their profile page.
         if (empty($user->email)) {
             $user->email = $user->username . "@example.com";
         }
         $user->auth = 'lti';
         $user->id = \user_create_user($user);
         // Get the updated user record.
         $user = $DB->get_record('user', ['id' => $user->id]);
     } else {
         if (helper::user_match($user, $dbuser)) {
             $user = $dbuser;
         } else {
             // If email is empty remove it, so we don't update the user with an empty email.
             if (empty($user->email)) {
                 unset($user->email);
             }
             $user->id = $dbuser->id;
             \user_update_user($user);
             // Get the updated user record.
             $user = $DB->get_record('user', ['id' => $user->id]);
         }
     }
     // Update user image.
     if (isset($this->user) && isset($this->user->image) && !empty($this->user->image)) {
         $image = $this->user->image;
     } else {
         // Use custom_user_image parameter as a fallback.
         $image = $this->resourceLink->getSetting('custom_user_image');
     }
     // Check if there is an image to process.
     if ($image) {
         helper::update_user_profile_image($user->id, $image);
     }
     // Check if we need to force the page layout to embedded.
     $isforceembed = $this->resourceLink->getSetting('custom_force_embed') == 1;
     // Check if we are an instructor.
     $isinstructor = $this->user->isStaff() || $this->user->isAdmin();
     if ($context->contextlevel == CONTEXT_COURSE) {
         $courseid = $context->instanceid;
         $urltogo = new moodle_url('/course/view.php', ['id' => $courseid]);
     } else {
         if ($context->contextlevel == CONTEXT_MODULE) {
             $cm = get_coursemodule_from_id(false, $context->instanceid, 0, false, MUST_EXIST);
             $urltogo = new moodle_url('/mod/' . $cm->modname . '/view.php', ['id' => $cm->id]);
             // If we are a student in the course module context we do not want to display blocks.
             if (!$isforceembed && !$isinstructor) {
                 $isforceembed = true;
             }
         } else {
             print_error('invalidcontext');
             exit;
         }
     }
     // Force page layout to embedded if necessary.
     if ($isforceembed) {
         $SESSION->forcepagelayout = 'embedded';
     } else {
         // May still be set from previous session, so unset it.
         unset($SESSION->forcepagelayout);
     }
     // Enrol the user in the course with no role.
     $result = helper::enrol_user($tool, $user->id);
     // Display an error, if there is one.
     if ($result !== helper::ENROLMENT_SUCCESSFUL) {
         print_error($result, 'enrol_lti');
         exit;
     }
     // Give the user the role in the given context.
     $roleid = $isinstructor ? $tool->roleinstructor : $tool->rolelearner;
     role_assign($roleid, $user->id, $tool->contextid);
     // Login user.
     $sourceid = $this->user->ltiResultSourcedId;
     $serviceurl = $this->resourceLink->getSetting('lis_outcome_service_url');
     // Check if we have recorded this user before.
     if ($userlog = $DB->get_record('enrol_lti_users', ['toolid' => $tool->id, 'userid' => $user->id])) {
         if ($userlog->sourceid != $sourceid) {
             $userlog->sourceid = $sourceid;
         }
         if ($userlog->serviceurl != $serviceurl) {
             $userlog->serviceurl = $serviceurl;
         }
         $userlog->lastaccess = time();
         $DB->update_record('enrol_lti_users', $userlog);
     } else {
         // Add the user details so we can use it later when syncing grades and members.
         $userlog = new stdClass();
         $userlog->userid = $user->id;
         $userlog->toolid = $tool->id;
         $userlog->serviceurl = $serviceurl;
         $userlog->sourceid = $sourceid;
         $userlog->consumerkey = $this->consumer->getKey();
         $userlog->consumersecret = $tool->secret;
         $userlog->lastgrade = 0;
         $userlog->lastaccess = time();
         $userlog->timecreated = time();
         $userlog->membershipsurl = $this->resourceLink->getSetting('ext_ims_lis_memberships_url');
         $userlog->membershipsid = $this->resourceLink->getSetting('ext_ims_lis_memberships_id');
         $DB->insert_record('enrol_lti_users', $userlog);
     }
     // Finalise the user log in.
     complete_user_login($user);
     // Everything's good. Set appropriate OK flag and message values.
     $this->ok = true;
     $this->message = get_string('success');
     if (empty($CFG->allowframembedding)) {
         // Provide an alternative link.
         $stropentool = get_string('opentool', 'enrol_lti');
         echo html_writer::tag('p', get_string('frameembeddingnotenabled', 'enrol_lti'));
         echo html_writer::link($urltogo, $stropentool, ['target' => '_blank']);
     } else {
         // All done, redirect the user to where they want to go.
         redirect($urltogo);
     }
 }
示例#12
0
 /**
  * Test for tool_provider::onLaunch() to verify that a LTI user has been enrolled.
  */
 public function test_on_launch_user_enrolment()
 {
     global $DB;
     $tp = $this->build_dummy_tp($this->tool->secret);
     // Suppress output and session header errors.
     ob_start();
     @$tp->onLaunch();
     ob_end_clean();
     $username = helper::create_username($tp->consumer->getKey(), $tp->user->ltiUserId);
     $user = $DB->get_record('user', ['username' => $username]);
     // User was found.
     $this->assertNotFalse($user);
     // User picture was not set.
     $this->assertEmpty($user->picture);
     // Check user enrolment.
     $enrolled = $DB->record_exists('user_enrolments', ['enrolid' => $this->tool->enrolid, 'userid' => $user->id]);
     $this->assertTrue($enrolled);
 }
示例#13
0
 /**
  * Test returning the list of available tools.
  */
 public function test_get_lti_tools()
 {
     // Create two tools belonging to the same course.
     $course1 = $this->getDataGenerator()->create_course();
     $data = new stdClass();
     $data->courseid = $course1->id;
     $tool1 = $this->create_tool($data);
     $tool2 = $this->create_tool($data);
     // Create two more tools in a separate course.
     $course2 = $this->getDataGenerator()->create_course();
     $data = new stdClass();
     $data->courseid = $course2->id;
     $tool3 = $this->create_tool($data);
     // Set the next tool to disabled.
     $data->status = ENROL_INSTANCE_DISABLED;
     $tool4 = $this->create_tool($data);
     // Get all the tools.
     $tools = \enrol_lti\helper::get_lti_tools();
     // Check that we got all the tools.
     $this->assertEquals(4, count($tools));
     // Get all the tools in course 1.
     $tools = \enrol_lti\helper::get_lti_tools(array('courseid' => $course1->id));
     // Check that we got all the tools in course 1.
     $this->assertEquals(2, count($tools));
     $this->assertTrue(isset($tools[$tool1->id]));
     $this->assertTrue(isset($tools[$tool2->id]));
     // Get all the tools in course 2 that are disabled.
     $tools = \enrol_lti\helper::get_lti_tools(array('courseid' => $course2->id, 'status' => ENROL_INSTANCE_DISABLED));
     // Check that we got all the tools in course 2 that are disabled.
     $this->assertEquals(1, count($tools));
     $this->assertTrue(isset($tools[$tool4->id]));
     // Get all the tools that are enabled.
     $tools = \enrol_lti\helper::get_lti_tools(array('status' => ENROL_INSTANCE_ENABLED));
     // Check that we got all the tools that are enabled.
     $this->assertEquals(3, count($tools));
     $this->assertTrue(isset($tools[$tool1->id]));
     $this->assertTrue(isset($tools[$tool2->id]));
     $this->assertTrue(isset($tools[$tool3->id]));
 }