function accountprefs_validate(Pieform $form, $values) { global $USER; $authobj = AuthFactory::create($USER->authinstance); if (isset($values['oldpassword'])) { if ($values['oldpassword'] !== '') { global $USER, $authtype, $authclass; if (!$authobj->authenticate_user_account($USER, $values['oldpassword'])) { $form->set_error('oldpassword', get_string('oldpasswordincorrect', 'account')); return; } password_validate($form, $values, $USER); } else { if ($values['password1'] !== '' || $values['password2'] !== '') { $form->set_error('oldpassword', get_string('mustspecifyoldpassword')); } } } if ($authobj->authname == 'internal' && $values['username'] != $USER->get('username')) { if (!AuthInternal::is_username_valid($values['username'])) { $form->set_error('username', get_string('usernameinvalidform', 'auth.internal')); } if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', strtolower($values['username']))) { $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal')); } } }
function is_question_manual_graded($question, $otherquestionsinuse) { if (!$this->selectmanual) { return false; } // We take our best shot at working whether a particular question is manually // graded follows: We look to see if any of the questions that this random // question might select if of a manually graded type. If a category contains // a mixture of manual and non-manual questions, and if all the attempts so // far selected non-manual ones, this will give the wrong answer, but we // don't care. Even so, this is an expensive calculation! $this->init_qtype_lists(); if (!$this->manualqtypes) { return false; } if ($question->questiontext) { $categorylist = question_categorylist($question->category); } else { $categorylist = $question->category; } return record_exists_select('question', "category IN ({$categorylist})\n AND parent = 0\n AND hidden = 0\n AND id NOT IN ({$otherquestionsinuse})\n AND qtype IN ({$this->manualqtypes})"); }
function check_unique($table, $field, $value, $id) { return !record_exists_select($table, "{$field} = '{$value}' AND id <> {$id}"); }
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later * @copyright For copyright information on Mahara, please see the README file distributed with this software. * */ define('INTERNAL', 1); define('JSON', 1); require dirname(dirname(dirname(__FILE__))) . '/init.php'; $result = get_records_sql_array('SELECT a.id, a.title, a.note, (u.profileicon = a.id) AS isdefault, COUNT (DISTINCT aa.artefact) AS attachcount, COUNT(DISTINCT va.view) AS viewcount, COUNT(DISTINCT s.id) AS skincount FROM {artefact} a LEFT OUTER JOIN {view_artefact} va ON va.artefact = a.id LEFT OUTER JOIN {artefact_attachment} aa ON aa.attachment = a.id LEFT OUTER JOIN {skin} s ON (s.bodybgimg = a.id OR s.viewbgimg = a.id) LEFT OUTER JOIN {usr} u ON (u.id = a.owner) WHERE artefacttype = \'profileicon\' AND a.owner = ? GROUP BY a.id, a.title, a.note, isdefault ORDER BY a.id', array($USER->get('id'))); $lastrow = array('id' => 0, 'isdefault' => 't', 'title' => get_string('standardavatartitle', 'artefact.file'), 'note' => get_string('standardavatarnote', 'artefact.file')); $usersdefaulticon = record_exists_select('usr', 'profileicon IS NULL AND id = ?', array($USER->get('id'))); if (!$usersdefaulticon) { $lastrow['isdefault'] = 'f'; } if (!$result) { $result = array(); } $result[] = $lastrow; $data['error'] = false; $data['data'] = $result; $data['count'] = $result ? count($result) : 0; json_reply(false, $data);
/** * Given a username, returns whether the user exists in the usr table * * @param string $username The username to attempt to identify * @return bool Whether the username exists */ public function user_exists($username) { $this->must_be_ready(); if (record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($username)))) { return true; } throw new AuthUnknownUserException("\"{$username}\" is not known to Auth"); }
function adduser_validate(Pieform $form, $values) { global $USER, $TRANSPORTER; $authobj = AuthFactory::create($values['authinstance']); $institution = $authobj->institution; // Institutional admins can only set their own institutions' authinstances if (!$USER->get('admin') && !$USER->is_institutional_admin($authobj->institution)) { $form->set_error('authinstance', get_string('notadminforinstitution', 'admin')); return; } $institution = new Institution($authobj->institution); // Don't exceed max user accounts for the institution if ($institution->isFull()) { $institution->send_admin_institution_is_full_message(); $form->set_error('authinstance', get_string('institutionmaxusersexceeded', 'admin')); return; } $username = $values['username']; $firstname = sanitize_firstname($values['firstname']); $lastname = sanitize_lastname($values['lastname']); $email = sanitize_email($values['email']); $password = $values['password']; if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) { $maxquotaenabled = get_config_plugin('artefact', 'file', 'maxquotaenabled'); $maxquota = get_config_plugin('artefact', 'file', 'maxquota'); if ($maxquotaenabled && $values['quota'] > $maxquota) { $form->set_error('quota', get_string('maxquotaexceededform', 'artefact.file', display_size($maxquota))); } } if (method_exists($authobj, 'is_username_valid_admin')) { if (!$authobj->is_username_valid_admin($username)) { $form->set_error('username', get_string('usernameinvalidadminform', 'auth.internal')); } } else { if (method_exists($authobj, 'is_username_valid')) { if (!$authobj->is_username_valid($username)) { $form->set_error('username', get_string('usernameinvalidform', 'auth.internal')); } } } if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($username)))) { $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal')); } if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) { $form->set_error('password', get_string('passwordinvalidform', 'auth.' . $authobj->type)); } if (isset($_POST['createmethod']) && $_POST['createmethod'] == 'leap2a') { $form->set_error('firstname', null); $form->set_error('lastname', null); $form->set_error('email', null); if (!$values['leap2afile'] && ($_FILES['leap2afile']['error'] == UPLOAD_ERR_INI_SIZE || $_FILES['leap2afile']['error'] == UPLOAD_ERR_FORM_SIZE)) { $form->reply(PIEFORM_ERR, array('message' => get_string('uploadedfiletoobig'), 'goto' => '/admin/users/add.php')); $form->set_error('leap2afile', get_string('uploadedfiletoobig')); return; } else { if (!$values['leap2afile']) { $form->set_error('leap2afile', $form->i18n('rule', 'required', 'required')); return; } } if ($values['leap2afile']['type'] == 'application/octet-stream') { require_once 'file.php'; $mimetype = file_mime_type($values['leap2afile']['tmp_name']); } else { $mimetype = trim($values['leap2afile']['type'], '"'); } $date = time(); $niceuser = preg_replace('/[^a-zA-Z0-9_-]/', '-', $values['username']); safe_require('import', 'leap'); $fakeimportrecord = (object) array('data' => array('importfile' => $values['leap2afile']['tmp_name'], 'importfilename' => $values['leap2afile']['name'], 'importid' => $niceuser . '-' . $date, 'mimetype' => $mimetype)); $TRANSPORTER = new LocalImporterTransport($fakeimportrecord); try { $TRANSPORTER->extract_file(); PluginImportLeap::validate_transported_data($TRANSPORTER); } catch (Exception $e) { $form->set_error('leap2afile', $e->getMessage()); } } else { if (!$form->get_error('firstname') && empty($firstname)) { $form->set_error('firstname', $form->i18n('rule', 'required', 'required')); } if (!$form->get_error('lastname') && empty($lastname)) { $form->set_error('lastname', $form->i18n('rule', 'required', 'required')); } if (!$form->get_error('email')) { if (!$form->get_error('email') && empty($email)) { $form->set_error('email', get_string('invalidemailaddress', 'artefact.internal')); } if (record_exists('usr', 'email', $email) || record_exists('artefact_internal_profile_email', 'email', $email)) { $form->set_error('email', get_string('emailalreadytaken', 'auth.internal')); } } } }
/** * is there a friend relationship between these two users? * * @param int $userid1 * @param int $userid2 */ function is_friend($userid1, $userid2) { return record_exists_select('usr_friend', '(usr1 = ? AND usr2 = ?) OR (usr2 = ? AND usr1 = ?)', array($userid1, $userid2, $userid1, $userid2)); }
public function add_owner_institution_access($instnames = array()) { if (!$this->id) { return false; } $institutions = empty($instnames) ? array_keys(load_user_institutions($this->owner)) : $instnames; if (!empty($institutions)) { db_begin(); foreach ($institutions as $i) { $exists = record_exists_select('view_access', 'view = ? AND institution = ? AND startdate IS NULL AND stopdate IS NULL', array($this->id, $i)); if (!$exists) { $vaccess = new stdClass(); $vaccess->view = $this->id; $vaccess->institution = $i; $vaccess->startdate = null; $vaccess->stopdate = null; $vaccess->allowcomments = 0; $vaccess->approvecomments = 1; $vaccess->ctime = db_format_timestamp(time()); insert_record('view_access', $vaccess); } } db_commit(); } return true; }
/** * Given a username, returns whether the user exists in the usr table * * @param string $username The username to attempt to identify * @return bool Whether the username exists */ public function user_exists($username) { $this->must_be_ready(); $userrecord = false; // The user is likely to be associated with the parent instance if (is_numeric($this->config['parent']) && $this->config['parent'] > 0) { $_instanceid = $this->config['parent']; $userrecord = record_exists_select('usr', 'LOWER(username) = ? and authinstance = ?', array(strtolower($username), $_instanceid)); } if (empty($userrecord)) { $_instanceid = $this->instanceid; $userrecord = record_exists_select('usr', 'LOWER(username) = ? and authinstance = ?', array(strtolower($username), $_instanceid)); } if ($userrecord != false) { return $userrecord; } throw new AuthUnknownUserException("\"{$username}\" is not known to Auth"); }
function site_statistics($full = false) { $data = array(); if ($full) { $data = site_data_current(); $data['weekly'] = true; if (is_postgres()) { $weekago = "CURRENT_DATE - INTERVAL '1 week'"; $thisweeksql = "(lastaccess > {$weekago})::int"; $todaysql = '(lastaccess > CURRENT_DATE)::int'; $eversql = "(NOT lastaccess IS NULL)::int"; } else { $weekago = 'CURRENT_DATE - INTERVAL 1 WEEK'; $thisweeksql = "lastaccess > {$weekago}"; $todaysql = 'lastaccess > CURRENT_DATE'; $eversql = "NOT lastaccess IS NULL"; } $sql = "SELECT SUM({$todaysql}) AS today, SUM({$thisweeksql}) AS thisweek, {$weekago} AS weekago, SUM({$eversql}) AS ever FROM {usr}"; $active = get_record_sql($sql); $data['usersloggedin'] = get_string('loggedinsince', 'admin', $active->today, $active->thisweek, format_date(strtotime($active->weekago), 'strftimedateshort'), $active->ever); $memberships = count_records_sql("\n SELECT COUNT(*)\n FROM {group_member} m JOIN {group} g ON g.id = m.group\n WHERE g.deleted = 0\n "); $data['groupmemberaverage'] = round($memberships / $data['users'], 1); $data['strgroupmemberaverage'] = get_string('groupmemberaverage', 'admin', $data['groupmemberaverage']); $data['viewsperuser'] = get_field_sql("\n SELECT (0.0 + COUNT(id)) / NULLIF(COUNT(DISTINCT \"owner\"), 0)\n FROM {view}\n WHERE NOT \"owner\" IS NULL AND \"owner\" > 0\n "); $data['viewsperuser'] = round($data['viewsperuser'], 1); $data['strviewsperuser'] = get_string('viewsperuser', 'admin', $data['viewsperuser']); } $data['name'] = get_config('sitename'); $data['release'] = get_config('release'); $data['version'] = get_config('version'); $data['installdate'] = format_date(strtotime(get_config('installation_time')), 'strftimedate'); $data['dbsize'] = db_total_size(); $data['diskusage'] = get_field('site_data', 'value', 'type', 'disk-usage'); $data['cronrunning'] = !record_exists_select('cron', 'nextrun IS NULL OR nextrun < CURRENT_DATE'); $data['siteclosedbyadmin'] = get_config('siteclosedbyadmin'); if ($latestversion = get_config('latest_version')) { $data['latest_version'] = $latestversion; if ($data['release'] == $latestversion) { $data['strlatestversion'] = get_string('uptodate', 'admin'); } else { $download_page = 'https://launchpad.net/mahara/+download'; $data['strlatestversion'] = get_string('latestversionis', 'admin', $download_page, $latestversion); } } return $data; }
} elseif (intval($days2expire) < 0) { print_header("{$site->fullname}: {$loginsite}", "{$site->fullname}", $navigation, '', '', true, "<div class=\"langmenu\">{$langmenu}</div>"); notice_yesno(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo); print_footer(); exit; } } reset_login_count(); redirect($urltogo); exit; } else { if (empty($errormsg)) { $errormsg = get_string("invalidlogin"); $errorcode = 3; } if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode === 'strict' && is_enabled_auth('mnet') && record_exists_sql("SELECT h.id FROM {$CFG->prefix}mnet_host h\n INNER JOIN {$CFG->prefix}mnet_host2service m ON h.id=m.hostid\n INNER JOIN {$CFG->prefix}mnet_service s ON s.id=m.serviceid\n WHERE s.name='sso_sp' AND h.deleted=0 AND m.publish = 1") && record_exists_select('user', "username = '******' AND mnethostid != {$CFG->mnet_localhost_id}")) { $errormsg .= get_string('loginlinkmnetuser', 'mnet', "mnet_email.php?u={$frm->username}"); } } } } /// Detect problems with timedout sessions if ($session_has_timed_out and !data_submitted()) { $errormsg = get_string('sessionerroruser', 'error'); $errorcode = 4; } /// First, let's remember where the user was trying to get to before they got here if (empty($SESSION->wantsurl)) { $SESSION->wantsurl = array_key_exists('HTTP_REFERER', $_SERVER) && $_SERVER["HTTP_REFERER"] != $CFG->wwwroot && $_SERVER["HTTP_REFERER"] != $CFG->wwwroot . '/' && $_SERVER["HTTP_REFERER"] != $CFG->httpswwwroot . '/login/' && $_SERVER["HTTP_REFERER"] != $CFG->httpswwwroot . '/login/index.php' ? $_SERVER["HTTP_REFERER"] : NULL; } /// Redirect to alternative login URL if needed
/** * Determine whether a view is accessible by a given token */ function view_has_token($view, $token) { if (!$view || !$token) { return false; } return record_exists_select('view_access', 'view = ? AND token = ? AND visible = ? AND (startdate IS NULL OR startdate < current_timestamp) AND (stopdate IS NULL OR stopdate > current_timestamp)', array($view, $token, (int) $visible)); }
/** * Adds a user to a group if appropriate * Note: does not check permissions * * @param int $groupid The id of the appropriate group * @param int $userid The id of the user to add */ function cluster_groups_add_member($groupid, $userid) { if ($group_record = get_record('groups', 'id', $groupid)) { //this works even for the site-level "course" $context = get_context_instance(CONTEXT_COURSE, $group_record->courseid); $filter = get_related_contexts_string($context); //if the user doesn't have an appropriate role, a group assignment //will not work, so avoid assigning in that case $select = "userid = {$userid} and contextid {$filter}"; if (!record_exists_select('role_assignments', $select)) { return; } groups_add_member($groupid, $userid); } }
public function read_submitted_permissions() { $this->errors = array(); // Role name. $name = optional_param('name', null, PARAM_MULTILANG); if (!is_null($name)) { $this->role->name = $name; if (html_is_blank($this->role->name)) { $this->errors['name'] = get_string('errorbadrolename', 'role'); } } if (record_exists_select('role', "name = '" . addslashes($this->role->name) . "' AND id != {$this->roleid}")) { $this->errors['name'] = get_string('errorexistsrolename', 'role'); } // 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_get_instance()->specialtoascii($this->role->shortname); $this->role->shortname = moodle_strtolower(clean_param($this->role->shortname, PARAM_ALPHANUMEXT)); if (empty($this->role->shortname)) { $this->errors['shortname'] = get_string('errorbadroleshortname', 'role'); } } if (record_exists_select('role', "shortname = '" . addslashes($this->role->shortname) . "' AND id != {$this->roleid}")) { $this->errors['shortname'] = get_string('errorexistsroleshortname', 'role'); } // Description. $description = optional_param('description', null, PARAM_CLEAN); if (!is_null($description)) { $this->role->description = $description; } // Legacy type. $legacytype = optional_param('legacytype', null, PARAM_RAW); if (!is_null($legacytype)) { if (array_key_exists($legacytype, $this->legacyroles)) { $this->role->legacytype = $legacytype; } else { $this->role->legacytype = ''; } } // 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(); }
/** * @param integer $quizid the id of the quiz object. * @return boolean Whether this quiz has any non-blank feedback text. */ function quiz_has_feedback($quizid) { static $cache = array(); if (!array_key_exists($quizid, $cache)) { $cache[$quizid] = record_exists_select('quiz_feedback', "quizid = {$quizid} AND feedbacktext <> ''"); } return $cache[$quizid]; }
} $significantchangemade = true; } /// Delete any teacher preview attempts if the quiz has been modified if ($significantchangemade) { $previewattempts = get_records_select('quiz_attempts', 'quiz = ' . $quiz->id . ' AND preview = 1'); if ($previewattempts) { foreach ($previewattempts as $attempt) { quiz_delete_attempt($attempt, $quiz); } } } question_showbank_actions($thispageurl, $cm); /// all commands have been dealt with, now print the page // Print basic page layout. if (isset($quiz->instance) and record_exists_select('quiz_attempts', "quiz = '{$quiz->instance}' AND preview = '0'")) { // one column layout with table of questions used in this quiz $strupdatemodule = has_capability('moodle/course:manageactivities', $contexts->lowest()) ? update_module_button($cm->id, $course->id, get_string('modulename', 'quiz')) : ""; $navigation = build_navigation($streditingquiz, $cm); print_header_simple($streditingquiz, '', $navigation, "", "", true, $strupdatemodule); $currenttab = 'edit'; $mode = 'editq'; include 'tabs.php'; print_box_start(); echo "<div class=\"quizattemptcounts\">\n"; echo '<a href="report.php?mode=overview&id=' . $cm->id . '">' . quiz_num_attempt_summary($quiz, $cm) . '</a><br />' . get_string('cannoteditafterattempts', 'quiz'); echo "</div>\n"; $sumgrades = quiz_print_question_list($quiz, $thispageurl, false, $quiz_showbreaks, $quiz_reordertool); if (!set_field('quiz', 'sumgrades', $sumgrades, 'id', $quiz->instance)) { error('Failed to set sumgrades'); }
/** * Can the current user delete this course? * Course creators have exception, * 1 day after the creation they can sill delete the course. * @param int $courseid * @return boolean */ function can_delete_course($courseid) { global $USER; $context = get_context_instance(CONTEXT_COURSE, $courseid); if (has_capability('moodle/course:delete', $context)) { return true; } // hack: now try to find out if creator created this course recently (1 day) if (!has_capability('moodle/course:create', $context)) { return false; } $since = time() - 60 * 60 * 24; $select = "module = 'course' AND action = 'new' AND userid = {$USER->id} AND url='view.php?id={$courseid}' AND time > {$since}"; return record_exists_select('log', $select); }
function test_record_exists_select() { $this->assertTrue(record_exists_select($this->table, 'numberfield = 101 AND id = 1')); $this->assertFalse(record_exists_select($this->table, 'numberfield = 102 AND id = 1')); $this->assertTrue(record_exists_select($this->table, 'numberfield IS NULL')); }
function exists() { return record_exists_select('question', "qtype = 'random' AND parent <> id"); }
/** * Determines whether the current user is allowed to create, edit, and delete associations * between a user and a class * * @param int $userid The id of the user being associated to the class * @param int $classid The id of the class we are associating the user to * * @return boolean True if the current user has the required permissions, otherwise false */ public static function can_manage_assoc($userid, $classid) { global $USER; if (!cmclasspage::can_enrol_into_class($classid)) { //the users who satisfty this condition are a superset of those who can manage associations return false; } else { if (cmclasspage::_has_capability('block/curr_admin:track:enrol', $classid)) { //current user has the direct capability return true; } } //get the context for the "indirect" capability $context = cm_context_set::for_user_with_capability('cluster', 'block/curr_admin:class:enrol_cluster_user', $USER->id); $allowed_clusters = array(); $allowed_clusters = cmclass::get_allowed_clusters($classid); //query to get users associated to at least one enabling cluster $cluster_select = ''; if (empty($allowed_clusters)) { $cluster_select = '0=1'; } else { $cluster_select = 'clusterid IN (' . implode(',', $allowed_clusters) . ')'; } $select = "userid = {$userid} AND {$cluster_select}"; //user just needs to be in one of the possible clusters if (record_exists_select(CLSTUSERTABLE, $select)) { return true; } return false; }
/** * The CSV file is parsed here so validation errors can be returned to the * user. The data from a successful parsing is stored in the <var>$CVSDATA</var> * array so it can be accessed by the submit function * * @param Pieform $form The form to validate * @param array $values The values submitted */ function uploadcsv_validate(Pieform $form, $values) { global $CSVDATA, $ALLOWEDKEYS, $FORMAT, $USER, $INSTITUTIONNAME, $UPDATES; // Don't even start attempting to parse if there are previous errors if ($form->has_errors()) { return; } if ($values['file']['size'] == 0) { $form->set_error('file', $form->i18n('rule', 'required', 'required', array())); return; } if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) { $maxquotaenabled = get_config_plugin('artefact', 'file', 'maxquotaenabled'); $maxquota = get_config_plugin('artefact', 'file', 'maxquota'); if ($maxquotaenabled && $values['quota'] > $maxquota) { $form->set_error('quota', get_string('maxquotaexceededform', 'artefact.file', display_size($maxquota))); } } require_once 'csvfile.php'; $authinstance = (int) $values['authinstance']; $institution = get_field('auth_instance', 'institution', 'id', $authinstance); if (!$USER->can_edit_institution($institution)) { $form->set_error('authinstance', get_string('notadminforinstitution', 'admin')); return; } //OVERWRITE 2: add $authname = get_field('auth_instance', 'authname', 'id', $authinstance); if ($authname != 'internal') { $form->set_error('authinstance', get_string('notadminforinstitution', 'admin')); return; } //END OVERWRITE 2 $authobj = AuthFactory::create($authinstance); $csvusers = new CsvFile($values['file']['tmp_name']); $csvusers->set('allowedkeys', $ALLOWEDKEYS); // Now we know all of the field names are valid, we need to make // sure that the required fields are included $mandatoryfields = array('username', 'email', 'firstname', 'lastname'); if (!$values['updateusers']) { $mandatoryfields[] = 'password'; } $csvusers->set('mandatoryfields', $mandatoryfields); $csvdata = $csvusers->get_data(); if (!empty($csvdata->errors['file'])) { $form->set_error('file', $csvdata->errors['file']); return; } $csverrors = new CSVErrors(); $formatkeylookup = array_flip($csvdata->format); // First pass validates usernames & passwords in the file, and builds // up a list indexed by username. $emails = array(); if (isset($formatkeylookup['remoteuser'])) { $remoteusers = array(); } $maxcsvlines = get_config('maxusercsvlines'); if ($maxcsvlines && $maxcsvlines < count($csvdata->data)) { $form->set_error('file', get_string('uploadcsverrortoomanyusers', 'admin', get_string('nusers', 'mahara', $maxcsvlines))); return; } foreach ($csvdata->data as $key => $line) { // If headers exists, increment i = key + 2 for actual line number $i = $csvusers->get('headerExists') ? $key + 2 : $key + 1; // Trim non-breaking spaces -- they get left in place by File_CSV foreach ($line as &$field) { $field = preg_replace('/^(\\s|\\xc2\\xa0)*(.*?)(\\s|\\xc2\\xa0)*$/', '$2', $field); } if (count($line) != count($csvdata->format)) { $csverrors->add($i, get_string('uploadcsverrorwrongnumberoffields', 'admin', $i)); continue; } // We have a line with the correct number of fields, but should validate these fields // Note: This validation should really be methods on each profile class, that way // it can be used in the profile screen as well. $username = $line[$formatkeylookup['username']]; $password = isset($formatkeylookup['password']) ? $line[$formatkeylookup['password']] : null; $email = $line[$formatkeylookup['email']]; if (isset($remoteusers)) { $remoteuser = strlen($line[$formatkeylookup['remoteuser']]) ? $line[$formatkeylookup['remoteuser']] : null; } if (method_exists($authobj, 'is_username_valid_admin')) { if (!$authobj->is_username_valid_admin($username)) { $csverrors->add($i, get_string('uploadcsverrorinvalidusername', 'admin', $i)); } } else { if (method_exists($authobj, 'is_username_valid')) { if (!$authobj->is_username_valid($username)) { $csverrors->add($i, get_string('uploadcsverrorinvalidusername', 'admin', $i)); } } } if (!$values['updateusers']) { // Note: only checks for valid form are done here, none of the checks // like whether the password is too easy. The user is going to have to // change their password on first login anyway. if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) { $csverrors->add($i, get_string('uploadcsverrorinvalidpassword', 'admin', $i)); } } // OVERWRITE 3: replacement, changed from: //if (isset($emails[$email])) { // // Duplicate email within this file. // $csverrors->add($i, get_string('uploadcsverroremailaddresstaken', 'admin', $i, $email)); //} //else if (!PHPMailer::ValidateAddress($email)) { // $csverrors->add($i, get_string('uploadcsverrorinvalidemail', 'admin', $i, $email)); //} //else if (!$values['updateusers']) { // // The email address must be new // if (record_exists('usr', 'email', $email) || record_exists('artefact_internal_profile_email', 'email', $email, 'verified', 1)) { // $csverrors->add($i, get_string('uploadcsverroremailaddresstaken', 'admin', $i, $email)); // } //} //$emails[$email] = 1; // TO: if (isset($emails[strtolower($email)])) { // Duplicate email within this file. $csverrors->add($i, get_string('uploadcsverroremailaddresstaken', 'admin', $i, $email)); } else { if (!PHPMailer::ValidateAddress($email)) { $csverrors->add($i, get_string('uploadcsverrorinvalidemail', 'admin', $i, $email)); } else { if (!$values['updateusers']) { // The email address must be new if (GcrInstitutionTable::isEmailAddressUsed($email)) { $csverrors->add($i, get_string('uploadcsverroremailaddresstaken', 'admin', $i, $email)); } } } } $emails[strtolower($email)] = 1; // END OVERWRITE 3 if (isset($remoteusers) && $remoteuser) { if (isset($remoteusers[$remoteuser])) { $csverrors->add($i, get_string('uploadcsverrorduplicateremoteuser', 'admin', $i, $remoteuser)); } else { if (!$values['updateusers']) { if ($remoteuserowner = get_record_sql(' SELECT u.username FROM {auth_remote_user} aru JOIN {usr} u ON aru.localusr = u.id WHERE aru.remoteusername = ? AND aru.authinstance = ?', array($remoteuser, $authinstance))) { $csverrors->add($i, get_string('uploadcsverrorremoteusertaken', 'admin', $i, $remoteuser, $remoteuserowner->username)); } } } $remoteusers[$remoteuser] = true; } // If we didn't even get a username, we can't check for duplicates, so move on. if (strlen($username) < 1) { continue; } if (isset($usernames[strtolower($username)])) { // Duplicate username within this file. $csverrors->add($i, get_string('uploadcsverroruseralreadyexists', 'admin', $i, $username)); } else { if (!$values['updateusers'] && record_exists_select('usr', 'LOWER(username) = ?', strtolower($username))) { $csverrors->add($i, get_string('uploadcsverroruseralreadyexists', 'admin', $i, $username)); } $usernames[strtolower($username)] = array('username' => $username, 'password' => $password, 'email' => $email, 'lineno' => $i, 'raw' => $line); if (!empty($remoteuser) && !empty($remoteusers[$remoteuser])) { $usernames[strtolower($username)]['remoteuser'] = $remoteuser; } } } // If the admin is trying to overwrite existing users, identified by username, // this second pass performs some additional checks if ($values['updateusers']) { foreach ($usernames as $lowerusername => $data) { $line = $data['lineno']; $username = $data['username']; $password = $data['password']; $email = $data['email']; // If the user already exists, they must already be in this institution. $userinstitutions = get_records_sql_assoc("\n SELECT COALESCE(ui.institution, 'mahara') AS institution, u.id\n FROM {usr} u LEFT JOIN {usr_institution} ui ON u.id = ui.usr\n WHERE LOWER(u.username) = ?", array($lowerusername)); if ($userinstitutions) { if (!isset($userinstitutions[$institution])) { if ($institution == 'mahara') { $institutiondisplay = array(); foreach ($userinstitutions as $i) { $institutiondisplay[] = $INSTITUTIONNAME[$i->institution]; } $institutiondisplay = join(', ', $institutiondisplay); $message = get_string('uploadcsverroruserinaninstitution', 'admin', $line, $username, $institutiondisplay); } else { $message = get_string('uploadcsverrorusernotininstitution', 'admin', $line, $username, $INSTITUTIONNAME[$institution]); } $csverrors->add($line, $message); } else { // Remember that this user is being updated $UPDATES[$username] = 1; } } else { // New user, check the password if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) { $csverrors->add($line, get_string('uploadcsverrorinvalidpassword', 'admin', $line)); } } // Check if the email already exists and if it's owned by this user. This query can return more // than one row when there are duplicate emails already on the site. If that happens, things are // already a bit out of hand, and we'll just allow an update if this user is one of the users who // owns the email. $emailowned = get_records_sql_assoc(' SELECT LOWER(u.username) AS lowerusername, ae.principal FROM {usr} u LEFT JOIN {artefact_internal_profile_email} ae ON u.id = ae.owner AND ae.verified = 1 AND ae.email = ? WHERE ae.owner IS NOT NULL OR u.email = ?', array($email, $email)); // If the email is owned by someone else, it could still be okay provided // that other user's email is also being changed in this csv file. if ($emailowned && !isset($emailowned[$lowerusername])) { foreach ($emailowned as $e) { // Only primary emails can be set in uploadcsv, so it's an error when someone else // owns the email as a secondary. if (!$e->principal) { $csverrors->add($line, get_string('uploadcsverroremailaddresstaken', 'admin', $line, $email)); break; } // It's also an error if the email owner is not being updated in this file if (!isset($usernames[$e->lowerusername])) { $csverrors->add($line, get_string('uploadcsverroremailaddresstaken', 'admin', $line, $email)); break; } // If the other user is being updated in this file, but isn't changing their // email address, it's ok, we've already notified duplicate emails within the file. } } if (isset($remoteusers) && !empty($data['remoteuser'])) { $remoteuser = $data['remoteuser']; $remoteuserowner = get_field_sql(' SELECT LOWER(u.username) FROM {usr} u JOIN {auth_remote_user} aru ON u.id = aru.localusr WHERE aru.remoteusername = ? AND aru.authinstance = ?', array($remoteuser, $authinstance)); if ($remoteuserowner && $remoteuserowner != $lowerusername && !isset($usernames[$remoteuserowner])) { // The remote username is owned by some other user who is not being updated in this file $csverrors->add($line, get_string('uploadcsverrorremoteusertaken', 'admin', $line, $remoteuser, $remoteuserowner)); } } } } if ($errors = $csverrors->process()) { $form->set_error('file', clean_html($errors), false); return; } $FORMAT = $csvdata->format; $CSVDATA = $csvdata->data; }
/** * Create a test user * @param array $record * @throws SystemException if creating failed * @return int new user id */ public function create_user($record) { // Data validation // Set default auth method for a new user is 'internal' for 'No institution' if not set if (empty($record['institution']) || empty($record['authname'])) { $record['institution'] = 'mahara'; $record['authname'] = 'internal'; } if (!($auth = get_record('auth_instance', 'institution', $record['institution'], 'authname', $record['authname']))) { throw new SystemException("The authentication method authname" . $record['authname'] . " for institution '" . $record['institution'] . "' does not exist."); } $record['authinstance'] = $auth->id; // Don't exceed max user accounts for the institution $institution = new Institution($record['institution']); if ($institution->isFull()) { throw new SystemException("Can not add new users to the institution '" . $record['institution'] . "' as it is full."); } $record['firstname'] = sanitize_firstname($record['firstname']); $record['lastname'] = sanitize_lastname($record['lastname']); $record['email'] = sanitize_email($record['email']); $authobj = AuthFactory::create($auth->id); if (method_exists($authobj, 'is_username_valid_admin') && !$authobj->is_username_valid_admin($record['username'])) { throw new SystemException("New username'" . $record['username'] . "' is not valid."); } if (method_exists($authobj, 'is_username_valid') && !$authobj->is_username_valid($record['username'])) { throw new SystemException("New username'" . $record['username'] . "' is not valid."); } if (record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($record['username'])))) { throw new ErrorException("The username'" . $record['username'] . "' has been taken."); } if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($record['password'])) { throw new ErrorException("The password'" . $record['password'] . "' is not valid."); } if (record_exists('usr', 'email', $record['email']) || record_exists('artefact_internal_profile_email', 'email', $record['email'])) { throw new ErrorException("The email'" . $record['email'] . "' has been taken."); } // Create new user db_begin(); raise_time_limit(180); $user = (object) array('authinstance' => $record['authinstance'], 'username' => $record['username'], 'firstname' => $record['firstname'], 'lastname' => $record['lastname'], 'email' => $record['email'], 'password' => $record['password'], 'passwordchange' => 0); if ($record['institution'] == 'mahara') { if ($record['role'] == 'admin') { $user->admin = 1; } else { if ($record['role'] == 'staff') { $user->staff = 1; } } } $remoteauth = $record['authname'] != 'internal'; if (!isset($record['remoteusername'])) { $record['remoteusername'] = null; } $user->id = create_user($user, array(), $record['institution'], $remoteauth, $record['remoteusername'], $record); if (isset($user->admin) && $user->admin) { require_once 'activity.php'; activity_add_admin_defaults(array($user->id)); } if ($record['institution'] != 'mahara') { if ($record['role'] == 'admin') { set_field('usr_institution', 'admin', 1, 'usr', $user->id, 'institution', $record['institution']); } else { if ($record['role'] == 'staff') { set_field('usr_institution', 'staff', 1, 'usr', $user->id, 'institution', $record['institution']); } } } db_commit(); $this->usercounter++; return $user->id; }
function edituser_site_validate(Pieform $form, $values) { global $USER, $SESSION; if (!($user = get_record('usr', 'id', $values['id']))) { return false; } if ($USER->get('admin') || get_config_plugin('artefact', 'file', 'institutionaloverride')) { $maxquotaenabled = get_config_plugin('artefact', 'file', 'maxquotaenabled'); $maxquota = get_config_plugin('artefact', 'file', 'maxquota'); if ($maxquotaenabled && $values['quota'] > $maxquota) { $form->set_error('quota', get_string('maxquotaexceededform', 'artefact.file', display_size($maxquota))); $SESSION->add_error_msg(get_string('maxquotaexceeded', 'artefact.file', display_size($maxquota))); } } $userobj = new User(); $userobj = $userobj->find_by_id($user->id); if (isset($values['username']) && !empty($values['username']) && $values['username'] != $userobj->username) { if (!isset($values['authinstance'])) { $authobj = AuthFactory::create($userobj->authinstance); } else { $authobj = AuthFactory::create($values['authinstance']); } if (method_exists($authobj, 'change_username')) { if (method_exists($authobj, 'is_username_valid_admin')) { if (!$authobj->is_username_valid_admin($values['username'])) { $form->set_error('username', get_string('usernameinvalidadminform', 'auth.internal')); } } else { if (method_exists($authobj, 'is_username_valid')) { if (!$authobj->is_username_valid($values['username'])) { $form->set_error('username', get_string('usernameinvalidform', 'auth.internal')); } } } if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', strtolower($values['username']))) { $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal')); } } else { $form->set_error('username', get_string('usernamechangenotallowed', 'admin')); } } // OVERWRITE 3: insert if (isset($values['email']) && !empty($values['email']) && $values['email'] != $userobj->email) { $email = sanitize_email($values['email']); if ($email == '') { $form->set_error('email', get_string('invalidemailaddress', 'artefact.internal')); } else { $values['email'] = $email; } if (GcrInstitutionTable::isEmailAddressUsed($email)) { $form->set_error('email', get_string('emailalreadytaken', 'auth.internal')); } } // END OVERWITE 3 // Check that the external username isn't already in use by someone else if (isset($values['authinstance']) && isset($values['remoteusername'])) { // there are 4 cases for changes on the page // 1) ai and remoteuser have changed // 2) just ai has changed // 3) just remoteuser has changed // 4) the ai changes and the remoteuser is wiped - this is a delete of the old ai-remoteuser // determine the current remoteuser $current_remotename = get_field('auth_remote_user', 'remoteusername', 'authinstance', $user->authinstance, 'localusr', $user->id); if (!$current_remotename) { $current_remotename = $user->username; } // what should the new remoteuser be $new_remoteuser = get_field('auth_remote_user', 'remoteusername', 'authinstance', $values['authinstance'], 'localusr', $user->id); if (!$new_remoteuser) { $new_remoteuser = $user->username; } if (strlen(trim($values['remoteusername'])) > 0) { // value changed on page - use it if ($values['remoteusername'] != $current_remotename) { $new_remoteuser = $values['remoteusername']; } } // what really counts is who owns the target remoteuser slot $target_owner = get_field('auth_remote_user', 'localusr', 'authinstance', $values['authinstance'], 'remoteusername', $new_remoteuser); // target remoteuser is owned by someone else if ($target_owner && $target_owner != $user->id) { $usedbyuser = get_field('usr', 'username', 'id', $target_owner); $SESSION->add_error_msg(get_string('duplicateremoteusername', 'auth', $usedbyuser)); $form->set_error('remoteusername', get_string('duplicateremoteusernameformerror', 'auth')); } } }
function accountprefs_validate(Pieform $form, $values) { global $USER; $authobj = AuthFactory::create($USER->authinstance); if (isset($values['oldpassword'])) { if ($values['oldpassword'] !== '') { global $USER, $authtype, $authclass; try { if (!$authobj->authenticate_user_account($USER, $values['oldpassword'])) { $form->set_error('oldpassword', get_string('oldpasswordincorrect', 'account')); return; } } catch (UserException $e) { $form->set_error('oldpassword', $e->getMessage()); return; } password_validate($form, $values, $USER); } else { if ($values['password1'] !== '' || $values['password2'] !== '') { $form->set_error('oldpassword', get_string('mustspecifyoldpassword')); } } } if ($authobj->authname == 'internal' && $values['username'] != $USER->get('username')) { if (!AuthInternal::is_username_valid($values['username'])) { $form->set_error('username', get_string('usernameinvalidform', 'auth.internal')); } if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', array(strtolower($values['username'])))) { $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal')); } } if (isset($values['urlid']) && get_config('cleanurls') && $values['urlid'] != $USER->get('urlid')) { if (strlen($values['urlid']) < 3) { $form->set_error('urlid', get_string('rule.minlength.minlength', 'pieforms', 3)); } else { if (record_exists('usr', 'urlid', $values['urlid'])) { $form->set_error('urlid', get_string('urlalreadytaken', 'account')); } } } if (get_config('allowmobileuploads')) { foreach ($values['mobileuploadtoken'] as $k => $text) { if (strlen($text) > 0 && !preg_match('/^[a-zA-Z0-9 !@#$%^&*()\\-_=+\\[{\\]};:\'",<\\.>\\/?]{6,}$/', $text)) { $form->set_error('mobileuploadtoken', get_string('badmobileuploadtoken', 'account')); } } } plugin_account_prefs_validate($form, $values); }
function tag_remove($tagid) { if (record_exists_select('lightboxgallery_image_meta', $this->sql_select('id = ' . $tagid))) { delete_records('lightboxgallery_image_meta', 'id', $tagid); } }
/** * Add an import request of an interactive import entry as an Mahara view+collection or artefact. * For view import * If the entry is for Profile or Dashboard page, the decision is APPEND(default), IGNORE or REPLACE * If there is a duplicated view (same title and description), the decision is APPEND(default), IGNORE, REPLACE, or ADDNEW * If else, the decision is IGNORE, or ADDNEW(default) * For artefact import * If there are duplicated artefacts, the decision is IGNORE * If ELSE If there is $entrytype NOT is_singular, e.g. an user may have up to 5 email addresses * the decision is ADDNEW(default) or IGNORE * If there is $entrytype is_singular, * the decision is REPLACE(default) or APPEND * Also update the list of * - duplicated artefacts which have same artefacttype and content * - existing artefacts which have same artefacttype but the content may be different to the entry data * * @param string $importid ID of the import * @param string $entryid ID of the entry * @param string $strategy Strategy of entry import * @param string $plugin * @param array $entrydata Data the entry including the following fields: * owner ID of the user who imports the entry (required) * type (required) * parent ID of the parent entry (e.g. the blog entryid of the blogpost entry). * content (required) * - title (required) * @return updated DB table 'import_entry_requests' */ public static function add_import_entry_request($importid, $entryid, $strategy, $plugin, $entrydata) { $duplicatedartefactids = array(); $existingartefactids = array(); $title = $entrydata['content']['title']; if ($plugin === 'core') { // For view import $decision = PluginImport::DECISION_ADDNEW; } else { safe_require('artefact', $plugin); $classname = generate_artefact_class_name($entrydata['type']); if ($duplicatedartefactids = call_static_method($classname, 'get_duplicated_artefacts', $entrydata)) { $decision = PluginImport::DECISION_IGNORE; } else { if (isset($entrydata['defaultdecision'])) { $decision = $entrydata['defaultdecision']; } else { $existingartefactids = call_static_method($classname, 'get_existing_artefacts', $entrydata); if (call_static_method($classname, 'is_singular') && !empty($existingartefactids)) { if ($entrydata['type'] == 'email') { $decision = PluginImport::DECISION_ADDNEW; } else { $decision = PluginImport::DECISION_REPLACE; } } else { $decision = PluginImport::DECISION_ADDNEW; } } } } // Update DB table if (!record_exists_select('import_entry_requests', 'importid = ? AND entryid = ? AND ownerid = ? AND entrytype = ? AND entrytitle = ?', array($importid, $entryid, $entrydata['owner'], $entrydata['type'], $title))) { return insert_record('import_entry_requests', (object) array('importid' => $importid, 'entryid' => $entryid, 'strategy' => $strategy, 'plugin' => $plugin, 'ownerid' => $entrydata['owner'], 'entrytype' => $entrydata['type'], 'entryparent' => isset($entrydata['parent']) ? $entrydata['parent'] : null, 'entrytitle' => $title, 'entrycontent' => serialize($entrydata['content']), 'duplicateditemids' => serialize($duplicatedartefactids), 'existingitemids' => serialize($existingartefactids), 'decision' => $decision)); } return false; }
/** * @param integer $quizid the id of the quiz object. * @return boolean Whether this quiz has any non-blank feedback text. */ function quiz_has_feedback($quizid) { static $cache = array(); if (!array_key_exists($quizid, $cache)) { $cache[$quizid] = record_exists_select('quiz_feedback', "quizid = {$quizid} AND " . sql_isnotempty('quiz_feedback', 'feedbacktext', false, true)); } return $cache[$quizid]; }
foreach ($courses as $course) { if ($course->id == SITEID) { continue; } //echo '<li>'; // NOTE: *** This loop cannot contain echos unless they are apart of the <ul> $listitems .= "<li id='{$course->id}' {$selected}><b>" . $course->fullname . "</b></li>"; //echo "<b><u>".$course->fullname."</u></b> ($course->id)<br/>".$course->summary."<br/><hr/><hr/>"; $selected = ""; // Clear selected option - can only have one // calculate the IN clause (the list of courses we are going to search) $in_sql = "IN('Registered','Orientation','Concepts','Implementation','Graded','Canceled')"; $divcourses .= "<div id='c{$course->id}' class='coursediv' style='display: none'>"; // Display Exam Info //if(record_exists('quiz_course_activation','username',$USER->username,'courseid',$course->id)){ if (record_exists_select('quiz_course_activation', "username = '******' AND courseid = '{$course->id}' AND status {$in_sql} ", "starttime DESC, endtime DESC")) { //$records = get_recordset('quiz_course_activation', array('username'=>$USER->username)); $records = get_records_select('quiz_course_activation', "username = '******' AND courseid = '{$course->id}' AND status {$in_sql} ", "starttime DESC, endtime DESC"); $currentTime = time(); // Check for current exam to add anchor $anc_sql = " IN('Registered','Orientation','Concepts','Implementation') AND {$currentTime} >= starttime AND {$currentTime} <= endtime"; //$now >= $starttime && $now <= $endtime $anchor_record = get_record_select('quiz_course_activation', "username = '******' AND courseid = '{$course->id}' AND status {$anc_sql} ORDER BY starttime, endtime DESC"); if (!empty($records)) { $format = "l dS \\of F Y - h:i:s A"; //$currentTime = time(); //$currentTime = date("U",mktime(6,0,1,10,16,2009)); $currentExam = ""; $prevExam = ""; foreach ($records as $record) { $quiz = get_record('quiz', 'course', $course->id, 'id', $record->quizid);
/** * The CSV file is parsed here so validation errors can be returned to the * user. The data from a successful parsing is stored in the <var>$CVSDATA</var> * array so it can be accessed by the submit function * * @param Pieform $form The form to validate * @param array $values The values submitted */ function uploadcsv_validate(Pieform $form, $values) { global $CSVDATA, $ALLOWEDKEYS, $FORMAT, $USER, $CSVERRORS; // Don't even start attempting to parse if there are previous errors if ($form->has_errors()) { return; } if ($values['file']['size'] == 0) { $form->set_error('file', $form->i18n('rule', 'required', 'required', array())); return; } require_once 'csvfile.php'; $authinstance = (int) $values['authinstance']; $institution = get_field('auth_instance', 'institution', 'id', $authinstance); if (!$USER->can_edit_institution($institution)) { $form->set_error('authinstance', get_string('notadminforinstitution', 'admin')); return; } $usernames = array(); $emails = array(); $csvusers = new CsvFile($values['file']['tmp_name']); $csvusers->set('allowedkeys', $ALLOWEDKEYS); // Now we know all of the field names are valid, we need to make // sure that the required fields are included $mandatoryfields = array('username', 'password'); $mandatoryfields = array_merge($mandatoryfields, array_keys(ArtefactTypeProfile::get_mandatory_fields())); if ($lockedprofilefields = get_column('institution_locked_profile_field', 'profilefield', 'name', $institution)) { $mandatoryfields = array_merge($mandatoryfields, $lockedprofilefields); } $csvusers->set('mandatoryfields', $mandatoryfields); $csvdata = $csvusers->get_data(); if (!empty($csvdata->errors['file'])) { $form->set_error('file', $csvdata->errors['file']); return; } foreach ($csvdata->data as $key => $line) { // If headers exists, increment i = key + 2 for actual line number $i = $csvusers->get('headerExists') ? $key + 2 : $key + 1; // Trim non-breaking spaces -- they get left in place by File_CSV foreach ($line as &$field) { $field = preg_replace('/^(\\s|\\xc2\\xa0)*(.*?)(\\s|\\xc2\\xa0)*$/', '$2', $field); } // We have a line with the correct number of fields, but should validate these fields // Note: This validation should really be methods on each profile class, that way // it can be used in the profile screen as well. $formatkeylookup = array_flip($csvdata->format); $username = $line[$formatkeylookup['username']]; $password = $line[$formatkeylookup['password']]; $email = $line[$formatkeylookup['email']]; $authobj = AuthFactory::create($authinstance); if (method_exists($authobj, 'is_username_valid') && !$authobj->is_username_valid($username)) { $CSVERRORS[] = get_string('uploadcsverrorinvalidusername', 'admin', $i); } if (record_exists_select('usr', 'LOWER(username) = ?', strtolower($username)) || isset($usernames[strtolower($username)])) { $CSVERRORS[] = get_string('uploadcsverroruseralreadyexists', 'admin', $i, $username); } if (record_exists('usr', 'email', $email) || record_exists('artefact_internal_profile_email', 'email', $email) || isset($emails[$email])) { $CSVERRORS[] = get_string('uploadcsverroremailaddresstaken', 'admin', $i, $email); } // Note: only checks for valid form are done here, none of the checks // like whether the password is too easy. The user is going to have to // change their password on first login anyway. if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) { $CSVERRORS[] = get_string('uploadcsverrorinvalidpassword', 'admin', $i); } $usernames[strtolower($username)] = 1; $emails[$email] = 1; } if (!empty($CSVERRORS)) { $form->set_error('file', implode("<br />\n", $CSVERRORS)); return; } $FORMAT = $csvdata->format; $CSVDATA = $csvdata->data; }
function adduser_validate(Pieform $form, $values) { global $USER; $authobj = AuthFactory::create($values['authinstance']); $institution = $authobj->institution; // Institutional admins can only set their own institutions' authinstances if (!$USER->get('admin') && !$USER->is_institutional_admin($authobj->institution)) { $form->set_error('authinstance', get_string('notadminforinstitution', 'admin')); return; } $institution = new Institution($authobj->institution); // Don't exceed max user accounts for the institution if ($institution->isFull()) { $SESSION->add_error_msg(get_string('institutionmaxusersexceeded', 'admin')); redirect('/admin/users/add.php'); } $username = $values['username']; $firstname = $values['firstname']; $lastname = $values['lastname']; $email = $values['email']; $password = $values['password']; if (method_exists($authobj, 'is_username_valid') && !$authobj->is_username_valid($username)) { $form->set_error('username', get_string('addusererrorinvalidusername', 'admin')); return; } if (!$form->get_error('username') && record_exists_select('usr', 'LOWER(username) = ?', strtolower($username))) { $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal')); return; } if (!$form->get_error('firstname') && !preg_match('/\\S/', $firstname)) { $form->set_error('firstname', $form->i18n('required')); } if (!$form->get_error('lastname') && !preg_match('/\\S/', $lastname)) { $form->set_error('lastname', $form->i18n('required')); } if (record_exists('usr', 'email', $email) || record_exists('artefact_internal_profile_email', 'email', $email)) { $form->set_error('email', get_string('emailalreadytaken', 'auth.internal')); } if (method_exists($authobj, 'is_password_valid') && !$authobj->is_password_valid($password)) { $form->set_error('password', get_string('passwordinvalidform', 'auth.' . $authobj->type)); return; } }