/** * Form validation * * @param array $data * @param array $files * @return array $errors An array of validataion errors for the form. */ function validation($data, $files) { global $COURSE, $DB; $errors = parent::validation($data, $files); $name = trim($data['name']); if (isset($data['idnumber'])) { $idnumber = trim($data['idnumber']); } else { $idnumber = ''; } if ($data['id'] and $grouping = $DB->get_record('groupings', array('id' => $data['id']))) { if (textlib::strtolower($grouping->name) != textlib::strtolower($name)) { if (groups_get_grouping_by_name($COURSE->id, $name)) { $errors['name'] = get_string('groupingnameexists', 'group', $name); } } if (!empty($idnumber) && $grouping->idnumber != $idnumber) { if (groups_get_grouping_by_idnumber($COURSE->id, $idnumber)) { $errors['idnumber'] = get_string('idnumbertaken'); } } } else { if (groups_get_grouping_by_name($COURSE->id, $name)) { $errors['name'] = get_string('groupingnameexists', 'group', $name); } else { if (!empty($idnumber) && groups_get_grouping_by_idnumber($COURSE->id, $idnumber)) { $errors['idnumber'] = get_string('idnumbertaken'); } } } return $errors; }
/** * Form validation * * @param array $data * @param array $files * @return array $errors An array of errors */ function validation($data, $files) { global $COURSE, $DB, $CFG; $errors = parent::validation($data, $files); $name = trim($data['name']); if ($data['id'] and $group = $DB->get_record('groups', array('id' => $data['id']))) { if (textlib::strtolower($group->name) != textlib::strtolower($name)) { if (groups_get_group_by_name($COURSE->id, $name)) { $errors['name'] = get_string('groupnameexists', 'group', $name); } } if (!empty($CFG->groupenrolmentkeypolicy) and $data['enrolmentkey'] != '' and $group->enrolmentkey !== $data['enrolmentkey']) { // enforce password policy only if changing password $errmsg = ''; if (!check_password_policy($data['enrolmentkey'], $errmsg)) { $errors['enrolmentkey'] = $errmsg; } } } else { if (groups_get_group_by_name($COURSE->id, $name)) { $errors['name'] = get_string('groupnameexists', 'group', $name); } } return $errors; }
/** * Update a user with a user object (will compare against the ID) * * @param object $user the user to update */ function user_update_user($user) { global $DB; // set the timecreate field to the current time if (!is_object($user)) { $user = (object) $user; } //check username if (isset($user->username)) { if ($user->username !== textlib::strtolower($user->username)) { throw new moodle_exception('usernamelowercase'); } else { if ($user->username !== clean_param($user->username, PARAM_USERNAME)) { throw new moodle_exception('invalidusername'); } } } // unset password here, for updating later if (isset($user->password)) { //check password toward the password policy if (!check_password_policy($user->password, $errmsg)) { throw new moodle_exception($errmsg); } $passwd = $user->password; unset($user->password); } $user->timemodified = time(); $DB->update_record('user', $user); // trigger user_updated event on the full database user row $updateduser = $DB->get_record('user', array('id' => $user->id)); // if password was set, then update its hash if (isset($passwd)) { $authplugin = get_auth_plugin($updateduser->auth); if ($authplugin->can_change_password()) { $authplugin->user_update_password($updateduser, $passwd); } } events_trigger('user_updated', $updateduser); add_to_log(SITEID, 'user', get_string('update'), '/view.php?id=' . $updateduser->id, fullname($updateduser)); }
/** * @todo Document this function * @param array $linkarray * @return array */ function filter_remove_duplicates($linkarray) { $concepts = array(); // keep a record of concepts as we cycle through $lconcepts = array(); // a lower case version for case insensitive $cleanlinks = array(); foreach ($linkarray as $key => $filterobject) { if ($filterobject->casesensitive) { $exists = in_array($filterobject->phrase, $concepts); } else { $exists = in_array(textlib::strtolower($filterobject->phrase), $lconcepts); } if (!$exists) { $cleanlinks[] = $filterobject; $concepts[] = $filterobject->phrase; $lconcepts[] = textlib::strtolower($filterobject->phrase); } } return $cleanlinks; }
/** * Tests the static strtolower method * @return void */ public function test_strtolower() { $str = "Žluťoučký koníček"; $low = 'žluťoučký koníček'; $this->assertSame(textlib::strtolower($str), $low); $iso2 = pack("H*", "ae6c75bb6f75e86bfd206b6f6eede8656b"); $this->assertSame(textlib::strtolower($iso2, 'iso-8859-2'), textlib::convert($low, 'utf-8', 'iso-8859-2')); $win = pack("H*", "8e6c759d6f75e86bfd206b6f6eede8656b"); $this->assertSame(textlib::strtolower($win, 'cp1250'), textlib::convert($low, 'utf-8', 'cp1250')); $str = '言語設定'; $this->assertSame(textlib::strtolower($str), $str); $str = '简体中文'; $this->assertSame(textlib::strtolower($str), $str); $str = pack("H*", "1b24423840386c405f446a1b2842"); //ISO-2022-JP $this->assertSame(textlib::strtolower($str, 'ISO-2022-JP'), $str); $str = pack("H*", "8cbe8cea90dd92e8"); //SHIFT-JIS $this->assertSame(textlib::strtolower($str, 'SHIFT-JIS'), $str); $str = pack("H*", "bcf2cce5d6d0cec4"); //GB2312 $this->assertSame(textlib::strtolower($str, 'GB2312'), $str); $str = pack("H*", "bcf2cce5d6d0cec4"); //GB18030 $this->assertSame(textlib::strtolower($str, 'GB18030'), $str); // typo3 has problems with integers $str = 1309528800; $this->assertSame((string) $str, textlib::strtolower($str)); }
print_course_search('', false, 'short'); } break; case FRONTPAGECATEGORYNAMES: echo html_writer::tag('a', get_string('skipa', 'access', textlib::strtolower(get_string('categories'))), array('href'=>'#skipcategories', 'class'=>'skip-block')); echo $OUTPUT->heading(get_string('categories'), 2, 'headingblock header'); echo $OUTPUT->box_start('generalbox categorybox'); print_whole_category_list(NULL, NULL, NULL, -1, false); echo $OUTPUT->box_end(); print_course_search('', false, 'short'); echo html_writer::tag('span', '', array('class'=>'skip-block-to', 'id'=>'skipcategories')); break; case FRONTPAGECATEGORYCOMBO: echo html_writer::tag('a', get_string('skipa', 'access', textlib::strtolower(get_string('courses'))), array('href'=>'#skipcourses', 'class'=>'skip-block')); echo $OUTPUT->heading(get_string('courses'), 2, 'headingblock header'); $renderer = $PAGE->get_renderer('core','course'); // if there are too many courses, budiling course category tree could be slow, // users should go to course index page to see the whole list. $coursecount = $DB->count_records('course'); if (empty($CFG->numcoursesincombo)) { // if $CFG->numcoursesincombo hasn't been set, use default value 500 $CFG->numcoursesincombo = 500; } if ($coursecount > $CFG->numcoursesincombo) { $link = new moodle_url('/course/'); echo $OUTPUT->notification(get_string('maxnumcoursesincombo', 'moodle', array('link'=>$link->out(), 'maxnumofcourses'=>$CFG->numcoursesincombo, 'numberofcourses'=>$coursecount))); } else { echo $renderer->course_category_tree(get_course_category_tree()); }
/** * Returns the number of children which are either files matching the specified extensions * or folders containing at least one such file. * * We usually don't need the exact number of non empty children if it is >=2 (see param $limit) * This function is used by repository_local to evaluate if the folder is empty. But * it also can be used to check if folder has only one subfolder because in some cases * this subfolder can be skipped. * * It is strongly recommended to overwrite this function so it uses a proper SQL * query and does not create file_info objects (later might require a lot of time * and memory usage on big sites). * * @param string|array $extensions, for example '*' or array('.gif','.jpg') * @param int $limit stop counting after at least $limit non-empty children are found * @return int */ public function count_non_empty_children($extensions = '*', $limit = 1) { $list = $this->get_children(); $cnt = 0; // first loop through files foreach ($list as $fileinfo) { if (!$fileinfo->is_directory()) { if ($extensions !== '*') { $filename = $fileinfo->get_visible_name(); $extension = textlib::strtolower(pathinfo($filename, PATHINFO_EXTENSION)); if (empty($extension) || !in_array('.' . $extension, $extensions)) { continue; } } if (++$cnt >= $limit) { return $cnt; } } } // now loop through directories foreach ($list as $fileinfo) { if ($fileinfo->is_directory() && $fileinfo->count_non_empty_children($extensions)) { if (++$cnt >= $limit) { return $cnt; } } } return $cnt; }
$progress = $completion->get_progress_all( implode(' AND ', $where), $where_params, $group, $firstnamesort ? 'u.firstname ASC' : 'u.lastname ASC', $csv ? 0 : COMPLETION_REPORT_PAGE, $csv ? 0 : $start, $context ); } if ($csv && $grandtotal && count($activities)>0) { // Only show CSV if there are some users/actvs $shortname = format_string($course->shortname, true, array('context' => $context)); header('Content-Disposition: attachment; filename=progress.'. preg_replace('/[^a-z0-9-]/','_',textlib::strtolower(strip_tags($shortname))).'.csv'); // Unicode byte-order mark for Excel if ($excel) { header('Content-Type: text/csv; charset=UTF-16LE'); print chr(0xFF).chr(0xFE); $sep="\t".chr(0); $line="\n".chr(0); } else { header('Content-Type: text/csv; charset=UTF-8'); $sep=","; $line="\n"; } } else { // Use SVG to draw sideways text if supported $svgcleverness = can_use_rotated_text();
} $permissiongranted = 1; if ( $newentry->concept and $newentry->definition ) { if ( !$glossary->allowduplicatedentries ) { // checking if the entry is valid (checking if it is duplicated when should not be) if ( $newentry->casesensitive ) { $dupentry = $DB->record_exists_select('glossary_entries', 'glossaryid = :glossaryid AND concept = :concept', array( 'glossaryid' => $glossary->id, 'concept' => $newentry->concept)); } else { $dupentry = $DB->record_exists_select('glossary_entries', 'glossaryid = :glossaryid AND LOWER(concept) = :concept', array( 'glossaryid' => $glossary->id, 'concept' => textlib::strtolower($newentry->concept))); } if ($dupentry) { $permissiongranted = 0; } } } else { $permissiongranted = 0; } if ($permissiongranted) { $newentry->glossaryid = $glossary->id; $newentry->sourceglossaryid = 0; $newentry->approved = 1; $newentry->userid = $USER->id; $newentry->teacherentry = 1; $newentry->definitionformat = $xmlentry['#']['FORMAT'][0]['#'];
/** * Checks if $query is one of the available webservices * * @param string $query The string to search for * @return bool Returns true if found, false if not */ public function is_related($query) { if (parent::is_related($query)) { return true; } $protocols = get_plugin_list('webservice'); foreach ($protocols as $protocol => $location) { if (strpos($protocol, $query) !== false) { return true; } $protocolstr = get_string('pluginname', 'webservice_' . $protocol); if (strpos(textlib::strtolower($protocolstr), $query) !== false) { return true; } } return false; }
/** * Internal callback function. */ function uu_process_template_callback($username, $firstname, $lastname, $block) { switch ($block[3]) { case 'u': $repl = $username; break; case 'f': $repl = $firstname; break; case 'l': $repl = $lastname; break; default: return $block[0]; } switch ($block[1]) { case '+': $repl = textlib::strtoupper($repl); break; case '-': $repl = textlib::strtolower($repl); break; case '~': $repl = textlib::strtotitle($repl); break; } if (!empty($block[2])) { $repl = textlib::substr($repl, 0, $block[2]); } return $repl; }
/** * Processes and stores configuration data for this authentication plugin. */ function process_config($config) { // Set to defaults if undefined if (!isset($config->host_url)) { $config->host_url = ''; } if (empty($config->ldapencoding)) { $config->ldapencoding = 'utf-8'; } if (!isset($config->contexts)) { $config->contexts = ''; } if (!isset($config->user_type)) { $config->user_type = 'default'; } if (!isset($config->user_attribute)) { $config->user_attribute = ''; } if (!isset($config->search_sub)) { $config->search_sub = ''; } if (!isset($config->opt_deref)) { $config->opt_deref = LDAP_DEREF_NEVER; } if (!isset($config->preventpassindb)) { $config->preventpassindb = 0; } if (!isset($config->bind_dn)) { $config->bind_dn = ''; } if (!isset($config->bind_pw)) { $config->bind_pw = ''; } if (!isset($config->ldap_version)) { $config->ldap_version = '3'; } if (!isset($config->objectclass)) { $config->objectclass = ''; } if (!isset($config->memberattribute)) { $config->memberattribute = ''; } if (!isset($config->memberattribute_isdn)) { $config->memberattribute_isdn = ''; } if (!isset($config->creators)) { $config->creators = ''; } if (!isset($config->create_context)) { $config->create_context = ''; } if (!isset($config->expiration)) { $config->expiration = ''; } if (!isset($config->expiration_warning)) { $config->expiration_warning = '10'; } if (!isset($config->expireattr)) { $config->expireattr = ''; } if (!isset($config->gracelogins)) { $config->gracelogins = ''; } if (!isset($config->graceattr)) { $config->graceattr = ''; } if (!isset($config->auth_user_create)) { $config->auth_user_create = ''; } if (!isset($config->forcechangepassword)) { $config->forcechangepassword = 0; } if (!isset($config->stdchangepassword)) { $config->stdchangepassword = 0; } if (!isset($config->passtype)) { $config->passtype = 'plaintext'; } if (!isset($config->changepasswordurl)) { $config->changepasswordurl = ''; } if (!isset($config->removeuser)) { $config->removeuser = AUTH_REMOVEUSER_KEEP; } if (!isset($config->ntlmsso_enabled)) { $config->ntlmsso_enabled = 0; } if (!isset($config->ntlmsso_subnet)) { $config->ntlmsso_subnet = ''; } if (!isset($config->ntlmsso_ie_fastpath)) { $config->ntlmsso_ie_fastpath = 0; } if (!isset($config->ntlmsso_type)) { $config->ntlmsso_type = 'ntlm'; } // Try to remove duplicates before storing the contexts (to avoid problems in sync_users()). $config->contexts = explode(';', $config->contexts); $config->contexts = array_map(create_function('$x', 'return textlib::strtolower(trim($x));'), $config->contexts); $config->contexts = implode(';', array_unique($config->contexts)); // Save settings set_config('host_url', trim($config->host_url), $this->pluginconfig); set_config('ldapencoding', trim($config->ldapencoding), $this->pluginconfig); set_config('contexts', $config->contexts, $this->pluginconfig); set_config('user_type', textlib::strtolower(trim($config->user_type)), $this->pluginconfig); set_config('user_attribute', textlib::strtolower(trim($config->user_attribute)), $this->pluginconfig); set_config('search_sub', $config->search_sub, $this->pluginconfig); set_config('opt_deref', $config->opt_deref, $this->pluginconfig); set_config('preventpassindb', $config->preventpassindb, $this->pluginconfig); set_config('bind_dn', trim($config->bind_dn), $this->pluginconfig); set_config('bind_pw', $config->bind_pw, $this->pluginconfig); set_config('ldap_version', $config->ldap_version, $this->pluginconfig); set_config('objectclass', trim($config->objectclass), $this->pluginconfig); set_config('memberattribute', textlib::strtolower(trim($config->memberattribute)), $this->pluginconfig); set_config('memberattribute_isdn', $config->memberattribute_isdn, $this->pluginconfig); set_config('creators', trim($config->creators), $this->pluginconfig); set_config('create_context', trim($config->create_context), $this->pluginconfig); set_config('expiration', $config->expiration, $this->pluginconfig); set_config('expiration_warning', trim($config->expiration_warning), $this->pluginconfig); set_config('expireattr', textlib::strtolower(trim($config->expireattr)), $this->pluginconfig); set_config('gracelogins', $config->gracelogins, $this->pluginconfig); set_config('graceattr', textlib::strtolower(trim($config->graceattr)), $this->pluginconfig); set_config('auth_user_create', $config->auth_user_create, $this->pluginconfig); set_config('forcechangepassword', $config->forcechangepassword, $this->pluginconfig); set_config('stdchangepassword', $config->stdchangepassword, $this->pluginconfig); set_config('passtype', $config->passtype, $this->pluginconfig); set_config('changepasswordurl', trim($config->changepasswordurl), $this->pluginconfig); set_config('removeuser', $config->removeuser, $this->pluginconfig); set_config('ntlmsso_enabled', (int) $config->ntlmsso_enabled, $this->pluginconfig); set_config('ntlmsso_subnet', trim($config->ntlmsso_subnet), $this->pluginconfig); set_config('ntlmsso_ie_fastpath', (int) $config->ntlmsso_ie_fastpath, $this->pluginconfig); set_config('ntlmsso_type', $config->ntlmsso_type, 'auth/ldap'); return true; }
public function __authenticate($username, $password, $serviceshortname) { global $CFG, $DB; //echo $OUTPUT->header(); if (!$CFG->enablewebservices) { throw new moodle_exception('enablewsdescription', 'webservice'); } $username = trim(textlib::strtolower($username)); if (is_restored_user($username)) { throw new moodle_exception('restoredaccountresetpassword', 'webservice'); } $user = authenticate_user_login($username, $password); if (!empty($user)) { //Non admin can not authenticate if maintenance mode $hassiteconfig = has_capability('moodle/site:config', context_system::instance(), $user); if (!empty($CFG->maintenance_enabled) and !$hassiteconfig) { throw new moodle_exception('sitemaintenance', 'admin'); } if (isguestuser($user)) { throw new moodle_exception('noguest'); } if (empty($user->confirmed)) { throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username); } // check credential expiry $userauth = get_auth_plugin($user->auth); if (!empty($userauth->config->expiration) and $userauth->config->expiration == 1) { $days2expire = $userauth->password_expire($user->username); if (intval($days2expire) < 0) { throw new moodle_exception('passwordisexpired', 'webservice'); } } // let enrol plugins deal with new enrolments if necessary enrol_check_plugins($user); // setup user session to check capability session_set_user($user); //check if the service exists and is enabled $service = $DB->get_record('external_services', array('shortname' => $serviceshortname, 'enabled' => 1)); if (empty($service)) { // will throw exception if no token found throw new moodle_exception('servicenotavailable', 'webservice'); } //check if there is any required system capability if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) { throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability); } //specific checks related to user restricted service if ($service->restrictedusers) { $authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id, 'userid' => $user->id)); if (empty($authoriseduser)) { throw new moodle_exception('usernotallowed', 'webservice', '', $serviceshortname); } if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) { throw new moodle_exception('invalidtimedtoken', 'webservice'); } if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) { throw new moodle_exception('invalidiptoken', 'webservice'); } } //Check if a token has already been created for this user and this service //Note: this could be an admin created or an user created token. // It does not really matter we take the first one that is valid. $tokenssql = "SELECT t.id, t.sid, t.token, t.validuntil, t.iprestriction\n FROM {external_tokens} t\n WHERE t.userid = ? AND t.externalserviceid = ? AND t.tokentype = ?\n ORDER BY t.timecreated ASC"; $tokens = $DB->get_records_sql($tokenssql, array($user->id, $service->id, EXTERNAL_TOKEN_PERMANENT)); //A bit of sanity checks foreach ($tokens as $key => $token) { /// Checks related to a specific token. (script execution continue) $unsettoken = false; //if sid is set then there must be a valid associated session no matter the token type if (!empty($token->sid)) { $session = session_get_instance(); if (!$session->session_exists($token->sid)) { //this token will never be valid anymore, delete it $DB->delete_records('external_tokens', array('sid' => $token->sid)); $unsettoken = true; } } //remove token if no valid anymore //Also delete this wrong token (similar logic to the web service servers // /webservice/lib.php/webservice_server::authenticate_by_token()) if (!empty($token->validuntil) and $token->validuntil < time()) { $DB->delete_records('external_tokens', array('token' => $token->token, 'tokentype' => EXTERNAL_TOKEN_PERMANENT)); $unsettoken = true; } // remove token if its ip not in whitelist if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) { $unsettoken = true; } if ($unsettoken) { unset($tokens[$key]); } } // if some valid tokens exist then use the most recent if (count($tokens) > 0) { $token = array_pop($tokens); } else { if ($serviceshortname == MOODLE_OFFICIAL_MOBILE_SERVICE and has_capability('moodle/webservice:createmobiletoken', get_system_context()) or !is_siteadmin($user) && has_capability('moodle/webservice:createtoken', get_system_context())) { // if service doesn't exist, dml will throw exception $service_record = $DB->get_record('external_services', array('shortname' => $serviceshortname, 'enabled' => 1), '*', MUST_EXIST); // create a new token $token = new stdClass(); $token->token = md5(uniqid(rand(), 1)); $token->userid = $user->id; $token->tokentype = EXTERNAL_TOKEN_PERMANENT; $token->contextid = context_system::instance()->id; $token->creatorid = $user->id; $token->timecreated = time(); $token->externalserviceid = $service_record->id; $tokenid = $DB->insert_record('external_tokens', $token); add_to_log(SITEID, 'webservice', 'automatically create user token', '', 'User ID: ' . $user->id); $token->id = $tokenid; } else { throw new moodle_exception('cannotcreatetoken', 'webservice', '', $serviceshortname); } } // log token access $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id)); add_to_log(SITEID, 'webservice', 'sending requested user token', '', 'User ID: ' . $user->id); $usertoken = new stdClass(); $usertoken->token = $token->token; //complete login process by activating session. // To restrict the admin user to login into application if (is_siteadmin($user)) { $heIsAdmin = new stdClass(); $heIsAdmin->error = 'admin_user'; echo json_encode($heIsAdmin); die; } Login::__app_complete_user_login($user); $forcePasswordChangesql = "SELECT up.userid\n FROM {user_preferences} up\n WHERE up.userid = ? AND up.name = ? AND up.value = ?"; $forcePasswordChange = $DB->get_records_sql($forcePasswordChangesql, array($user->id, 'auth_forcepasswordchange', 1)); //User Update Profile starts here $admins = get_admins(); $currentAdmin = end($admins); $admintokensql = "SELECT et.token\n FROM {external_tokens} et\n WHERE et.userid = ?"; $currrentAdminToken = $DB->get_records_sql($admintokensql, array($currentAdmin->id), 0, 1); $unique_key = substr(md5(mt_rand(0, 1000000)), 0, 7); $keys = array_keys($currrentAdminToken); $appuser = new stdClass(); $user->token = $token->token; $user->forcePasswordChange = !empty($forcePasswordChange) ? true : false; $user->updateProfile = substr($unique_key, 0, 3) . $keys[0] . substr($unique_key, 3, 7); //Get User role $rolesql = "SELECT id\n FROM {role} \n WHERE shortname = ?"; $roleid = array_values($DB->get_records_sql($rolesql, array('reportuser'))); $reportuser = array_values($DB->get_records_sql("SELECT id FROM {role_assignments} WHERE roleid=" . $roleid[0]->id . " AND userid=" . $user->id . "")); if ($reportuser[0]->id != '') { $user->role = 'reportuser'; } else { $user->role = ''; } //User Update Profile ends here unset($user->password); $appuser->USER = $user; $user->country_value = $user->country; $user->country = get_string($user->country, 'countries'); echo json_encode($appuser); } else { throw new moodle_exception('usernamenotfound', 'moodle'); } }
public function test_deprecated_textlib() { $this->assertSame(textlib::strtolower('HUH'), core_text::strtolower('HUH')); $this->assertDebuggingCalled(null, null, 'This fails if any other test uses the deprecated textlib class.'); }
/** * Renders html to display a name with the link to the course module on a course page * * If module is unavailable for user but still needs to be displayed * in the list, just the name is returned without a link * * Note, that for course modules that never have separate pages (i.e. labels) * this function return an empty string * * @param cm_info $mod * @param array $displayoptions * @return string */ public function course_section_cm_name(cm_info $mod, $displayoptions = array()) { global $CFG; $output = ''; if (!$mod->uservisible && (empty($mod->showavailability) || empty($mod->availableinfo))) { // nothing to be displayed to the user return $output; } $url = $mod->get_url(); if (!$url) { return $output; } //Accessibility: for files get description via icon, this is very ugly hack! $instancename = $mod->get_formatted_name(); $altname = ''; $altname = $mod->modfullname; // Avoid unnecessary duplication: if e.g. a forum name already // includes the word forum (or Forum, etc) then it is unhelpful // to include that in the accessible description that is added. if (false !== strpos(textlib::strtolower($instancename), textlib::strtolower($altname))) { $altname = ''; } // File type after name, for alphabetic lists (screen reader). if ($altname) { $altname = get_accesshide(' ' . $altname); } // For items which are hidden but available to current user // ($mod->uservisible), we show those as dimmed only if the user has // viewhiddenactivities, so that teachers see 'items which might not // be available to some students' dimmed but students do not see 'item // which is actually available to current student' dimmed. $conditionalhidden = $this->is_cm_conditionally_hidden($mod); $accessiblebutdim = (!$mod->visible || $conditionalhidden) && (!$mod->uservisible || has_capability('moodle/course:viewhiddenactivities', context_course::instance($mod->course))); $linkclasses = ''; $accesstext = ''; $textclasses = ''; if ($accessiblebutdim) { $linkclasses .= ' dimmed'; $textclasses .= ' dimmed_text'; if ($conditionalhidden) { $linkclasses .= ' conditionalhidden'; $textclasses .= ' conditionalhidden'; } if ($mod->uservisible) { // show accessibility note only if user can access the module himself $accesstext = get_accesshide(get_string('hiddenfromstudents') . ': '); } } // Get on-click attribute value if specified and decode the onclick - it // has already been encoded for display (puke). $onclick = htmlspecialchars_decode($mod->get_on_click(), ENT_QUOTES); $groupinglabel = ''; if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($mod->course))) { $groupings = groups_get_all_groupings($mod->course); $groupinglabel = html_writer::tag('span', '(' . format_string($groupings[$mod->groupingid]->name) . ')', array('class' => 'groupinglabel ' . $textclasses)); } // Display link itself. $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(), 'class' => 'iconlarge activityicon', 'alt' => $mod->modfullname)) . $accesstext . html_writer::tag('span', $instancename . $altname, array('class' => 'instancename')); if ($mod->uservisible) { $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick)) . $groupinglabel; } else { // We may be displaying this just in order to show information // about visibility, without the actual link ($mod->uservisible) $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses)) . $groupinglabel; } return $output; }
/** * Create a test user * @param array|stdClass $record * @param array $options * @return stdClass user record */ public function create_user($record = null, array $options = null) { global $DB, $CFG; $this->usercounter++; $i = $this->usercounter; $record = (array) $record; if (!isset($record['auth'])) { $record['auth'] = 'manual'; } if (!isset($record['firstname']) and !isset($record['lastname'])) { $country = rand(0, 5); $firstname = rand(0, 4); $lastname = rand(0, 4); $female = rand(0, 1); $record['firstname'] = $this->firstnames[$country * 10 + $firstname + $female * 5]; $record['lastname'] = $this->lastnames[$country * 10 + $lastname + $female * 5]; } else { if (!isset($record['firstname'])) { $record['firstname'] = 'Firstname' . $i; } else { if (!isset($record['lastname'])) { $record['lastname'] = 'Lastname' . $i; } } } if (!isset($record['idnumber'])) { $record['idnumber'] = ''; } if (!isset($record['mnethostid'])) { $record['mnethostid'] = $CFG->mnet_localhost_id; } if (!isset($record['username'])) { $record['username'] = textlib::strtolower($record['firstname']) . textlib::strtolower($record['lastname']); while ($DB->record_exists('user', array('username' => $record['username'], 'mnethostid' => $record['mnethostid']))) { $record['username'] = $record['username'] . '_' . $i; } } if (!isset($record['password'])) { $record['password'] = '******'; } if (!isset($record['email'])) { $record['email'] = $record['username'] . '@example.com'; } if (!isset($record['confirmed'])) { $record['confirmed'] = 1; } if (!isset($record['lang'])) { $record['lang'] = 'en'; } if (!isset($record['maildisplay'])) { $record['maildisplay'] = 1; } if (!isset($record['deleted'])) { $record['deleted'] = 0; } $record['timecreated'] = time(); $record['timemodified'] = $record['timecreated']; $record['lastip'] = '0.0.0.0'; $record['password'] = hash_internal_user_password($record['password']); if ($record['deleted']) { $delname = $record['email'] . '.' . time(); while ($DB->record_exists('user', array('username' => $delname))) { $delname++; } $record['idnumber'] = ''; $record['email'] = md5($record['username']); $record['username'] = $delname; $record['picture'] = 0; } $userid = $DB->insert_record('user', $record); if (!$record['deleted']) { context_user::instance($userid); } return $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST); }
/** * Writes the common <question> data and re-dispateches the whole grouped * <QUESTION> data to the qtype for appending its qtype specific data processing * * @param array $data * @param array $raw * @return array */ public function process_question(array $data, array $raw) { global $CFG; // firstly make sure that the category data and the <questions> wrapper are written // note that because of MDL-27693 we can't use {@link self::process_question_category()} // and {@link self::on_questions_start()} to do so if (empty($this->currentcategorywritten)) { $this->xmlwriter->begin_tag('question_category', array('id' => $this->currentcategory['id'])); foreach ($this->currentcategory as $name => $value) { if ($name === 'id') { continue; } $this->xmlwriter->full_tag($name, $value); } $this->currentcategorywritten = true; } if (empty($this->questionswrapperwritten)) { $this->xmlwriter->begin_tag('questions'); $this->questionswrapperwritten = true; } $qtype = $data['qtype']; // replay the upgrade step 2008050700 {@see question_fix_random_question_parents()} if ($qtype == 'random' and $data['parent'] != $data['id']) { $data['parent'] = $data['id']; } // replay the upgrade step 2010080900 and part of 2010080901 $data['generalfeedbackformat'] = $data['questiontextformat']; $data['oldquestiontextformat'] = $data['questiontextformat']; if ($CFG->texteditors !== 'textarea') { $data['questiontext'] = text_to_html($data['questiontext'], false, false, true); $data['questiontextformat'] = FORMAT_HTML; $data['generalfeedback'] = text_to_html($data['generalfeedback'], false, false, true); $data['generalfeedbackformat'] = FORMAT_HTML; } // Migrate files in questiontext. $this->fileman->contextid = $this->currentcategory['contextid']; $this->fileman->component = 'question'; $this->fileman->filearea = 'questiontext'; $this->fileman->itemid = $data['id']; $data['questiontext'] = moodle1_converter::migrate_referenced_files($data['questiontext'], $this->fileman); // Migrate files in generalfeedback. $this->fileman->filearea = 'generalfeedback'; $data['generalfeedback'] = moodle1_converter::migrate_referenced_files($data['generalfeedback'], $this->fileman); // replay the upgrade step 2010080901 - updating question image if (!empty($data['image'])) { if (textlib::substr(textlib::strtolower($data['image']), 0, 7) == 'http://') { // it is a link, appending to existing question text $data['questiontext'] .= ' <img src="' . $data['image'] . '" />'; } else { // it is a file in course_files $filename = basename($data['image']); $filepath = dirname($data['image']); if (empty($filepath) or $filepath == '.' or $filepath == '/') { $filepath = '/'; } else { // append / $filepath = '/' . trim($filepath, './@#$ ') . '/'; } if (file_exists($this->converter->get_tempdir_path() . '/course_files' . $filepath . $filename)) { $this->fileman->contextid = $this->currentcategory['contextid']; $this->fileman->component = 'question'; $this->fileman->filearea = 'questiontext'; $this->fileman->itemid = $data['id']; $this->fileman->migrate_file('course_files' . $filepath . $filename, '/', $filename); // note this is slightly different from the upgrade code as we put the file into the // root folder here. this makes our life easier as we do not need to create all the // directories within the specified filearea/itemid $data['questiontext'] .= ' <img src="@@PLUGINFILE@@/' . $filename . '" />'; } else { $this->log('question file not found', backup::LOG_WARNING, array($data['id'], $filepath . $filename)); } } } unset($data['image']); // replay the upgrade step 2011060301 - Rename field defaultgrade on table question to defaultmark $data['defaultmark'] = $data['defaultgrade']; // write the common question data $this->xmlwriter->begin_tag('question', array('id' => $data['id'])); foreach (array('parent', 'name', 'questiontext', 'questiontextformat', 'generalfeedback', 'generalfeedbackformat', 'defaultmark', 'penalty', 'qtype', 'length', 'stamp', 'version', 'hidden', 'timecreated', 'timemodified', 'createdby', 'modifiedby') as $fieldname) { if (!array_key_exists($fieldname, $data)) { throw new moodle1_convert_exception('missing_common_question_field', $fieldname); } $this->xmlwriter->full_tag($fieldname, $data[$fieldname]); } // unless we know that the given qtype does not append any own structures, // give the handler a chance to do so now if (!in_array($qtype, array('description', 'random'))) { $handler = $this->get_qtype_handler($qtype); if ($handler === false) { $this->log('question type converter not found', backup::LOG_ERROR, $qtype); } else { $this->xmlwriter->begin_tag('plugin_qtype_' . $qtype . '_question'); $handler->use_xml_writer($this->xmlwriter); $handler->process_question($data, $raw); $this->xmlwriter->end_tag('plugin_qtype_' . $qtype . '_question'); } } $this->xmlwriter->end_tag('question'); }
/** * Returns list of children which are either files matching the specified extensions * or folders that contain at least one such file. * * @param string|array $extensions, either '*' or array of lowercase extensions, i.e. array('.gif','.jpg') * @return array of file_info instances */ public function get_non_empty_children($extensions = '*') { if (!$this->lf->is_directory()) { return array(); } $result = array(); $fs = get_file_storage(); $storedfiles = $fs->get_directory_files($this->context->id, 'course', 'legacy', 0, $this->lf->get_filepath(), false, true, "filepath, filename"); foreach ($storedfiles as $file) { $extension = textlib::strtolower(pathinfo($file->get_filename(), PATHINFO_EXTENSION)); if ($file->is_directory() || $extensions === '*' || !empty($extension) && in_array('.' . $extension, $extensions)) { $fileinfo = new file_info_area_course_legacy($this->browser, $this->context, $file, $this->urlbase, $this->topvisiblename, $this->itemidused, $this->readaccess, $this->writeaccess, false); if (!$file->is_directory() || $fileinfo->count_non_empty_children($extensions)) { $result[] = $fileinfo; } } } return $result; }
public function read_submitted_permissions() { global $DB; $this->errors = array(); // Role short name. We clean this in a special way. We want to end up // with only lowercase safe ASCII characters. $shortname = optional_param('shortname', null, PARAM_RAW); if (!is_null($shortname)) { $this->role->shortname = $shortname; $this->role->shortname = textlib::specialtoascii($this->role->shortname); $this->role->shortname = textlib::strtolower(clean_param($this->role->shortname, PARAM_ALPHANUMEXT)); if (empty($this->role->shortname)) { $this->errors['shortname'] = get_string('errorbadroleshortname', 'role'); } } if ($DB->record_exists_select('role', 'shortname = ? and id <> ?', array($this->role->shortname, $this->roleid))) { $this->errors['shortname'] = get_string('errorexistsroleshortname', 'role'); } // Role name. $name = optional_param('name', null, PARAM_TEXT); if (!is_null($name)) { $this->role->name = $name; // Hack: short names of standard roles are equal to archetypes, empty name means localised via lang packs. $archetypes = get_role_archetypes(); if (!isset($archetypes[$shortname]) and html_is_blank($this->role->name)) { $this->errors['name'] = get_string('errorbadrolename', 'role'); } } if ($this->role->name !== '' and $DB->record_exists_select('role', 'name = ? and id <> ?', array($this->role->name, $this->roleid))) { $this->errors['name'] = get_string('errorexistsrolename', 'role'); } // Description. $description = optional_param('description', null, PARAM_RAW); if (!is_null($description)) { $this->role->description = $description; } // Legacy type. $archetype = optional_param('archetype', null, PARAM_RAW); if (isset($archetype)) { $archetypes = get_role_archetypes(); if (isset($archetypes[$archetype])) { $this->role->archetype = $archetype; } else { $this->role->archetype = ''; } } // Assignable context levels. foreach ($this->allcontextlevels as $cl => $notused) { $assignable = optional_param('contextlevel' . $cl, null, PARAM_BOOL); if (!is_null($assignable)) { if ($assignable) { $this->contextlevels[$cl] = $cl; } else { unset($this->contextlevels[$cl]); } } } // Now read the permissions for each capability. parent::read_submitted_permissions(); }
/** * Given some text (which may contain HTML) and an ideal length, * this function truncates the text neatly on a word boundary if possible * * @category string * @global stdClass $CFG * @param string $text text to be shortened * @param int $ideal ideal string length * @param boolean $exact if false, $text will not be cut mid-word * @param string $ending The string to append if the passed string is truncated * @return string $truncate shortened string */ function shorten_text($text, $ideal = 30, $exact = false, $ending = '...') { global $CFG; // if the plain text is shorter than the maximum length, return the whole text if (textlib::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) { return $text; } // Splits on HTML tags. Each open/close/empty tag will be the first thing // and only tag in its 'line' preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER); $total_length = textlib::strlen($ending); $truncate = ''; // This array stores information about open and close tags and their position // in the truncated string. Each item in the array is an object with fields // ->open (true if open), ->tag (tag name in lower case), and ->pos // (byte position in truncated text) $tagdetails = array(); foreach ($lines as $line_matchings) { // if there is any html-tag in this line, handle it and add it (uncounted) to the output if (!empty($line_matchings[1])) { // if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>) if (preg_match('/^<(\\s*.+?\\/\\s*|\\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\\s.+?)?)>$/is', $line_matchings[1])) { // do nothing // if tag is a closing tag (f.e. </b>) } else { if (preg_match('/^<\\s*\\/([^\\s]+?)\\s*>$/s', $line_matchings[1], $tag_matchings)) { // record closing tag $tagdetails[] = (object) array('open' => false, 'tag' => textlib::strtolower($tag_matchings[1]), 'pos' => textlib::strlen($truncate)); // if tag is an opening tag (f.e. <b>) } else { if (preg_match('/^<\\s*([^\\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) { // record opening tag $tagdetails[] = (object) array('open' => true, 'tag' => textlib::strtolower($tag_matchings[1]), 'pos' => textlib::strlen($truncate)); } } } // add html-tag to $truncate'd text $truncate .= $line_matchings[1]; } // calculate the length of the plain text part of the line; handle entities as one character $content_length = textlib::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); if ($total_length + $content_length > $ideal) { // the number of characters which are left $left = $ideal - $total_length; $entities_length = 0; // search for html entities if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) { // calculate the real length of all entities in the legal range foreach ($entities[0] as $entity) { if ($entity[1] + 1 - $entities_length <= $left) { $left--; $entities_length += textlib::strlen($entity[0]); } else { // no more characters left break; } } } $truncate .= textlib::substr($line_matchings[2], 0, $left + $entities_length); // maximum length is reached, so get off the loop break; } else { $truncate .= $line_matchings[2]; $total_length += $content_length; } // if the maximum length is reached, get off the loop if ($total_length >= $ideal) { break; } } // if the words shouldn't be cut in the middle... if (!$exact) { // ...search the last occurence of a space... for ($k = textlib::strlen($truncate); $k > 0; $k--) { if ($char = textlib::substr($truncate, $k, 1)) { if ($char === '.' or $char === ' ') { $breakpos = $k + 1; break; } else { if (strlen($char) > 2) { // Chinese/Japanese/Korean text $breakpos = $k + 1; // can be truncated at any UTF-8 break; // character boundary. } } } } if (isset($breakpos)) { // ...and cut the text in this position $truncate = textlib::substr($truncate, 0, $breakpos); } } // add the defined ending to the text $truncate .= $ending; // Now calculate the list of open html tags based on the truncate position $open_tags = array(); foreach ($tagdetails as $taginfo) { if (isset($breakpos) && $taginfo->pos >= $breakpos) { // Don't include tags after we made the break! break; } if ($taginfo->open) { // add tag to the beginning of $open_tags list array_unshift($open_tags, $taginfo->tag); } else { $pos = array_search($taginfo->tag, array_reverse($open_tags, true)); // can have multiple exact same open tags, close the last one if ($pos !== false) { unset($open_tags[$pos]); } } } // close all unclosed html-tags foreach ($open_tags as $tag) { $truncate .= '</' . $tag . '>'; } return $truncate; }
/** * Removes excess backups from the external system and the local file system. * * The number of backups keep comes from $config->backup_auto_keep * * @param stdClass $course * @return bool */ public static function remove_excess_backups($course) { $config = get_config('backup'); $keep = (int) $config->backup_auto_keep; $storage = $config->backup_auto_storage; $dir = $config->backup_auto_destination; $backupword = str_replace(' ', '_', textlib::strtolower(get_string('backupfilename'))); $backupword = trim(clean_filename($backupword), '_'); if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) { $dir = null; } // Clean up excess backups in the course backup filearea if ($storage == 0 || $storage == 2) { $fs = get_file_storage(); $context = get_context_instance(CONTEXT_COURSE, $course->id); $component = 'backup'; $filearea = 'automated'; $itemid = 0; $files = array(); // Store all the matching files into timemodified => stored_file array foreach ($fs->get_area_files($context->id, $component, $filearea, $itemid) as $file) { if (strpos($file->get_filename(), $backupword) !== 0) { continue; } $files[$file->get_timemodified()] = $file; } if (count($files) <= $keep) { // There are less matching files than the desired number to keep // do there is nothing to clean up. return 0; } // Sort by keys descending (newer to older filemodified) krsort($files); $remove = array_splice($files, $keep); foreach ($remove as $file) { $file->delete(); } //mtrace('Removed '.count($remove).' old backup file(s) from the automated filearea'); } // Clean up excess backups in the specified external directory if (!empty($dir) && ($storage == 1 || $storage == 2)) { // Calculate backup filename regex, ignoring the date/time/info parts that can be // variable, depending of languages, formats and automated backup settings $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' . $course->id . '-'; $regex = '#^' . preg_quote($filename, '#') . '.*\\.mbz$#'; // Store all the matching files into fullpath => timemodified array $files = array(); foreach (scandir($dir) as $file) { if (preg_match($regex, $file, $matches)) { $files[$file] = filemtime($dir . '/' . $file); } } if (count($files) <= $keep) { // There are less matching files than the desired number to keep // do there is nothing to clean up. return 0; } // Sort by values descending (newer to older filemodified) arsort($files); $remove = array_splice($files, $keep); foreach (array_keys($remove) as $file) { unlink($dir . '/' . $file); } //mtrace('Removed '.count($remove).' old backup file(s) from external directory'); } return true; }
/** * Set whether to show advanced elements in the form on first displaying form. Default is not to * display advanced elements in the form until 'Show Advanced' is pressed. * * You can get the last state of the form and possibly save it for this user by using * value 'mform_showadvanced_last' in submitted data. * * @param bool $showadvancedNow if true will show adavance elements. */ function setShowAdvanced($showadvancedNow = null) { if ($showadvancedNow === null) { if ($this->_showAdvanced !== null) { return; } else { //if setShowAdvanced is called without any preference //make the default to not show advanced elements. $showadvancedNow = get_user_preferences(textlib::strtolower($this->_formName . '_showadvanced', 0)); } } //value of hidden element $hiddenLast = optional_param('mform_showadvanced_last', -1, PARAM_INT); //value of button $buttonPressed = optional_param('mform_showadvanced', 0, PARAM_RAW); //toggle if button pressed or else stay the same if ($hiddenLast == -1) { $next = $showadvancedNow; } elseif ($buttonPressed) { //toggle on button press $next = !$hiddenLast; } else { $next = $hiddenLast; } $this->_showAdvanced = $next; if ($showadvancedNow != $next) { set_user_preference($this->_formName . '_showadvanced', $next); } $this->setConstants(array('mform_showadvanced_last' => $next)); }
if (function_exists('weblink_auth')) { $user = weblink_auth($SESSION->wantsurl); } if ($user) { $frm->username = $user->username; } else { $frm = data_submitted(); } } else { $frm = data_submitted(); } } /// Check if the user has actually submitted login data to us if ($frm and isset($frm->username)) { // Login WITH cookies $frm->username = trim(textlib::strtolower($frm->username)); if (is_enabled_auth('none')) { if ($frm->username !== clean_param($frm->username, PARAM_USERNAME)) { $errormsg = get_string('username') . ': ' . get_string("invalidusername"); $errorcode = 2; $user = null; } } if ($user) { //user already supplied by aut plugin prelogin hook } else { if ($frm->username == 'guest' and empty($CFG->guestloginbutton)) { $user = false; /// Can't log in as guest if guest button is disabled $frm = false; } else {
/** * Used for building the names of the different custom parameters * * @param string $key Parameter name * * @return string Processed name */ function lti_map_keyname($key) { $newkey = ""; $key = textlib::strtolower(trim($key)); foreach (str_split($key) as $ch) { if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) { $newkey .= $ch; } else { $newkey .= '_'; } } return $newkey; }
/** * Prints a section full of activity modules */ function print_section($course, $section, $mods, $modnamesused, $absolute = false, $width = "100%", $hidecompletion = false) { global $CFG, $USER, $DB, $PAGE, $OUTPUT; static $initialised; static $groupbuttons; static $groupbuttonslink; static $isediting; static $ismoving; static $strmovehere; static $strmovefull; static $strunreadpostsone; static $groupings; static $modulenames; if (!isset($initialised)) { $groupbuttons = ($course->groupmode or !$course->groupmodeforce); $groupbuttonslink = !$course->groupmodeforce; $isediting = $PAGE->user_is_editing(); $ismoving = $isediting && ismoving($course->id); if ($ismoving) { $strmovehere = get_string("movehere"); $strmovefull = strip_tags(get_string("movefull", "", "'{$USER->activitycopyname}'")); } $modulenames = array(); $initialised = true; } $modinfo = get_fast_modinfo($course); $completioninfo = new completion_info($course); //Accessibility: replace table with list <ul>, but don't output empty list. if (!empty($section->sequence)) { // Fix bug #5027, don't want style=\"width:$width\". echo "<ul class=\"section img-text\">\n"; $sectionmods = explode(",", $section->sequence); foreach ($sectionmods as $modnumber) { if (empty($mods[$modnumber])) { continue; } /** * @var cm_info */ $mod = $mods[$modnumber]; if ($ismoving and $mod->id == $USER->activitycopy) { // do not display moving mod continue; } if (isset($modinfo->cms[$modnumber])) { // We can continue (because it will not be displayed at all) // if: // 1) The activity is not visible to users // and // 2a) The 'showavailability' option is not set (if that is set, // we need to display the activity so we can show // availability info) // or // 2b) The 'availableinfo' is empty, i.e. the activity was // hidden in a way that leaves no info, such as using the // eye icon. if (!$modinfo->cms[$modnumber]->uservisible && (empty($modinfo->cms[$modnumber]->showavailability) || empty($modinfo->cms[$modnumber]->availableinfo))) { // visibility shortcut continue; } } else { if (!file_exists("{$CFG->dirroot}/mod/{$mod->modname}/lib.php")) { // module not installed continue; } if (!coursemodule_visible_for_user($mod) && empty($mod->showavailability)) { // full visibility check continue; } } if (!isset($modulenames[$mod->modname])) { $modulenames[$mod->modname] = get_string('modulename', $mod->modname); } $modulename = $modulenames[$mod->modname]; // In some cases the activity is visible to user, but it is // dimmed. This is done if viewhiddenactivities is true and if: // 1. the activity is not visible, or // 2. the activity has dates set which do not include current, or // 3. the activity has any other conditions set (regardless of whether // current user meets them) $canviewhidden = has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $mod->id)); $accessiblebutdim = false; if ($canviewhidden) { $accessiblebutdim = !$mod->visible; if (!empty($CFG->enableavailability)) { $accessiblebutdim = $accessiblebutdim || $mod->availablefrom > time() || $mod->availableuntil && $mod->availableuntil < time() || count($mod->conditionsgrade) > 0 || count($mod->conditionscompletion) > 0; } } $liclasses = array(); $liclasses[] = 'activity'; $liclasses[] = $mod->modname; $liclasses[] = 'modtype_' . $mod->modname; $extraclasses = $mod->get_extra_classes(); if ($extraclasses) { $liclasses = array_merge($liclasses, explode(' ', $extraclasses)); } echo html_writer::start_tag('li', array('class' => join(' ', $liclasses), 'id' => 'module-' . $modnumber)); if ($ismoving) { echo '<a title="' . $strmovefull . '"' . ' href="' . $CFG->wwwroot . '/course/mod.php?moveto=' . $mod->id . '&sesskey=' . sesskey() . '">' . '<img class="movetarget" src="' . $OUTPUT->pix_url('movehere') . '" ' . ' alt="' . $strmovehere . '" /></a><br /> '; } $classes = array('mod-indent'); if (!empty($mod->indent)) { $classes[] = 'mod-indent-' . $mod->indent; if ($mod->indent > 15) { $classes[] = 'mod-indent-huge'; } } echo html_writer::start_tag('div', array('class' => join(' ', $classes))); // Get data about this course-module list($content, $instancename) = get_print_section_cm_text($modinfo->cms[$modnumber], $course); //Accessibility: for files get description via icon, this is very ugly hack! $altname = ''; $altname = $mod->modfullname; if (!empty($customicon)) { $archetype = plugin_supports('mod', $mod->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER); if ($archetype == MOD_ARCHETYPE_RESOURCE) { $mimetype = mimeinfo_from_icon('type', $customicon); $altname = get_mimetype_description($mimetype); } } // Avoid unnecessary duplication: if e.g. a forum name already // includes the word forum (or Forum, etc) then it is unhelpful // to include that in the accessible description that is added. if (false !== strpos(textlib::strtolower($instancename), textlib::strtolower($altname))) { $altname = ''; } // File type after name, for alphabetic lists (screen reader). if ($altname) { $altname = get_accesshide(' ' . $altname); } // We may be displaying this just in order to show information // about visibility, without the actual link $contentpart = ''; if ($mod->uservisible) { // Nope - in this case the link is fully working for user $linkclasses = ''; $textclasses = ''; if ($accessiblebutdim) { $linkclasses .= ' dimmed'; $textclasses .= ' dimmed_text'; $accesstext = '<span class="accesshide">' . get_string('hiddenfromstudents') . ': </span>'; } else { $accesstext = ''; } if ($linkclasses) { $linkcss = 'class="' . trim($linkclasses) . '" '; } else { $linkcss = ''; } if ($textclasses) { $textcss = 'class="' . trim($textclasses) . '" '; } else { $textcss = ''; } // Get on-click attribute value if specified $onclick = $mod->get_on_click(); if ($onclick) { $onclick = ' onclick="' . $onclick . '"'; } if ($url = $mod->get_url()) { // Display link itself echo '<a ' . $linkcss . $mod->extra . $onclick . ' href="' . $url . '"><img src="' . $mod->get_icon_url() . '" class="activityicon" alt="' . $modulename . '" /> ' . $accesstext . '<span class="instancename">' . $instancename . $altname . '</span></a>'; // If specified, display extra content after link if ($content) { $contentpart = '<div class="' . trim('contentafterlink' . $textclasses) . '">' . $content . '</div>'; } } else { // No link, so display only content $contentpart = '<div ' . $textcss . $mod->extra . '>' . $accesstext . $content . '</div>'; } if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', get_context_instance(CONTEXT_COURSE, $course->id))) { if (!isset($groupings)) { $groupings = groups_get_all_groupings($course->id); } echo " <span class=\"groupinglabel\">(" . format_string($groupings[$mod->groupingid]->name) . ')</span>'; } } else { $textclasses = $extraclasses; $textclasses .= ' dimmed_text'; if ($textclasses) { $textcss = 'class="' . trim($textclasses) . '" '; } else { $textcss = ''; } $accesstext = '<span class="accesshide">' . get_string('notavailableyet', 'condition') . ': </span>'; if ($url = $mod->get_url()) { // Display greyed-out text of link echo '<div ' . $textcss . $mod->extra . ' >' . '<img src="' . $mod->get_icon_url() . '" class="activityicon" alt="' . $modulename . '" /> <span>' . $instancename . $altname . '</span></div>'; // Do not display content after link when it is greyed out like this. } else { // No link, so display only content (also greyed) $contentpart = '<div ' . $textcss . $mod->extra . '>' . $accesstext . $content . '</div>'; } } // Module can put text after the link (e.g. forum unread) echo $mod->get_after_link(); // If there is content but NO link (eg label), then display the // content here (BEFORE any icons). In this case cons must be // displayed after the content so that it makes more sense visually // and for accessibility reasons, e.g. if you have a one-line label // it should work similarly (at least in terms of ordering) to an // activity. if (empty($url)) { echo $contentpart; } if ($isediting) { if ($groupbuttons and plugin_supports('mod', $mod->modname, FEATURE_GROUPS, 0)) { if (!($mod->groupmodelink = $groupbuttonslink)) { $mod->groupmode = $course->groupmode; } } else { $mod->groupmode = false; } echo ' '; echo make_editing_buttons($mod, $absolute, true, $mod->indent, $section->section); echo $mod->get_after_edit_icons(); } // Completion $completion = $hidecompletion ? COMPLETION_TRACKING_NONE : $completioninfo->is_enabled($mod); if ($completion != COMPLETION_TRACKING_NONE && isloggedin() && !isguestuser() && $mod->uservisible) { $completiondata = $completioninfo->get_data($mod, true); $completionicon = ''; if ($isediting) { switch ($completion) { case COMPLETION_TRACKING_MANUAL: $completionicon = 'manual-enabled'; break; case COMPLETION_TRACKING_AUTOMATIC: $completionicon = 'auto-enabled'; break; default: // wtf } } else { if ($completion == COMPLETION_TRACKING_MANUAL) { switch ($completiondata->completionstate) { case COMPLETION_INCOMPLETE: $completionicon = 'manual-n'; break; case COMPLETION_COMPLETE: $completionicon = 'manual-y'; break; } } else { // Automatic switch ($completiondata->completionstate) { case COMPLETION_INCOMPLETE: $completionicon = 'auto-n'; break; case COMPLETION_COMPLETE: $completionicon = 'auto-y'; break; case COMPLETION_COMPLETE_PASS: $completionicon = 'auto-pass'; break; case COMPLETION_COMPLETE_FAIL: $completionicon = 'auto-fail'; break; } } } if ($completionicon) { $imgsrc = $OUTPUT->pix_url('i/completion-' . $completionicon); $imgalt = s(get_string('completion-alt-' . $completionicon, 'completion', $mod->name)); if ($completion == COMPLETION_TRACKING_MANUAL && !$isediting) { $imgtitle = s(get_string('completion-title-' . $completionicon, 'completion', $mod->name)); $newstate = $completiondata->completionstate == COMPLETION_COMPLETE ? COMPLETION_INCOMPLETE : COMPLETION_COMPLETE; // In manual mode the icon is a toggle form... // If this completion state is used by the // conditional activities system, we need to turn // off the JS. if (!empty($CFG->enableavailability) && condition_info::completion_value_used_as_condition($course, $mod)) { $extraclass = ' preventjs'; } else { $extraclass = ''; } echo "\n<form class='togglecompletion{$extraclass}' method='post' action='" . $CFG->wwwroot . "/course/togglecompletion.php'><div>\n<input type='hidden' name='id' value='{$mod->id}' />\n<input type='hidden' name='modulename' value='" . s($mod->name) . "' />\n<input type='hidden' name='sesskey' value='" . sesskey() . "' />\n<input type='hidden' name='completionstate' value='{$newstate}' />\n<input type='image' src='{$imgsrc}' alt='{$imgalt}' title='{$imgtitle}' />\n</div></form>"; } else { // In auto mode, or when editing, the icon is just an image echo "<span class='autocompletion'>"; echo "<img src='{$imgsrc}' alt='{$imgalt}' title='{$imgalt}' /></span>"; } } } // If there is content AND a link, then display the content here // (AFTER any icons). Otherwise it was displayed before if (!empty($url)) { echo $contentpart; } // Show availability information (for someone who isn't allowed to // see the activity itself, or for staff) if (!$mod->uservisible) { echo '<div class="availabilityinfo">' . $mod->availableinfo . '</div>'; } else { if ($canviewhidden && !empty($CFG->enableavailability)) { $ci = new condition_info($mod); $fullinfo = $ci->get_full_information(); if ($fullinfo) { echo '<div class="availabilityinfo">' . get_string($mod->showavailability ? 'userrestriction_visible' : 'userrestriction_hidden', 'condition', $fullinfo) . '</div>'; } } } echo html_writer::end_tag('div'); echo html_writer::end_tag('li') . "\n"; } } elseif ($ismoving) { echo "<ul class=\"section\">\n"; } if ($ismoving) { echo '<li><a title="' . $strmovefull . '"' . ' href="' . $CFG->wwwroot . '/course/mod.php?movetosection=' . $section->id . '&sesskey=' . sesskey() . '">' . '<img class="movetarget" src="' . $OUTPUT->pix_url('movehere') . '" ' . ' alt="' . $strmovehere . '" /></a></li> '; } if (!empty($section->sequence) || $ismoving) { echo "</ul><!--class='section'-->\n\n"; } }
/** * will update a local user record from an external source. * is a lighter version of the one in moodlelib -- won't do * expensive ops such as enrolment * * If you don't pass $updatekeys, there is a performance hit and * values removed from DB won't be removed from moodle. * * @param string $username username * @param bool $updatekeys * @return stdClass */ function update_user_record($username, $updatekeys = false) { global $CFG, $DB; //just in case check text case $username = trim(textlib::strtolower($username)); // get the current user record $user = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id)); if (empty($user)) { // trouble error_log("Cannot update non-existent user: {$username}"); print_error('auth_dbusernotexist', 'auth_db', $username); die; } // Ensure userid is not overwritten $userid = $user->id; $updated = false; if ($newinfo = $this->get_userinfo($username)) { $newinfo = truncate_userinfo($newinfo); if (empty($updatekeys)) { // all keys? this does not support removing values $updatekeys = array_keys($newinfo); } foreach ($updatekeys as $key) { if (isset($newinfo[$key])) { $value = $newinfo[$key]; } else { $value = ''; } if (!empty($this->config->{'field_updatelocal_' . $key})) { if (isset($user->{$key}) and $user->{$key} != $value) { // only update if it's changed $DB->set_field('user', $key, $value, array('id' => $userid)); $updated = true; } } } } if ($updated) { $DB->set_field('user', 'timemodified', time(), array('id' => $userid)); } return $DB->get_record('user', array('id' => $userid, 'deleted' => 0)); }
function my_link_sort($a, $b) { $a = textlib::strtolower(substr($a->link, strpos($a->link, '>') + 1)); $b = textlib::strtolower(substr($b->link, strpos($b->link, '>') + 1)); return strcmp($a, $b); }
/** * Processes and stores configuration data for this authentication plugin. */ function process_config($config) { // CAS settings if (!isset($config->hostname)) { $config->hostname = ''; } if (!isset($config->port)) { $config->port = ''; } if (!isset($config->casversion)) { $config->casversion = ''; } if (!isset($config->baseuri)) { $config->baseuri = ''; } if (!isset($config->language)) { $config->language = ''; } if (!isset($config->proxycas)) { $config->proxycas = ''; } if (!isset($config->logoutcas)) { $config->logoutcas = ''; } if (!isset($config->multiauth)) { $config->multiauth = ''; } if (!isset($config->certificate_check)) { $config->certificate_check = ''; } if (!isset($config->certificate_path)) { $config->certificate_path = ''; } if (!isset($config->logout_return_url)) { $config->logout_return_url = ''; } // LDAP settings if (!isset($config->host_url)) { $config->host_url = ''; } if (!isset($config->start_tls)) { $config->start_tls = false; } if (empty($config->ldapencoding)) { $config->ldapencoding = 'utf-8'; } if (!isset($config->pagesize)) { $config->pagesize = LDAP_DEFAULT_PAGESIZE; } if (!isset($config->contexts)) { $config->contexts = ''; } if (!isset($config->user_type)) { $config->user_type = 'default'; } if (!isset($config->user_attribute)) { $config->user_attribute = ''; } if (!isset($config->search_sub)) { $config->search_sub = ''; } if (!isset($config->opt_deref)) { $config->opt_deref = LDAP_DEREF_NEVER; } if (!isset($config->bind_dn)) { $config->bind_dn = ''; } if (!isset($config->bind_pw)) { $config->bind_pw = ''; } if (!isset($config->ldap_version)) { $config->ldap_version = '3'; } if (!isset($config->objectclass)) { $config->objectclass = ''; } if (!isset($config->memberattribute)) { $config->memberattribute = ''; } if (!isset($config->memberattribute_isdn)) { $config->memberattribute_isdn = ''; } if (!isset($config->attrcreators)) { $config->attrcreators = ''; } if (!isset($config->groupecreators)) { $config->groupecreators = ''; } if (!isset($config->removeuser)) { $config->removeuser = AUTH_REMOVEUSER_KEEP; } // save CAS settings set_config('hostname', trim($config->hostname), $this->pluginconfig); set_config('port', trim($config->port), $this->pluginconfig); set_config('casversion', $config->casversion, $this->pluginconfig); set_config('baseuri', trim($config->baseuri), $this->pluginconfig); set_config('language', $config->language, $this->pluginconfig); set_config('proxycas', $config->proxycas, $this->pluginconfig); set_config('logoutcas', $config->logoutcas, $this->pluginconfig); set_config('multiauth', $config->multiauth, $this->pluginconfig); set_config('certificate_check', $config->certificate_check, $this->pluginconfig); set_config('certificate_path', $config->certificate_path, $this->pluginconfig); set_config('logout_return_url', $config->logout_return_url, $this->pluginconfig); // save LDAP settings set_config('host_url', trim($config->host_url), $this->pluginconfig); set_config('start_tls', $config->start_tls, $this->pluginconfig); set_config('ldapencoding', trim($config->ldapencoding), $this->pluginconfig); set_config('pagesize', (int) trim($config->pagesize), $this->pluginconfig); set_config('contexts', trim($config->contexts), $this->pluginconfig); set_config('user_type', textlib::strtolower(trim($config->user_type)), $this->pluginconfig); set_config('user_attribute', textlib::strtolower(trim($config->user_attribute)), $this->pluginconfig); set_config('search_sub', $config->search_sub, $this->pluginconfig); set_config('opt_deref', $config->opt_deref, $this->pluginconfig); set_config('bind_dn', trim($config->bind_dn), $this->pluginconfig); set_config('bind_pw', $config->bind_pw, $this->pluginconfig); set_config('ldap_version', $config->ldap_version, $this->pluginconfig); set_config('objectclass', trim($config->objectclass), $this->pluginconfig); set_config('memberattribute', textlib::strtolower(trim($config->memberattribute)), $this->pluginconfig); set_config('memberattribute_isdn', $config->memberattribute_isdn, $this->pluginconfig); set_config('attrcreators', trim($config->attrcreators), $this->pluginconfig); set_config('groupecreators', trim($config->groupecreators), $this->pluginconfig); set_config('removeuser', $config->removeuser, $this->pluginconfig); return true; }
message_send($eventdata); message_paypal_error_to_admin("Payment pending", $data); die; } // If our status is not completed or not pending on an echeck clearance then ignore and die // This check is redundant at present but may be useful if paypal extend the return codes in the future if (!($data->payment_status == "Completed" or $data->payment_status == "Pending" and $data->pending_reason == "echeck")) { die; } // At this point we only proceed with a status of completed or pending with a reason of echeck if ($existing = $DB->get_record("enrol_paypal", array("txn_id" => $data->txn_id))) { // Make sure this transaction doesn't exist already message_paypal_error_to_admin("Transaction {$data->txn_id} is being repeated!", $data); die; } if (textlib::strtolower($data->business) !== textlib::strtolower($plugin->get_config('paypalbusiness'))) { // Check that the email is the one we want it to be message_paypal_error_to_admin("Business email is {$data->business} (not " . $plugin->get_config('paypalbusiness') . ")", $data); die; } if (!($user = $DB->get_record('user', array('id' => $data->userid)))) { // Check that user exists message_paypal_error_to_admin("User {$data->userid} doesn't exist", $data); die; } if (!($course = $DB->get_record('course', array('id' => $data->courseid)))) { // Check that course exists message_paypal_error_to_admin("Course {$data->courseid} doesn't exist", $data); die; } $coursecontext = context_course::instance($course->id, IGNORE_MISSING);
function validation($usernew, $files) { global $CFG, $DB; $usernew = (object)$usernew; $usernew->username = trim($usernew->username); $user = $DB->get_record('user', array('id'=>$usernew->id)); $err = array(); if (!empty($usernew->newpassword)) { $errmsg = '';//prevent eclipse warning if (!check_password_policy($usernew->newpassword, $errmsg)) { $err['newpassword'] = $errmsg; } } if (empty($usernew->username)) { //might be only whitespace $err['username'] = get_string('required'); } else if (!$user or $user->username !== $usernew->username) { //check new username does not exist if ($DB->record_exists('user', array('username'=>$usernew->username, 'mnethostid'=>$CFG->mnet_localhost_id))) { $err['username'] = get_string('usernameexists'); } //check allowed characters if ($usernew->username !== textlib::strtolower($usernew->username)) { $err['username'] = get_string('usernamelowercase'); } else { if ($usernew->username !== clean_param($usernew->username, PARAM_USERNAME)) { $err['username'] = get_string('invalidusername'); } } } if (!$user or $user->email !== $usernew->email) { if (!validate_email($usernew->email)) { $err['email'] = get_string('invalidemail'); } else if ($DB->record_exists('user', array('email'=>$usernew->email, 'mnethostid'=>$CFG->mnet_localhost_id))) { $err['email'] = get_string('emailexists'); } } /// Next the customisable profile fields $err += profile_validation($usernew, $files); if (count($err) == 0){ return true; } else { return $err; } }