$struserupdated = get_string('useraccountupdated', 'admin');
$strusernotupdated = get_string('usernotupdatederror', 'error');
-$strusernotadded = get_string('usernotaddedregistered', 'error');
$struseradded = get_string('newuser');
+$strusernotadded = get_string('usernotaddedregistered', 'error');
$strusernotaddederror = get_string('usernotaddederror', 'error');
+
+$struserdeleted = get_string('userdeleted', 'admin');
+$strusernotdeletederror = get_string('usernotdeletederror', 'error');
+$strusernotdeletedmissing = get_string('usernotdeletedmissing', 'error');
+
$strcannotassignrole = get_string('cannotassignrole', 'error');
$strduplicateusername = get_string('duplicateusername', 'error');
$strindent = '-->';
'maildisplay' => 1,
'htmleditor' => 1,
'autosubscribe' => 1,
- 'mnethostid' => 1,
+ 'mnethostid' => 0,
'institution' => 0,
'department' => 0,
'idnumber' => 0,
'icq' => 0,
'oldusername' => 0,
'emailstop' => 1,
+ 'deleted' => 0,
'password' => !$createpassword,
);
$headers[$key] = $value;
}
- $usersnew = 0;
- $usersupdated = 0;
- $userserrors = 0;
- $renames = 0;
- $renameerrors = 0;
- $newusernames = array();
- // We'll need courses a lot, so fetch it early and keep it in memory, indexed by their shortname
- $tmp =& get_courses('all','','id,shortname,visible');
- $courses = array();
- foreach ($tmp as $c) {
- $courses[$c->shortname] = $c;
+ // check that required fields are present or a default value for them exists
+ $headersOk = true;
+ // disable the check if we also have deleting information (ie. deleted column)
+ if (!in_array('deleted', $headers)) {
+ foreach ($fields as $key => $required) {
+ if($required && !in_array($key, $headers) && (!isset($formdata->$key) || $formdata->$key==='')) {
+ notify(get_string('missingfield', 'error', $key));
+ $headersOk = false;
+ }
+ }
}
- unset($tmp);
+ if($headersOk) {
+ $usersnew = 0;
+ $usersupdated = 0;
+ $userserrors = 0;
+ $usersdeleted = 0;
+ $renames = 0;
+ $renameerrors = 0;
+ $deleteerrors = 0;
+ $newusernames = array();
+ // We'll need courses a lot, so fetch it early and keep it in memory, indexed by their shortname
+ $tmp =& get_courses('all','','id,shortname,visible');
+ $courses = array();
+ foreach ($tmp as $c) {
+ $courses[$c->shortname] = $c;
+ }
+ unset($tmp);
- echo '<p id="results">';
- while (!feof ($fp)) {
- $user = new object();
- // by default, use the local mnet id (this may be changed in the file)
- $user->mnethostid = $CFG->mnet_localhost_id;
- $line = explode($csv_delimiter, fgets($fp,LINE_MAX_SIZE));
- ++$linenum;
- $ok = true;
- // add fields to user object
- foreach ($line as $key => $value) {
- if($value !== '') {
- $key = $headers[$key];
- //decode encoded commas
- $value = str_replace($csv_encode,$csv_delimiter,trim($value));
- // special fields: password and username
- if ($key == 'password' && !empty($value)) {
- $user->$key = hash_internal_user_password($value);
- } else if($key == 'username') {
- $user->$key = addslashes($textlib->strtolower($value));
- } else {
- $user->$key = addslashes($value);
+ echo '<p id="results">';
+ while (!feof ($fp)) {
+ $errors = '';
+ $user = new object();
+ // by default, use the local mnet id (this may be changed in the file)
+ $user->mnethostid = $CFG->mnet_localhost_id;
+ $line = explode($csv_delimiter, fgets($fp,LINE_MAX_SIZE));
+ ++$linenum;
+ // add fields to user object
+ foreach ($line as $key => $value) {
+ if($value !== '') {
+ $key = $headers[$key];
+ //decode encoded commas
+ $value = str_replace($csv_encode,$csv_delimiter,trim($value));
+ // special fields: password and username
+ if ($key == 'password' && !empty($value)) {
+ $user->$key = hash_internal_user_password($value);
+ } else if($key == 'username') {
+ $value = $textlib->strtolower(addslashes($value));
+ if(empty($CFG->extendedusernamechars)) {
+ $value = eregi_replace('[^(-\.[:alnum:])]', '', $value);
+ }
+ @$newusernames[$value]++;
+ $user->$key = $value;
+ } else {
+ $user->$key = addslashes($value);
+ }
}
}
- }
- // add default values for remaining fields
- foreach ($fields as $key => $value) {
- if(isset($user->$key)) {
- continue;
- }
- if(!isset($formdata->$key) || $formdata->$key==='') { // no default value was submited
- if($value) { // the field is required
- notify(get_string('erroronline', 'error', $linenum). ': ' .get_string('missingfield', 'error', $key));
- $ok = false;
+
+ // add default values for remaining fields
+ foreach ($fields as $key => $required) {
+ if(isset($user->$key)) {
+ continue;
}
- continue;
- }
- // process templates
- $template = $formdata->$key;
- $templatelen = strlen($template);
- $value = '';
- for ($i = 0 ; $i < $templatelen; ++$i) {
- if($template[$i] == '%') {
- $case = 0; // 1=lowercase, 2=uppercase
- $len = 0; // number of characters to keep
- $info = null; // data to process
- for($j = $i + 1; is_null($info) && $j < $templatelen; ++$j) {
- $car = $template[$j];
- if ($car >= '0' && $car <= '9') {
- $len = $len * 10 + (int)$car;
- } else if($car == '-') {
- $case = 1;
- } else if($car == '+') {
- $case = 2;
- } else if($car == 'f') { // first name
- $info = @$user->firstname;
- } else if($car == 'l') { // last name
- $info = @$user->lastname;
- } else if($car == 'u') { // username
- $info = @$user->username;
- } else if($car == '%' && $j == $i+1) {
- $info = '%';
- } else { // invalid character
- $info = '';
- }
+ if(!isset($formdata->$key) || $formdata->$key==='') { // no default value was submited
+ // if the field is required, give an error only if we are adding the user or deleting a user with unkown username
+ if($required && (empty($user->deleted) || $key == 'username')) {
+ $errors .= get_string('missingfield', 'error', $key) . ' ';
}
- if($info==='' || is_null($info)) { // invalid template
- continue;
+ continue;
+ }
+ // process templates
+ $template = $formdata->$key;
+ $templatelen = strlen($template);
+ $value = '';
+ for ($i = 0 ; $i < $templatelen; ++$i) {
+ if($template[$i] == '%') {
+ $case = 0; // 1=lowercase, 2=uppercase
+ $len = 0; // number of characters to keep
+ $info = null; // data to process
+ for($j = $i + 1; is_null($info) && $j < $templatelen; ++$j) {
+ $car = $template[$j];
+ if ($car >= '0' && $car <= '9') {
+ $len = $len * 10 + (int)$car;
+ } else if($car == '-') {
+ $case = 1;
+ } else if($car == '+') {
+ $case = 2;
+ } else if($car == 'f') { // first name
+ $info = @$user->firstname;
+ } else if($car == 'l') { // last name
+ $info = @$user->lastname;
+ } else if($car == 'u') { // username
+ $info = @$user->username;
+ } else if($car == '%' && $j == $i+1) {
+ $info = '%';
+ } else { // invalid character
+ $info = '';
+ }
+ }
+ if($info==='' || is_null($info)) { // invalid template
+ continue;
+ }
+ $i = $j - 1;
+ // change case
+ if($case == 1) {
+ $info = $textlib->strtolower($info);
+ } else if($case == 2) {
+ $info = $textlib->strtoupper($info);
+ }
+ if($len) { // truncate data
+ $info = $textlib->substr($info, 0, $len);
+ }
+ $value .= $info;
+ } else {
+ $value .= $template[$i];
}
- $i = $j - 1;
- // change case
- if($case == 1) {
- $info = $textlib->strtolower($info);
- } else if($case == 2) {
- $info = $textlib->strtoupper($info);
+ }
+
+ if($key == 'username') {
+ $value = $textlib->strtolower($value);
+ if(empty($CFG->extendedusernamechars)) {
+ $value = eregi_replace('[^(-\.[:alnum:])]', '', $value);
}
- if($len) { // truncate data
- $info = $textlib->substr($info, 0, $len);
+ @$newusernames[$value]++;
+ // check for new username duplicates
+ if($newusernames[$value] > 1) {
+ if($skipduplicates) {
+ $errors .= $strduplicateusername . ' (' . stripslashes($value) . '). ';
+ continue;
+ } else {
+ $value .= $newusernames[$value];
+ }
}
- $value .= $info;
- } else {
- $value .= $template[$i];
}
+ $user->$key = $value;
}
-
- if($key == 'username') {
- $value = $textlib->strtolower($value);
- if(empty($CFG->extendedusernamechars)) {
- $value = eregi_replace('[^(-\.[:alnum:])]', '', $value);
- }
- // check for new username duplicates
- if(empty($newusernames[$value])) {
- $newusernames[$value] = 1;
- } else {
- if($skipduplicates) {
- notify($strduplicateusername . ': ' . $value);
- $ok = false;
- continue;
+ if($errors) {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $errors);
+ ++$userserrors;
+ continue;
+ }
+
+ // delete user
+ if(@$user->deleted) {
+ $info = ': ' . stripslashes($user->username) . '. ';
+ if($user =& get_record('user', 'username', $user->username, 'mnethostid', $user->mnethostid)) {
+ $user->timemodified = time();
+ $user->username = addslashes($user->email . $user->timemodified); // Remember it just in case
+ $user->deleted = 1;
+ $user->email = ''; // Clear this field to free it up
+ $user->idnumber = ''; // Clear this field to free it up
+ if (update_record('user', $user)) {
+ // not sure if this is needed. unenrol_student($user->id); // From all courses
+ delete_records('role_assignments', 'userid', $user->id); // unassign all roles
+ // remove all context assigned on this user?
+ echo $struserdeleted . $info . '<br />';
+ ++$usersdeleted;
} else {
- ++$newusernames[$value];
- $value .= $newusernames[$value];
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $strusernotdeletederror . $info);
+ ++$deleteerrors;
}
- }
+ } else {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $strusernotdeletedmissing . $info);
+ ++$deleteerrors;
+ }
+ continue;
}
- $user->$key = $value;
- }
- if(!$ok) {
- ++$userserrors;
- continue;
- }
-
- $user->confirmed = 1;
- $user->timemodified = time();
-
- // save the user to the database
- $username = $user->username;
+
+ // save the user to the database
+ $user->confirmed = 1;
+ $user->timemodified = time();
- // before insert/update, check whether we should be updating an old record instead
- if ($allowrenames && !empty($user->oldusername) ) {
- $user->oldusername = $textlib->strtolower($user->oldusername);
- $info = ': ' . $user->oldusername . '-->' . $user->username . '. ';
- if ($olduser = get_record('user', 'username', $user->oldusername, 'mnethostid', $user->mnethostid)) {
- if (set_field('user', 'username', $user->username, 'id', $olduser->id)) {
- echo $struserrenamed . $info;
- $renames++;
+ // before insert/update, check whether we should be updating an old record instead
+ if ($allowrenames && !empty($user->oldusername) ) {
+ $user->oldusername = $textlib->strtolower($user->oldusername);
+ $info = ': ' . stripslashes($user->oldusername) . '-->' . stripslashes($user->username) . '. ';
+ if ($olduser =& get_record('user', 'username', $user->oldusername, 'mnethostid', $user->mnethostid)) {
+ if (set_field('user', 'username', $user->username, 'id', $olduser->id)) {
+ echo $struserrenamed . $info;
+ $renames++;
+ } else {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $strusernotrenamedexists . $info);
+ $renameerrors++;
+ continue;
+ }
} else {
- notify($strusernotrenamedexists . $info);
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $strusernotrenamedmissing . $info);
$renameerrors++;
continue;
}
- } else {
- notify($strusernotrenamedmissing . $info);
- $renameerrors++;
- continue;
}
- }
- // save the information
- if ($olduser = get_record('user', 'username', $username, 'mnethostid', $user->mnethostid)) {
- $user->id = $olduser->id;
- $info = ': ' . $username .' (ID = ' . $user->id . ')';
- if ($updateaccounts) {
- // Record is being updated
- if (update_record('user', $user)) {
- echo $struserupdated . $info . '<br />';
- $usersupdated++;
+ // save the information
+ if ($olduser =& get_record('user', 'username', $user->username, 'mnethostid', $user->mnethostid)) {
+ $user->id = $olduser->id;
+ $info = ': ' . stripslashes($user->username) .' (ID = ' . $user->id . ')';
+ if ($updateaccounts) {
+ // Record is being updated
+ if (update_record('user', $user)) {
+ echo $struserupdated . $info . '<br />';
+ $usersupdated++;
+ } else {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $strusernotupdated . $info);
+ $userserrors++;
+ continue;
+ }
} else {
- notify($strusernotupdated . $info);
+ //Record not added - user is already registered
+ //In this case, output userid from previous registration
+ //This can be used to obtain a list of userids for existing users
+ echo $strusernotadded . $info . '<br />';
$userserrors++;
- continue;
}
- } else {
- //Record not added - user is already registered
- //In this case, output userid from previous registration
- //This can be used to obtain a list of userids for existing users
- echo $strusernotadded . $info . '<br />';
- $userserrors++;
- }
- } else { // new user
- if ($user->id = insert_record('user', $user)) {
- $info = ': ' . $username .' (ID = ' . $user->id . ')';
- echo $struseradded . $info . '<br />';
- $usersnew++;
- if (empty($user->password) && $createpassword) {
- // passwords will be created and sent out on cron
- insert_record('user_preferences', array( 'userid' => $user->id, 'name' => 'create_password', 'value' => 1));
- insert_record('user_preferences', array( 'userid' => $user->id, 'name' => 'auth_forcepasswordchange', 'value' => 1));
+ } else { // new user
+ if ($user->id = insert_record('user', $user)) {
+ $info = ': ' . stripslashes($user->username) .' (ID = ' . $user->id . ')';
+ echo $struseradded . $info . '<br />';
+ $usersnew++;
+ if (empty($user->password) && $createpassword) {
+ // passwords will be created and sent out on cron
+ insert_record('user_preferences', array( 'userid' => $user->id, 'name' => 'create_password', 'value' => 1));
+ insert_record('user_preferences', array( 'userid' => $user->id, 'name' => 'auth_forcepasswordchange', 'value' => 1));
+ }
+ } else {
+ // Record not added -- possibly some other error
+ notify(get_string('erroronline', 'error', $linenum). ': ' . $strusernotaddederror . ': ' . stripslashes($user->username));
+ $userserrors++;
+ continue;
}
- } else {
- // Record not added -- possibly some other error
- notify($strusernotaddederror . ': ' . $username);
- $userserrors++;
- continue;
}
- }
- // find course enrolments, groups and roles/types
- for($ncourses = 1; $addcourse = @$user->{'course' . $ncourses}; ++$ncourses) {
- // find course
- if(!$course = @$courses[$addcourse]) {
- notify(get_string('unknowncourse', 'error', $addcourse));
- continue;
- }
- // find role
- if ($addrole = @$user->{'role' . $ncourses}) {
- $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
- if (!$ok = role_assign($addrole, $user->id, 0, $coursecontext->id)) {
- echo $strindent . $strcannotassignrole . '<br >';
+ // find course enrolments, groups and roles/types
+ for($ncourses = 1; $addcourse = @$user->{'course' . $ncourses}; ++$ncourses) {
+ // find course
+ if(!$course = @$courses[$addcourse]) {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . get_string('unknowncourse', 'error', $addcourse));
+ continue;
}
- } else {
- // if no role, then find "old" enrolment type
- switch ($addtype = @$user->{'type' . $ncourses}) {
- case 2: // teacher
- $ok = add_teacher($user->id, $course->id, 1);
- break;
- case 3: // non-editing teacher
- $ok = add_teacher($user->id, $course->id, 0);
- break;
- case 1: // student
- default:
- $ok = enrol_student($user->id, $course->id);
- break;
+ // find role
+ if ($addrole = @$user->{'role' . $ncourses}) {
+ $coursecontext =& get_context_instance(CONTEXT_COURSE, $course->id);
+ if (!$ok = role_assign($addrole, $user->id, 0, $coursecontext->id)) {
+ echo $strindent . $strcannotassignrole . '<br >';
+ }
+ } else {
+ // if no role, then find "old" enrolment type
+ switch ($addtype = @$user->{'type' . $ncourses}) {
+ case 2: // teacher
+ $ok = add_teacher($user->id, $course->id, 1);
+ break;
+ case 3: // non-editing teacher
+ $ok = add_teacher($user->id, $course->id, 0);
+ break;
+ case 1: // student
+ default:
+ $ok = enrol_student($user->id, $course->id);
+ break;
+ }
+ }
+ if ($ok) { // OK
+ echo $strindent . get_string('enrolledincourse', '', $addcourse) . '<br />';
+ } else {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . get_string('enrolledincoursenot', '', $addcourse));
}
- }
- if ($ok) { // OK
- echo $strindent . get_string('enrolledincourse', '', $addcourse) . '<br />';
- } else {
- notify(get_string('enrolledincoursenot', '', $addcourse));
- }
- // find group to add to
- if ($addgroup = @$user->{'group' . $ncourses}) {
- if ($gid = groups_get_group_by_name($course->id, $addgroup)) {
- $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
- if (count(get_user_roles($coursecontext, $user->id))) {
- if (groups_add_member($gid, $user->id)) {
- echo $strindent . get_string('addedtogroup','',$addgroup) . '<br />';
+ // find group to add to
+ if ($addgroup = @$user->{'group' . $ncourses}) {
+ if ($gid =& groups_get_group_by_name($course->id, $addgroup)) {
+ $coursecontext =& get_context_instance(CONTEXT_COURSE, $course->id);
+ if (count(get_user_roles($coursecontext, $user->id))) {
+ if (groups_add_member($gid, $user->id)) {
+ echo $strindent . get_string('addedtogroup','',$addgroup) . '<br />';
+ } else {
+ notify(get_string('erroronline', 'error', $linenum). ': ' . get_string('addedtogroupnot','',$addgroup));
+ }
} else {
- notify(get_string('addedtogroupnot','',$addgroup));
+ notify(get_string('erroronline', 'error', $linenum). ': ' . get_string('addedtogroupnotenrolled','',$addgroup));
}
} else {
- notify(get_string('addedtogroupnotenrolled','',$addgroup));
+ notify(get_string('erroronline', 'error', $linenum). ': ' . get_string('groupunknown','error',$addgroup));
}
- } else {
- notify(get_string('groupunknown','error',$addgroup));
}
}
}
+ echo '</p>';
+ notify(get_string('userscreated', 'admin') . ': ' . $usersnew);
+ notify(get_string('usersupdated', 'admin') . ': ' . $usersupdated);
+ notify(get_string('usersdeleted', 'admin') . ': ' . $usersdeleted);
+ notify(get_string('deleteerrors', 'admin') . ': ' . $deleteerrors);
+ if ($allowrenames) {
+ notify(get_string('usersrenamed', 'admin') . ': ' . $renames);
+ notify(get_string('renameerrors', 'admin') . ': ' . $renameerrors);
+ }
+ notify(get_string('errors', 'admin') . ': ' . $userserrors);
}
- echo '</p>';
-
fclose($fp);
- notify(get_string('userscreated', 'admin') . ': ' . $usersnew);
- notify(get_string('usersupdated', 'admin') . ': ' . $usersupdated);
- notify(get_string('errors', 'admin') . ': ' . $userserrors);
- if ($allowrenames) {
- notify(get_string('usersrenamed', 'admin') . ': ' . $renames);
- notify(get_string('renameerrors', 'admin') . ': ' . $renameerrors);
- }
echo '<hr />';
}
<li>The first record of the file is special, and contains a list of fieldnames. This defines the format of the rest of the file.
<blockquote>
<p><strong>Required fieldnames:</strong> these fields must be included in the first record, and defined for each user</p>
- <p><code class="example1">firstname, lastname</code></p>
+ <p><code>firstname, lastname</code></p>
<p><strong>Optional fieldnames: </strong>all of these are completely optional. If a values is present for the field in the file, then that value is used; else, the default value for that field is used.</p>
- <p> <code class="example1">institution, department, city, country, lang, auth, timezone, idnumber, icq, phone1, phone2, address, url, description, mailformat, maildisplay, htmleditor, autosubscribe, emailstop</code></p>
+ <p> <code>institution, department, city, country, lang, auth, timezone, idnumber, icq, phone1, phone2, address, url, description, mailformat, maildisplay, htmleditor, autosubscribe, emailstop, deleted</code></p>
<p><strong>Enrolment fieldnames (optional): </strong>The course names are the "shortnames" of the courses - if present then the user will be enrolled in those courses. For groups use group name; for roles use id. Group names must be associated to the corresponding courses, i.e. group1 to course1, etc.</p>
- <p><code class="example1">course1, group1, type1, role1, course2, group2, type2, role2, etc.</code></p>
+ <p><code>course1, group1, type1, role1, course2, group2, type2, role2, etc.</code></p>
</blockquote>
</li>
<li>Commas within the data should be encoded as &#44 - the script will automatically decode these back to commas. </li>
jonest, verysecret, Tom, Jones, jonest@someplace.edu, en, 3663737, 1, Intro101, Section 1, 1<br />
reznort, somesecret, Trent, Reznor, reznort@someplace.edu, en_us, 6736733, 0, Advanced202, Section 3, 3
</code></p>
+<p>The CSV file may contain full informations for some users and use default values for others (use extra commas to corectly associate data to headers). For example, the following file will use default values for username, city and country for user Trent Reznor:</p>
+<p><code>username, password, firstname, lastname, country, city<br />
+jonest, verysecret, Tom, Jones, RO, Constanta<br />
+, somesecret, Trent, Reznor, ,
+</code></p>
<h2>Templates</h2>
<p>The default values are processed as templates in which the following codes are allowed:</p>
</ul>
<p>Template processing is done only on default values, and not on the values retrieved from the CSV file.</p>
<p>In order to create corect Moodle usernames, the username is always converted to lowercase. Moreover, if the "Allow extended characters in usernames" option in the Site policies page is off, characters different to letters, digits, dash (-) and dot (.) are removed.
-For example if the firstname is John Jr. and the lastname is Doe, the username %-f%-l will produce john jr.doe when Allow extended characters in usernames is on, and johnjr.doe when off (notice the extra space).</p>
+For example if the firstname is John Jr. and the lastname is Doe, the username %-f_%-l will produce john jr._doe when Allow extended characters in usernames is on, and johnjr.doe when off.</p>
<p>When the "New username duplicate handling" setting is set to Append counter, an auto-increment counter will be append to duplicate usernames produced by the template.
For example, if the CSV file contains the users named John Doe, Jane Doe and Jenny Doe without explicit usernames, the default username is %-1f%-l and New username duplicate handling is set to Append counter, then the usernames produced will be jdoe, jdoe2 and jdoe3.
</p>
<p>By default Moodle assumes that you will be creating new user accounts, and skips records where the username matches an existing account. However, if you set "Update existing accounts" to <b>Yes</b>, the existing user account will be updated. </p>
-<p>When updating existing accounts you can change usernames as well. Set "Allow renames" to <b>Yes</b> and include in your file a field called <code class="example1">oldusername</code>.</p>
+<p>When updating existing accounts you can change usernames as well. Set "Allow renames" to <b>Yes</b> and include in your file a field called <code>oldusername</code>.</p>
<p><b>Warning:</b> any errors updating existing accounts can affect your users badly. Be careful when using the options to update.</p>
+
+<h2>Deleting accounts</h2>
+<p>If the <code>deleted</code> field is present, users with value 1 for it will be deleted. In this case, all the fields may be omitted, except for <code>username</code> (which should be present in the CSV file, or a default value for it should be available).</p>
+<p>Deleting and uploading accounts could be done with a single CSV file. For example, the following file will add the user Tom Jones and delete the user reznort:</p>
+<p><code>username, firstname, lastname, deleted<br />
+jonest, Tom, Jones, 0<br />
+reznort, , , 1
+</code></p>
--- /dev/null
+<?php //$Id$
+
+require_once($CFG->dirroot . '/user/filters/lib.php');
+
+/**
+ * Generic filter based on a date.
+ */
+class user_filter_date extends user_filter_type {
+ /**
+ * the end Unix timestamp (0 if disabled)
+ */
+ var $_value2;
+ /**
+ * the fields available for comparisson
+ */
+ var $_fields;
+ /**
+ * Constructor
+ * @param string $name the name of the filter instance
+ * @param string $label the label of the filter instance
+ * @param string $field the field used for filtering data
+ * @param int $start the start Unix timestamp (0 if disabled)
+ * @param int $end the end Unix timestamp (0 if disabled)
+ */
+ function user_filter_date($name, $label, $field, $fields=null, $start=0, $end=0) {
+ parent::user_filter_type($name, $label, $field, $start);
+ $this->_value2 = $end;
+ $this->_fields = $fields;
+ }
+
+ /**
+ * Adds controls specific to this filter in the form.
+ * @param object $mform a MoodleForm object to setup
+ */
+ function setupForm(&$mform) {
+ $objs = array();
+ if(is_array($this->_fields)) {
+ $objs[] =& $mform->createElement('select', $this->_name . '_fld', null, $this->_fields);
+ }
+ $objs[] =& $mform->createElement('checkbox', $this->_name . '_sck', null, get_string('isafter', 'filters'));
+ $objs[] =& $mform->createElement('date_selector', $this->_name . '_sdt', null);
+ $objs[] =& $mform->createElement('checkbox', $this->_name . '_eck', null, get_string('isbefore', 'filters'));
+ $objs[] =& $mform->createElement('date_selector', $this->_name . '_edt', null);
+ $grp =& $mform->addElement('group', $this->_name . '_grp', $this->_label, $objs, '', false);
+ $grp->setHelpButton(array('date','','filters'));
+ $mform->setDefault($this->_name . '_sck', !empty($this->_value));
+ $mform->setDefault($this->_name . '_eck', !empty($this->_value2));
+ $mform->setDefault($this->_name . '_sdt', $this->_value);
+ $mform->setDefault($this->_name . '_edt', $this->_value2);
+ if(is_array($this->_fields)) {
+ $mform->setDefault($this->_name . '_fld', $this->_field);
+ }
+ $mform->disabledIf($this->_name . '_sdt', $this->_name . '_sck');
+ $mform->disabledIf($this->_name . '_edt', $this->_name . '_eck');
+ }
+
+ /**
+ * Retrieves data from the form data
+ * @param object $formdata data submited with the form
+ */
+ function checkData($formdata) {
+ $fld = $this->_name . '_fld';
+ $sdt = $this->_name . '_sdt';
+ $edt = $this->_name . '_edt';
+ $sck = $this->_name . '_sck';
+ $eck = $this->_name . '_eck';
+ if(@$formdata->$fld) {
+ $this->_field = @$formdata->$fld;
+ }
+ $this->_value = @$formdata->$sck ? (int)@$formdata->$sdt : 0;
+ $this->_value2 = @$formdata->$eck ? (int)@$formdata->$edt : 0;
+ }
+
+ /**
+ * Returns the condition to be used with SQL where
+ * @return string the filtering condition or null if the filter is disabled
+ */
+ function getSQLFilter() {
+ if(empty($this->_value) && empty($this->_value2)) {
+ return null;
+ }
+ $res = $this->_field . '>0' ;
+ if($this->_value) {
+ $res .= ' AND ' . $this->_field . '>=' . $this->_value;
+ }
+ if($this->_value2) {
+ $res .= ' AND ' . $this->_field . '<=' . $this->_value2;
+ }
+ return $res;
+ }
+
+ /**
+ * Returns a human friendly description of the filter.
+ * @return string filter description
+ */
+ function getDescription() {
+ if(is_array($this->_fields)) {
+ $res = $this->_fields[$this->_field] . ' ';
+ } else {
+ $res = $this->_label . ' ';
+ }
+ if($this->_value && $this->_value2) {
+ $res .= get_string('isbetween', 'filters', array(userdate($this->_value), userdate($this->_value2)));
+ } else if($this->_value) {
+ $res .= get_string('isafter', 'filters', userdate($this->_value));
+ } else {
+ $res .= get_string('isbefore', 'filters', userdate($this->_value2));
+ }
+ return $res;
+ }
+}
+?>
\ No newline at end of file