function export_validate(Pieform $form, $values) { global $SESSION; if ($values['what'] == 'views') { $viewchosen = false; foreach ($values as $key => $value) { if (substr($key, 0, 5) == 'view_' && $value) { $viewchosen = true; } } if (!$viewchosen) { $form->set_error('what', ''); $SESSION->add_error_msg(get_string('youmustselectatleastoneviewtoexport', 'export')); } } else { if ($values['what'] == 'collections') { $viewchosen = false; foreach ($values as $key => $value) { if (substr($key, 0, 11) == 'collection_' && $value) { $viewchosen = true; } } if (!$viewchosen) { $form->set_error('what', ''); $SESSION->add_error_msg(get_string('youmustselectatleastonecollectiontoexport', 'export')); } } } }
function gwfontform_validate(Pieform $form, $values) { global $USER, $SESSION; require_once 'file.php'; require_once 'uploadmanager.php'; $valid = false; if ($values['gwfzipfile'] != null) { $filetype = $values['gwfzipfile']['type']; // Ensures that the correct file was chosen $accepted = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/s-compressed'); foreach ($accepted as $mimetype) { if ($mimetype == $filetype) { $valid = true; break; } } // Safari and Chrome don't register zip mime types. Something better could be used here. // Check if file extension, that is the last 4 characters in file name, equals '.zip'... $valid = substr($values['gwfzipfile']['name'], -4) == '.zip' ? true : false; if (!$valid) { $form->set_error('gwfzipfile', get_string('notvalidzipfile', 'skin')); } // pass it through the virus checker $um = new upload_manager('gwfzipfile'); if ($error = $um->preprocess_file()) { $form->set_error($inputname, $error); } } }
function importeuropassform_validate(Pieform $form, $values) { global $USER, $SESSION; $filetype = $values['file']['type']; if (!$filetype || $filetype != 'text/xml') { $form->set_error('file', get_string('notvalidxmlfile', 'artefact.europass')); } // Check if at least one import option is checked... $options = array(); if (!empty($values['identification'])) { $options[] = 'identification'; } if (!empty($values['application'])) { $options[] = 'application'; } if (!empty($values['workexperience'])) { $options[] = 'workexperience'; } if (!empty($values['education'])) { $options[] = 'education'; } if (!empty($values['languages'])) { $options[] = 'languages'; } if (!empty($values['skills'])) { $options[] = 'skills'; } if (!empty($values['additionalinfo'])) { $options[] = 'additionalinfo'; } if (empty($options)) { $form->set_error('additionalinfo', get_string('nocheckedoptions', 'artefact.europass')); } }
function forgotpass_validate(Pieform $form, $values) { // See if the user input an email address or a username. We favour email addresses if (!$form->get_error('emailusername')) { // Check if the user who associates to username or email address is using the external authentication if (record_exists_sql('SELECT u.authinstance FROM {usr} u INNER JOIN {auth_instance} ai ON (u.authinstance = ai.id) WHERE (LOWER(u.email) = ? OR LOWER(u.username) = ?) AND ((ai.authname != \'internal\') AND (ai.authname != \'none\'))', array_fill(0, 2, strtolower($values['emailusername'])))) { $form->set_error('emailusername', get_string('forgotpassuserusingexternalauthentication', 'mahara', get_config('wwwroot') . 'contact.php')); } else { if (!($authinstance = get_field_sql('SELECT u.authinstance FROM {usr} u INNER JOIN {auth_instance} ai ON (u.authinstance = ai.id) WHERE (LOWER(u.email) = ? OR LOWER(u.username) = ?) AND ai.authname = \'internal\'', array_fill(0, 2, strtolower($values['emailusername']))))) { $form->set_error('emailusername', get_string('forgotpassnosuchemailaddressorusername')); } } } if ($form->get_error('emailusername')) { return; } $authobj = AuthFactory::create($authinstance); if (!method_exists($authobj, 'change_password')) { die_info(get_string('cantchangepassword')); } }
function addvariantform_validate(Pieform $form, $values) { global $USER, $SESSION; require_once 'file.php'; require_once 'uploadmanager.php'; // Make sure they didn't hack the hidden variable to have the name of // a font that doesn't exist if (!record_exists('skin_fonts', 'name', $values['fontname'])) { $form->set_error('fontname', get_string('nosuchfont', 'skin')); } $uploadfiles = array('fontfileEOT' => array('required' => true, 'suffix' => 'eot'), 'fontfileSVG' => array('required' => true, 'suffix' => 'svg'), 'fontfileTTF' => array('required' => true, 'suffix' => 'ttf'), 'fontfileWOFF' => array('required' => true, 'suffix' => 'woff')); foreach ($uploadfiles as $inputname => $details) { $um = new upload_manager($inputname, false, null, $details['required']); if ($error = $um->preprocess_file()) { $form->set_error($inputname, $error); } if ($details['suffix']) { $reqext = ".{$details['suffix']}"; $fileext = substr($values[$inputname]['name'], -1 * strlen($reqext)); if ($fileext != $reqext) { $form->set_error($inputname, get_string('notvalidfontfile', 'skin', strtoupper($details['suffix']))); } } } }
/** * 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>$LEAP2AFILES</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 bulkimport_validate(Pieform $form, $values) { global $LEAP2AFILES, $USER; // Don't even start attempting to parse if there are previous errors if ($form->has_errors()) { return; } require_once 'csvfile.php'; $zipfile = $values['file']; if (!is_file($zipfile)) { $form->set_error('file', get_string('importfilenotafile', 'admin')); return; } if (!is_readable($zipfile)) { $form->set_error('file', get_string('importfilenotreadable', 'admin')); return; } // Create temporary directory $importdir = get_config('dataroot') . 'import/' . $USER->get('id') . '/' . time() . '/'; if (!check_dir_exists($importdir)) { throw new SystemException("Couldn't create the temporary export directory {$importdir}"); } $command = sprintf('%s %s %s', escapeshellcmd(get_config('pathtounzip')), escapeshellarg($zipfile), '-d ' . escapeshellarg($importdir)); $output = array(); exec($command, $output, $returnvar); if ($returnvar != 0) { log_debug("unzip command failed with return value {$returnvar}"); // Let's make it obvious if the cause is obvious :) if ($returnvar == 127) { log_debug("This means that 'unzip' isn't installed, or the config var \$cfg->pathtounzip is not" . " pointing at unzip (see Mahara's file lib/config-defaults.php)"); } throw new SystemException(get_string('unzipfailed', 'admin', hsc($zipfile))); } else { log_debug("Unzipped {$zipfile} into {$importdir}"); } $csvfilename = $importdir . '/usernames.csv'; if (!is_readable($csvfilename)) { $form->set_error('file', get_string('importfilemissinglisting', 'admin')); return; } $csvusers = new CsvFile($csvfilename); $csvusers->set('headerExists', false); $csvusers->set('format', array('username', 'filename')); $csvdata = $csvusers->get_data(); if (!empty($csvdata->errors['file'])) { $form->set_error('file', get_string('invalidlistingfile', 'admin')); return; } foreach ($csvdata->data as $user) { $username = $user[0]; $filename = $user[1]; $LEAP2AFILES[$username] = "{$importdir}/users/{$filename}"; } }
function importskinform_validate(Pieform $form, $values) { global $USER, $SESSION; $filetype = $values['file']['type']; if (!$filetype || $filetype != 'text/xml') { $form->set_error('file', get_string('notvalidxmlfile', 'skin')); } require_once 'file.php'; require_once 'uploadmanager.php'; $um = new upload_manager('file'); if ($error = $um->preprocess_file()) { $form->set_error('file', $error); } }
/** * 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>$LEAP2AFILES</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 bulkimport_validate(Pieform $form, $values) { global $LEAP2AFILES, $USER; // Don't even start attempting to parse if there are previous errors if ($form->has_errors()) { return; } require_once 'csvfile.php'; $zipfile = $values['file']; if (!is_file($zipfile)) { $form->set_error('file', get_string('importfilenotafile', 'admin')); return; } if (!is_readable($zipfile)) { $form->set_error('file', get_string('importfilenotreadable', 'admin')); return; } // Create temporary directory $importdir = get_config('dataroot') . 'import/' . $USER->get('id') . '/' . time() . '/'; if (!check_dir_exists($importdir)) { throw new SystemException("Couldn't create the temporary export directory {$importdir}"); } $archive = new ZipArchive(); if ($archive->open($zipfile) && $archive->extractTo($importdir)) { // successfully extracted $archive->close(); log_debug("Unzipped {$zipfile} into {$importdir}"); } else { throw new SystemException(get_string('unzipfailed', 'admin', hsc($zipfile))); } $csvfilename = $importdir . '/usernames.csv'; if (!is_readable($csvfilename)) { $form->set_error('file', get_string('importfilemissinglisting', 'admin')); return; } $csvusers = new CsvFile($csvfilename); $csvusers->set('headerExists', false); $csvusers->set('format', array('username', 'filename')); $csvdata = $csvusers->get_data(); if (!empty($csvdata->errors['file'])) { $form->set_error('file', get_string('invalidlistingfile', 'admin')); return; } foreach ($csvdata->data as $user) { $username = $user[0]; $filename = $user[1]; $LEAP2AFILES[$username] = "{$importdir}/users/{$filename}"; } }
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 editsitepage_validate(Pieform $form, $values) { $allowedinstitutions = get_institution_selector(false); if (array_search($values['pageinstitution'], array_flip($allowedinstitutions['options'])) === false) { $form->set_error(null, get_string('staticpageinstitutionbad', 'admin', $values['pageinstitution'])); } }
function editgroup_validate(Pieform $form, $values) { $cid = get_field('group', 'id', 'name', $values['name']); if ($cid && $cid != $values['id']) { $form->set_error('name', get_string('groupalreadyexists', 'group')); } }
function contactus_validate(Pieform $form, $values) { $captcharequired = get_config('captcha_on_contact_form'); if ((is_null($captcharequired) || $captcharequired) && !$values['captcha']) { $form->set_error('captcha', get_string('captchaincorrect')); } }
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 changerole_validate(Pieform $form, $values) { global $user, $group; if (!group_can_change_role($group->id, $user->id, $values['role'])) { $form->set_error('role', get_string('usercannotchangetothisrole', 'group')); } }
function creategroup_validate(Pieform $form, $values) { //global $USER; //global $SESSION; if (get_field('group', 'id', 'name', $values['name'])) { $form->set_error('name', get_string('groupalreadyexists', 'group')); } }
function edit_annotation_feedback_validate(Pieform $form, $values) { require_once get_config('libroot.php') . 'antispam.php'; $result = probation_validate_content($values['message']); if ($result !== true) { $form->set_error('message', get_string('newuserscantpostlinksorimages')); } }
function newurl_validate(Pieform $form, $values) { global $iframesources; if (!($urldata = process_allowed_iframe_url($values['url']))) { $form->set_error('url', get_string('iframeinvalidsite', 'admin')); } if (isset($iframesources[$urldata['key']])) { $form->set_error('url', get_string('urlalreadyexists', 'admin')); } }
function contactus_validate(Pieform $form, $values) { global $SESSION; $spamtrap = new_spam_trap(array(array('type' => 'name', 'value' => $values['name']), array('type' => 'email', 'value' => $values['email']), array('type' => 'subject', 'value' => $values['subject']), array('type' => 'body', 'value' => $values['message']))); if ($form->spam_error() || $spamtrap->is_spam()) { $msg = get_string('formerror'); $emailcontact = get_config('emailcontact'); if (!empty($emailcontact)) { $msg .= ' ' . get_string('formerroremail', 'mahara', $emailcontact, $emailcontact); } $form->set_error(null, $msg); } }
function editurl_validate(Pieform $form, $values) { if (empty($values['startdate'])) { $values['startdate'] = null; } if (empty($values['stopdate'])) { $values['stopdate'] = null; } if ($values['stopdate'] && time() > $values['stopdate']) { $form->set_error('stopdate', get_string('stopdatecannotbeinpast1', 'view')); } if ($values['startdate'] && $values['stopdate'] && $values['startdate'] > $values['stopdate']) { $form->set_error('startdate', get_string('startdatemustbebeforestopdate', 'view')); } }
function forgotpass_validate(Pieform $form, $values) { // See if the user input an email address or a username. We favour email addresses if (!$form->get_error('emailusername')) { if (!($authinstance = get_field_sql('SELECT authinstance FROM {usr} WHERE LOWER(email) = ?', array(strtolower($values['emailusername']))))) { if (!($authinstance = get_field_sql('SELECT authinstance FROM {usr} WHERE LOWER(username) = ?', array(strtolower($values['emailusername']))))) { $form->set_error('emailusername', get_string('forgotpassnosuchemailaddressorusername')); } } } if ($form->get_error('emailusername')) { return; } $authobj = AuthFactory::create($authinstance); if (!method_exists($authobj, 'change_password')) { die_info(get_string('cantchangepassword')); } }
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; } }
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) = ?', strtolower($values['username']))) { $form->set_error('username', get_string('usernamealreadytaken', 'auth.internal')); } } // Don't let users turn multiple blogs off unless they only have 1 blog if ($USER->get_account_preference('multipleblogs') && empty($values['multipleblogs']) && count_records('artefact', 'artefacttype', 'blog', 'owner', $USER->get('id')) != 1) { $form->set_error('multipleblogs', get_string('disablemultipleblogserror', 'account')); } }
/** * 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 import_validate(Pieform $form, $values) { global $USER, $TRANSPORTER; if (!isset($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_-]/', '-', $USER->get('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()); $TRANSPORTER->cleanup(); } // Check if import data may exceed the user's file quota $importdata = $TRANSPORTER->files_info(); require_once 'function.dirsize.php'; $importdatasize = dirsize($importdata['tempdir'] . 'extract/files'); if ($USER->get('quotaused') + $importdatasize > $USER->get('quota')) { $form->set_error('leap2afile', get_string('importexceedquota', 'import')); $TRANSPORTER->cleanup(); } }
/** * @todo add note: because the form select thing will eventually enforce * that the result for $values['institution'] was in the original lot, * and because that only allows authmethods that use 'internal' auth, we * can guarantee that the auth method is internal */ function auth_register_validate(Pieform $form, $values) { global $SESSION; $registerterms = get_config('registerterms'); $spamtrap = new_spam_trap(array(array('type' => 'name', 'value' => $values['firstname']), array('type' => 'name', 'value' => $values['lastname']), array('type' => 'email', 'value' => $values['email']))); if ($form->spam_error() || $spamtrap->is_spam()) { $msg = get_string('formerror'); $emailcontact = get_config('emailcontact'); if (!empty($emailcontact)) { $msg .= ' ' . get_string('formerroremail', 'mahara', $emailcontact, $emailcontact); } $form->set_error(null, $msg); return; } $institution = $values['institution']; safe_require('auth', 'internal'); // First name and last name must contain at least one non whitespace // character, so that there's something to read if (!$form->get_error('firstname') && !preg_match('/\\S/', $values['firstname'])) { $form->set_error('firstname', $form->i18n('required')); } if (!$form->get_error('lastname') && !preg_match('/\\S/', $values['lastname'])) { $form->set_error('lastname', $form->i18n('required')); } // The e-mail address cannot already be in the system if (!$form->get_error('email') && (record_exists('usr', 'email', $values['email']) || record_exists('artefact_internal_profile_email', 'email', $values['email']))) { $form->set_error('email', get_string('emailalreadytaken', 'auth.internal')); } // If the user hasn't agreed to the terms and conditions, don't bother if ($registerterms && $values['tandc'] != 'yes') { $form->set_error('tandc', get_string('youmaynotregisterwithouttandc', 'auth.internal'), false); } $institution = get_record_sql(' SELECT i.name, i.maxuseraccounts, i.registerallowed, COUNT(u.id) AS count FROM {institution} i LEFT OUTER JOIN {usr_institution} ui ON ui.institution = i.name LEFT OUTER JOIN {usr} u ON (ui.usr = u.id AND u.deleted = 0) WHERE i.name = ? GROUP BY i.name, i.maxuseraccounts, i.registerallowed', array($institution)); if (!empty($institution->maxuseraccounts) && $institution->count >= $institution->maxuseraccounts) { // the institution is full so we need to alert the admins of the institution to this fact so // they can either increase the maxusers or turn off the public registration. require_once get_config('docroot') . 'lib/institution.php'; $institutionobj = new Institution($institution->name); $institutionobj->send_admin_institution_is_full_message(); $form->set_error('institution', get_string('institutionfull')); } if (!$institution || !$institution->registerallowed) { $form->set_error('institution', get_string('registrationnotallowed')); } }
/** * Gets the value of the expiry element and converts it to a time in seconds. * * @param Pieform $form The form the element is attached to * @param array $element The element to get the value for * @return int The number of seconds until expiry */ function pieform_element_bytes_get_value(Pieform $form, $element) { /*{{{*/ $name = $element['name']; $global = $form->get_property('method') == 'get' ? $_GET : $_POST; $unit = $global[$name . '_units']; $allunits = pieform_element_bytes_get_bytes_units(); $number = $global[$name]; if (!is_numeric($number)) { $form->set_error($name, $form->i18n('element', 'bytes', 'invalidvalue', $element)); } if (!in_array($unit, $allunits) || $number < 0) { return null; } return $number * pieform_element_bytes_in($unit); }
/** * 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, $MANDATORYFIELDS, $FORMAT, $USER, $UPDATES, $MEMBERS, $GROUPS; // 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; } $institution = $values['institution']; if (!$USER->can_edit_institution($institution)) { $form->set_error('institution', get_string('notadminforinstitution', 'admin')); return; } require_once 'csvfile.php'; $csvgroups = new CsvFile($values['file']['tmp_name']); $csvgroups->set('allowedkeys', $ALLOWEDKEYS); $csvgroups->set('mandatoryfields', $MANDATORYFIELDS); $csvdata = $csvgroups->get_data(); if (!empty($csvdata->errors['file'])) { $form->set_error('file', $csvdata->errors['file']); return; } $csverrors = new CSVErrors(); $formatkeylookup = array_flip($csvdata->format); $shortnames = array(); $hadadmin = array(); $num_lines = count($csvdata->data); foreach ($csvdata->data as $key => $line) { // If headers exists, increment i = key + 2 for actual line number $i = $csvgroups->get('headerExists') ? $key + 2 : $key + 1; // In adding 5000 groups, this part was approx 8% of the wall time. if (!($key % 25)) { set_progress_info('uploadgroupmemberscsv', $key, $num_lines * 10, get_string('validating', 'admin')); } // 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); } $shortname = $line[$formatkeylookup['shortname']]; $username = $line[$formatkeylookup['username']]; $role = $line[$formatkeylookup['role']]; $gid = get_field('group', 'id', 'shortname', $shortname, 'institution', $institution); if (!$gid) { $csverrors->add($i, get_string('uploadgroupmemberscsverrornosuchshortname', 'admin', $i, $shortname, $institution)); continue; } $uid = get_field_sql('SELECT id FROM {usr} WHERE LOWER(username) = ?', array(strtolower($username))); if (!$uid) { $csverrors->add($i, get_string('uploadgroupmemberscsverrornosuchusername', 'admin', $i, $username)); continue; } if ($institution != 'mahara' && !record_exists('usr_institution', 'usr', $uid, 'institution', $institution)) { $csverrors->add($i, get_string('uploadgroupmemberscsverrorusernotininstitution', 'admin', $i, $username, $institution)); continue; } if (!in_array($role, array_keys(group_get_role_info($gid)))) { $csverrors->add($i, get_string('uploadgroupmemberscsverrorinvalidrole', 'admin', $i, $role)); continue; } if (!isset($MEMBERS[$gid])) { $MEMBERS[$gid] = array(); } if (isset($MEMBERS[$gid][$uid])) { $csverrors->add($i, get_string('uploadgroupmemberscsverrorduplicateusername', 'admin', $i, $shortname, $username)); continue; } $MEMBERS[$gid][$uid] = $role; $GROUPS[$gid] = $shortname; if ($role == 'admin') { $hasadmin[$shortname] = 1; } } foreach ($GROUPS as $shortname) { if (!isset($hasadmin[$shortname])) { $csverrors->add($i, get_string('uploadgroupmemberscsverrornoadminlisted', 'admin', $i, $shortname)); } } if ($errors = $csverrors->process()) { $form->set_error('file', clean_html($errors)); return; } $FORMAT = $csvdata->format; $CSVDATA = $csvdata->data; }
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')); } } } }
function changeauth_validate(Pieform $form, $values) { global $userids, $SESSION; // Make sure all users are members of the institution that // this authinstance belongs to. $authobj = AuthFactory::create($values['authinstance']); if ($authobj->institution != 'mahara') { $ph = $userids; $ph[] = $authobj->institution; $institutionusers = count_records_sql(' SELECT COUNT(usr) FROM {usr_institution} WHERE usr IN (' . join(',', array_fill(0, count($userids), '?')) . ') AND institution = ?', $ph); if ($institutionusers != count($userids)) { $SESSION->add_error_msg(get_string('someusersnotinauthinstanceinstitution', 'admin')); $form->set_error('authinstance', get_string('someusersnotinauthinstanceinstitution', 'admin')); } } }
function edituser_institution_validate(Pieform $form, $values) { $user = new User(); if (!$user->find_by_id($values['id'])) { return false; } global $USER; $userinstitutions = $user->get('institutions'); if (isset($values['add']) && $USER->get('admin') && (empty($userinstitutions) || get_config('usersallowedmultipleinstitutions'))) { // check if the institution is full require_once get_config('docroot') . 'lib/institution.php'; $institution = new Institution($values['addinstitution']); if ($institution->isFull()) { $institution->send_admin_institution_is_full_message(); $form->set_error(null, get_string('institutionmaxusersexceeded', 'admin')); } } }