1: # The LearningOnline Network with CAPA
2: # Utility functions for managing LON-CAPA user accounts
3: #
4: # $Id: lonuserutils.pm,v 1.4 2007/11/10 22:18:09 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA#
23: # /home/httpd/html/adm/gpl.txt
24: #
25: # http://www.lon-capa.org/
26: #
27: #
28: ###############################################################
29: ###############################################################
30:
31: package Apache::lonuserutils;
32:
33: use strict;
34: use Apache::lonnet;
35: use Apache::loncommon();
36: use Apache::lonhtmlcommon;
37: use Apache::lonlocal;
38: use LONCAPA();
39:
40: ###############################################################
41: ###############################################################
42: # Drop student from all sections of a course, except optional $csec
43: sub modifystudent {
44: my ($udom,$unam,$courseid,$csec,$desiredhost)=@_;
45: # if $csec is undefined, drop the student from all the courses matching
46: # this one. If $csec is defined, drop them from all other sections of
47: # this course and add them to section $csec
48: my $cdom = $env{'course.'.$courseid.'.domain'};
49: my $cnum = $env{'course.'.$courseid.'.num'};
50: my %roles = &Apache::lonnet::dump('roles',$udom,$unam);
51: my ($tmp) = keys(%roles);
52: # Bail out if we were unable to get the students roles
53: return "$1" if ($tmp =~ /^(con_lost|error|no_such_host)/i);
54: # Go through the roles looking for enrollment in this course
55: my $result = '';
56: foreach my $course (keys(%roles)) {
57: if ($course=~m{^/\Q$cdom\E/\Q$cnum\E(?:\/)*(?:\s+)*(\w+)*\_st$}) {
58: # We are in this course
59: my $section=$1;
60: $section='' if ($course eq "/$cdom/$cnum".'_st');
61: if (defined($csec) && $section eq $csec) {
62: $result .= 'ok:';
63: } elsif ( ((!$section) && (!$csec)) || ($section ne $csec) ) {
64: my (undef,$end,$start)=split(/\_/,$roles{$course});
65: my $now=time;
66: # if this is an active role
67: if (!($start && ($now<$start)) || !($end && ($now>$end))) {
68: my $reply=&Apache::lonnet::modifystudent
69: # dom name id mode pass f m l g
70: ($udom,$unam,'', '', '',undef,undef,undef,undef,
71: $section,time,undef,undef,$desiredhost);
72: $result .= $reply.':';
73: }
74: }
75: }
76: }
77: if ($result eq '') {
78: $result = 'Unable to find section for this student';
79: } else {
80: $result =~ s/(ok:)+/ok/g;
81: }
82: return $result;
83: }
84:
85: sub modifyuserrole {
86: my ($context,$setting,$changeauth,$cid,$udom,$uname,$uid,$umode,$upass,
87: $first,$middle,$last,$gene,$sec,$forceid,$desiredhome,$email,$role,
88: $end,$start) = @_;
89: my ($scope,$userresult,$authresult,$roleresult);
90: if ($setting eq 'course' || $context eq 'course') {
91: $scope = '/'.$cid;
92: $scope =~ s/\_/\//g;
93: if ($role ne 'cc' && $sec ne '') {
94: $scope .='/'.$sec;
95: }
96: } elsif ($setting eq 'domain') {
97: $scope = '/'.$env{'request.role.domain'}.'/';
98: } elsif ($setting eq 'construction_space') {
99: $scope = '/'.$env{'user.domain'}.'/'.$env{'user.name'};
100: }
101: if ($context eq 'domain') {
102: my $uhome = &Apache::lonnet::homeserver($uname,$udom);
103: if ($uhome ne 'no_host') {
104: if (($changeauth) && (&Apache::lonnet::allowed('mau',$udom))) {
105: if ((($umode =~ /^krb4|krb5|internal$/) && $upass ne '') ||
106: ($umode eq 'localauth')) {
107: $authresult = &Apache::lonnet::modifyuserauth($udom,$uname,$umode,$upass);
108: }
109: }
110: }
111: }
112: $userresult =
113: &Apache::lonnet::modifyuser($udom,$uname,$uid,$umode,$upass,$first,
114: $middle,$last,$gene,$forceid,$desiredhome,
115: $email,$role,$start,$end);
116: if ($userresult eq 'ok') {
117: if ($role ne '') {
118: $roleresult = &Apache::lonnet::assignrole($udom,$uname,$scope,
119: $role,$end,$start);
120: }
121: }
122: return ($userresult,$authresult,$roleresult);
123: }
124:
125: ###############################################################
126: ###############################################################
127: # build a role type and role selection form
128: sub domain_roles_select {
129: # Set up the role type and role selection boxes when in
130: # domain context
131: #
132: # Role types
133: my @roletypes = ('domain','construction_space','course');
134: my %lt = &role_type_names();
135: #
136: # build up the menu information to be passed to
137: # &Apache::loncommon::linked_select_forms
138: my %select_menus;
139: if ($env{'form.roletype'} eq '') {
140: $env{'form.roletype'} = 'domain';
141: }
142: foreach my $roletype (@roletypes) {
143: # set up the text for this domain
144: $select_menus{$roletype}->{'text'}= $lt{$roletype};
145: # we want a choice of 'default' as the default in the second menu
146: if ($env{'form.roletype'} ne '') {
147: $select_menus{$roletype}->{'default'} = $env{'form.showrole'};
148: } else {
149: $select_menus{$roletype}->{'default'} = 'Any';
150: }
151: # Now build up the other items in the second menu
152: my @roles;
153: if ($roletype eq 'domain') {
154: @roles = &domain_roles();
155: } elsif ($roletype eq 'construction_space') {
156: @roles = &construction_space_roles();
157: } else {
158: @roles = &course_roles('domain');
159: }
160: my $order = ['Any',@roles];
161: $select_menus{$roletype}->{'order'} = $order;
162: foreach my $role (@roles) {
163: $select_menus{$roletype}->{'select2'}->{$role} =
164: &Apache::lonnet::plaintext($role);
165: }
166: $select_menus{$roletype}->{'select2'}->{'Any'} = &mt('Any');
167: }
168: my $result = &Apache::loncommon::linked_select_forms
169: ('studentform',(' 'x3).&mt('Role: '),$env{'form.roletype'},
170: 'roletype','showrole',\%select_menus,['domain','construction_space','course']);
171: return $result;
172: }
173:
174: ###############################################################
175: ###############################################################
176: sub hidden_input {
177: my ($name,$value) = @_;
178: return '<input type="hidden" name="'.$name.'" value="'.$value.'" />'."\n";
179: }
180:
181: sub print_upload_manager_header {
182: my ($r,$datatoken,$distotal,$krbdefdom,$context)=@_;
183: my $javascript;
184: #
185: if (! exists($env{'form.upfile_associate'})) {
186: $env{'form.upfile_associate'} = 'forward';
187: }
188: if ($env{'form.associate'} eq 'Reverse Association') {
189: if ( $env{'form.upfile_associate'} ne 'reverse' ) {
190: $env{'form.upfile_associate'} = 'reverse';
191: } else {
192: $env{'form.upfile_associate'} = 'forward';
193: }
194: }
195: if ($env{'form.upfile_associate'} eq 'reverse') {
196: $javascript=&upload_manager_javascript_reverse_associate();
197: } else {
198: $javascript=&upload_manager_javascript_forward_associate();
199: }
200: #
201: # Deal with restored settings
202: my $password_choice = '';
203: if (exists($env{'form.ipwd_choice'}) &&
204: $env{'form.ipwd_choice'} ne '') {
205: # If a column was specified for password, assume it is for an
206: # internal password. This is a bug waiting to be filed (could be
207: # local or krb auth instead of internal) but I do not have the
208: # time to mess around with this now.
209: $password_choice = 'int';
210: }
211: #
212: my $javascript_validations =
213: &javascript_validations('auth',$krbdefdom,$password_choice,undef,
214: $env{'request.role.domain'});
215: my $checked=(($env{'form.noFirstLine'})?' checked="checked" ':'');
216: $r->print(&mt('Total number of records found in file: <b>[_1]</b>.',$distotal).
217: "<br />\n");
218: $r->print('<div class="LC_left_float"><h3>'.
219: &mt('Identify fields in uploaded list')."</h3>\n");
220: $r->print(&mt('Enter as many fields as you can.<br /> The system will inform you and bring you back to this page, <br /> if the data selected are insufficient to add users.')."<br />\n");
221: $r->print(&hidden_input('action','upload').
222: &hidden_input('state','got_file').
223: &hidden_input('associate','').
224: &hidden_input('datatoken',$datatoken).
225: &hidden_input('fileupload',$env{'form.fileupload'}).
226: &hidden_input('upfiletype',$env{'form.upfiletype'}).
227: &hidden_input('upfile_associate',$env{'form.upfile_associate'}));
228: $r->print('<br /><input type="button" value="Reverse Association" '.
229: 'name="'.&mt('Reverse Association').'" '.
230: 'onClick="javascript:this.form.associate.value=\'Reverse Association\';submit(this.form);" />');
231: $r->print('<label><input type="checkbox" name="noFirstLine"'.$checked.'/>'.
232: &mt('Ignore First Line').'</label>');
233: $r->print("<br /><br />\n".
234: '<script type="text/javascript" language="Javascript">'."\n".
235: $javascript."\n".$javascript_validations.'</script>');
236: }
237:
238: ###############################################################
239: ###############################################################
240: sub javascript_validations {
241: my ($mode,$krbdefdom,$curr_authtype,$curr_authfield,$domain)=@_;
242: my $authheader;
243: if ($mode eq 'auth') {
244: my %param = ( formname => 'studentform',
245: kerb_def_dom => $krbdefdom,
246: curr_authtype => $curr_authtype);
247: $authheader = &Apache::loncommon::authform_header(%param);
248: } elsif ($mode eq 'createcourse') {
249: my %param = ( formname => 'ccrs',
250: kerb_def_dom => $krbdefdom,
251: curr_authtype => $curr_authtype );
252: $authheader = &Apache::loncommon::authform_header(%param);
253: } elsif ($mode eq 'modifycourse') {
254: my %param = ( formname => 'cmod',
255: kerb_def_dom => $krbdefdom,
256: mode => 'modifycourse',
257: curr_authtype => $curr_authtype,
258: curr_autharg => $curr_authfield );
259: $authheader = &Apache::loncommon::authform_header(%param);
260: }
261:
262: my %alert = &Apache::lonlocal::texthash
263: (username => 'You need to specify the username field.',
264: authen => 'You must choose an authentication type.',
265: krb => 'You need to specify the Kerberos domain.',
266: ipass => 'You need to specify the initial password.',
267: name => 'The optional name field was not specified.',
268: snum => 'The optional ID number field was not specified.',
269: section => 'The optional section field was not specified.',
270: email => 'The optional email address field was not specified.',
271: role => 'The optional role field was not specified.',
272: continue => 'Continue adding users?',
273: );
274:
275: # my $pjump_def = &Apache::lonhtmlcommon::pjump_javascript_definition();
276: my $function_name =(<<END);
277: function verify_message (vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail) {
278: END
279: my ($authnum,%can_assign) = &Apache::loncommon::get_assignable_auth($domain);
280: my $auth_checks;
281: if ($mode eq 'createcourse') {
282: $auth_checks .= (<<END);
283: if (vf.autoadds[0].checked == true) {
284: if (current.radiovalue == null || current.radiovalue == 'nochange') {
285: alert('$alert{'authen'}');
286: return;
287: }
288: }
289: END
290: } else {
291: $auth_checks .= (<<END);
292: var foundatype=0;
293: if (founduname==0) {
294: alert('$alert{'username'}');
295: return;
296: }
297:
298: END
299: if ($authnum > 1) {
300: $auth_checks .= (<<END);
301: if (current.radiovalue == null || current.radiovalue == '' || current.radiovalue == 'nochange') {
302: // They did not check any of the login radiobuttons.
303: alert('$alert{'authen'}');
304: return;
305: }
306: END
307: }
308: }
309: if ($mode eq 'createcourse') {
310: $auth_checks .= "
311: if ( (vf.autoadds[0].checked == true) &&
312: (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') ) {
313: ";
314: } elsif ($mode eq 'modifycourse') {
315: $auth_checks .= "
316: if (vf.elements[current.argfield].value == null || vf.elements[current.argfield].value == '') {
317: ";
318: }
319: if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
320: $auth_checks .= (<<END);
321: var alertmsg = '';
322: switch (current.radiovalue) {
323: case 'krb':
324: alertmsg = '$alert{'krb'}';
325: break;
326: default:
327: alertmsg = '';
328: }
329: if (alertmsg != '') {
330: alert(alertmsg);
331: return;
332: }
333: }
334: END
335: } else {
336: $auth_checks .= (<<END);
337: foundatype=1;
338: if (current.argfield == null || current.argfield == '') {
339: var alertmsg = '';
340: switch (current.value) {
341: case 'krb':
342: alertmsg = '$alert{'krb'}';
343: break;
344: case 'loc':
345: case 'fsys':
346: alertmsg = '$alert{'ipass'}';
347: break;
348: case 'fsys':
349: alertmsg = '';
350: break;
351: default:
352: alertmsg = '';
353: }
354: if (alertmsg != '') {
355: alert(alertmsg);
356: return;
357: }
358: }
359: END
360: }
361: my $section_checks;
362: my $optional_checks = '';
363: if ( ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
364: $optional_checks = (<<END);
365: vf.submit();
366: }
367: END
368: } else {
369: $section_checks = §ion_check_js();
370: $optional_checks = (<<END);
371: var message='';
372: if (foundname==0) {
373: message='$alert{'name'}';
374: }
375: if (foundid==0) {
376: if (message!='') {
377: message+='\\n';
378: }
379: message+='$alert{'snum'}';
380: }
381: if (foundsec==0) {
382: if (message!='') {
383: message+='\\n';
384: }
385: }
386: if (foundemail==0) {
387: if (message!='') {
388: message+='\\n';
389: }
390: message+='$alert{'email'}';
391: }
392: if (message!='') {
393: message+= '\\n$alert{'continue'}';
394: if (confirm(message)) {
395: vf.state.value='enrolling';
396: vf.submit();
397: }
398: } else {
399: vf.state.value='enrolling';
400: vf.submit();
401: }
402: }
403: END
404: }
405: my $result = $function_name;
406: if ( ($mode eq 'auth') || ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
407: $result .= $auth_checks;
408: }
409: $result .= $optional_checks."\n".$section_checks;
410: if ( ($mode eq 'auth') || ($mode eq 'createcourse') || ($mode eq 'modifycourse') ) {
411: $result .= $authheader;
412: }
413: return $result;
414: }
415: ###############################################################
416: ###############################################################
417: sub upload_manager_javascript_forward_associate {
418: return(<<ENDPICK);
419: function verify(vf,sec_caller) {
420: var founduname=0;
421: var foundpwd=0;
422: var foundname=0;
423: var foundid=0;
424: var foundsec=0;
425: var foundemail=0;
426: var foundrole=0;
427: var tw;
428: for (i=0;i<=vf.nfields.value;i++) {
429: tw=eval('vf.f'+i+'.selectedIndex');
430: if (tw==1) { founduname=1; }
431: if ((tw>=2) && (tw<=6)) { foundname=1; }
432: if (tw==7) { foundid=1; }
433: if (tw==8) { foundsec=1; }
434: if (tw==9) { foundpwd=1; }
435: if (tw==10) { foundemail=1; }
436: if (tw==11) { foundrole=1; }
437: }
438: verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundemail,foundrole);
439: }
440:
441: //
442: // vf = this.form
443: // tf = column number
444: //
445: // values of nw
446: //
447: // 0 = none
448: // 1 = username
449: // 2 = names (lastname, firstnames)
450: // 3 = fname (firstname)
451: // 4 = mname (middlename)
452: // 5 = lname (lastname)
453: // 6 = gen (generation)
454: // 7 = id
455: // 8 = section
456: // 9 = ipwd (password)
457: // 10 = email address
458: // 11 = role
459:
460: function flip(vf,tf) {
461: var nw=eval('vf.f'+tf+'.selectedIndex');
462: var i;
463: // make sure no other columns are labeled the same as this one
464: for (i=0;i<=vf.nfields.value;i++) {
465: if ((i!=tf) && (eval('vf.f'+i+'.selectedIndex')==nw)) {
466: eval('vf.f'+i+'.selectedIndex=0;')
467: }
468: }
469: // If we set this to 'lastname, firstnames', clear out all the ones
470: // set to 'fname','mname','lname','gen' (3,4,5,6) currently.
471: if (nw==2) {
472: for (i=0;i<=vf.nfields.value;i++) {
473: if ((eval('vf.f'+i+'.selectedIndex')>=3) &&
474: (eval('vf.f'+i+'.selectedIndex')<=6)) {
475: eval('vf.f'+i+'.selectedIndex=0;')
476: }
477: }
478: }
479: // If we set this to one of 'fname','mname','lname','gen' (3,4,5,6),
480: // clear out any that are set to 'lastname, firstnames' (2)
481: if ((nw>=3) && (nw<=6)) {
482: for (i=0;i<=vf.nfields.value;i++) {
483: if (eval('vf.f'+i+'.selectedIndex')==2) {
484: eval('vf.f'+i+'.selectedIndex=0;')
485: }
486: }
487: }
488: // If we set the password, make the password form below correspond to
489: // the new value.
490: if (nw==9) {
491: changed_radio('int',document.studentform);
492: set_auth_radio_buttons('int',document.studentform);
493: vf.intarg.value='';
494: vf.krbarg.value='';
495: vf.locarg.value='';
496: }
497: }
498:
499: function clearpwd(vf) {
500: var i;
501: for (i=0;i<=vf.nfields.value;i++) {
502: if (eval('vf.f'+i+'.selectedIndex')==9) {
503: eval('vf.f'+i+'.selectedIndex=0;')
504: }
505: }
506: }
507:
508: ENDPICK
509: }
510:
511: ###############################################################
512: ###############################################################
513: sub upload_manager_javascript_reverse_associate {
514: return(<<ENDPICK);
515: function verify(vf,sec_caller) {
516: var founduname=0;
517: var foundpwd=0;
518: var foundname=0;
519: var foundid=0;
520: var foundsec=0;
521: var foundrole=0;
522: var tw;
523: for (i=0;i<=vf.nfields.value;i++) {
524: tw=eval('vf.f'+i+'.selectedIndex');
525: if (i==0 && tw!=0) { founduname=1; }
526: if (((i>=1) && (i<=5)) && tw!=0 ) { foundname=1; }
527: if (i==6 && tw!=0) { foundid=1; }
528: if (i==7 && tw!=0) { foundsec=1; }
529: if (i==8 && tw!=0) { foundpwd=1; }
530: if (i==9 && tw!=0) { foundrole=1; }
531: }
532: verify_message(vf,founduname,foundpwd,foundname,foundid,foundsec,foundrole);
533: }
534:
535: function flip(vf,tf) {
536: var nw=eval('vf.f'+tf+'.selectedIndex');
537: var i;
538: // picked the all one name field, reset the other name ones to blank
539: if (tf==1 && nw!=0) {
540: for (i=2;i<=5;i++) {
541: eval('vf.f'+i+'.selectedIndex=0;')
542: }
543: }
544: //picked one of the piecewise name fields, reset the all in
545: //one field to blank
546: if ((tf>=2) && (tf<=5) && (nw!=0)) {
547: eval('vf.f1.selectedIndex=0;')
548: }
549: // intial password specified, pick internal authentication
550: if (tf==8 && nw!=0) {
551: changed_radio('int',document.studentform);
552: set_auth_radio_buttons('int',document.studentform);
553: vf.krbarg.value='';
554: vf.intarg.value='';
555: vf.locarg.value='';
556: }
557: }
558:
559: function clearpwd(vf) {
560: var i;
561: if (eval('vf.f8.selectedIndex')!=0) {
562: eval('vf.f8.selectedIndex=0;')
563: }
564: }
565: ENDPICK
566: }
567:
568: ###############################################################
569: ###############################################################
570: sub print_upload_manager_footer {
571: my ($r,$i,$keyfields,$defdom,$today,$halfyear,$context)=@_;
572: my $formname;
573: if ($context eq 'course') {
574: $formname = 'document.studentform';
575: } elsif ($context eq 'construction_space') {
576: $formname = 'document.studentform';
577: } elsif ($context eq 'domain') {
578: $formname = 'document.studentform';
579: }
580: my ($krbdef,$krbdefdom) =
581: &Apache::loncommon::get_kerberos_defaults($defdom);
582: my %param = ( formname => $formname,
583: kerb_def_dom => $krbdefdom,
584: kerb_def_auth => $krbdef
585: );
586: if (exists($env{'form.ipwd_choice'}) &&
587: defined($env{'form.ipwd_choice'}) &&
588: $env{'form.ipwd_choice'} ne '') {
589: $param{'curr_authtype'} = 'int';
590: }
591: my $krbform = &Apache::loncommon::authform_kerberos(%param);
592: my $intform = &Apache::loncommon::authform_internal(%param);
593: my $locform = &Apache::loncommon::authform_local(%param);
594: my $date_table = &date_setting_table(undef,undef,$context);
595:
596: my $Str = "\n".'<div class="LC_left_float">';
597: $Str .= &hidden_input('nfields',$i);
598: $Str .= &hidden_input('keyfields',$keyfields);
599: $Str .= "<h3>".&mt('Login Type')."</h3>\n";
600: if ($context eq 'domain') {
601: $Str .= '<p>'.&mt('Change authentication for existing users to these settings?').' <span class="LC_nobreak"><label><input type="radio" name="changeauth" value="No" checked="checked" />'.&mt('No').'</label> <label><input type="radio" name="changeauth" value="Yes" />'.&mt('Yes').'</label></span></p>';
602: } else {
603: $Str .= "<p>\n".
604: &mt('Note: this will not take effect if the user already exists').
605: &Apache::loncommon::help_open_topic('Auth_Options').
606: "</p>\n";
607: }
608: $Str .= &set_login($defdom,$krbform,$intform,$locform);
609: my ($home_server_pick,$numlib) =
610: &Apache::loncommon::home_server_form_item($defdom,'lcserver',
611: 'default','hide');
612: if ($numlib > 1) {
613: $Str .= '<h3>'.&mt('LON-CAPA Home Server for New Users')."</h3>\n".
614: &mt('LON-CAPA domain: [_1] with home server: [_2]',$defdom,
615: $home_server_pick).'<br />';
616: } else {
617: $Str .= $home_server_pick;
618: }
619: $Str .= '<h3>'.&mt('Starting and Ending Dates').
620: "</h3>\n";
621: $Str .= "<p>\n".$date_table."</p>\n";
622: if ($context eq 'domain') {
623: $Str .= '<h3>'.&mt('Settings for assigning roles:').'</h3>'."\n".
624: &mt('Pick the action to take on roles for these users:').'<br /><span class="LC_nobreak"><label><input type="radio" name="roleaction" value="norole" checked="checked" /> '.&mt('No role changes').'</label> <label><input type="radio" name="roleaction" value="domain" /> '.&mt('Add a domain role').'</label> <label><input type="radio" name="roleaction" value="course" /> '.&mt('Add a course role').'</label></span>';
625: }
626: if ($context eq 'construction_space') {
627: $Str .= '<h3>'.&mt('Default role')."</h3>\n".
628: &mt('Choose the role to assign to users without one specified in the uploaded file');
629: } elsif ($context eq 'course') {
630: $Str .= '<h3>'.&mt('Default role and section')."</h3>\n".
631: &mt('Choose the role and/or section to assign to users without one specified in the uploaded file');
632: } else {
633: $Str .= '<br /><br /><b>'.&mt('Default role and/or section')."</b><br />\n".
634: &mt('Role and/or section for users without one in the uploaded file.');
635: }
636: $Str .= '<br /><br />';
637: my ($options,$cb_script,$coursepick) = &default_role_selector($context,'defaultrole',1);
638: if ($context eq 'domain') {
639: $Str .= '<span class="LC_role_level">'.&mt('Domain Level').'</span><br />'.$options.'<br /><br /><span class="LC_role_level">'.&mt('Course Level').'</span><br />'.$cb_script.$coursepick;
640: } else {
641: $Str .= $options;
642: }
643: if ($context eq 'course') {
644: $Str .= "<h3>".&mt('Full Update')."</h3>\n".
645: '<label><input type="checkbox" name="fullup" value="yes">'.
646: ' '.&mt('Full update (also print list of users not enrolled anymore)').
647: "</label></p>\n";
648: }
649: $Str .= "<h3>".&mt('ID/Student Number')."</h3>\n";
650: $Str .= "<p>\n".'<label><input type="checkbox" name="forceid" value="yes">';
651: $Str .= &mt('Disable ID/Student Number Safeguard and Force Change '.
652: 'of Conflicting IDs').
653: '</label><br />'."\n".
654: &mt('(only do if you know what you are doing.)')."</p><p>\n";
655: $Str .= '</div><div class="LC_clear_float_footer"><br /><input type="button"'.
656: 'onClick="javascript:verify(this.form,this.form.csec)" '.
657: 'value="Update Users" />'."<br />\n";
658: if ($context eq 'course') {
659: $Str .= &mt('Note: for large courses, this operation may be time '.
660: 'consuming');
661: }
662: $Str .= '</div>';
663: $r->print($Str);
664: return;
665: }
666:
667: ###############################################################
668: ###############################################################
669: sub print_upload_manager_form {
670: my ($r,$context) = @_;
671: my $firstLine;
672: my $datatoken;
673: if (!$env{'form.datatoken'}) {
674: $datatoken=&Apache::loncommon::upfile_store($r);
675: } else {
676: $datatoken=$env{'form.datatoken'};
677: &Apache::loncommon::load_tmp_file($r);
678: }
679: my @records=&Apache::loncommon::upfile_record_sep();
680: if($env{'form.noFirstLine'}){
681: $firstLine=shift(@records);
682: }
683: my $total=$#records;
684: my $distotal=$total+1;
685: my $today=time;
686: my $halfyear=$today+15552000;
687: #
688: # Restore memorized settings
689: my $col_setting_names = { 'username_choice' => 'scalar', # column settings
690: 'names_choice' => 'scalar',
691: 'fname_choice' => 'scalar',
692: 'mname_choice' => 'scalar',
693: 'lname_choice' => 'scalar',
694: 'gen_choice' => 'scalar',
695: 'id_choice' => 'scalar',
696: 'sec_choice' => 'scalar',
697: 'ipwd_choice' => 'scalar',
698: 'email_choice' => 'scalar',
699: 'role_choice' => 'scalar',
700: };
701: my $defdom = $env{'request.role.domain'};
702: if ($context eq 'course') {
703: &Apache::loncommon::restore_course_settings('enrollment_upload',
704: $col_setting_names);
705: } else {
706: &Apache::loncommon::restore_settings($context,'user_upload',
707: $col_setting_names);
708: }
709: #
710: # Determine kerberos parameters as appropriate
711: my ($krbdef,$krbdefdom) =
712: &Apache::loncommon::get_kerberos_defaults($defdom);
713: #
714: &print_upload_manager_header($r,$datatoken,$distotal,$krbdefdom,$context);
715: my $i;
716: my $keyfields;
717: if ($total>=0) {
718: my @field=
719: (['username',&mt('Username'), $env{'form.username_choice'}],
720: ['names',&mt('Last Name, First Names'),$env{'form.names_choice'}],
721: ['fname',&mt('First Name'), $env{'form.fname_choice'}],
722: ['mname',&mt('Middle Names/Initials'),$env{'form.mname_choice'}],
723: ['lname',&mt('Last Name'), $env{'form.lname_choice'}],
724: ['gen', &mt('Generation'), $env{'form.gen_choice'}],
725: ['id', &mt('ID/Student Number'),$env{'form.id_choice'}],
726: ['sec', &mt('Section'), $env{'form.sec_choice'}],
727: ['ipwd', &mt('Initial Password'),$env{'form.ipwd_choice'}],
728: ['email',&mt('E-mail Address'), $env{'form.email_choice'}],
729: ['role',&mt('Role'), $env{'form.role_choice'}]);
730: if ($env{'form.upfile_associate'} eq 'reverse') {
731: &Apache::loncommon::csv_print_samples($r,\@records);
732: $i=&Apache::loncommon::csv_print_select_table($r,\@records,
733: \@field);
734: foreach (@field) {
735: $keyfields.=$_->[0].',';
736: }
737: chop($keyfields);
738: } else {
739: unshift(@field,['none','']);
740: $i=&Apache::loncommon::csv_samples_select_table($r,\@records,
741: \@field);
742: my %sone=&Apache::loncommon::record_sep($records[0]);
743: $keyfields=join(',',sort(keys(%sone)));
744: }
745: }
746: $r->print('</div>');
747: &print_upload_manager_footer($r,$i,$keyfields,$defdom,$today,$halfyear,
748: $context);
749: }
750:
751: sub setup_date_selectors {
752: my ($starttime,$endtime,$mode) = @_;
753: if (! defined($starttime)) {
754: $starttime = time;
755: unless ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
756: if (exists($env{'course.'.$env{'request.course.id'}.
757: '.default_enrollment_start_date'})) {
758: $starttime = $env{'course.'.$env{'request.course.id'}.
759: '.default_enrollment_start_date'};
760: }
761: }
762: }
763: if (! defined($endtime)) {
764: $endtime = time+(6*30*24*60*60); # 6 months from now, approx
765: unless ($mode eq 'createcourse') {
766: if (exists($env{'course.'.$env{'request.course.id'}.
767: '.default_enrollment_end_date'})) {
768: $endtime = $env{'course.'.$env{'request.course.id'}.
769: '.default_enrollment_end_date'};
770: }
771: }
772: }
773: my $startdateform = &Apache::lonhtmlcommon::date_setter('studentform',
774: 'startdate',
775: $starttime);
776: my $enddateform = &Apache::lonhtmlcommon::date_setter('studentform',
777: 'enddate',
778: $endtime);
779: if ($mode eq 'create_enrolldates') {
780: $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
781: 'startenroll',
782: $starttime);
783: $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
784: 'endenroll',
785: $endtime);
786: }
787: if ($mode eq 'create_defaultdates') {
788: $startdateform = &Apache::lonhtmlcommon::date_setter('ccrs',
789: 'startaccess',
790: $starttime);
791: $enddateform = &Apache::lonhtmlcommon::date_setter('ccrs',
792: 'endaccess',
793: $endtime);
794: }
795: return ($startdateform,$enddateform);
796: }
797:
798:
799: sub get_dates_from_form {
800: my $startdate = &Apache::lonhtmlcommon::get_date_from_form('startdate');
801: my $enddate = &Apache::lonhtmlcommon::get_date_from_form('enddate');
802: if ($env{'form.no_end_date'}) {
803: $enddate = 0;
804: }
805: return ($startdate,$enddate);
806: }
807:
808: sub date_setting_table {
809: my ($starttime,$endtime,$mode) = @_;
810: my ($startform,$endform)=&setup_date_selectors($starttime,$endtime,$mode);
811: my $dateDefault;
812: if ($mode eq 'create_enrolldates' || $mode eq 'create_defaultdates') {
813: $dateDefault = ' ';
814: } elsif ($mode ne 'construction_space' && $mode ne 'domain') {
815: $dateDefault = '<nobr>'.
816: '<label><input type="checkbox" name="makedatesdefault" /> '.
817: &mt('make these dates the default for future enrollment').
818: '</label></nobr>';
819: }
820: my $perpetual = '<nobr><label><input type="checkbox" name="no_end_date"';
821: if (defined($endtime) && $endtime == 0) {
822: $perpetual .= ' checked';
823: }
824: $perpetual.= ' /> '.&mt('no ending date').'</label></nobr>';
825: if ($mode eq 'create_enrolldates') {
826: $perpetual = ' ';
827: }
828: my $result = &Apache::lonhtmlcommon::start_pick_box()."\n".
829: &Apache::lonhtmlcommon::row_title(&mt('Starting Date'),
830: 'LC_oddrow_value')."\n".
831: $startform."\n".
832: &Apache::lonhtmlcommon::row_closure(1).
833: &Apache::lonhtmlcommon::row_title(&mt('Ending Date'),
834: 'LC_oddrow_value')."\n".
835: $endform.' '.$perpetual.
836: &Apache::lonhtmlcommon::row_closure(1).
837: &Apache::lonhtmlcommon::end_pick_box().'<br />';
838: if ($dateDefault) {
839: $result .= $dateDefault.'<br />'."\n";
840: }
841: return $result;
842: }
843:
844: sub make_dates_default {
845: my ($startdate,$enddate,$context) = @_;
846: my $result = '';
847: if ($context eq 'course') {
848: my $dom = $env{'course.'.$env{'request.course.id'}.'.domain'};
849: my $crs = $env{'course.'.$env{'request.course.id'}.'.num'};
850: my $put_result = &Apache::lonnet::put('environment',
851: {'default_enrollment_start_date'=>$startdate,
852: 'default_enrollment_end_date' =>$enddate},$dom,$crs);
853: if ($put_result eq 'ok') {
854: $result .= "Set default start and end dates for course<br />";
855: #
856: # Refresh the course environment
857: &Apache::lonnet::coursedescription($env{'request.course.id'},
858: {'freshen_cache' => 1});
859: } else {
860: $result .= &mt('Unable to set default dates for course').":".$put_result.
861: '<br />';
862: }
863: }
864: return $result;
865: }
866:
867: sub default_role_selector {
868: my ($context,$checkpriv) = @_;
869: my %customroles;
870: my ($options,$coursepick,$cb_jscript);
871: if ($context ne 'construction_space') {
872: %customroles = &my_custom_roles();
873: }
874:
875: my %lt=&Apache::lonlocal::texthash(
876: 'rol' => "Role",
877: 'grs' => "Section",
878: 'exs' => "Existing sections",
879: 'new' => "New section",
880: );
881: $options = '<select name="defaultrole">'."\n".
882: ' <option value="">'.&mt('Please select').'</option>'."\n";
883: if ($context eq 'course') {
884: $options .= &default_course_roles($context,$checkpriv,%customroles);
885: } elsif ($context eq 'construction_space') {
886: my @roles = &construction_space_roles($checkpriv);
887: foreach my $role (@roles) {
888: my $plrole=&Apache::lonnet::plaintext($role);
889: $options .= ' <option value="'.$role.'">'.$plrole.'</option>'."\n";
890: }
891: } elsif ($context eq 'domain') {
892: my @roles = &domain_roles($checkpriv);
893: foreach my $role (@roles) {
894: my $plrole=&Apache::lonnet::plaintext($role);
895: $options .= ' <option value="'.$role.'">'.$plrole.'</option>';
896: }
897: my $courseform = &Apache::loncommon::selectcourse_link
898: ('studentform','defaultcourse','defaultdomain','defaultdesc',"$env{'request.role.domain'}",undef,'Course');
899: $cb_jscript =
900: &Apache::loncommon::coursebrowser_javascript($env{'request.role.domain'},'defaultsec','studentform');
901: $coursepick = &Apache::loncommon::start_data_table().
902: &Apache::loncommon::start_data_table_header_row().
903: '<th>'.$courseform.'</th><th>'.$lt{'rol'}.'</th>'.
904: '<th>'.$lt{'grs'}.'</th>'.
905: &Apache::loncommon::end_data_table_header_row().
906: &Apache::loncommon::start_data_table_row()."\n".
907: '<td><input type="text" name="defaultdesc" value="" onFocus="this.blur();opencrsbrowser('."'studentform','defcourse','defdomain','coursedesc',''".')" /></td>'."\n".
908: '<td><select name="courserole">'."\n".
909: &default_course_roles($context,$checkpriv,%customroles)."\n".
910: '</select></td><td>'.
911: '<table class="LC_createuser">'.
912: '<tr class="LC_section_row"><td valign"top">'.
913: $lt{'exs'}.'<br /><select name="defaultsec">'.
914: ' <option value=""><--'.&mt('Pick course first').
915: '</select></td>'.
916: '<td> </td>'.
917: '<td valign="top">'.$lt{'new'}.'<br />'.
918: '<input type="text" name="newsec" value="" size="5" />'.
919: '<input type="hidden" name="groups" value="" /></td>'.
920: '</tr></table></td>'.
921: &Apache::loncommon::end_data_table_row().
922: &Apache::loncommon::end_data_table()."\n".
923: '<input type="hidden" name="defaultcourse" value="" />'.
924: '<input type="hidden" name="defaultdomain" value="" />';
925: }
926: $options .= '</select>';
927: return ($options,$cb_jscript,$coursepick);
928: }
929:
930: sub default_course_roles {
931: my ($context,$checkpriv,%customroles) = @_;
932: my $output;
933: my @roles = &course_roles($context,$checkpriv);
934: foreach my $role (@roles) {
935: my $plrole=&Apache::lonnet::plaintext($role);
936: $output .= ' <option value="'.$role.'">'.$plrole.'</option>';
937: }
938: if (keys(%customroles) > 0) {
939: my %customroles = &my_custom_roles();
940: foreach my $cust (sort(keys(%customroles))) {
941: my $custrole='cr_cr_'.$env{'user.domain'}.
942: '_'.$env{'user.name'}.'_'.$cust;
943: $output .= ' <option value="'.$custrole.'">'.$cust.'</option>';
944: }
945: }
946: return $output;
947: }
948:
949: sub construction_space_roles {
950: my ($checkpriv) = @_;
951: my @allroles = ('ca','aa');
952: my @roles;
953: if ($checkpriv) {
954: foreach my $role (@allroles) {
955: if (&Apache::lonnet::allowed('c'.$role,$env{'user.domain'}.'/'.$env{'user.name'})) {
956: push(@roles,$role);
957: }
958: }
959: return @roles;
960: } else {
961: return @allroles;
962: }
963: }
964:
965: sub domain_roles {
966: my ($checkpriv) = @_;
967: my @allroles = ('dc','li','dg','au','sc');
968: my @roles;
969: if ($checkpriv) {
970: foreach my $role (@allroles) {
971: if (&Apache::lonnet::allowed('c'.$role,$env{'request.role.domain'})) {
972: push(@roles,$role);
973: }
974: }
975: return @roles;
976: } else {
977: return @allroles;
978: }
979: }
980:
981: sub course_roles {
982: my ($context,$checkpriv) = @_;
983: my @allroles = ('st','ta','ep','in','cc');
984: my @roles;
985: if ($context eq 'domain') {
986: @roles = @allroles;
987: } elsif ($context eq 'course') {
988: if ($env{'request.course.id'}) {
989: if ($checkpriv) {
990: foreach my $role (@allroles) {
991: if (&Apache::lonnet::allowed('c'.$role,$env{'request.course.id'})) {
992: push(@roles,$role);
993: } else {
994: if ($role ne 'cc' && $env{'request.course.section'} ne '') {
995: if (!&Apache::lonnet::allowed('c'.$role,
996: $env{'request.course.id'}.'/'.
997: $env{'request.course.section'})) {
998: push(@roles,$role);
999: }
1000: }
1001: }
1002: }
1003: } else {
1004: @roles = @allroles;
1005: }
1006: }
1007: }
1008: return @roles;
1009: }
1010:
1011: sub curr_role_permissions {
1012: my ($context,$setting,$checkpriv) = @_;
1013: my @roles;
1014: if ($context eq 'construction_space') {
1015: @roles = &construction_space_roles($checkpriv);
1016: } elsif ($context eq 'domain') {
1017: if ($setting eq 'course') {
1018: @roles = &course_roles($context,$checkpriv);
1019: } else {
1020: @roles = &domain_roles($checkpriv);
1021: }
1022: } elsif ($context eq 'course') {
1023: @roles = &course_roles($context,$checkpriv);
1024: }
1025: return @roles;
1026: }
1027:
1028: # ======================================================= Existing Custom Roles
1029:
1030: sub my_custom_roles {
1031: my %returnhash=();
1032: my %rolehash=&Apache::lonnet::dump('roles');
1033: foreach my $key (keys %rolehash) {
1034: if ($key=~/^rolesdef\_(\w+)$/) {
1035: $returnhash{$1}=$1;
1036: }
1037: }
1038: return %returnhash;
1039: }
1040:
1041: sub print_userlist {
1042: my ($r,$mode,$permission,$context,$formname,$totcodes,$codetitles,
1043: $idlist,$idlist_titles) = @_;
1044: my $format = $env{'form.output'};
1045: if (! exists($env{'form.sortby'})) {
1046: $env{'form.sortby'} = 'username';
1047: }
1048: if ($env{'form.Status'} !~ /^(Any|Expired|Active|Future)$/) {
1049: $env{'form.Status'} = 'Active';
1050: }
1051: my $status_select = &Apache::lonhtmlcommon::StatusOptions
1052: ($env{'form.Status'});
1053:
1054: if ($env{'form.showrole'} eq '') {
1055: $env{'form.showrole'} = 'Any';
1056: }
1057: if (! defined($env{'form.output'}) ||
1058: $env{'form.output'} !~ /^(csv|excel|html)$/ ) {
1059: $env{'form.output'} = 'html';
1060: }
1061:
1062: my @statuses;
1063: if ($env{'form.Status'} eq 'Any') {
1064: @statuses = ('previous','active','future');
1065: } elsif ($env{'form.Status'} eq 'Expired') {
1066: @statuses = ('previous');
1067: } elsif ($env{'form.Status'} eq 'Active') {
1068: @statuses = ('active');
1069: } elsif ($env{'form.Status'} eq 'Future') {
1070: @statuses = ('future');
1071: }
1072:
1073: # if ($context eq 'course') {
1074: # $r->print(&display_adv_courseroles());
1075: # }
1076: #
1077: # Interface output
1078: $r->print('<form name="studentform" method="post" action="/adm/createuser">'."\n".
1079: '<input type="hidden" name="action" value="'.
1080: $env{'form.action'}.'" />');
1081: $r->print("<p>\n");
1082: if ($env{'form.action'} ne 'modifystudent') {
1083: my %lt=&Apache::lonlocal::texthash('csv' => "CSV",
1084: 'excel' => "Excel",
1085: 'html' => 'HTML');
1086: my $output_selector = '<select size="1" name="output" >';
1087: foreach my $outputformat ('html','csv','excel') {
1088: my $option = '<option value="'.$outputformat.'" ';
1089: if ($outputformat eq $env{'form.output'}) {
1090: $option .= 'selected ';
1091: }
1092: $option .='>'.$lt{$outputformat}.'</option>';
1093: $output_selector .= "\n".$option;
1094: }
1095: $output_selector .= '</select>';
1096: $r->print('<label>'.&mt('Output Format: [_1]',$output_selector).'</label>'.(' 'x3));
1097: }
1098: $r->print('<label>'.&mt('User Status: [_1]',$status_select).'</label>'.(' 'x3)."\n");
1099: my $roleselected = '';
1100: if ($env{'form.showrole'} eq 'Any') {
1101: $roleselected = ' selected="selected" ';
1102: }
1103: my $role_select;
1104: if ($context eq 'domain') {
1105: $role_select = &domain_roles_select();
1106: $r->print('<label>'.&mt('Role Type: [_1]',$role_select).'</label>');
1107: } else {
1108: $role_select = '<select name="showrole">'."\n".
1109: '<option value="Any" '.$roleselected.'>'.
1110: &mt('Any role').'</option>';
1111: my @poss_roles = &curr_role_permissions($context);
1112: foreach my $role (@poss_roles) {
1113: $roleselected = '';
1114: if ($role eq $env{'form.showrole'}) {
1115: $roleselected = ' selected="selected" ';
1116: }
1117: my $plrole=&Apache::lonnet::plaintext($role);
1118: $role_select .= '<option value="'.$role.'"'.$roleselected.'>'.$plrole.'</option>';
1119: }
1120: $roleselected = '';
1121: if ($env{'form.showrole'} eq 'cr') {
1122: $roleselected = ' selected="selected" ';
1123: }
1124: $role_select .= '<option value="cr"'.$roleselected.'>'.&mt('Custom role').'</option>'.
1125: '</select>';
1126: $r->print('<label>'.&mt('Role: [_1]',$role_select).'</label>');
1127: }
1128: if (!(($context eq 'domain') && ($env{'form.roletype'} eq 'course'))) {
1129: $r->print(&list_submit_button(&mt('Update Display'))."\n</p>\n");
1130: }
1131: my ($indexhash,$keylist) = &make_keylist_array();
1132: my (%userlist,%userinfo);
1133: if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
1134: my $courseform =
1135: &Apache::lonhtmlcommon::course_selection($formname,$totcodes,
1136: $codetitles,$idlist,$idlist_titles);
1137: $r->print('<p>'.&Apache::lonhtmlcommon::start_pick_box()."\n".
1138: &Apache::lonhtmlcommon::start_pick_box()."\n".
1139: &Apache::lonhtmlcommon::row_title(&mt('Select Course(s)'),
1140: 'LC_oddrow_value')."\n".
1141: $courseform."\n".
1142: &Apache::lonhtmlcommon::row_closure(1).
1143: &Apache::lonhtmlcommon::end_pick_box().'</p>'.
1144: '<p>'.&list_submit_button(&mt('Update Display')).
1145: "\n</p>\n");
1146: }
1147: $r->print('<hr />'.&mt('Searching').' ...<br /> <br />');
1148: $r->rflush();
1149: if ($context eq 'course') {
1150: my $classlist = &Apache::loncoursedata::get_classlist();
1151: my $secidx = &Apache::loncoursedata::CL_SECTION();
1152: foreach my $student (keys(%{$classlist})) {
1153: if (exists($permission->{'view_section'})) {
1154: if ($classlist->{$student}[$secidx] ne $permission->{'view_section'}) {
1155: next;
1156: } else {
1157: $userlist{$student} = $classlist->{$student};
1158: }
1159: } else {
1160: $userlist{$student} = $classlist->{$student};
1161: }
1162: }
1163: my $cid =$env{'request.course.id'};
1164: my $cdom=$env{'course.'.$cid.'.domain'};
1165: my $cnum=$env{'course.'.$cid.'.num'};
1166: my $showroles;
1167: if ($env{'form.showrole'} ne 'Any') {
1168: $showroles = [$env{'form.showrole'}];
1169: } else {
1170: $showroles = undef;
1171: }
1172: my %advrolehash = &Apache::lonnet::get_my_roles($cnum,$cdom,undef,
1173: \@statuses,$showroles);
1174: &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
1175: \%advrolehash);
1176: } else {
1177: my (%cstr_roles,%dom_roles);
1178: if ($context eq 'construction_space') {
1179: # List co-authors and assistant co-authors
1180: my @possroles = ('ca','aa');
1181: %cstr_roles = &Apache::lonnet::get_my_roles(undef,undef,undef,
1182: \@statuses,\@possroles);
1183: &gather_userinfo($context,$format,\%userlist,$indexhash,\%userinfo,
1184: \%cstr_roles);
1185: } elsif ($context eq 'domain') {
1186: if ($env{'form.roletype'} eq 'domain') {
1187: %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'});
1188: foreach my $key (keys(%dom_roles)) {
1189: if (ref($dom_roles{$key}) eq 'HASH') {
1190: &gather_userinfo($context,$format,\%userlist,$indexhash,
1191: \%userinfo,$dom_roles{$key});
1192: }
1193: }
1194: } elsif ($env{'form.roletype'} eq 'construction_space') {
1195: my %dom_roles = &Apache::lonnet::get_domain_roles($env{'request.role.domain'},['au']);
1196: my %coauthors;
1197: foreach my $key (keys(%dom_roles)) {
1198: if (ref($dom_roles{$key}) eq 'HASH') {
1199: if ($env{'form.showrole'} eq 'au') {
1200: &gather_userinfo($context,$format,\%userlist,$indexhash,
1201: \%userinfo,$dom_roles{$key});
1202: } else {
1203: my @possroles;
1204: if ($env{'form.showrole'} eq 'Any') {
1205: @possroles = ('ca','aa');
1206: } else {
1207: @possroles = ($env{'form.showrole'});
1208: }
1209: foreach my $author (sort(keys(%{$dom_roles{$key}}))) {
1210: my ($role,$authorname,$authordom) = split(/:/,$author);
1211: my $extent = '/'.$authordom.'/'.$authorname;
1212: %{$coauthors{$extent}} =
1213: &Apache::lonnet::get_my_roles($authorname,
1214: $authordom,undef,\@statuses,\@possroles);
1215: }
1216: &gather_userinfo($context,$format,\%userlist,
1217: $indexhash,\%userinfo,\%coauthors);
1218: }
1219: }
1220: }
1221: } elsif ($env{'form.roletype'} eq 'course') {
1222: if ($env{'form.coursepick'}) {
1223: my %courses = &process_coursepick();
1224: my %allusers;
1225: foreach my $cid (keys(%courses)) {
1226: my %coursehash =
1227: &Apache::lonnet::coursedescription($cid,{'one_time' => 1});
1228: my $cdom = $coursehash{'domain'};
1229: my $cnum = $coursehash{'num'};
1230: my $cdesc = $coursehash{'description'};
1231: my (@roles,@sections,%access,%users,%userdata,
1232: %users,%statushash);
1233: if ($env{'form.showrole'} eq 'Any') {
1234: @roles = &course_roles($context);
1235: } else {
1236: @roles = ($env{'form.showrole'});
1237: }
1238: foreach my $role (@roles) {
1239: %{$users{$role}} = ();
1240: }
1241: foreach my $type (@statuses) {
1242: $access{$type} = $type;
1243: }
1244: &Apache::loncommon::get_course_users($cdom,$cnum,\%access,\@roles,\@sections,\%users,\%userdata,\%statushash);
1245: foreach my $user (keys(%userdata)) {
1246: next if (ref($userinfo{$user}) eq 'HASH');
1247: foreach my $item ('fullname','id') {
1248: $userinfo{$user}{$item} = $userdata{$user}[$indexhash->{$item}];
1249: }
1250: }
1251: foreach my $role (keys(%users)) {
1252: foreach my $user (keys(%{$users{$role}})) {
1253: my $uniqid = $user.':'.$role;
1254: $allusers{$uniqid}{$cid} = { desc => $cdesc,
1255: secs => $statushash{$user}{$role},
1256: };
1257: }
1258: }
1259: }
1260: &gather_userinfo($context,$format,\%userlist,$indexhash,
1261: \%userinfo,\%allusers);
1262: } else {
1263: return;
1264: }
1265: }
1266: }
1267: }
1268: if (keys(%userlist) == 0) {
1269: if ($context eq 'construction_space') {
1270: $r->print(&mt('There are no co-authors to display.')."\n");
1271: } elsif ($context eq 'domain') {
1272: if ($env{'form.roletype'} eq 'domain') {
1273: $r->print(&mt('There are no users with domain roles to display.')."\n");
1274: } elsif ($env{'form.roletype'} eq 'construction_space') {
1275: $r->print(&mt('There are no authors or co-authors to display.')."\n");
1276: } elsif ($env{'form.roletype'} eq 'course') {
1277: $r->print(&mt('There are no course users to display')."\n");
1278: }
1279: } elsif ($context eq 'course') {
1280: $r->print(&mt('There are no course users to display.')."\n");
1281: }
1282: } else {
1283: # Print out the available choices
1284: my $usercount;
1285: if ($env{'form.action'} eq 'modifystudent') {
1286: ($usercount) = &show_users_list($r,$context,'view','modify',
1287: $env{'form.Status'},\%userlist,$keylist);
1288: } else {
1289: ($usercount) = &show_users_list($r,$context,$env{'form.output'},
1290: 'aboutme',$env{'form.Status'},\%userlist,$keylist);
1291: }
1292: if (!$usercount) {
1293: $r->print('<br />'.&mt('There are no users matching the search criteria.'));
1294: }
1295: }
1296: $r->print('</form>');
1297: }
1298:
1299: sub list_submit_button {
1300: my ($text) = @_;
1301: return '<input type="submit" value="'.$text.'" />';
1302: }
1303:
1304: sub gather_userinfo {
1305: my ($context,$format,$userlist,$indexhash,$userinfo,$rolehash) = @_;
1306: foreach my $item (keys(%{$rolehash})) {
1307: @{$userlist->{$item}} = ();
1308: my %userdata;
1309: if ($context eq 'construction_space' || $context eq 'course') {
1310: ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
1311: split(/:/,$item);
1312: ($userdata{'start'},$userdata{'end'})=split(/:/,$rolehash->{$item});
1313: &build_user_record(\%userdata,$userinfo,$indexhash,$item,$userlist);
1314: } elsif ($context eq 'domain') {
1315: if ($env{'form.roletype'} eq 'domain') {
1316: ($userdata{'role'},$userdata{'username'},$userdata{'domain'}) =
1317: split(/:/,$item);
1318: ($userdata{'end'},$userdata{'start'})=split(/:/,$rolehash->{$item});
1319: &build_user_record(\%userdata,$userinfo,$indexhash,$item,$userlist);
1320: } elsif ($env{'form.roletype'} eq 'construction_space') {
1321: if (ref($rolehash->{$item}) eq 'HASH') {
1322: $userdata{'extent'} = $item;
1323: foreach my $key (keys(%{$rolehash->{$item}})) {
1324: ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) = split(/:/,$key);
1325: ($userdata{'start'},$userdata{'end'}) =
1326: split(/:/,$rolehash->{$item}{$key});
1327: my $uniqid = $key.':'.$item;
1328: &build_user_record(\%userdata,$userinfo,$indexhash,$uniqid,$userlist);
1329: }
1330: }
1331: } elsif ($env{'form.roletype'} eq 'course') {
1332: ($userdata{'username'},$userdata{'domain'},$userdata{'role'}) =
1333: split(/:/,$item);
1334: if (ref($rolehash->{$item}) eq 'HASH') {
1335: foreach my $cid (sort(keys(%{$rolehash->{$item}}))) {
1336: if (ref($rolehash->{$item}{$cid}) eq 'HASH') {
1337: my $spanstart = '';
1338: my $spanend = '; ';
1339: my $space = ', ';
1340: if ($format eq 'html' || $format eq 'view') {
1341: $spanstart = '<span class="LC_nobreak">';
1342: $spanend = '</span><br />';
1343: $space = ', ';
1344: }
1345: $userdata{'extent'} .= $spanstart.
1346: $rolehash->{$item}{$cid}{'desc'}.$space;
1347: if (ref($rolehash->{$item}{$cid}{'secs'}) eq 'HASH') {
1348: foreach my $sec (sort(keys(%{$rolehash->{$item}{$cid}{'secs'}}))) {
1349: $userdata{'extent'} .= $sec.$space.$rolehash->{$item}{$cid}{'secs'}{$sec}.$spanend;
1350: }
1351: }
1352: }
1353: }
1354: }
1355: &build_user_record(\%userdata,$userinfo,$indexhash,$item,$userlist);
1356: }
1357: }
1358: }
1359: return;
1360: }
1361:
1362: sub build_user_record {
1363: my ($userdata,$userinfo,$indexhash,$record_key,$userlist) = @_;
1364: &process_date_info($userdata);
1365: my $username = $userdata->{'username'};
1366: my $domain = $userdata->{'domain'};
1367: if (ref($userinfo->{$username.':'.$domain}) eq 'HASH') {
1368: $userdata->{'fullname'} =
1369: $userinfo->{$username.':'.$domain}{'fullname'};
1370: $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
1371: } else {
1372: &aggregate_user_info($domain,$username,$userinfo);
1373: $userdata->{'fullname'} = $userinfo->{$username.':'.$domain}{'fullname'};
1374: $userdata->{'id'} = $userinfo->{$username.':'.$domain}{'id'};
1375: }
1376: foreach my $key (keys(%{$indexhash})) {
1377: if (defined($userdata->{$key})) {
1378: $userlist->{$record_key}[$indexhash->{$key}] = $userdata->{$key};
1379: }
1380: }
1381: return;
1382: }
1383:
1384: sub courses_selector {
1385: my ($cdom,$formname) = @_;
1386: my %coursecodes = ();
1387: my %codes = ();
1388: my @codetitles = ();
1389: my %cat_titles = ();
1390: my %cat_order = ();
1391: my %idlist = ();
1392: my %idnums = ();
1393: my %idlist_titles = ();
1394: my $caller = 'global';
1395: my $totcodes = 0;
1396: my $format_reply;
1397: my $jscript = '';
1398:
1399: my $totcodes =
1400: &Apache::courseclassifier::retrieve_instcodes(\%coursecodes,
1401: $cdom,$totcodes);
1402: if ($totcodes > 0) {
1403: $format_reply =
1404: &Apache::lonnet::auto_instcode_format($caller,$cdom,\%coursecodes,
1405: \%codes,\@codetitles,\%cat_titles,\%cat_order);
1406: if ($format_reply eq 'ok') {
1407: my $numtypes = @codetitles;
1408: &Apache::courseclassifier::build_code_selections(\%codes,\@codetitles,\%cat_titles,\%cat_order,\%idlist,\%idnums,\%idlist_titles);
1409: my ($scripttext,$longtitles) = &Apache::courseclassifier::javascript_definitions(\@codetitles,\%idlist,\%idlist_titles,\%idnums,\%cat_titles);
1410: my $longtitles_str = join('","',@{$longtitles});
1411: my $allidlist = $idlist{$codetitles[0]};
1412: $jscript .= &Apache::courseclassifier::courseset_js_start($formname,$longtitles_str,$allidlist);
1413: $jscript .= $scripttext;
1414: $jscript .= &Apache::courseclassifier::javascript_code_selections($formname,@codetitles);
1415: }
1416: }
1417: my $cb_jscript = &Apache::loncommon::coursebrowser_javascript($cdom);
1418:
1419: my %elements = (
1420: Year => 'selectbox',
1421: coursepick => 'radio',
1422: coursetotal => 'text',
1423: courselist => 'text',
1424: );
1425: $jscript .= &Apache::lonhtmlcommon::set_form_elements(\%elements);
1426: if ($env{'form.coursepick'} eq 'category') {
1427: $jscript .= qq|
1428: function setCourseCat(formname) {
1429: if (formname.Year.options[formname.Year.selectedIndex].value == -1) {
1430: return;
1431: }
1432: courseSet('Year');
1433: for (var j=0; j<formname.Semester.length; j++) {
1434: if (formname.Semester.options[j].value == "$env{'form.Semester'}") {
1435: formname.Semester.options[j].selected = true;
1436: }
1437: }
1438: if (formname.Semester.options[formname.Semester.selectedIndex].value == -1) {
1439: return;
1440: }
1441: courseSet('Semester');
1442: for (var j=0; j<formname.Department.length; j++) {
1443: if (formname.Department.options[j].value == "$env{'form.Department'}") { formname.Department.options[j].selected = true;
1444: }
1445: }
1446: if (formname.Department.options[formname.Department.selectedIndex].value == -1) {
1447: return;
1448: }
1449: courseSet('Department');
1450: for (var j=0; j<formname.Number.length; j++) {
1451: if (formname.Number.options[j].value == "$env{'form.Number'}") {
1452: formname.Number.options[j].selected = true;
1453: }
1454: }
1455: }
1456: |;
1457: }
1458: return ($cb_jscript,$jscript,$totcodes,\@codetitles,\%idlist,
1459: \%idlist_titles);
1460: }
1461:
1462: sub course_selector_loadcode {
1463: my ($formname) = @_;
1464: my $loadcode;
1465: if ($env{'form.coursepick'} ne '') {
1466: $loadcode = 'javascript:setFormElements(document.'.$formname.')';
1467: if ($env{'form.coursepick'} eq 'category') {
1468: $loadcode .= ';javascript:setCourseCat(document.'.$formname.')';
1469: }
1470: }
1471: return $loadcode;
1472: }
1473:
1474: sub process_coursepick {
1475: my $coursefilter = $env{'form.coursepick'};
1476: my $cdom = $env{'request.role.domain'};
1477: my %courses;
1478: if ($coursefilter eq 'all') {
1479: %courses = &Apache::lonnet::courseiddump($cdom,'.','.','.','.','.',
1480: undef,undef,'Course');
1481: } elsif ($coursefilter eq 'category') {
1482: my $instcode = &instcode_from_coursefilter();
1483: %courses = &Apache::lonnet::courseiddump($cdom,'.','.',$instcode,'.','.',
1484: undef,undef,'Course');
1485: } elsif ($coursefilter eq 'specific') {
1486: if ($env{'form.coursetotal'} > 1) {
1487: my @course_ids = split(/&&/,$env{'form.courselist'});
1488: foreach my $cid (@course_ids) {
1489: $courses{$cid} = '';
1490: }
1491: } else {
1492: $courses{$env{'form.courselist'}} = '';
1493: }
1494: }
1495: return %courses;
1496: }
1497:
1498: sub instcode_from_coursefilter {
1499: my $instcode = '';
1500: my @cats = ('Semester','Year','Department','Number');
1501: foreach my $category (@cats) {
1502: if (defined($env{'form.'.$category})) {
1503: unless ($env{'form.'.$category} eq '-1') {
1504: $instcode .= $env{'form.'.$category};
1505: }
1506: }
1507: }
1508: if ($instcode eq '') {
1509: $instcode = '.';
1510: }
1511: return $instcode;
1512: }
1513:
1514: sub display_adv_courseroles {
1515: my $output;
1516: #
1517: # List course personnel
1518: my %coursepersonnel =
1519: &Apache::lonnet::get_course_adv_roles($env{'request.course.id'});
1520: #
1521: $output = '<br />'.&Apache::loncommon::start_data_table();
1522: foreach my $role (sort(keys(%coursepersonnel))) {
1523: next if ($role =~ /^\s*$/);
1524: $output .= &Apache::loncommon::start_data_table_row().
1525: '<td>'.$role.'</td><td>';
1526: foreach my $user (split(',',$coursepersonnel{$role})) {
1527: my ($puname,$pudom)=split(':',$user);
1528: $output .= ' '.&Apache::loncommon::aboutmewrapper(
1529: &Apache::loncommon::plainname($puname,$pudom),
1530: $puname,$pudom);
1531: }
1532: $output .= '</td>'.&Apache::loncommon::end_data_table_row();
1533: }
1534: $output .= &Apache::loncommon::end_data_table();
1535: }
1536:
1537: sub make_keylist_array {
1538: my ($index,$keylist);
1539: $index->{'domain'} = &Apache::loncoursedata::CL_SDOM();
1540: $index->{'username'} = &Apache::loncoursedata::CL_SNAME();
1541: $index->{'end'} = &Apache::loncoursedata::CL_END();
1542: $index->{'start'} = &Apache::loncoursedata::CL_START();
1543: $index->{'id'} = &Apache::loncoursedata::CL_ID();
1544: $index->{'section'} = &Apache::loncoursedata::CL_SECTION();
1545: $index->{'fullname'} = &Apache::loncoursedata::CL_FULLNAME();
1546: $index->{'status'} = &Apache::loncoursedata::CL_STATUS();
1547: $index->{'type'} = &Apache::loncoursedata::CL_TYPE();
1548: $index->{'lockedtype'} = &Apache::loncoursedata::CL_LOCKEDTYPE();
1549: $index->{'groups'} = &Apache::loncoursedata::CL_GROUP();
1550: $index->{'email'} = &Apache::loncoursedata::CL_PERMANENTEMAIL();
1551: $index->{'role'} = &Apache::loncoursedata::CL_ROLE();
1552: $index->{'extent'} = &Apache::loncoursedata::CL_EXTENT();
1553: foreach my $key (keys(%{$index})) {
1554: $keylist->[$index->{$key}] = $key;
1555: }
1556: return ($index,$keylist);
1557: }
1558:
1559: sub aggregate_user_info {
1560: my ($udom,$uname,$userinfo) = @_;
1561: my %info=&Apache::lonnet::get('environment',
1562: ['firstname','middlename',
1563: 'lastname','generation','id'],
1564: $udom,$uname);
1565: my ($tmp) = keys(%info);
1566: my ($fullname,$id);
1567: if ($tmp =~/^(con_lost|error|no_such_host)/i) {
1568: $fullname = 'not available';
1569: $id = 'not available';
1570: &Apache::lonnet::logthis('unable to retrieve environment '.
1571: 'for '.$uname.':'.$udom);
1572: } else {
1573: $fullname = &Apache::lonnet::format_name(@info{qw/firstname middlename lastname generation/},'lastname');
1574: $id = $info{'id'};
1575: }
1576: $userinfo->{$uname.':'.$udom} = {
1577: fullname => $fullname,
1578: id => $id,
1579: };
1580: return;
1581: }
1582:
1583: sub process_date_info {
1584: my ($userdata) = @_;
1585: my $now = time;
1586: $userdata->{'status'} = 'Active';
1587: if ($userdata->{'start'} > 0) {
1588: if ($now < $userdata->{'start'}) {
1589: $userdata->{'status'} = 'Future';
1590: }
1591: }
1592: if ($userdata->{'end'} > 0) {
1593: if ($now > $userdata->{'end'}) {
1594: $userdata->{'status'} = 'Expired';
1595: }
1596: }
1597: return;
1598: }
1599:
1600: sub show_users_list {
1601: my ($r,$context,$mode,$linkto,$statusmode,$userlist,$keylist)=@_;
1602: #
1603: # Variables for excel output
1604: my ($excel_workbook, $excel_sheet, $excel_filename,$row,$format);
1605: #
1606: # Variables for csv output
1607: my ($CSVfile,$CSVfilename);
1608: #
1609: my $sortby = $env{'form.sortby'};
1610: my @sortable = ('username','domain','id','fullname','start','end','email','role');
1611: if ($context eq 'course') {
1612: push(@sortable,('section','groups','type'));
1613: } else {
1614: push(@sortable,'extent');
1615: }
1616: if (!grep(/^\Q$sortby\E$/,@sortable)) {
1617: $sortby = 'username';
1618: }
1619: my ($cid,$cdom,$cnum,$classgroups,$displayphotos,$displayclickers);
1620: if ($context eq 'course') {
1621: $cid=$env{'request.course.id'};
1622: $cdom = $env{'course.'.$cid.'.domain'};
1623: $cnum = $env{'course.'.$cid.'.num'};
1624: ($classgroups) = &Apache::loncoursedata::get_group_memberships(
1625: $userlist,$keylist,$cdom,$cnum);
1626: if (! exists($env{'form.displayphotos'})) {
1627: $env{'form.displayphotos'} = 'off';
1628: }
1629: $displayphotos = $env{'form.displayphotos'};
1630: if (! exists($env{'form.displayclickers'})) {
1631: $env{'form.displayclickers'} = 'off';
1632: }
1633: $displayclickers = $env{'form.displayclickers'};
1634: if ($env{'course.'.$cid.'.internal.showphoto'}) {
1635: $r->print('
1636: <script type="text/javascript">
1637: function photowindow(photolink) {
1638: var title = "Photo_Viewer";
1639: var options = "scrollbars=1,resizable=1,menubar=0";
1640: options += ",width=240,height=240";
1641: stdeditbrowser = open(photolink,title,options,"1");
1642: stdeditbrowser.focus();
1643: }
1644: </script>
1645: ');
1646: }
1647: $r->print(<<END);
1648: <input type="hidden" name="displayphotos" value="$displayphotos" />
1649: <input type="hidden" name="displayclickers" value="$displayclickers" />
1650: END
1651: }
1652: unless ($mode eq 'autoenroll') {
1653: $r->print(<<END);
1654: <input type="hidden" name="state" value="$env{'form.state'}" />
1655: END
1656: }
1657: $r->print(<<END);
1658: <input type="hidden" name="sortby" value="$sortby" />
1659: END
1660:
1661: my %lt=&Apache::lonlocal::texthash(
1662: 'username' => "username",
1663: 'domain' => "domain",
1664: 'id' => 'ID',
1665: 'fullname' => "name",
1666: 'section' => "section",
1667: 'groups' => "active groups",
1668: 'start' => "start date",
1669: 'end' => "end date",
1670: 'status' => "status",
1671: 'role' => "role",
1672: 'type' => "enroll type/action",
1673: 'email' => "email address",
1674: 'clicker' => "clicker id",
1675: 'photo' => "photo",
1676: 'extent' => "extent",
1677: );
1678: if ($context eq 'domain' && $env{'form.roletype'} eq 'course') {
1679: $lt{'extent'} = &mt('Course(s): description, section(s), status');
1680: } elsif ($context eq 'construction_space') {
1681: $lt{'extent'} = &mt('Author');
1682: }
1683: my @cols = ('username','domain','id','fullname');
1684: if ($context eq 'course') {
1685: push(@cols,'section');
1686: }
1687: if (!($context eq 'domain' && $env{'form.roletype'} eq 'course')) {
1688: push(@cols,('start','end'));
1689: }
1690: if ($env{'form.showrole'} eq 'Any' || $env{'form.showrole'} eq 'cr') {
1691: push(@cols,'role');
1692: }
1693: if ($context eq 'domain' && ($env{'form.roletype'} eq 'construction_space' ||
1694: $env{'form.roletype'} eq 'course')) {
1695: push (@cols,'extent');
1696: }
1697: if (($statusmode eq 'Any') &&
1698: (!($context eq 'domain' && $env{'form.roletype'} eq 'course'))) {
1699: push(@cols,'status');
1700: }
1701: if ($context eq 'course') {
1702: push(@cols,'groups');
1703: }
1704: push(@cols,'email');
1705:
1706: my $rolefilter = $env{'form.showrole'};
1707: if ($env{'form.showrole'} ne 'Any') {
1708: $rolefilter = &Apache::lonnet::plaintext($env{'form.showrole'});
1709: }
1710: my $results_description = &results_header_row($rolefilter,$statusmode,
1711: $context);
1712: $r->print('<b>'.$results_description.'</b><br />');
1713: my $output;
1714: if ($mode eq 'html' || $mode eq 'view') {
1715: $r->print(<<END);
1716: <input type="hidden" name="sname" value="" />
1717: <input type="hidden" name="sdom" value="" />
1718: END
1719: if ($linkto eq 'aboutme') {
1720: $output = &mt("Select a user name to view the user's personal page.");
1721: } elsif ($linkto eq 'modify') {
1722: $output = &mt("Select a user name to modify the user's information");
1723: }
1724: $output .= "\n<p>\n".
1725: &Apache::loncommon::start_data_table().
1726: &Apache::loncommon::start_data_table_header_row();
1727: if ($mode eq 'autoenroll') {
1728: $output .= "
1729: <th><a href=\"javascript:document.studentform.sortby.value='type';document.studentform.submit();\">$lt{'type'}</a></th>
1730: ";
1731: } else {
1732: $output .= "
1733: <th>Count</th>
1734: ";
1735: }
1736: foreach my $item (@cols) {
1737: $output .= "<th><a href=\"javascript:document.studentform.sortby.value='$item';document.studentform.submit();\">$lt{$item}</a></th>\n";
1738: }
1739: my %role_types = &role_type_names();
1740: if ($context eq 'course') {
1741: if ($env{'form.showrole'} eq 'st' || $env{'form.showrole'} eq 'Any') {
1742: # Clicker display on or off?
1743: my %clicker_options = &Apache::lonlocal::texthash(
1744: 'on' => 'Show',
1745: 'off' => 'Hide',
1746: );
1747: my $clickerchg = 'on';
1748: if ($displayclickers eq 'on') {
1749: $clickerchg = 'off';
1750: }
1751: $output .= ' <th>'."\n".' '.
1752: '<a href="javascript:document.studentform.displayclickers.value='.
1753: "'".$clickerchg."'".';document.studentform.submit();">'.
1754: $clicker_options{$clickerchg}.'</a> '.$lt{'clicker'}."\n".
1755: ' </th>'."\n";
1756:
1757: # Photo display on or off?
1758: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1759: my %photo_options = &Apache::lonlocal::texthash(
1760: 'on' => 'Show',
1761: 'off' => 'Hide',
1762: );
1763: my $photochg = 'on';
1764: if ($displayphotos eq 'on') {
1765: $photochg = 'off';
1766: }
1767: $output .= ' <th>'."\n".' '.
1768: '<a href="javascript:document.studentform.displayphotos.value='.
1769: "'".$photochg."'".';document.studentform.submit();">'.
1770: $photo_options{$photochg}.'</a> '.$lt{'photo'}."\n".
1771: ' </th>'."\n";
1772: }
1773: }
1774: $output .= &Apache::loncommon::end_data_table_header_row();
1775: }
1776: # Done with the HTML header line
1777: } elsif ($mode eq 'csv') {
1778: #
1779: # Open a file
1780: $CSVfilename = '/prtspool/'.
1781: $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1782: time.'_'.rand(1000000000).'.csv';
1783: unless ($CSVfile = Apache::File->new('>/home/httpd'.$CSVfilename)) {
1784: $r->log_error("Couldn't open $CSVfilename for output $!");
1785: $r->print("Problems occured in writing the csv file. ".
1786: "This error has been logged. ".
1787: "Please alert your LON-CAPA administrator.");
1788: $CSVfile = undef;
1789: }
1790: #
1791: # Write headers and data to file
1792: print $CSVfile '"'.$results_description.'"'."\n";
1793: print $CSVfile '"'.join('","',map {
1794: &Apache::loncommon::csv_translate($lt{$_})
1795: } (@cols)).'"'."\n";
1796: } elsif ($mode eq 'excel') {
1797: # Create the excel spreadsheet
1798: ($excel_workbook,$excel_filename,$format) =
1799: &Apache::loncommon::create_workbook($r);
1800: return if (! defined($excel_workbook));
1801: $excel_sheet = $excel_workbook->addworksheet('userlist');
1802: $excel_sheet->write($row++,0,$results_description,$format->{'h2'});
1803: #
1804: my @colnames = map {$lt{$_}} (@cols);
1805: $excel_sheet->write($row++,0,\@colnames,$format->{'bold'});
1806: }
1807:
1808: # Done with header lines in all formats
1809:
1810: my %index;
1811: my $i;
1812: foreach my $idx (@$keylist) {
1813: $index{$idx} = $i++;
1814: }
1815: my $usercount = 0;
1816: # Get groups, role, permanent e-mail so we can sort on them if
1817: # necessary.
1818: foreach my $user (keys(%{$userlist})) {
1819: my ($uname,$udom,$role,$groups,$email);
1820: next if (($statusmode ne 'Any') &&
1821: ($userlist->{$user}->[$index{'status'}] ne $statusmode));
1822: if ($context eq 'domain') {
1823: if ($env{'form.roletype'} eq 'domain') {
1824: ($role,$uname,$udom) = split(/:/,$user);
1825:
1826: } elsif ($env{'form.roletype'} eq 'construction_space') {
1827: ($uname,$udom,$role) = split(/:/,$user,-1);
1828: } elsif ($env{'form.roletype'} eq 'course') {
1829: ($uname,$udom,$role) = split(/:/,$user);
1830: }
1831: } else {
1832: ($uname,$udom,$role) = split(/:/,$user,-1);
1833: if (($context eq 'course') && $role eq '') {
1834: $role = 'st';
1835: }
1836: }
1837: $userlist->{$user}->[$index{'role'}] = $role;
1838: if (($env{'form.showrole'} ne 'Any') && (!($env{'form.showrole'} eq 'cr' && $role =~ /^cr\//)) && ($role ne $env{'form.showrole'})) {
1839: delete($userlist->{$user});
1840: next;
1841: }
1842: if (ref($classgroups) eq 'HASH') {
1843: $groups = $classgroups->{$user};
1844: }
1845: if (ref($groups->{active}) eq 'HASH') {
1846: $userlist->{$user}->[$index{'groups'}] = join(', ',keys(%{$groups->{'active'}}));
1847: }
1848: my %emails = &Apache::loncommon::getemails($uname,$udom);
1849: if ($emails{'permanentemail'} =~ /\S/) {
1850: $userlist->{$user}->[$index{'email'}] = $emails{'permanentemail'};
1851: }
1852: $usercount ++;
1853: }
1854: my $autocount = 0;
1855: my $manualcount = 0;
1856: my $lockcount = 0;
1857: my $unlockcount = 0;
1858: if ($usercount) {
1859: $r->print($output);
1860: } else {
1861: if ($mode eq 'autoenroll') {
1862: return ($usercount,$autocount,$manualcount,$lockcount,$unlockcount);
1863: } else {
1864: return;
1865: }
1866: }
1867: #
1868: # Sort the users
1869: my $index = $index{$sortby};
1870: my $second = $index{'username'};
1871: my $third = $index{'domain'};
1872: my @sorted_users = sort {
1873: lc($userlist->{$a}->[$index]) cmp lc($userlist->{$b}->[$index])
1874: ||
1875: lc($userlist->{$a}->[$second]) cmp lc($userlist->{$b}->[$second]) ||
1876: lc($userlist->{$a}->[$third]) cmp lc($userlist->{$b}->[$third])
1877: } (keys(%$userlist));
1878: my $rowcount = 0;
1879: foreach my $user (@sorted_users) {
1880: my %in;
1881: my $sdata = $userlist->{$user};
1882: $rowcount ++;
1883: foreach my $item (@{$keylist}) {
1884: $in{$item} = $sdata->[$index{$item}];
1885: }
1886: $in{'role'}=&Apache::lonnet::plaintext($sdata->[$index{'role'}]);
1887: if (! defined($in{'start'}) || $in{'start'} == 0) {
1888: $in{'start'} = &mt('none');
1889: } else {
1890: $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
1891: }
1892: if (! defined($in{'end'}) || $in{'end'} == 0) {
1893: $in{'end'} = &mt('none');
1894: } else {
1895: $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
1896: }
1897: if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll') {
1898: $r->print(&Apache::loncommon::start_data_table_row());
1899: $r->print("<td>$rowcount</td>\n");
1900: if ($linkto eq 'aboutme') {
1901: $in{'username'} =
1902: &Apache::loncommon::aboutmewrapper($in{'username'},
1903: $in{'username'},
1904: $in{'domain'});
1905: } elsif ($linkto eq 'modify') {
1906: $in{'username'} = '<a href="'.
1907: "javascript:document.studentform.sname.value='".
1908: $in{'username'}.
1909: "';document.studentform.sdom.value='".$in{'domain'}.
1910: "';document.studentform.state.value='selected".
1911: "';document.studentform.submit();".'">'.
1912: $in{'username'}."</a>\n";
1913: }
1914: foreach my $item (@cols) {
1915: $r->print('<td>'.$in{$item}.'</td>'."\n");
1916: }
1917: if ($context eq 'course') {
1918: if ($env{'form.showrole'} eq 'st' || $env{'form.showrole'} eq 'Any') {
1919: if ($displayclickers eq 'on') {
1920: my $clickers =
1921: (&Apache::lonnet::userenvironment($in{'domain'},$in{'username'},'clickers'))[1];
1922: if ($clickers!~/\w/) { $clickers='-'; }
1923: $r->print('<td>'.$clickers.'</td>');
1924: } else {
1925: $r->print(' <td> </td> ');
1926: }
1927: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1928: if ($displayphotos eq 'on' && $sdata->[$index{'role'}] eq 'st') {
1929: my $imgurl =
1930: &Apache::lonnet::retrievestudentphoto($in{'domain'},$in{'username'},
1931: 'gif','thumbnail');
1932: $r->print(' <td align="right"><a href="javascript:photowindow('."'".&Apache::lonnet::studentphoto($in{'domain'},$in{'username'},'jpg')."'".')"><img src="'.$imgurl.'" border="1"></a></td>');
1933: } else {
1934: $r->print(' <td> </td> ');
1935: }
1936: }
1937: }
1938: }
1939: $r->print(&Apache::loncommon::end_data_table_row());
1940: } elsif ($mode eq 'csv') {
1941: next if (! defined($CSVfile));
1942: # no need to bother with $linkto
1943: if (! defined($in{'start'}) || $in{'start'} == 0) {
1944: $in{'start'} = &mt('none');
1945: } else {
1946: $in{'start'} = &Apache::lonlocal::locallocaltime($in{'start'});
1947: }
1948: if (! defined($in{'end'}) || $in{'end'} == 0) {
1949: $in{'end'} = &mt('none');
1950: } else {
1951: $in{'end'} = &Apache::lonlocal::locallocaltime($in{'end'});
1952: }
1953: my @line = ();
1954: foreach my $item (@cols) {
1955: push @line,&Apache::loncommon::csv_translate($in{$item});
1956: }
1957: print $CSVfile '"'.join('","',@line).'"'."\n";
1958: } elsif ($mode eq 'excel') {
1959: my $col = 0;
1960: foreach my $item (@cols) {
1961: if ($item eq 'start' || $item eq 'end') {
1962: if (defined($item) && $item != 0) {
1963: $excel_sheet->write($row,$col++,
1964: &Apache::lonstathelpers::calc_serial($in{item}),
1965: $format->{'date'});
1966: } else {
1967: $excel_sheet->write($row,$col++,'none');
1968: }
1969: } else {
1970: $excel_sheet->write($row,$col++,$in{$item});
1971: }
1972: }
1973: $row++;
1974: }
1975: }
1976: if ($mode eq 'view' || $mode eq 'html' || $mode eq 'autoenroll') {
1977: $r->print(&Apache::loncommon::end_data_table().'<br />');
1978: } elsif ($mode eq 'excel') {
1979: $excel_workbook->close();
1980: $r->print('<p><a href="'.$excel_filename.'">'.
1981: &mt('Your Excel spreadsheet').'</a> '.&mt('is ready for download').'.</p>'."\n");
1982: } elsif ($mode eq 'csv') {
1983: close($CSVfile);
1984: $r->print('<a href="'.$CSVfilename.'">'.
1985: &mt('Your CSV file').'</a> is ready for download.'.
1986: "\n");
1987: $r->rflush();
1988: }
1989: if ($mode eq 'autoenroll') {
1990: return ($usercount,$autocount,$manualcount,$lockcount,$unlockcount);
1991: } else {
1992: return ($usercount);
1993: }
1994: }
1995:
1996: sub role_type_names {
1997: my %lt = &Apache::lonlocal::texthash (
1998: 'domain' => 'Domain Roles',
1999: 'construction_space' => 'Co-Author Roles',
2000: 'course' => 'Course Roles',
2001: );
2002: return %lt;
2003: }
2004:
2005: sub results_header_row {
2006: my ($rolefilter,$statusmode,$context) = @_;
2007: my $description;
2008: if ($context eq 'course') {
2009: $description = &mt('Course - ').$env{'course.'.$env{'request.course.id'}.'.description'}.': ';
2010: if ($statusmode eq 'Expired') {
2011: $description .= &mt('Users in course with expired [_1] roles',$rolefilter);
2012: }
2013: if ($statusmode eq 'Future') {
2014: $description .= &mt('Users in course with future [_1] roles',$rolefilter);
2015: } elsif ($statusmode eq 'Active') {
2016: $description .= &mt('Users in course with active [_1] roles',$rolefilter);
2017: } else {
2018: if ($rolefilter eq 'Any') {
2019: $description .= &mt('All users in course');
2020: } else {
2021: $description .= &mt('All users in course with [_1] roles',$rolefilter);
2022: }
2023: }
2024: } elsif ($context eq 'construction_space') {
2025: $description = &mt('Author space for [_1].').' ';
2026: if ($statusmode eq 'Expired') {
2027: $description .= &mt('Co-authors with expired [_1] roles',$rolefilter);
2028: } elsif ($statusmode eq 'Future') {
2029: $description .= &mt('Co-authors with future [_1] roles',$rolefilter);
2030: } elsif ($statusmode eq 'Active') {
2031: $description .= &mt('Co-authors with active [_1] roles',$rolefilter);
2032: } else {
2033: if ($rolefilter eq 'Any') {
2034: $description .= &mt('All co-authors',$rolefilter);
2035: } else {
2036: $description .= &mt('All co-authors with [_1] roles',$rolefilter);
2037: }
2038: }
2039: } elsif ($context eq 'domain') {
2040: my $domdesc = &Apache::lonnet::domain($env{'request.role.domain'},'description');
2041: $description = &mt('Domain - ').$domdesc.': ';
2042: if ($env{'form.roletype'} eq 'domain') {
2043: if ($statusmode eq 'Expired') {
2044: $description .= &mt('Users in domain with expired [_1] roles',$rolefilter);
2045: } elsif ($statusmode eq 'Future') {
2046: $description .= &mt('Users in domain with future [_1] roles',$rolefilter);
2047: } elsif ($statusmode eq 'Active') {
2048: $description .= &mt('Users in domain with active [_1] roles',$rolefilter);
2049: } else {
2050: if ($rolefilter eq 'Any') {
2051: $description .= &mt('All users in domain',$rolefilter);
2052: } else {
2053: $description .= &mt('All users in domain with [_1] roles',$rolefilter);
2054: }
2055: }
2056: } elsif ($env{'form.roletype'} eq 'construction_space') {
2057: if ($statusmode eq 'Expired') {
2058: $description .= &mt('Co-authors in domain with expired [_1] roles',$rolefilter);
2059: } elsif ($statusmode eq 'Future') {
2060: $description .= &mt('Co-authors in domain with future [_1] roles',$rolefilter);
2061: } elsif ($statusmode eq 'Active') {
2062: $description .= &mt('Co-authors in domain with active [_1] roles',$rolefilter);
2063: } else {
2064: if ($rolefilter eq 'Any') {
2065: $description .= &mt('All users with co-author roles in domain',$rolefilter);
2066: } else {
2067: $description .= &mt('All co-authors in domain with [_1] roles',$rolefilter);
2068: }
2069: }
2070: } elsif ($env{'form.roletype'} eq 'course') {
2071: my $coursefilter = $env{'form.coursepick'};
2072: if ($coursefilter eq 'category') {
2073: my $instcode = &instcode_from_coursefilter();
2074: if ($instcode eq '.') {
2075: $description .= &mt('All courses in domain').' - ';
2076: } else {
2077: $description .= &mt('Courses in domain with institutional code: [_1]',$instcode).' - ';
2078: }
2079: } elsif ($coursefilter eq 'selected') {
2080: $description .= &mt('Selected courses in domain').' - ';
2081: } elsif ($coursefilter eq 'all') {
2082: $description .= &mt('All courses in domain').' - ';
2083: }
2084: if ($statusmode eq 'Expired') {
2085: $description .= &mt('users with expired [_1] roles',$rolefilter);
2086: } elsif ($statusmode eq 'Future') {
2087: $description .= &mt('users with future [_1] roles',$rolefilter);
2088: } elsif ($statusmode eq 'Active') {
2089: $description .= &mt('users with active [_1] roles',$rolefilter);
2090: } else {
2091: if ($rolefilter eq 'Any') {
2092: $description .= &mt('all users');
2093: } else {
2094: $description .= &mt('users with [_1] roles',$rolefilter);
2095: }
2096: }
2097: }
2098: }
2099: return $description;
2100: }
2101:
2102: #################################################
2103: #################################################
2104: sub show_drop_list {
2105: my ($r,$classlist,$keylist,$nosort)=@_;
2106: my $cid=$env{'request.course.id'};
2107: if (! exists($env{'form.sortby'})) {
2108: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
2109: ['sortby']);
2110: }
2111: my $sortby = $env{'form.sortby'};
2112: if ($sortby !~ /^(username|domain|section|groups|fullname|id|start|end)$/) {
2113: $sortby = 'username';
2114: }
2115: my $cdom = $env{'course.'.$cid.'.domain'};
2116: my $cnum = $env{'course.'.$cid,'.num'};
2117: my ($classgroups) = &Apache::loncoursedata::get_group_memberships(
2118: $classlist,$keylist,$cdom,$cnum);
2119: #
2120: my $action = "drop";
2121: $r->print(<<END);
2122: <input type="hidden" name="sortby" value="$sortby" />
2123: <input type="hidden" name="action" value="$action" />
2124: <input type="hidden" name="state" value="done" />
2125: <script>
2126: function checkAll(field) {
2127: for (i = 0; i < field.length; i++)
2128: field[i].checked = true ;
2129: }
2130:
2131: function uncheckAll(field) {
2132: for (i = 0; i < field.length; i++)
2133: field[i].checked = false ;
2134: }
2135: </script>
2136: <p>
2137: <input type="hidden" name="phase" value="four">
2138: END
2139:
2140: my %lt=&Apache::lonlocal::texthash('usrn' => "username",
2141: 'dom' => "domain",
2142: 'sn' => "student name",
2143: 'sec' => "section",
2144: 'start' => "start date",
2145: 'end' => "end date",
2146: 'groups' => "active groups",
2147: );
2148: if ($nosort) {
2149: $r->print(&Apache::loncommon::start_data_table());
2150: $r->print(<<END);
2151: <tr>
2152: <th> </th>
2153: <th>$lt{'usrn'}</th>
2154: <th>$lt{'dom'}</th>
2155: <th>ID</th>
2156: <th>$lt{'sn'}</th>
2157: <th>$lt{'sec'}</th>
2158: <th>$lt{'start'}</th>
2159: <th>$lt{'end'}</th>
2160: <th>$lt{'groups'}</th>
2161: </tr>
2162: END
2163:
2164: } else {
2165: $r->print(&Apache::loncommon::start_data_table());
2166: $r->print(<<END);
2167: <tr><th> </th>
2168: <th>
2169: <a href="/adm/dropadd?action=$action&sortby=username">$lt{'usrn'}</a>
2170: </th><th>
2171: <a href="/adm/dropadd?action=$action&sortby=domain">$lt{'dom'}</a>
2172: </th><th>
2173: <a href="/adm/dropadd?action=$action&sortby=id">ID</a>
2174: </th><th>
2175: <a href="/adm/dropadd?action=$action&sortby=fullname">$lt{'sn'}</a>
2176: </th><th>
2177: <a href="/adm/dropadd?action=$action&sortby=section">$lt{'sec'}</a>
2178: </th><th>
2179: <a href="/adm/dropadd?action=$action&sortby=start">$lt{'start'}</a>
2180: </th><th>
2181: <a href="/adm/dropadd?action=$action&sortby=end">$lt{'end'}</a>
2182: </th><th>
2183: <a href="/adm/dropadd?action=$action&sortby=groups">$lt{'groups'}</a>
2184: </th>
2185: </tr>
2186: END
2187: }
2188: #
2189: # Sort the students
2190: my %index;
2191: my $i;
2192: foreach (@$keylist) {
2193: $index{$_} = $i++;
2194: }
2195: $index{'groups'} = scalar(@$keylist);
2196: my $index = $index{$sortby};
2197: my $second = $index{'username'};
2198: my $third = $index{'domain'};
2199: my @Sorted_Students = sort {
2200: lc($classlist->{$a}->[$index]) cmp lc($classlist->{$b}->[$index])
2201: ||
2202: lc($classlist->{$a}->[$second]) cmp lc($classlist->{$b}->[$second])
2203: ||
2204: lc($classlist->{$a}->[$third]) cmp lc($classlist->{$b}->[$third])
2205: } (keys(%$classlist));
2206: foreach my $student (@Sorted_Students) {
2207: my $error;
2208: my $sdata = $classlist->{$student};
2209: my $username = $sdata->[$index{'username'}];
2210: my $domain = $sdata->[$index{'domain'}];
2211: my $section = $sdata->[$index{'section'}];
2212: my $name = $sdata->[$index{'fullname'}];
2213: my $id = $sdata->[$index{'id'}];
2214: my $start = $sdata->[$index{'start'}];
2215: my $end = $sdata->[$index{'end'}];
2216: my $groups = $classgroups->{$student};
2217: my $active_groups;
2218: if (ref($groups->{active}) eq 'HASH') {
2219: $active_groups = join(', ',keys(%{$groups->{'active'}}));
2220: }
2221: if (! defined($start) || $start == 0) {
2222: $start = &mt('none');
2223: } else {
2224: $start = &Apache::lonlocal::locallocaltime($start);
2225: }
2226: if (! defined($end) || $end == 0) {
2227: $end = &mt('none');
2228: } else {
2229: $end = &Apache::lonlocal::locallocaltime($end);
2230: }
2231: my $status = $sdata->[$index{'status'}];
2232: next if ($status ne 'Active');
2233: #
2234: $r->print(&Apache::loncommon::start_data_table_row());
2235: $r->print(<<"END");
2236: <td><input type="checkbox" name="droplist" value="$student"></td>
2237: <td>$username</td>
2238: <td>$domain</td>
2239: <td>$id</td>
2240: <td>$name</td>
2241: <td>$section</td>
2242: <td>$start</td>
2243: <td>$end</td>
2244: <td>$active_groups</td>
2245: END
2246: $r->print(&Apache::loncommon::end_data_table_row());
2247: }
2248: $r->print(&Apache::loncommon::end_data_table().'<br />');
2249: %lt=&Apache::lonlocal::texthash(
2250: 'dp' => "Expire Users' Roles",
2251: 'ca' => "check all",
2252: 'ua' => "uncheck all",
2253: );
2254: $r->print(<<"END");
2255: </p><p>
2256: <input type="button" value="$lt{'ca'}" onclick="javascript:checkAll(document.studentform.droplist)">
2257: <input type="button" value="$lt{'ua'}" onclick="javascript:uncheckAll(document.studentform.droplist)">
2258: <p><input type=submit value="$lt{'dp'}"></p>
2259: END
2260: return;
2261: }
2262:
2263: #
2264: # Print out the initial form to get the file containing a list of users
2265: #
2266: sub print_first_users_upload_form {
2267: my ($r,$context) = @_;
2268: my $str;
2269: $str = '<input type="hidden" name="phase" value="two">';
2270: $str .= '<input type="hidden" name="action" value="upload" />';
2271: $str .= '<input type="hidden" name="state" value="got_file" />';
2272: $str .= "<h3>".&mt('Upload a file containing information about users')."</h3>\n";
2273: $str .= &Apache::loncommon::upfile_select_html();
2274: $str .= "<p>\n";
2275: $str .= '<input type="submit" name="fileupload" value="'.
2276: &mt('Upload file of users').'">'."\n";
2277: $str .= '<label><input type="checkbox" name="noFirstLine" /> '.
2278: &mt('Ignore First Line')."</label></p>\n";
2279: $str .= &Apache::loncommon::help_open_topic("Course_Create_Class_List",
2280: &mt("How do I create a users list from a spreadsheet")).
2281: "<br />\n";
2282: $str .= &Apache::loncommon::help_open_topic("Course_Convert_To_CSV",
2283: &mt("How do I create a CSV file from a spreadsheet")).
2284: "<br />\n";
2285: $str .= &Apache::loncommon::end_page();
2286: $r->print($str);
2287: return;
2288: }
2289:
2290: # ================================================= Drop/Add from uploaded file
2291: sub upfile_drop_add {
2292: my ($r,$context) = @_;
2293: &Apache::loncommon::load_tmp_file($r);
2294: my @userdata=&Apache::loncommon::upfile_record_sep();
2295: if($env{'form.noFirstLine'}){shift(@userdata);}
2296: my @keyfields = split(/\,/,$env{'form.keyfields'});
2297: my %fields=();
2298: for (my $i=0; $i<=$env{'form.nfields'}; $i++) {
2299: if ($env{'form.upfile_associate'} eq 'reverse') {
2300: if ($env{'form.f'.$i} ne 'none') {
2301: $fields{$keyfields[$i]}=$env{'form.f'.$i};
2302: }
2303: } else {
2304: $fields{$env{'form.f'.$i}}=$keyfields[$i];
2305: }
2306: }
2307: #
2308: # Store the field choices away
2309: foreach my $field (qw/username names
2310: fname mname lname gen id sec ipwd email role/) {
2311: $env{'form.'.$field.'_choice'}=$fields{$field};
2312: }
2313: &Apache::loncommon::store_course_settings('enrollment_upload',
2314: { 'username_choice' => 'scalar',
2315: 'names_choice' => 'scalar',
2316: 'fname_choice' => 'scalar',
2317: 'mname_choice' => 'scalar',
2318: 'lname_choice' => 'scalar',
2319: 'gen_choice' => 'scalar',
2320: 'id_choice' => 'scalar',
2321: 'sec_choice' => 'scalar',
2322: 'ipwd_choice' => 'scalar',
2323: 'email_choice' => 'scalar',
2324: 'role_choice' => 'scalar' });
2325: #
2326: my ($startdate,$enddate) = &get_dates_from_form();
2327: if ($env{'form.makedatesdefault'}) {
2328: $r->print(&make_dates_default($startdate,$enddate));
2329: }
2330: # Determine domain and desired host (home server)
2331: my $domain=$env{'request.role.domain'};
2332: my $desiredhost = $env{'form.lcserver'};
2333: if (lc($desiredhost) eq 'default') {
2334: $desiredhost = undef;
2335: } else {
2336: my %home_servers = &Apache::lonnet::get_servers($domain,'library');
2337: if (! exists($home_servers{$desiredhost})) {
2338: $r->print('<span class="LC_error">'.&mt('Error').
2339: &mt('Invalid home server specified').'</span>');
2340: $r->print(&Apache::loncommon::end_page());
2341: return;
2342: }
2343: }
2344: # Determine authentication mechanism
2345: my $changeauth;
2346: if ($context eq 'domain') {
2347: $changeauth = $env{'form.changeauth'};
2348: }
2349: my $amode = '';
2350: my $genpwd = '';
2351: if ($env{'form.login'} eq 'krb') {
2352: $amode='krb';
2353: $amode.=$env{'form.krbver'};
2354: $genpwd=$env{'form.krbarg'};
2355: } elsif ($env{'form.login'} eq 'int') {
2356: $amode='internal';
2357: if ((defined($env{'form.intarg'})) && ($env{'form.intarg'})) {
2358: $genpwd=$env{'form.intarg'};
2359: }
2360: } elsif ($env{'form.login'} eq 'loc') {
2361: $amode='localauth';
2362: if ((defined($env{'form.locarg'})) && ($env{'form.locarg'})) {
2363: $genpwd=$env{'form.locarg'};
2364: }
2365: }
2366: if ($amode =~ /^krb/) {
2367: if (! defined($genpwd) || $genpwd eq '') {
2368: $r->print('<span class="Error">'.
2369: &mt('Unable to enroll users').' '.
2370: &mt('No Kerberos domain was specified.').'</span></p>');
2371: $amode = ''; # This causes the loop below to be skipped
2372: }
2373: }
2374: my ($cid,$defaultsec,$defaultrole,$setting);
2375: if ($context eq 'domain') {
2376: $setting = $env{'form.roleaction'};
2377: if ($setting eq 'domain') {
2378: $defaultrole = $env{'form.defaultrole'};
2379: } elsif ($setting eq 'course') {
2380: $defaultrole = $env{'form.courserole'};
2381: }
2382: } elsif ($context eq 'construction_space') {
2383: $defaultrole = $env{'form.defaultrole'};
2384: }
2385: if ($context eq 'domain' && $setting eq 'course') {
2386: if ($env{'form.newsec'} ne '') {
2387: $defaultsec = $env{'form.newsec'};
2388: } elsif ($env{'form.defaultsec'} ne '') {
2389: $defaultsec = $env{'form.defaultsec'}
2390: }
2391: }
2392: if ($env{'request.course.id'} ne '') {
2393: $cid = $env{'request.course.id'};
2394: } elsif ($env{'form.defaultdomain'} ne '' && $env{'form.defaultcourse'} ne '') {
2395: $cid = $env{'form.defaultdomain'}.'_'.
2396: $env{'form.defaultcourse'};
2397: }
2398: if ( $domain eq &LONCAPA::clean_domain($domain)
2399: && ($amode ne '')) {
2400: #######################################
2401: ## Add/Modify Users ##
2402: #######################################
2403: if ($context eq 'course') {
2404: $r->print('<h3>'.&mt('Enrolling Users')."</h3>\n<p>\n");
2405: } elsif ($context eq 'construction_space') {
2406: $r->print('<h3>'.&mt('Updating Co-authors')."</h3>\n<p>\n");
2407: } else {
2408: $r->print('<h3>'.&mt('Adding/Modifying Users')."</h3>\n<p>\n");
2409: }
2410: my %counts = (
2411: user => 0,
2412: auth => 0,
2413: role => 0,
2414: );
2415: my $flushc=0;
2416: my %student=();
2417: my %curr_groups;
2418: my %userchg;
2419: if ($context eq 'course') {
2420: # Get information about course groups
2421: %curr_groups = &Apache::longroup::coursegroups();
2422: }
2423: # Get new users list
2424: foreach (@userdata) {
2425: my %entries=&Apache::loncommon::record_sep($_);
2426: # Determine user name
2427: unless (($entries{$fields{'username'}} eq '') ||
2428: (!defined($entries{$fields{'username'}}))) {
2429: my ($fname, $mname, $lname,$gen) = ('','','','');
2430: if (defined($fields{'names'})) {
2431: ($lname,$fname,$mname)=($entries{$fields{'names'}}=~
2432: /([^\,]+)\,\s*(\w+)\s*(.*)$/);
2433: } else {
2434: if (defined($fields{'fname'})) {
2435: $fname=$entries{$fields{'fname'}};
2436: }
2437: if (defined($fields{'mname'})) {
2438: $mname=$entries{$fields{'mname'}};
2439: }
2440: if (defined($fields{'lname'})) {
2441: $lname=$entries{$fields{'lname'}};
2442: }
2443: if (defined($fields{'gen'})) {
2444: $gen=$entries{$fields{'gen'}};
2445: }
2446: }
2447: if ($entries{$fields{'username'}}
2448: ne &LONCAPA::clean_username($entries{$fields{'username'}})) {
2449: $r->print('<br />'.
2450: &mt('<b>[_1]</b>: Unacceptable username for user [_2] [_3] [_4] [_5]',
2451: $entries{$fields{'username'}},$fname,$mname,$lname,$gen).
2452: '</b>');
2453: } else {
2454: my $username = $entries{$fields{'username'}};
2455: my $sec;
2456: if ($context eq 'course' || $setting eq 'course') {
2457: # determine section number
2458: if (defined($fields{'sec'})) {
2459: if (defined($entries{$fields{'sec'}})) {
2460: $sec=$entries{$fields{'sec'}};
2461: }
2462: } else {
2463: $sec = $defaultsec;
2464: }
2465: # remove non alphanumeric values from section
2466: $sec =~ s/\W//g;
2467: if ($sec eq "none" || $sec eq 'all') {
2468: $r->print('<br />'.
2469: &mt('<b>[_1]</b>: Unable to enroll: section name "[_2]" for user [_3] [_4] [_5] [_6] is a reserved word.',
2470: $username,$sec,$fname,$mname,$lname,$gen));
2471: next;
2472: } elsif (($sec ne '') && (exists($curr_groups{$sec}))) {
2473: $r->print('<br />'.
2474: &mt('<b>[_1]</b>: Unable to enroll: section name "[_2]" for user [_3] [_4] [_5] [_6] is a course group. Section names and group names must be distinct.',
2475: $username,$sec,$fname,$mname,$lname,$gen));
2476: next;
2477: }
2478: }
2479: # determine id number
2480: my $id='';
2481: if (defined($fields{'id'})) {
2482: if (defined($entries{$fields{'id'}})) {
2483: $id=$entries{$fields{'id'}};
2484: }
2485: $id=~tr/A-Z/a-z/;
2486: }
2487: # determine email address
2488: my $email='';
2489: if (defined($fields{'email'})) {
2490: if (defined($entries{$fields{'email'}})) {
2491: $email=$entries{$fields{'email'}};
2492: unless ($email=~/^[^\@]+\@[^\@]+$/) { $email=''; } }
2493: }
2494: # determine user password
2495: my $password = $genpwd;
2496: if (defined($fields{'ipwd'})) {
2497: if ($entries{$fields{'ipwd'}}) {
2498: $password=$entries{$fields{'ipwd'}};
2499: }
2500: }
2501: # determine user role
2502: my $role = '';
2503: if (defined($fields{'role'})) {
2504: if ($entries{$fields{'role'}}) {
2505: my @poss_roles =
2506: &curr_role_permissions($context,$setting);
2507: if (grep(/^\Q$entries{$fields{'role'}}\E/,@poss_roles)) {
2508: $role=$entries{$fields{'role'}};
2509: } else {
2510: my $rolestr = join(', ',@poss_roles);
2511: $r->print('<br />'.
2512: &mt('<b>[_1]</b>: You do not have permission to add the requested role [_2] for the user.',$entries{$fields{'username'}},$entries{$fields{'role'}}).'<br />'.&mt('Allowable role(s) is/are: [_1].',$rolestr)."\n");
2513: next;
2514: }
2515: }
2516: }
2517: if ($role eq '') {
2518: $role = $defaultrole;
2519: }
2520: # Clean up whitespace
2521: foreach (\$domain,\$username,\$id,\$fname,\$mname,
2522: \$lname,\$gen,\$sec,\$role) {
2523: $$_ =~ s/(\s+$|^\s+)//g;
2524: }
2525: if ($password || $env{'form.login'} eq 'loc') {
2526: my ($userresult,$authresult,$roleresult);
2527: if ($role eq 'st') {
2528: &modifystudent($domain,$username,$cid,$sec,
2529: $desiredhost);
2530: $roleresult =
2531: &Apache::lonnet::modifystudent
2532: ($domain,$username,$id,$amode,$password,
2533: $fname,$mname,$lname,$gen,$sec,$enddate,
2534: $startdate,$env{'form.forceid'},
2535: $desiredhost,$email);
2536: } else {
2537: ($userresult,$authresult,$roleresult) =
2538: &modifyuserrole($context,$setting,
2539: $changeauth,$cid,$domain,$username,
2540: $id,$amode,$password,$fname,
2541: $mname,$lname,$gen,$sec,
2542: $env{'form.forceid'},$desiredhost,
2543: $email,$role,$enddate,$startdate);
2544: }
2545: $flushc =
2546: &user_change_result($r,$userresult,$authresult,
2547: $roleresult,\%counts,$flushc,
2548: $username,%userchg);
2549: } else {
2550: if ($context eq 'course') {
2551: $r->print('<br />'.
2552: &mt('<b>[_1]</b>: Unable to enroll. No password specified.',$username)
2553: );
2554: } elsif ($context eq 'construction_space') {
2555: $r->print('<br />'.
2556: &mt('<b>[_1]</b>: Unable to add co-author. No password specified.',$username)
2557: );
2558: } else {
2559: $r->print('<br />'.
2560: &mt('<b>[_1]</b>: Unable to add user. No password specified.',$username)
2561: );
2562: }
2563: }
2564: }
2565: }
2566: } # end of foreach (@userdata)
2567: # Flush the course logs so reverse user roles immediately updated
2568: if ($context eq 'course' || ($context eq 'domain' && $setting eq 'course')) {
2569: &Apache::lonnet::flushcourselogs();
2570: }
2571: $r->print("</p>\n<p>\n".&mt('Processed [_1] user(s).',$counts{'user'}).
2572: "</p>\n");
2573: if ($counts{'role'} > 0) {
2574: $r->print("<p>\n".
2575: &mt('Roles added for [_1] users. If user is active, the new role will be available when the user next logs in to LON-CAPA.',$counts{'role'})."</p>\n");
2576: }
2577: if ($counts{'auth'} > 0) {
2578: $r->print("<p>\n".
2579: &mt('Authentication changed for [_1] existing users.',
2580: $counts{'auth'})."</p>\n");
2581: }
2582: $r->print('<form name="uploadresult" action="/adm/createuser">');
2583: $r->print(&Apache::lonhtmlcommon::echo_form_input(['phase','prevphase','currstate']));
2584: $r->print('</form>');
2585: #####################################
2586: # Drop students #
2587: #####################################
2588: if ($env{'form.fullup'} eq 'yes') {
2589: $r->print('<h3>'.&mt('Dropping Students')."</h3>\n");
2590: # Get current classlist
2591: my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist();
2592: if (! defined($classlist)) {
2593: $r->print(&mt('There are no students currently enrolled.').
2594: "\n");
2595: } else {
2596: # Remove the students we just added from the list of students.
2597: foreach (@userdata) {
2598: my %entries=&Apache::loncommon::record_sep($_);
2599: unless (($entries{$fields{'username'}} eq '') ||
2600: (!defined($entries{$fields{'username'}}))) {
2601: delete($classlist->{$entries{$fields{'username'}}.
2602: ':'.$domain});
2603: }
2604: }
2605: # Print out list of dropped students.
2606: &show_drop_list($r,$classlist,$keylist,'nosort');
2607: }
2608: }
2609: } # end of unless
2610: }
2611:
2612: sub user_change_result {
2613: my ($r,$userresult,$authresult,$roleresult,$counts,$flushc,$username,
2614: $userchg) = @_;
2615: my $okresult = 0;
2616: if ($userresult ne 'ok') {
2617: if ($userresult =~ /^error:(.+)$/) {
2618: my $error = $1;
2619: $r->print('<br />'.
2620: &mt('<b>[_1]</b>: Unable to add/modify: [_2]',$username,$error));
2621: }
2622: } else {
2623: $counts->{'user'} ++;
2624: $okresult = 1;
2625: }
2626: if ($authresult ne 'ok') {
2627: if ($authresult =~ /^error:(.+)$/) {
2628: my $error = $1;
2629: $r->print('<br />'.
2630: &mt('<b>[_1]</b>: Unable to modify authentication: [_2]',$username,$error));
2631: }
2632: } else {
2633: $counts->{'auth'} ++;
2634: $okresult = 1;
2635: }
2636: if ($roleresult ne 'ok') {
2637: if ($roleresult =~ /^error:(.+)$/) {
2638: my $error = $1;
2639: $r->print('<br />'.
2640: &mt('<b>[_1]</b>: Unable to add role: [_2]',$username,$error));
2641: }
2642: } else {
2643: $counts->{'role'} ++;
2644: $okresult = 1;
2645: }
2646: if ($okresult) {
2647: $flushc++;
2648: $userchg->{$username}=1;
2649: $r->print('. ');
2650: if ($flushc>15) {
2651: $r->rflush;
2652: $flushc=0;
2653: }
2654: }
2655: return $flushc;
2656: }
2657:
2658: # ========================================================= Menu Phase Two Drop
2659: sub print_expire_menu {
2660: my ($r,$context) = @_;
2661: $r->print("<h3>".&mt("Expire Users' Roles")."</h3>");
2662: my $cid=$env{'request.course.id'};
2663: my ($classlist,$keylist) = &Apache::loncoursedata::get_classlist();
2664: if (! defined($classlist)) {
2665: $r->print(&mt('There are no students currently enrolled.')."\n");
2666: return;
2667: }
2668: # Print out the available choices
2669: &show_drop_list($r,$classlist,$keylist);
2670: return;
2671: }
2672:
2673:
2674: # ================================================================== Phase four
2675:
2676: sub expire_user_list {
2677: my ($r,$context) = @_;
2678: my $count=0;
2679: my @droplist = &Apache::loncommon::get_env_multiple('form.droplist');
2680: foreach (@droplist) {
2681: my ($uname,$udom)=split(/\:/,$_);
2682: # drop student
2683: my $result = &modifystudent($udom,$uname,$env{'request.course.id'});
2684: if ($result eq 'ok' || $result eq 'ok:') {
2685: $r->print(&mt('Dropped [_1]',$uname.'@'.$udom).'<br>');
2686: $count++;
2687: } else {
2688: $r->print(
2689: &mt('Error dropping [_1]:[_2]',$uname.'@'.$udom,$result).
2690: '<br />');
2691: }
2692: }
2693: $r->print('<p><b>'.&mt('Dropped [_1] user(s).',$count).'</b></p>');
2694: $r->print('<p>'.&mt('Re-enrollment will re-activate data.')) if ($count);
2695: }
2696:
2697: sub section_check_js {
2698: my $groupslist;
2699: my %curr_groups = &Apache::longroup::coursegroups();
2700: if (%curr_groups) {
2701: $groupslist = join('","',sort(keys(%curr_groups)));
2702: }
2703: return <<"END";
2704: function validate(caller) {
2705: var groups = new Array("$groupslist");
2706: var secname = caller.value;
2707: if ((secname == 'all') || (secname == 'none')) {
2708: alert("'"+secname+"' may not be used as the name for a section, as it is a reserved word.\\nPlease choose a different section name.");
2709: return 'error';
2710: }
2711: if (secname != '') {
2712: for (var k=0; k<groups.length; k++) {
2713: if (secname == groups[k]) {
2714: alert("'"+secname+"' may not be used as the name for a section, as it is the name of a course group.\\nSection names and group names must be distinct. Please choose a different section name.");
2715: return 'error';
2716: }
2717: }
2718: }
2719: return 'ok';
2720: }
2721: END
2722: }
2723:
2724: sub set_login {
2725: my ($dom,$authformkrb,$authformint,$authformloc) = @_;
2726: my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
2727: my $response;
2728: my ($authnum,%can_assign) =
2729: &Apache::loncommon::get_assignable_auth($dom);
2730: if ($authnum) {
2731: $response = &Apache::loncommon::start_data_table();
2732: if (($can_assign{'krb4'}) || ($can_assign{'krb5'})) {
2733: $response .= &Apache::loncommon::start_data_table_row().
2734: '<td>'.$authformkrb.'</td>'.
2735: &Apache::loncommon::end_data_table_row()."\n";
2736: }
2737: if ($can_assign{'int'}) {
2738: $response .= &Apache::loncommon::start_data_table_row().
2739: '<td>'.$authformint.'</td>'.
2740: &Apache::loncommon::end_data_table_row()."\n"
2741: }
2742: if ($can_assign{'loc'}) {
2743: $response .= &Apache::loncommon::start_data_table_row().
2744: '<td>'.$authformloc.'</td>'.
2745: &Apache::loncommon::end_data_table_row()."\n";
2746: }
2747: $response .= &Apache::loncommon::end_data_table();
2748: }
2749: return $response;
2750: }
2751:
2752: 1;
2753:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>