function lockdownbrowser_check_for_lock()
{
    global $CFG, $DB;
    $id = optional_param('id', 0, PARAM_INT);
    // Course Module ID
    $q = optional_param('q', 0, PARAM_INT);
    // or quiz ID
    $attempt = optional_param('attempt', 0, PARAM_INT);
    // A particular attempt ID for review
    $script = substr(strrchr($_SERVER['SCRIPT_NAME'], "/"), 1);
    if ($attempt) {
        $discriminator = $attempt;
    } else {
        if ($q) {
            $discriminator = $q;
        } else {
            if ($id) {
                $discriminator = $id;
            }
        }
    }
    if ("attempt.php" == $script && ($script . "NONE" . $discriminator == $_SESSION['LOCKDOWNBROWSER_CONTEXT'] || $script . "VALID" . $discriminator == $_SESSION['LOCKDOWNBROWSER_CONTEXT'])) {
        return 1;
    } else {
        if ("review.php" == $script && ($script . "NONE" . $discriminator == $_SESSION['LOCKDOWNBROWSER_CONTEXT'] || $script . "VALID" . $discriminator == $_SESSION['LOCKDOWNBROWSER_CONTEXT'])) {
            return 1;
        }
    }
    // debug
    //echo " DOING LDB CHECK";
    if ($id) {
        if (!($cm = get_coursemodule_from_id('quiz', $id))) {
            error("There is no coursemodule with id {$id}");
        }
        if (!($course = $DB->get_record("course", array("id" => $cm->course)))) {
            error("Course is misconfigured");
        }
        if (!($quiz = $DB->get_record("quiz", array("id" => $cm->instance)))) {
            error("The quiz with id {$cm->instance} corresponding to this coursemodule {$id} is missing");
        }
    } else {
        if ($q) {
            if (!($quiz = $DB->get_record("quiz", array("id" => $q)))) {
                error("There is no quiz with id {$q}");
            }
            if (!($course = $DB->get_record("course", array("id" => $quiz->course)))) {
                error("The course with id {$quiz->course} that the quiz with id {$q} belongs to is missing");
            }
            if (!($cm = get_coursemodule_from_instance("quiz", $quiz->id, $course->id))) {
                error("The course module for the quiz with id {$q} is missing");
            }
        } else {
            if ($attempt) {
                if (!($attempt = $DB->get_record("quiz_attempts", array("id" => $attempt)))) {
                    error("No such attempt ID exists");
                }
                if (!($quiz = $DB->get_record("quiz", array("id" => $attempt->quiz)))) {
                    error("The quiz with id {$attempt->quiz} belonging to attempt {$attempt} is missing");
                }
                if (!($course = $DB->get_record("course", array("id" => $quiz->course)))) {
                    error("The course with id {$quiz->course} that the quiz with id {$quiz->id} belongs to is missing");
                }
                if (!($cm = get_coursemodule_from_instance("quiz", $quiz->id, $course->id))) {
                    error("The course module for the quiz with id {$quiz->id} is missing");
                }
            } else {
                echo "<div style='font-size: 150%; color: red'>Cannot get quiz from: " . me() . "</div>";
                die;
            }
        }
    }
    $ldbopt = lockdownbrowser_get_quiz_options($quiz->id);
    if (!$ldbopt) {
        $_SESSION['LOCKDOWNBROWSER_CONTEXT'] = $script . "NONE" . $discriminator;
    } else {
        $context = context_module::instance($cm->id);
        if (has_capability('mod/quiz:manage', $context) && has_capability('mod/quiz:view', $context) && has_capability('mod/quiz:attempt', $context)) {
            $_SESSION['LOCKDOWNBROWSER_CONTEXT'] = $script . "NONE" . $discriminator;
        } else {
            $ok = true;
            $myerror = "Unknown";
            if (!isset($_COOKIE[$CFG->block_lockdownbrowser_LDB_SESSION_COOKIE . $CFG->sessioncookie])) {
                $myerror = "<div style='font-size: 150%; color:red; text-align: center; padding: 30px'>Session</div>";
                $ok = false;
            } else {
                $sesskey = $_COOKIE[$CFG->block_lockdownbrowser_LDB_SESSION_COOKIE . $CFG->sessioncookie];
            }
            if ($ok) {
                $ldb_detected = lockdownbrowser_browser_detected();
                if (!$ldb_detected) {
                    $myerror = "<div style='font-size: 150%; color:red; text-align: center; padding: 30px'>" . get_string('ldb_required', 'block_lockdownbrowser') . "</div>";
                    //if (strlen($CFG->block_lockdownbrowser_LDB_DOWNLOAD) > 0) {
                    //	$myerror .= "<div style='font-size: 125%; color:black; text-align: center;'>".
                    //		   get_string('click','block_lockdownbrowser')." <a href='".$CFG->block_lockdownbrowser_LDB_DOWNLOAD."' target='_blank'>".get_string('here','block_lockdownbrowser')."</a>".get_string('todownload','block_lockdownbrowser')."</div>";
                    //}
                    if (!empty($CFG->block_lockdownbrowser_LDB_DOWNLOAD)) {
                        $myerror .= "<div style='font-size: 125%; color:black; text-align: center;'>" . get_string('click', 'block_lockdownbrowser') . " <a href='" . $CFG->block_lockdownbrowser_LDB_DOWNLOAD . "' target='_blank'>" . get_string('here', 'block_lockdownbrowser') . "</a>" . get_string('todownload', 'block_lockdownbrowser') . "</div>";
                    } else {
                        $myerror .= "<div style='font-size: 125%; color:black; text-align: center;'>" . get_string('ldb_download_disabled', 'block_lockdownbrowser') . "</div>";
                    }
                    $ok = false;
                }
            }
            if ($ok) {
                $ldbs = optional_param('ldbs', 0, PARAM_TEXT);
                if (!$ldbs) {
                    $use_existing = false;
                    $existing = $DB->get_record('block_lockdownbrowser_sess', array('sesskey' => $sesskey));
                    if ($existing && strcmp($existing->sesskey, $sesskey) == 0) {
                        $existobj1 = $DB->get_record('block_lockdownbrowser_toke', array('id' => $existing->id));
                        if ($existobj1 && strcmp($existobj1->sesskey, $sesskey) == 0) {
                            $obj1 = $existobj1;
                            $use_existing = true;
                        }
                    }
                    if (!$use_existing) {
                        $errmsg = lockdownbrowser_allocate_token1($sesskey, me() . "&ldbs=" . $sesskey);
                        if (is_string($errmsg)) {
                            $myerror = "Database error: " . $errmsg;
                            $ok = false;
                        }
                    }
                } else {
                    if ($ldbs != $sesskey || !lockdownbrowser_validate_token2()) {
                        $myerror = "<div style='font-size: 150%; color:red; text-align: center; padding: 30px'>Session</div>";
                        $ok = false;
                    }
                }
            }
            if ($ok) {
                $_SESSION['LOCKDOWNBROWSER_CONTEXT'] = $script . "VALID" . $discriminator;
            } else {
                $_SESSION['LOCKDOWNBROWSER_CONTEXT'] = $script . "INVALID" . $discriminator;
                echo $myerror;
                die;
            }
        }
    }
}
function lockdownbrowser_MonitorActionExamSync($parameters)
{
    global $DB;
    if (!isloggedin()) {
        lockdownbrowser_MonitorServiceError(2004, "Must be logged in to perform the requested action");
    }
    if (!is_siteadmin()) {
        lockdownbrowser_MonitorServiceError(2024, "Must be logged in as admin to perform the requested action");
    }
    if (!isset($parameters["courseRefId"]) || strlen($parameters["courseRefId"]) == 0) {
        lockdownbrowser_MonitorServiceError(2025, "No courseRefId parameter was specified");
    }
    $course_id = intval($parameters["courseRefId"]);
    $coursemodules = get_coursemodules_in_course("quiz", $course_id);
    if ($coursemodules === FALSE) {
        $coursemodules = array();
    }
    $body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n";
    if (empty($coursemodules)) {
        $body .= "<assessmentList />\r\n";
        lockdownbrowser_MonitorServiceResponse("text/xml", $body, TRUE);
    }
    $body .= "<assessmentList>\r\n";
    foreach ($coursemodules as $cm) {
        $modrec = $DB->get_record("modules", array("id" => $cm->module));
        if ($modrec === FALSE) {
            continue;
        }
        $quiz = $DB->get_record($modrec->name, array("id" => $cm->instance));
        if ($quiz === FALSE) {
            continue;
        }
        $body .= "\t<assessment>\r\n";
        $body .= "\t\t<id>";
        $body .= utf8_encode(htmlspecialchars(trim($cm->id)));
        $body .= "</id>\r\n";
        $body .= "\t\t<title>";
        $body .= utf8_encode(htmlspecialchars(trim($cm->name)));
        $body .= "</title>\r\n";
        $settings = lockdownbrowser_get_quiz_options($cm->instance);
        if ($settings !== FALSE) {
            $body .= "\t\t<ldbEnabled>true</ldbEnabled>\r\n";
        } else {
            $body .= "\t\t<ldbEnabled>false</ldbEnabled>\r\n";
        }
        if ($settings !== FALSE && isset($settings->password) && !is_null($settings->password) && strlen($settings->password) > 0) {
            $body .= "\t\t<exitPassword>";
            $body .= utf8_encode(htmlspecialchars($settings->password));
            $body .= "</exitPassword>\r\n";
        }
        if ($settings !== FALSE && isset($settings->monitor) && !is_null($settings->monitor) && strlen($settings->monitor) > 0) {
            $body .= "\t\t<monitorEnabled>true</monitorEnabled>\r\n";
            $body .= "\t\t<extendedData>";
            $body .= utf8_encode(htmlspecialchars($settings->monitor));
            $body .= "</extendedData>\r\n";
        } else {
            $body .= "\t\t<monitorEnabled>false</monitorEnabled>\r\n";
        }
        // Moodle browser security
        //   popup (0=none, 1=full screen pop-up with some JavaScript security)
        // Moodle 2.2.0+ (quiz module 2011100600+)
        //   browsersecurity ('-', 'securewindow', 'safebrowser')
        // if this setting is not disabled, it will interfere with the LDB integration
        if (isset($quiz->browsersecurity)) {
            if ($quiz->browsersecurity != "-") {
                $launch_in_new_window = TRUE;
            } else {
                $launch_in_new_window = FALSE;
            }
        } else {
            if ($quiz->popup != 0) {
                $launch_in_new_window = TRUE;
            } else {
                $launch_in_new_window = FALSE;
            }
        }
        if ($launch_in_new_window) {
            $body .= "\t\t<launchInNewWindow>true</launchInNewWindow>\r\n";
        } else {
            $body .= "\t\t<launchInNewWindow>false</launchInNewWindow>\r\n";
        }
        if ($settings !== FALSE && $launch_in_new_window) {
            $body .= "\t\t<ok>false</ok>\r\n";
        } else {
            $body .= "\t\t<ok>true</ok>\r\n";
        }
        $body .= "\t</assessment>\r\n";
    }
    $body .= "</assessmentList>\r\n";
    lockdownbrowser_MonitorServiceResponse("text/xml", $body, TRUE);
}