public function get_content() { global $CFG, $USER, $OUTPUT; if (has_capability('block/papercut:view', $this->context)) { $this->content = new stdClass(); $this->content->footer = ''; $this->content->items = array(); $this->content->icons = array(); $serverip = explode('.', $_SERVER['SERVER_ADDR']); $internal = address_in_subnet(getremoteaddr(), $serverip[0] . '.' . $serverip[1]); $strnobalance = get_string('nobalance', 'block_papercut'); $image = $OUTPUT->pix_icon('balance_not_available', $strnobalance, 'block_papercut'); $http = $CFG->block_papercut_https ? 'https://' : 'http://'; $serverurl = $http . $CFG->block_papercut_server_url . ':' . $CFG->block_papercut_server_port; $scriptattrs = array('type' => 'text/javascript'); $wisgetsattrs = $scriptattrs; $widgetsattrs['src'] = $serverurl . '/content/widgets/widgets.js'; $script1 = "var pcUsername = '******';" . "var pcServerURL = '{$serverurl}'; pcGetUserDetails();"; $script2 = "pcInitUserEnvironmentalImpactWidget('widgetEnvironment');" . "pcInitUserBalanceWidget('widgetBalance');"; if ($internal) { $this->content->text .= html_writer::tag('script', '', $widgetsattrs); } $this->content->text .= html_writer::tag('script', $script1, $scriptattrs); $this->content->text .= html_writer::tag('div', $image, array('id' => 'widgetBalance')); $this->content->text .= html_writer::tag('div', '', array('id' => 'widgetEnvironment')); if ($internal) { $this->content->text .= html_writer::tag('script', $script2, $scriptattrs); } return $this->content; } }
public function test_ipaddress_access_rule() { $quiz = new stdClass(); $attempt = new stdClass(); $cm = new stdClass(); $cm->id = 0; // Test the allowed case by getting the user's IP address. However, this // does not always work, for example using the mac install package on my laptop. $quiz->subnet = getremoteaddr(null); if (!empty($quiz->subnet)) { $quiz->questions = ''; $quizobj = new quiz($quiz, $cm, null); $rule = new quizaccess_ipaddress($quizobj, 0); $this->assertFalse($rule->prevent_access()); $this->assertFalse($rule->description()); $this->assertFalse($rule->prevent_new_attempt(0, $attempt)); $this->assertFalse($rule->is_finished(0, $attempt)); $this->assertFalse($rule->end_time($attempt)); $this->assertFalse($rule->time_left_display($attempt, 0)); } $quiz->subnet = '0.0.0.0'; $quiz->questions = ''; $quizobj = new quiz($quiz, $cm, null); $rule = new quizaccess_ipaddress($quizobj, 0); $this->assertNotEmpty($rule->prevent_access()); $this->assertEmpty($rule->description()); $this->assertFalse($rule->prevent_new_attempt(0, $attempt)); $this->assertFalse($rule->is_finished(0, $attempt)); $this->assertFalse($rule->end_time($attempt)); $this->assertFalse($rule->time_left_display($attempt, 0)); }
public function prevent_access() { if (address_in_subnet(getremoteaddr(), $this->quiz->subnet)) { return false; } else { return get_string('subnetwrong', 'quizaccess_ipaddress'); } }
function definition() { global $COURSE, $USER, $CFG, $DB; $mform =& $this->_form; if (isset($this->_customdata)) { $features = $this->_customdata; } else { $features = array(); } // course id needs to be passed for auth purposes $mform->addElement('hidden', 'id', optional_param('id', 0, PARAM_INT)); $mform->setType('id', PARAM_INT); $mform->addElement('header', 'general', get_string('importfile', 'grades')); $mform->addElement('advcheckbox', 'feedback', get_string('importfeedback', 'grades')); $mform->setDefault('feedback', 0); // Restrict the possible upload file types. if (!empty($features['acceptedtypes'])) { $acceptedtypes = $features['acceptedtypes']; } else { $acceptedtypes = '*'; } // File upload. $mform->addElement('filepicker', 'userfile', get_string('file'), null, array('accepted_types' => $acceptedtypes)); $mform->disabledIf('userfile', 'url', 'noteq', ''); $mform->addElement('text', 'url', get_string('fileurl', 'gradeimport_xml'), 'size="80"'); $mform->setType('url', PARAM_URL); $mform->disabledIf('url', 'userfile', 'noteq', ''); $mform->addHelpButton('url', 'fileurl', 'gradeimport_xml'); if (!empty($CFG->gradepublishing)) { $mform->addElement('header', 'publishing', get_string('publishing', 'grades')); $options = array(get_string('nopublish', 'grades'), get_string('createnewkey', 'userkey')); $keys = $DB->get_records_select('user_private_key', "script='grade/import' AND instance=? AND userid=?", array($COURSE->id, $USER->id)); if ($keys) { foreach ($keys as $key) { $options[$key->value] = $key->value; // TODO: add more details - ip restriction, valid until ?? } } $mform->addElement('select', 'key', get_string('userkey', 'userkey'), $options); $mform->addHelpButton('key', 'userkey', 'userkey'); $mform->addElement('static', 'keymanagerlink', get_string('keymanager', 'userkey'), '<a href="' . $CFG->wwwroot . '/grade/import/keymanager.php?id=' . $COURSE->id . '">' . get_string('keymanager', 'userkey') . '</a>'); $mform->addElement('text', 'iprestriction', get_string('keyiprestriction', 'userkey'), array('size' => 80)); $mform->addHelpButton('iprestriction', 'keyiprestriction', 'userkey'); $mform->setDefault('iprestriction', getremoteaddr()); // own IP - just in case somebody does not know what user key is $mform->addElement('date_time_selector', 'validuntil', get_string('keyvaliduntil', 'userkey'), array('optional' => true)); $mform->addHelpButton('validuntil', 'keyvaliduntil', 'userkey'); $mform->setDefault('validuntil', time() + 3600 * 24 * 7); // only 1 week default duration - just in case somebody does not know what user key is $mform->disabledIf('iprestriction', 'key', 'noteq', 1); $mform->disabledIf('validuntil', 'key', 'noteq', 1); $mform->disabledIf('iprestriction', 'url', 'eq', ''); $mform->disabledIf('validuntil', 'url', 'eq', ''); $mform->disabledIf('key', 'url', 'eq', ''); } $this->add_action_buttons(false, get_string('uploadgrades', 'grades')); }
function plaintext_is_ok() { global $CFG; $trusted_hosts = explode(',', get_config('mnet', 'mnet_trusted_hosts')); foreach ($trusted_hosts as $host) { if (address_in_subnet(getremoteaddr(), $host)) { return true; } } return false; }
function sso_user_login($username, $password) { global $CFG, $SESSION; include $CFG->libdir . '/snoopy/Snoopy.class.inc'; if (empty($CFG->hivehost)) { return false; // Hive config variables not configured yet } /// Set up Snoopy $snoopy = new Snoopy(); $submit_url = $CFG->hiveprotocol . '://' . $CFG->hivehost . ':' . $CFG->hiveport . '' . $CFG->hivepath; $submit_vars['HIVE_UNAME'] = $username; $submit_vars['HIVE_UPASS'] = $password; $submit_vars['HIVE_ENDUSER'] = $username; $submit_vars['HIVE_REQ'] = '2112'; $submit_vars['HIVE_REF'] = 'hin:hive@API Login 3'; $submit_vars['HIVE_RET'] = 'ORG'; $submit_vars['HIVE_REM'] = ''; $submit_vars['HIVE_PROD'] = '0'; $submit_vars['HIVE_USERIP'] = getremoteaddr(); /// We use POST to call Hive with a bit more security $snoopy->submit($submit_url, $submit_vars); /// Extract HIVE_SESSION from headers foreach ($snoopy->headers as $header) { if (strpos($header, 'HIVE_SESSION=') !== false) { $header = explode('HIVE_SESSION=', $header); if (count($header) > 1) { $cookie = explode(';', $header[1]); $cookie = $cookie[0]; $SESSION->HIVE_SESSION = $cookie; return true; } } } /// Try again with the guest username and password $submit_vars['HIVE_UNAME'] = $CFG->hiveusername; $submit_vars['HIVE_UPASS'] = $CFG->hivepassword; $submit_vars['HIVE_ENDUSER'] = $CFG->hiveusername; $snoopy->submit($submit_url, $submit_vars); foreach ($snoopy->headers as $header) { if (strpos($header, 'HIVE_SESSION=') !== false) { $header = explode('HIVE_SESSION=', $header); if (count($header) > 1) { $cookie = explode(';', $header[1]); $cookie = $cookie[0]; $SESSION->HIVE_SESSION = $cookie; return true; } } } return false; // No cookie found }
static function initial_checks($id, $password) { $vpl = new mod_vpl($id); //No context validation (session is OK) //self::validate_context($vpl->get_context()); if (!$vpl->pass_network_check()) { throw new Exception(get_string('opnotallowfromclient', VPL) . ' ' . getremoteaddr()); } if (!$vpl->pass_password_check($password)) { throw new Exception(get_string('requiredpassword', VPL)); } return $vpl; }
function find_lms_user($installid, $username, $signature, $confirmaction = null, $firstname = null, $lastname = null, $email = null) { global $CFG; // find this host from the installid if (empty($CFG->lmshosts) || !is_array($CFG->lmshosts) || !array_key_exists($installid, $CFG->lmshosts)) { return LMS_NO_SUCH_HOST; } $host = $CFG->lmshosts[$installid]; // validate our md5 hash if ($confirmaction == 'signupconfirmation') { $stringtohash = $installid . '|' . $username . '|' . $firstname . '|' . $lastname . '|' . $email . '|' . $host['token']; } else { $stringtohash = $installid . '|' . $username . '|' . $host['token']; // firstname, lastname and email cannot be relied upon not to change // so we only want to add them to the hash on signup, not for auth or anything else. } $checksig = md5($stringtohash); if ($checksig != $signature) { return LMS_INVALID_HASH; } // if we have an ip address, check it. if (array_key_exists('networkaddress', $host) && empty($confirmaction)) { if (!address_in_subnet(getremoteaddr(), $host['networkaddress'])) { return LMS_INVALID_NETWORK; } } if (!empty($confirmaction) && !empty($host['confirmurl'])) { $client = new Snoopy(); $client->agent = LMS_SNOOPY_USER_AGENT; $client->read_timeout = 5; $client->use_gzip = true; $postdata = array('action' => $confirmaction, 'username' => $username, 'signature' => $signature); @$client->submit($host['confirmurl'], $postdata); if ($client->results != 'OK') { return clean_param($client->results, PARAM_CLEAN); } } // find our user (we only want to check username and installid, the others could potentially change.. if (!($user = get_record_sql('SELECT u.* FROM ' . $CFG->prefix . 'users u JOIN ' . $CFG->prefix . 'users_alias ua ON ua.user_id = u.ident WHERE ua.installid = ? AND ua.username = ?', array($installid, $username)))) { return LMS_NO_SUCH_USER; } return $user; }
/** * Provides a hook into the login page. * * @param object &$frm Form object. * @param object &$user User object. */ public function loginpage_hook(&$frm, &$user) { global $DB; if (empty($frm)) { $frm = data_submitted(); } if (empty($frm)) { return true; } $autoappend = get_config('auth_oidc', 'autoappend'); if (empty($autoappend)) { // If we're not doing autoappend, just let things flow naturally. return true; } $username = $frm->username; $password = $frm->password; $auth = 'oidc'; $existinguser = $DB->get_record('user', ['username' => $username]); if (!empty($existinguser)) { // We don't want to prevent access to existing accounts. return true; } $username .= $autoappend; $success = $this->user_login($username, $password); if ($success !== true) { // No o365 user, continue normally. return false; } $existinguser = $DB->get_record('user', ['username' => $username]); if (!empty($existinguser)) { $user = $existinguser; return true; } // The user is authenticated but user creation may be disabled. if (!empty($CFG->authpreventaccountcreation)) { $failurereason = AUTH_LOGIN_UNAUTHORISED; // Trigger login failed event. $event = \core\event\user_login_failed::create(array('other' => array('username' => $username, 'reason' => $failurereason))); $event->trigger(); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Unknown user, can not create new accounts: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } $user = create_user_record($username, $password, $auth); return true; }
function definition() { global $COURSE, $USER, $CFG; $mform =& $this->_form; $this->set_upload_manager(new upload_manager('userfile', false, false, null, false, 0, true, true, false)); // course id needs to be passed for auth purposes $mform->addElement('hidden', 'id', optional_param('id')); $mform->setType('id', PARAM_INT); $mform->addElement('header', 'general', get_string('importfile', 'grades')); $mform->disabledIf('url', 'userfile', 'noteq', ''); $mform->addElement('advcheckbox', 'feedback', get_string('importfeedback', 'grades')); $mform->setDefault('feedback', 0); // file upload $mform->addElement('file', 'userfile', get_string('file')); $mform->setType('userfile', PARAM_FILE); $mform->disabledIf('userfile', 'url', 'noteq', ''); $mform->addElement('text', 'url', get_string('fileurl', 'gradeimport_xml'), 'size="80"'); if (!empty($CFG->gradepublishing)) { $mform->addElement('header', 'publishing', get_string('publishing', 'grades')); $options = array(get_string('nopublish', 'grades'), get_string('createnewkey', 'userkey')); if ($keys = get_records_select('user_private_key', "script='grade/import' AND instance={$COURSE->id} AND userid={$USER->id}")) { foreach ($keys as $key) { $options[$key->value] = $key->value; // TODO: add more details - ip restriction, valid until ?? } } $mform->addElement('select', 'key', get_string('userkey', 'userkey'), $options); $mform->setHelpButton('key', array(false, get_string('userkey', 'userkey'), false, true, false, get_string("userkeyhelp", 'grades'))); $mform->addElement('static', 'keymanagerlink', get_string('keymanager', 'userkey'), '<a href="' . $CFG->wwwroot . '/grade/import/keymanager.php?id=' . $COURSE->id . '">' . get_string('keymanager', 'userkey') . '</a>'); $mform->addElement('text', 'iprestriction', get_string('keyiprestriction', 'userkey'), array('size' => 80)); $mform->setHelpButton('iprestriction', array(false, get_string('keyiprestriction', 'userkey'), false, true, false, get_string("keyiprestrictionhelp", 'userkey'))); $mform->setDefault('iprestriction', getremoteaddr()); // own IP - just in case somebody does not know what user key is $mform->addElement('date_time_selector', 'validuntil', get_string('keyvaliduntil', 'userkey'), array('optional' => true)); $mform->setHelpButton('validuntil', array(false, get_string('keyvaliduntil', 'userkey'), false, true, false, get_string("keyvaliduntilhelp", 'userkey'))); $mform->setDefault('validuntil', time() + 3600 * 24 * 7); // only 1 week default duration - just in case somebody does not know what user key is $mform->disabledIf('iprestriction', 'key', 'noteq', 1); $mform->disabledIf('validuntil', 'key', 'noteq', 1); $mform->disabledIf('iprestriction', 'url', 'eq', ''); $mform->disabledIf('validuntil', 'url', 'eq', ''); $mform->disabledIf('key', 'url', 'eq', ''); } $this->add_action_buttons(false, get_string('uploadgrades', 'grades')); }
/** * See if the request has the proper remote address * * @param Zend_Controller_Request_Http $request The request to check * @return boolean */ public function isValid($request) { if (!empty($this->_ipAddresses)) { $remoteaddr = getremoteaddr(); // Check for localhost IPv6 if (empty($remoteaddr) and $request->getServer('REMOTE_ADDR') == '::1') { $remoteaddr = '127.0.0.1'; } // Can get get the remote address ? if (empty($remoteaddr)) { $this->_setValue($request->getServer('REMOTE_ADDR')); $this->_error(self::NOT_FOUND); return false; } // Address valid ? if (!address_in_subnet($remoteaddr, $this->_ipAddresses)) { $this->_setValue($remoteaddr); $this->_error(self::NOT_VALID); return false; } } return true; }
/** * Returns request IP address. * * @return string IP address or null if unknown */ protected function magic_get_requestip() { return getremoteaddr(null); }
/** * The user submitted echeck form. * * @param object $form Form parameters * @param object $course Course info * @access private */ function echeck_submit($form, $course) { global $CFG, $USER, $SESSION; require_once 'authorizenetlib.php'; prevent_double_paid($course); $useripno = getremoteaddr(); $curcost = get_course_cost($course); $isbusinesschecking = $form->acctype == 'BUSINESSCHECKING'; // NEW ECHECK ORDER $timenow = time(); $order = new stdClass(); $order->paymentmethod = AN_METHOD_ECHECK; $order->refundinfo = $isbusinesschecking ? 1 : 0; $order->ccname = $form->firstname . ' ' . $form->lastname; $order->courseid = $course->id; $order->userid = $USER->id; $order->status = AN_STATUS_NONE; // it will be changed... $order->settletime = 0; // cron changes this. $order->transid = 0; // Transaction Id $order->timecreated = $timenow; $order->amount = $curcost['cost']; $order->currency = $curcost['currency']; $order->id = insert_record("enrol_authorize", $order); if (!$order->id) { email_to_admin("Error while trying to insert new data", $order); return "Insert record error. Admin has been notified!"; } $extra = new stdClass(); $extra->x_bank_aba_code = $form->abacode; $extra->x_bank_acct_num = $form->accnum; $extra->x_bank_acct_type = $form->acctype; $extra->x_echeck_type = $isbusinesschecking ? 'CCD' : 'WEB'; $extra->x_bank_name = $form->bankname; $extra->x_currency_code = $curcost['currency']; $extra->x_amount = $curcost['cost']; $extra->x_first_name = $form->firstname; $extra->x_last_name = $form->lastname; $extra->x_country = $USER->country; $extra->x_address = $USER->address; $extra->x_city = $USER->city; $extra->x_state = ''; $extra->x_zip = ''; $extra->x_invoice_num = $order->id; $extra->x_description = $course->shortname; $extra->x_cust_id = $USER->id; $extra->x_email = $USER->email; $extra->x_customer_ip = $useripno; $extra->x_email_customer = empty($CFG->enrol_mailstudents) ? 'FALSE' : 'TRUE'; $extra->x_phone = ''; $extra->x_fax = ''; $message = ''; if (AN_REVIEW != authorize_action($order, $message, $extra, AN_ACTION_AUTH_CAPTURE)) { email_to_admin($message, $order); return $message; } $SESSION->ccpaid = 1; // security check: don't duplicate payment redirect($CFG->wwwroot, get_string("reviewnotify", "enrol_authorize"), '30'); }
function ewiki_author($defstr = "") { $author = @$GLOBALS["ewiki_author"]; $ip = getremoteaddr() or $ip = "127.0.0.0"; $port = $_SERVER["REMOTE_PORT"] or $port = "null"; $hostname = $ip; $remote = ($ip != $hostname ? $hostname . " " : "") . $ip . ":" . $port; empty($author) && (($author = $defstr) || ($author = $_SERVER["HTTP_FROM"]) || ($author = $_SERVER["PHP_AUTH_USER"])); empty($author) && ($author = $remote) || ($author = addslashes($author) . " (" . $remote . ")"); return $author; }
/** * Is current ip in give list? * * @param string $list * @return bool */ function remoteip_in_list($list) { $inlist = false; $clientip = getremoteaddr(null); if (!$clientip) { // Ensure access on cli. return true; } $list = explode("\n", $list); foreach ($list as $subnet) { $subnet = trim($subnet); if (address_in_subnet($clientip, $subnet)) { $inlist = true; break; } } return $inlist; }
/** * The other half to print_entry, this checks the form data * * This function checks that the user has completed the task on the * enrolment entry page and then enrolls them. * * @param form the form data submitted, as an object * @param course the current course, as an object */ function check_entry($form, $course) { global $CFG, $USER, $SESSION, $THEME; if (empty($form->password)) { $form->password = ''; } if (empty($course->password)) { // do not allow entry when no course password set // automatic login when manual primary, no login when secondary at all!! error('illegal enrolment attempted'); } $groupid = $this->check_group_entry($course->id, $form->password); if (stripslashes($form->password) == $course->password or $groupid !== false) { if (isguestuser()) { // only real user guest, do not use this for users with guest role $USER->enrolkey[$course->id] = true; add_to_log($course->id, 'course', 'guest', 'view.php?id=' . $course->id, getremoteaddr()); } else { /// Update or add new enrolment if (enrol_into_course($course, $USER, 'manual')) { // force a refresh of mycourses unset($USER->mycourses); if ($groupid !== false) { if (!groups_add_member($groupid, $USER->id)) { print_error('couldnotassigngroup'); } } } else { print_error('couldnotassignrole'); } } if ($SESSION->wantsurl) { $destination = $SESSION->wantsurl; unset($SESSION->wantsurl); } else { $destination = "{$CFG->wwwroot}/course/view.php?id={$course->id}"; } redirect($destination); } else { if (!isset($CFG->enrol_manual_showhint) or $CFG->enrol_manual_showhint) { $this->errormsg = get_string('enrolmentkeyhint', '', substr($course->password, 0, 1)); } else { $this->errormsg = get_string('enrolmentkeyerror', 'enrol_manual'); } } }
if (!$sessionverify) { $SESSION->sessionverify = 1; redirect("index.php?sessionstarted=1&sessionverify=1&lang={$CFG->lang}"); } else { if (empty($SESSION->sessionverify)) { print_error('installsessionerror', 'admin', "index.php?sessionstarted=1&lang={$CFG->lang}"); } unset($SESSION->sessionverify); } } // at this stage there can be only one admin unless more were added by install - users may change username, so do not rely on that $adminids = explode(',', $CFG->siteadmins); $adminuser = get_complete_user_data('id', reset($adminids)); if ($adminuser->password === 'adminsetuppending') { // prevent installation hijacking if ($adminuser->lastip !== getremoteaddr()) { print_error('installhijacked', 'admin'); } // login user and let him set password and admin details $adminuser->newadminuser = 1; complete_user_login($adminuser); redirect("{$CFG->wwwroot}/user/editadvanced.php?id={$adminuser->id}"); // Edit thyself } else { unset_config('adminsetuppending'); } } else { // just make sure upgrade logging is properly terminated upgrade_finished('upgradesettings.php'); } // Turn xmlstrictheaders back on now.
/** * Main post-install tasks to be executed after the BD schema is available * * This function is automatically executed after Moodle core DB has been * created at initial install. It's in charge of perform the initial tasks * not covered by the {@link install.xml} file, like create initial users, * roles, templates, moving stuff from other plugins... * * Note that the function is only invoked once, at install time, so if new tasks * are needed in the future, they will need to be added both here (for new sites) * and in the corresponding {@link upgrade.php} file (for existing sites). * * All plugins within Moodle (modules, blocks, reports...) support the existence of * their own install.php file, using the "Frankenstyle" component name as * defined at {@link http://docs.moodle.org/dev/Frankenstyle}, for example: * - {@link xmldb_page_install()}. (modules don't require the plugintype ("mod_") to be used. * - {@link xmldb_enrol_meta_install()}. * - {@link xmldb_workshopform_accumulative_install()}. * - .... * * Finally, note that it's also supported to have one uninstall.php file that is * executed also once, each time one plugin is uninstalled (before the DB schema is * deleted). Those uninstall files will contain one function, using the "Frankenstyle" * naming conventions, like {@link xmldb_enrol_meta_uninstall()} or {@link xmldb_workshop_uninstall()}. */ function xmldb_main_install() { global $CFG, $DB, $SITE, $OUTPUT; // Make sure system context exists $syscontext = context_system::instance(0, MUST_EXIST, false); if ($syscontext->id != SYSCONTEXTID) { throw new moodle_exception('generalexceptionmessage', 'error', '', 'Unexpected new system context id!'); } // Create site course if ($DB->record_exists('course', array())) { throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create frontpage course, courses already exist.'); } $newsite = new stdClass(); $newsite->fullname = ''; $newsite->shortname = ''; $newsite->summary = NULL; $newsite->newsitems = 3; $newsite->numsections = 1; $newsite->category = 0; $newsite->format = 'site'; // Only for this course $newsite->timecreated = time(); $newsite->timemodified = $newsite->timecreated; if (defined('SITEID')) { $newsite->id = SITEID; $DB->import_record('course', $newsite); $DB->get_manager()->reset_sequence('course'); } else { $newsite->id = $DB->insert_record('course', $newsite); define('SITEID', $newsite->id); } // set the field 'numsections'. We can not use format_site::update_format_options() because // the file is not loaded $DB->insert_record('course_format_options', array('courseid' => SITEID, 'format' => 'site', 'sectionid' => 0, 'name' => 'numsections', 'value' => $newsite->numsections)); $SITE = get_site(); if ($newsite->id != $SITE->id) { throw new moodle_exception('generalexceptionmessage', 'error', '', 'Unexpected new site course id!'); } // Make sure site course context exists context_course::instance($SITE->id); // Update the global frontpage cache $SITE = $DB->get_record('course', array('id' => $newsite->id), '*', MUST_EXIST); // Create default course category if ($DB->record_exists('course_categories', array())) { throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create default course category, categories already exist.'); } $cat = new stdClass(); $cat->name = get_string('miscellaneous'); $cat->depth = 1; $cat->sortorder = MAX_COURSES_IN_CATEGORY; $cat->timemodified = time(); $catid = $DB->insert_record('course_categories', $cat); $DB->set_field('course_categories', 'path', '/' . $catid, array('id' => $catid)); // Make sure category context exists context_coursecat::instance($catid); $defaults = array('rolesactive' => '0', 'auth' => 'email', 'auth_pop3mailbox' => 'INBOX', 'enrol_plugins_enabled' => 'manual,guest,self,cohort', 'theme' => theme_config::DEFAULT_THEME, 'filter_multilang_converted' => 1, 'siteidentifier' => random_string(32) . get_host_from_url($CFG->wwwroot), 'backup_version' => 2008111700, 'backup_release' => '2.0 dev', 'mnet_dispatcher_mode' => 'off', 'sessiontimeout' => 7200, 'stringfilters' => '', 'filterall' => 0, 'texteditors' => 'atto,tinymce,textarea', 'upgrade_minmaxgradestepignored' => 1, 'upgrade_extracreditweightsstepignored' => 1, 'upgrade_calculatedgradeitemsignored' => 1); foreach ($defaults as $key => $value) { set_config($key, $value); } // Bootstrap mnet $mnethost = new stdClass(); $mnethost->wwwroot = $CFG->wwwroot; $mnethost->name = ''; $mnethost->name = ''; $mnethost->public_key = ''; if (empty($_SERVER['SERVER_ADDR'])) { // SERVER_ADDR is only returned by Apache-like webservers preg_match("@^(?:http[s]?://)?([A-Z0-9\\-\\.]+).*@i", $CFG->wwwroot, $matches); $my_hostname = $matches[1]; $my_ip = gethostbyname($my_hostname); // Returns unmodified hostname on failure. DOH! if ($my_ip == $my_hostname) { $mnethost->ip_address = 'UNKNOWN'; } else { $mnethost->ip_address = $my_ip; } } else { $mnethost->ip_address = $_SERVER['SERVER_ADDR']; } $mnetid = $DB->insert_record('mnet_host', $mnethost); set_config('mnet_localhost_id', $mnetid); // Initial insert of mnet applications info $mnet_app = new stdClass(); $mnet_app->name = 'moodle'; $mnet_app->display_name = 'Moodle'; $mnet_app->xmlrpc_server_url = '/mnet/xmlrpc/server.php'; $mnet_app->sso_land_url = '/auth/mnet/land.php'; $mnet_app->sso_jump_url = '/auth/mnet/jump.php'; $moodleapplicationid = $DB->insert_record('mnet_application', $mnet_app); $mnet_app = new stdClass(); $mnet_app->name = 'mahara'; $mnet_app->display_name = 'Mahara'; $mnet_app->xmlrpc_server_url = '/api/xmlrpc/server.php'; $mnet_app->sso_land_url = '/auth/xmlrpc/land.php'; $mnet_app->sso_jump_url = '/auth/xmlrpc/jump.php'; $DB->insert_record('mnet_application', $mnet_app); // Set up the probably-to-be-removed-soon 'All hosts' record $mnetallhosts = new stdClass(); $mnetallhosts->wwwroot = ''; $mnetallhosts->ip_address = ''; $mnetallhosts->public_key = ''; $mnetallhosts->public_key_expires = 0; $mnetallhosts->last_connect_time = 0; $mnetallhosts->last_log_id = 0; $mnetallhosts->deleted = 0; $mnetallhosts->name = 'All Hosts'; $mnetallhosts->applicationid = $moodleapplicationid; $mnetallhosts->id = $DB->insert_record('mnet_host', $mnetallhosts, true); set_config('mnet_all_hosts_id', $mnetallhosts->id); // Create guest record - do not assign any role, guest user gets the default guest role automatically on the fly if ($DB->record_exists('user', array())) { throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create default users, users already exist.'); } $guest = new stdClass(); $guest->auth = 'manual'; $guest->username = '******'; $guest->password = hash_internal_user_password('guest'); $guest->firstname = get_string('guestuser'); $guest->lastname = ' '; $guest->email = 'root@localhost'; $guest->description = get_string('guestuserinfo'); $guest->mnethostid = $CFG->mnet_localhost_id; $guest->confirmed = 1; $guest->lang = $CFG->lang; $guest->timemodified = time(); $guest->id = $DB->insert_record('user', $guest); if ($guest->id != 1) { echo $OUTPUT->notification('Unexpected id generated for the Guest account. Your database configuration or clustering setup may not be fully supported', 'notifyproblem'); } // Store guest id set_config('siteguest', $guest->id); // Make sure user context exists context_user::instance($guest->id); // Now create admin user $admin = new stdClass(); $admin->auth = 'manual'; $admin->firstname = get_string('admin'); $admin->lastname = get_string('user'); $admin->username = '******'; $admin->password = '******'; $admin->email = ''; $admin->confirmed = 1; $admin->mnethostid = $CFG->mnet_localhost_id; $admin->lang = $CFG->lang; $admin->maildisplay = 1; $admin->timemodified = time(); $admin->lastip = CLI_SCRIPT ? '0.0.0.0' : getremoteaddr(); // installation hijacking prevention $admin->id = $DB->insert_record('user', $admin); if ($admin->id != 2) { echo $OUTPUT->notification('Unexpected id generated for the Admin account. Your database configuration or clustering setup may not be fully supported', 'notifyproblem'); } if ($admin->id != $guest->id + 1) { echo $OUTPUT->notification('Nonconsecutive id generated for the Admin account. Your database configuration or clustering setup may not be fully supported.', 'notifyproblem'); } // Store list of admins set_config('siteadmins', $admin->id); // Make sure user context exists context_user::instance($admin->id); // Install the roles system. $managerrole = create_role('', 'manager', '', 'manager'); $coursecreatorrole = create_role('', 'coursecreator', '', 'coursecreator'); $editteacherrole = create_role('', 'editingteacher', '', 'editingteacher'); $noneditteacherrole = create_role('', 'teacher', '', 'teacher'); $studentrole = create_role('', 'student', '', 'student'); $guestrole = create_role('', 'guest', '', 'guest'); $userrole = create_role('', 'user', '', 'user'); $frontpagerole = create_role('', 'frontpage', '', 'frontpage'); // Now is the correct moment to install capabilities - after creation of legacy roles, but before assigning of roles update_capabilities('moodle'); // Default allow role matrices. foreach ($DB->get_records('role') as $role) { foreach (array('assign', 'override', 'switch') as $type) { $function = 'allow_' . $type; $allows = get_default_role_archetype_allows($type, $role->archetype); foreach ($allows as $allowid) { $function($role->id, $allowid); } } } // Set up the context levels where you can assign each role. set_role_contextlevels($managerrole, get_default_contextlevels('manager')); set_role_contextlevels($coursecreatorrole, get_default_contextlevels('coursecreator')); set_role_contextlevels($editteacherrole, get_default_contextlevels('editingteacher')); set_role_contextlevels($noneditteacherrole, get_default_contextlevels('teacher')); set_role_contextlevels($studentrole, get_default_contextlevels('student')); set_role_contextlevels($guestrole, get_default_contextlevels('guest')); set_role_contextlevels($userrole, get_default_contextlevels('user')); // Init theme and JS revisions set_config('themerev', time()); set_config('jsrev', time()); // No admin setting for this any more, GD is now required, remove in Moodle 2.6. set_config('gdversion', 2); // Install licenses require_once $CFG->libdir . '/licenselib.php'; license_manager::install_licenses(); // Init profile pages defaults if ($DB->record_exists('my_pages', array())) { throw new moodle_exception('generalexceptionmessage', 'error', '', 'Can not create default profile pages, records already exist.'); } $mypage = new stdClass(); $mypage->userid = NULL; $mypage->name = '__default'; $mypage->private = 0; $mypage->sortorder = 0; $DB->insert_record('my_pages', $mypage); $mypage->private = 1; $DB->insert_record('my_pages', $mypage); // Set a sensible default sort order for the most-used question types. set_config('multichoice_sortorder', 1, 'question'); set_config('truefalse_sortorder', 2, 'question'); set_config('match_sortorder', 3, 'question'); set_config('shortanswer_sortorder', 4, 'question'); set_config('numerical_sortorder', 5, 'question'); set_config('essay_sortorder', 6, 'question'); }
/** * BC internal function * @param object $url * @param object $config * @return string */ function url_get_encrypted_parameter($url, $config) { global $CFG; if (file_exists("{$CFG->dirroot}/local/externserverfile.php")) { require_once "{$CFG->dirroot}/local/externserverfile.php"; if (function_exists('extern_server_file')) { return extern_server_file($url, $config); } } return md5(getremoteaddr() . $config->secretphrase); }
/** * login if not already logged in * * @global object * @global object * @param int $chatid * @param string $version * @param int $groupid * @param object $course * @return bool|int Returns the chat users sid or false */ function chat_login_user($chatid, $version, $groupid, $course) { global $USER, $DB; if ($version != 'sockets' and $chatuser = $DB->get_record('chat_users', array('chatid' => $chatid, 'userid' => $USER->id, 'groupid' => $groupid))) { // This will update logged user information. $chatuser->version = $version; $chatuser->ip = $USER->lastip; $chatuser->lastping = time(); $chatuser->lang = current_language(); // Sometimes $USER->lastip is not setup properly during login. // Update with current value if possible or provide a dummy value for the db. if (empty($chatuser->ip)) { $chatuser->ip = getremoteaddr(); } if ($chatuser->course != $course->id or $chatuser->userid != $USER->id) { return false; } $DB->update_record('chat_users', $chatuser); } else { $chatuser = new stdClass(); $chatuser->chatid = $chatid; $chatuser->userid = $USER->id; $chatuser->groupid = $groupid; $chatuser->version = $version; $chatuser->ip = $USER->lastip; $chatuser->lastping = $chatuser->firstping = $chatuser->lastmessageping = time(); $chatuser->sid = random_string(32); $chatuser->course = $course->id; // Caching - needed for current_language too. $chatuser->lang = current_language(); // Caching - to resource intensive to find out later. // Sometimes $USER->lastip is not setup properly during login. // Update with current value if possible or provide a dummy value for the db. if (empty($chatuser->ip)) { $chatuser->ip = getremoteaddr(); } $DB->insert_record('chat_users', $chatuser); if ($version == 'sockets') { // Do not send 'enter' message, chatd will do it. } else { chat_send_chatmessage($chatuser, 'enter', true); } } return $chatuser->sid; }
function verify($challenge_field, $response_field) { global $CFG; require_once $CFG->libdir . '/recaptchalib.php'; $response = recaptcha_check_answer($CFG->recaptchaprivatekey, getremoteaddr(), $challenge_field, $response_field, $this->_https); if (!$response->is_valid) { $attributes = $this->getAttributes(); $attributes['error_message'] = $response->error; $this->setAttributes($attributes); return $response->error; } return true; }
function set_encrypted_parameter() { global $CFG; if (!empty($this->resource->reference) && file_exists($CFG->dirroot . "/mod/resource/type/file/externserverfile.php")) { include $CFG->dirroot . "/mod/resource/type/file/externserverfile.php"; if (function_exists('extern_server_file')) { return extern_server_file($this->resource->reference); } } return md5(getremoteaddr() . $CFG->resource_secretphrase); }
/** * Legacy add_to_log() code. * * @param int $courseid The course id * @param string $module The module name e.g. forum, journal, resource, course, user etc * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify. * @param string $url The file and parameters used to see the results of the action * @param string $info Additional description information * @param int $cm The course_module->id if there is one * @param int|\stdClass $user If log regards $user other than $USER */ public function legacy_add_to_log($courseid, $module, $action, $url, $info, $cm, $user) { // Note that this function intentionally does not follow the normal Moodle DB access idioms. // This is for a good reason: it is the most frequently used DB update function, // so it has been optimised for speed. global $DB, $CFG, $USER; if (!$this->is_logging()) { return; } if ($cm === '' || is_null($cm)) { // Postgres won't translate empty string to its default. $cm = 0; } if ($user) { $userid = $user; } else { if (\core\session\manager::is_loggedinas()) { // Don't log. return; } $userid = empty($USER->id) ? '0' : $USER->id; } if (isset($CFG->logguests) and !$CFG->logguests) { if (!$userid or isguestuser($userid)) { return; } } $remoteaddr = getremoteaddr(); $timenow = time(); if (!empty($url)) { // Could break doing html_entity_decode on an empty var. $url = html_entity_decode($url, ENT_QUOTES, 'UTF-8'); } else { $url = ''; } // Restrict length of log lines to the space actually available in the // database so that it doesn't cause a DB error. Log a warning so that // developers can avoid doing things which are likely to cause this on a // routine basis. if (\core_text::strlen($action) > 40) { $action = \core_text::substr($action, 0, 37) . '...'; debugging('Warning: logged very long action', DEBUG_DEVELOPER); } if (!empty($info) && \core_text::strlen($info) > 255) { $info = \core_text::substr($info, 0, 252) . '...'; debugging('Warning: logged very long info', DEBUG_DEVELOPER); } // If the 100 field size is changed, also need to alter print_log in course/lib.php. if (!empty($url) && \core_text::strlen($url) > 100) { $url = \core_text::substr($url, 0, 97) . '...'; debugging('Warning: logged very long URL', DEBUG_DEVELOPER); } if (defined('MDL_PERFDB')) { global $PERF; $PERF->logwrites++; } $log = array('time' => $timenow, 'userid' => $userid, 'course' => $courseid, 'ip' => $remoteaddr, 'module' => $module, 'cmid' => $cm, 'action' => $action, 'url' => $url, 'info' => $info); try { $DB->insert_record_raw('log', $log, false); } catch (\dml_exception $e) { debugging('Error: Could not insert a new entry to the Moodle log. ' . $e->errorcode, DEBUG_ALL); // MDL-11893, alert $CFG->supportemail if insert into log failed. if ($CFG->supportemail and empty($CFG->noemailever)) { // Function email_to_user is not usable because email_to_user tries to write to the logs table, // and this will get caught in an infinite loop, if disk is full. $site = get_site(); $subject = 'Insert into log failed at your moodle site ' . $site->fullname; $message = "Insert into log table failed at " . date('l dS \\of F Y h:i:s A') . ".\n It is possible that your disk is full.\n\n"; $message .= "The failed query parameters are:\n\n" . var_export($log, true); $lasttime = get_config('admin', 'lastloginserterrormail'); if (empty($lasttime) || time() - $lasttime > 60 * 60 * 24) { // Limit to 1 email per day. // Using email directly rather than messaging as they may not be able to log in to access a message. mail($CFG->supportemail, $subject, $message); set_config('lastloginserterrormail', time(), 'admin'); } } } }
$newuser->auth = $auth; $newuser->policyagreed = 1; $newuser->idnumber = $idnumber; $newuser->username = $username; $newuser->password = md5($hashedpassword); // manual auth checks password validity, so we need to set a valid password // $DB->set_field('user', 'password', $hashedpassword, array('id'=>$user->id)); $newuser->firstname = $firstname; $newuser->lastname = $lastname; $newuser->email = $email; if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) { $newuser->lang = $CFG->lang; } $newuser->confirmed = 1; // don't want an email going out about this user $newuser->lastip = getremoteaddr(); $newuser->timecreated = time(); $newuser->timemodified = $newuser->timecreated; $newuser->mnethostid = $CFG->mnet_localhost_id; // make sure we haven't exceeded any field limits $newuser = truncate_user($newuser); $newuser->id = $DB->insert_record('user', $newuser); $user = get_complete_user_data('id', $newuser->id); \core\event\user_created::create_from_userid($user->id)->trigger(); } } // if we can find a cohortid matching what we sent in, enrol this user in that cohort by adding a record to cohort_members if (!empty($cohort)) { $ids = explode(',', $cohort); foreach ($ids as $cohort) { if ($DB->record_exists('cohort', array('idnumber' => $cohort))) {
/** * Store user last access times - called when use enters a course or site * * @global object * @global object * @global object * @uses LASTACCESS_UPDATE_SECS * @uses SITEID * @param int $courseid, empty means site * @return void */ function user_accesstime_log($courseid = 0) { global $USER, $CFG, $DB; if (!isloggedin() or session_is_loggedinas()) { // no access tracking return; } if (empty($courseid)) { $courseid = SITEID; } $timenow = time(); /// Store site lastaccess time for the current user if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) { /// Update $USER->lastaccess for next checks $USER->lastaccess = $timenow; $last = new stdClass(); $last->id = $USER->id; $last->lastip = getremoteaddr(); $last->lastaccess = $timenow; $DB->update_record_raw('user', $last); } if ($courseid == SITEID) { /// no user_lastaccess for frontpage return; } /// Store course lastaccess times for the current user if (empty($USER->currentcourseaccess[$courseid]) or $timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS) { $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid' => $USER->id, 'courseid' => $courseid)); if ($lastaccess === false) { // Update course lastaccess for next checks $USER->currentcourseaccess[$courseid] = $timenow; $last = new stdClass(); $last->userid = $USER->id; $last->courseid = $courseid; $last->timeaccess = $timenow; $DB->insert_record_raw('user_lastaccess', $last, false); } else { if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS) { // no need to update now, it was updated recently in concurrent login ;-) } else { // Update course lastaccess for next checks $USER->currentcourseaccess[$courseid] = $timenow; $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid' => $USER->id, 'courseid' => $courseid)); } } } }
/** * Write session handler. * * {@see http://php.net/manual/en/function.session-set-save-handler.php} * * NOTE: Do not write to output or throw any exceptions! * Hopefully the next page is going to display nice error or it recovers... * * @param string $sid * @param string $session_data * @return bool success */ public function handler_write($sid, $session_data) { global $USER; // TODO: MDL-20625 we need to rollback all active transactions and log error if any open needed if ($this->failed) { // do not write anything back - we failed to start the session properly return false; } $userid = 0; if (!empty($USER->realuser)) { $userid = $USER->realuser; } else { if (!empty($USER->id)) { $userid = $USER->id; } } if (isset($this->record->id)) { $data = base64_encode($session_data); // There might be some binary mess :-( // Skip db update if nothing changed, // do not update the timemodified each second. $hash = sha1($data); if ($this->lasthash === $hash and $this->record->userid == $userid and time() - $this->record->timemodified < 20 and $this->record->lastip == getremoteaddr()) { // No need to update anything! return true; } $this->record->sessdata = $data; $this->record->userid = $userid; $this->record->timemodified = time(); $this->record->lastip = getremoteaddr(); try { $this->database->update_record_raw('sessions', $this->record); $this->lasthash = $hash; } catch (dml_exception $ex) { if ($this->database->get_dbfamily() === 'mysql') { try { $this->database->set_field('sessions', 'state', 9, array('id' => $this->record->id)); } catch (Exception $ignored) { } error_log('Can not write database session - please verify max_allowed_packet is at least 4M!'); } else { error_log('Can not write database session'); } return false; } catch (Exception $ex) { error_log('Can not write database session'); return false; } } else { // fresh new session try { $record = new stdClass(); $record->state = 0; $record->sid = $sid; $record->sessdata = base64_encode($session_data); // there might be some binary mess :-( $record->userid = $userid; $record->timecreated = $record->timemodified = time(); $record->firstip = $record->lastip = getremoteaddr(); $record->id = $this->database->insert_record_raw('sessions', $record); $this->record = $this->database->get_record('sessions', array('id' => $record->id)); $this->lasthash = sha1($record->sessdata); $this->database->get_session_lock($this->record->id, SESSION_ACQUIRE_LOCK_TIMEOUT); } catch (Exception $ex) { // this should not happen error_log('Can not write new database session or acquire session lock'); $this->failed = true; return false; } } return true; }
/** * login if not already logged in * * @global object * @global object * @param int $chatid * @param string $version * @param int $groupid * @param object $course * @return bool|int Returns the chat users sid or false */ function chat_login_user($chatid, $version, $groupid, $course) { global $USER, $DB; if ($version != 'sockets' and $chatuser = $DB->get_record('chat_users', array('chatid' => $chatid, 'userid' => $USER->id, 'groupid' => $groupid))) { // this will update logged user information $chatuser->version = $version; $chatuser->ip = $USER->lastip; $chatuser->lastping = time(); $chatuser->lang = current_language(); // Sometimes $USER->lastip is not setup properly // during login. Update with current value if possible // or provide a dummy value for the db if (empty($chatuser->ip)) { $chatuser->ip = getremoteaddr(); if (empty($chatuser->ip)) { $chatuser->ip = ''; } } if ($chatuser->course != $course->id or $chatuser->userid != $USER->id) { return false; } $DB->update_record('chat_users', $chatuser); } else { $chatuser = new object(); $chatuser->chatid = $chatid; $chatuser->userid = $USER->id; $chatuser->groupid = $groupid; $chatuser->version = $version; $chatuser->ip = $USER->lastip; $chatuser->lastping = $chatuser->firstping = $chatuser->lastmessageping = time(); $chatuser->sid = random_string(32); $chatuser->course = $course->id; //caching - needed for current_language too $chatuser->lang = current_language(); //caching - to resource intensive to find out later // Sometimes $USER->lastip is not setup properly // during login. Update with current value if possible // or provide a dummy value for the db if (empty($chatuser->ip)) { $chatuser->ip = getremoteaddr(); if (empty($chatuser->ip)) { $chatuser->ip = ''; } } $DB->insert_record('chat_users', $chatuser); if ($version == 'sockets') { // do not send 'enter' message, chatd will do it } else { $message = new object(); $message->chatid = $chatuser->chatid; $message->userid = $chatuser->userid; $message->groupid = $groupid; $message->message = 'enter'; $message->system = 1; $message->timestamp = time(); $DB->insert_record('chat_messages', $message); $DB->insert_record('chat_messages_current', $message); } } return $chatuser->sid; }
function local_ombieltoken_authenticate_user($username) { global $CFG, $DB; $authsenabled = get_enabled_auth_plugins(); $authplugin = get_auth_plugin('cosign'); if ($username) { $user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id); } else { $user = get_complete_user_data('username', auth_plugin_cosign::get_cosign_username(), $CFG->mnet_localhost_id); } if ($user) { if ($user->auth !== 'cosign') { // Invalid auth - we only allow cosign users in this token generator add_to_log(SITEID, 'login', 'error', 'index.php', $username); return false; } if (!empty($user->suspended)) { add_to_log(SITEID, 'login', 'error', 'index.php', $username); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Suspended Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } } else { // check if there's a deleted record (cheaply) if ($DB->get_field('user', 'id', array('username' => $username, 'deleted' => 1))) { error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Deleted Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); } return false; } $user = update_user_record($username); return $user; }
function check_value($value, $item) { global $SESSION, $CFG, $USER; require_once $CFG->libdir . '/recaptchalib.php'; $challenge = optional_param('recaptcha_challenge_field', '', PARAM_RAW); if ($value == $USER->sesskey and $challenge == '') { return true; } $remoteip = getremoteaddr(null); $response = recaptcha_check_answer($CFG->recaptchaprivatekey, $remoteip, $challenge, $value); if ($response->is_valid) { $SESSION->feedback->captchacheck = $USER->sesskey; return true; } unset($SESSION->feedback->captchacheck); return false; }
$buttonoptions['forcenew'] = true; echo '<div class="controls">'; print_single_button($CFG->wwwroot . '/mod/quiz/attempt.php', $buttonoptions, get_string('startagain', 'quiz')); echo '</div>'; /// Notices about restrictions that would affect students. if ($quiz->popup == 1) { notify(get_string('popupnotice', 'quiz')); } else { if ($quiz->popup == 2) { notify(get_string('safebrowsernotice', 'quiz')); } } if ($timestamp < $quiz->timeopen || $quiz->timeclose && $timestamp > $quiz->timeclose) { notify(get_string('notavailabletostudents', 'quiz')); } if ($quiz->subnet && !address_in_subnet(getremoteaddr(), $quiz->subnet)) { notify(get_string('subnetnotice', 'quiz')); } } else { if ($quiz->attempts != 1) { print_heading(format_string($quiz->name) . ' - ' . $strattemptnum); } else { print_heading(format_string($quiz->name)); } } // Start the form $quiz->thispageurl = $CFG->wwwroot . '/mod/quiz/attempt.php?q=' . s($quiz->id) . '&page=' . s($page); $quiz->cmid = $cm->id; echo '<form id="responseform" method="post" action="', $quiz->thispageurl . '" enctype="multipart/form-data"' . ' onkeypress="return check_enter(event);" accept-charset="utf-8">', "\n"; echo '<script type="text/javascript">', "\n", 'document.getElementById("responseform").setAttribute("autocomplete", "off")', "\n", "</script>\n"; if ($quiz->timelimit > 0) {