File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.240.2.6: download - view: text, annotated - select for diffs
Fri Dec 25 00:26:16 2009 UTC (14 years, 5 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3
  - Prevent double breadcrumbs during role switching.
  - Don't direct DCs to non-existent page after adhoc course role selection.

    1: # The LearningOnline Network with CAPA
    2: # User Roles Screen
    3: #
    4: # $Id: lonroles.pm,v 1.240.2.6 2009/12/25 00:26:16 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: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonroles - User Roles Screen
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: Invoked by /etc/httpd/conf/srm.conf:
   39: 
   40:  <Location /adm/roles>
   41:  PerlAccessHandler       Apache::lonacc
   42:  SetHandler perl-script
   43:  PerlHandler Apache::lonroles
   44:  ErrorDocument     403 /adm/login
   45:  ErrorDocument	  500 /adm/errorhandler
   46:  </Location>
   47: 
   48: =head1 OVERVIEW
   49: 
   50: =head2 Choosing Roles
   51: 
   52: C<lonroles> is a handler that allows a user to switch roles in
   53: mid-session. LON-CAPA attempts to work with "No Role Specified", the
   54: default role that a user has before selecting a role, as widely as
   55: possible, but certain handlers for example need specification which
   56: course they should act on, etc. Both in this scenario, and when the
   57: handler determines via C<lonnet>'s C<&allowed> function that a certain
   58: action is not allowed, C<lonroles> is used as error handler. This
   59: allows the user to select another role which may have permission to do
   60: what they were trying to do. C<lonroles> can also be accessed via the
   61: B<CRS> button in the Remote Control. 
   62: 
   63: =begin latex
   64: 
   65: \begin{figure}
   66: \begin{center}
   67: \includegraphics[width=0.45\paperwidth,keepaspectratio]{Sample_Roles_Screen}
   68:   \caption{\label{Sample_Roles_Screen}Sample Roles Screen} 
   69: \end{center}
   70: \end{figure}
   71: 
   72: =end latex
   73: 
   74: =head2 Role Initialization
   75: 
   76: The privileges for a user are established at login time and stored in the session environment. As a consequence, a new role does not become active till the next login. Handlers are able to query for privileges using C<lonnet>'s C<&allowed> function. When a user first logs in, their role is the "common" role, which means that they have the sum of all of their privileges. During a session it might become necessary to choose a particular role, which as a consequence also limits the user to only the privileges in that particular role.
   77: 
   78: =head1 INTRODUCTION
   79: 
   80: This module enables a user to select what role he wishes to
   81: operate under (instructor, student, teaching assistant, course
   82: coordinator, etc).  These roles are pre-established by the actions
   83: of upper-level users.
   84: 
   85: This is part of the LearningOnline Network with CAPA project
   86: described at http://www.lon-capa.org.
   87: 
   88: =head1 HANDLER SUBROUTINE
   89: 
   90: This routine is called by Apache and mod_perl.
   91: 
   92: =over 4
   93: 
   94: =item *
   95: 
   96: Roles Initialization (yes/no)
   97: 
   98: =item *
   99: 
  100: Get Error Message from Environment
  101: 
  102: =item *
  103: 
  104: Who is this?
  105: 
  106: =item *
  107: 
  108: Generate Page Output
  109: 
  110: =item *
  111: 
  112: Choice or no choice
  113: 
  114: =item *
  115: 
  116: Table
  117: 
  118: =item *
  119: 
  120: Privileges
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: 
  127: package Apache::lonroles;
  128: 
  129: use strict;
  130: use Apache::lonnet;
  131: use Apache::lonuserstate();
  132: use Apache::Constants qw(:common);
  133: use Apache::File();
  134: use Apache::lonmenu;
  135: use Apache::loncommon;
  136: use Apache::lonhtmlcommon;
  137: use Apache::lonannounce;
  138: use Apache::lonlocal;
  139: use Apache::lonpageflip();
  140: use Apache::lonnavdisplay();
  141: use Apache::lonmainmenu();
  142: use GDBM_File;
  143: use LONCAPA qw(:DEFAULT :match);
  144: use HTML::Entities;
  145:  
  146: 
  147: sub redirect_user {
  148:     my ($r,$title,$url,$msg,$launch_nav) = @_;
  149:     $msg = $title if (! defined($msg));
  150:     &Apache::loncommon::content_type($r,'text/html');
  151:     &Apache::loncommon::no_cache($r);
  152:     $r->send_http_header;
  153:     my $swinfo=&Apache::lonmenu::rawconfig();
  154:     my $navwindow;
  155:     if ($launch_nav eq 'on') {
  156: 	$navwindow.=&Apache::lonnavdisplay::launch_win('now',undef,undef,
  157: 						       ($url =~ m-^/adm/whatsnew-));
  158:     } else {
  159: 	$navwindow.=&Apache::lonnavmaps::close();
  160:     }
  161: 
  162:     # Breadcrumbs
  163:     my $brcrum = [{'href' => $url,
  164:                    'text' => 'Switching Role'},];
  165:     my $start_page = &Apache::loncommon::start_page('Switching Role',undef,
  166:                                                     {'redirect' => [1,$url],
  167:                                                      'bread_crumbs' => $brcrum,});
  168:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  169:     my $end_page   = &Apache::loncommon::end_page();
  170: 
  171: # Note to style police: 
  172: # This must only replace the spaces, nothing else, or it bombs elsewhere.
  173:     $url=~s/ /\%20/g;
  174:     $r->print(<<ENDREDIR);
  175: $start_page
  176: <script type="text/javascript">
  177: // <![CDATA[
  178: $swinfo
  179: // ]]>
  180: </script>
  181: $navwindow
  182: <p>$msg</p>
  183: $end_page
  184: ENDREDIR
  185:     return;
  186: }
  187: 
  188: sub error_page {
  189:     my ($r,$error,$dest)=@_;
  190:     &Apache::loncommon::content_type($r,'text/html');
  191:     &Apache::loncommon::no_cache($r);
  192:     $r->send_http_header;
  193:     return OK if $r->header_only;
  194:     # Breadcrumbs
  195:     my $brcrum = [{'href' => $dest,
  196:                    'text' => 'Problems during Course Initialization'},];
  197:     $r->print(&Apache::loncommon::start_page('Problems during Course Initialization',
  198:                                              undef,
  199:                                              {'bread_crumbs' => $brcrum,})
  200:     );
  201:     $r->print(
  202:         '<script type="text/javascript">'.
  203:         '// <![CDATA['.
  204:         &Apache::lonmenu::rawconfig().
  205:         '// ]]>'.
  206:         '</script>'.
  207: 	      '<p class="LC_error">'.&mt('The following problems occurred:').
  208:           '<br />'.
  209: 	      $error.
  210: 	      '</p><br /><a href="'.$dest.'">'.&mt('Continue').'</a>'
  211:     );
  212:     $r->print(&Apache::loncommon::end_page());
  213: }
  214: 
  215: sub handler {
  216: 
  217:     my $r = shift;
  218: 
  219:     my $now=time;
  220:     my $then=$env{'user.login.time'};
  221:     my $refresh=$env{'user.refresh.time'};
  222:     if (!$refresh) {
  223:         $refresh = $then;
  224:     }
  225:     my $envkey;
  226:     my %dcroles = ();
  227:     my $numdc = &check_fordc(\%dcroles,$then);
  228:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
  229:     my $custommenu = &Apache::loncommon::needs_gci_custom();
  230: 
  231: # ================================================================== Roles Init
  232:     if ($env{'form.selectrole'}) {
  233: 
  234:         my $locknum=&Apache::lonnet::get_locks();
  235:         if ($locknum) { return 409; }
  236: 
  237:         if ($env{'form.newrole'}) {
  238:             $env{'form.'.$env{'form.newrole'}}=1;
  239: 	}
  240: 	if ($env{'request.course.id'}) {
  241:             # Check if user is CC trying to select a course role
  242:             if ($env{'form.switchrole'}) {
  243:                 if (!defined($env{'user.role.'.$env{'form.switchrole'}})) {
  244:                     &adhoc_course_role($refresh,$then);
  245:                 }
  246:             }
  247: 	    my %temp=('logout_'.$env{'request.course.id'} => time);
  248: 	    &Apache::lonnet::put('email_status',\%temp);
  249: 	    &Apache::lonnet::delenv('user.state.'.$env{'request.course.id'});
  250: 	}
  251: 	&Apache::lonnet::appenv({"request.course.id"   => '',
  252: 			 	 "request.course.fn"   => '',
  253: 				 "request.course.uri"  => '',
  254: 				 "request.course.sec"  => '',
  255: 				 "request.role"        => 'cm',
  256:                                  "request.role.adv"    => $env{'user.adv'},
  257: 				 "request.role.domain" => $env{'user.domain'}});
  258: # Check if user is a DC trying to enter a course or author space and needs privs to be created
  259:         if ($numdc > 0) {
  260:             foreach my $envkey (keys %env) {
  261: # Is this an ad-hoc Coordinator role?
  262:                 if (my ($ccrole,$domain,$coursenum) =
  263: 		    ($envkey =~ m-^form\.(cc|co)\./($match_domain)/($match_courseid)$-)) {
  264:                     if ($dcroles{$domain}) {
  265:                         &Apache::lonnet::check_adhoc_privs($domain,$coursenum,
  266:                                                            $then,$refresh,$now,$ccrole);
  267:                     }
  268:                     last;
  269:                 }
  270: # Is this an ad-hoc CA-role?
  271:                 if (my ($domain,$user) =
  272: 		    ($envkey =~ m-^form\.ca\./($match_domain)/($match_username)$-)) {
  273:                     if (($domain eq $env{'user.domain'}) && ($user eq $env{'user.name'})) {
  274:                         delete($env{$envkey});
  275:                         $env{'form.au./'.$domain.'/'} = 1;
  276:                         my ($server_status,$home) = &check_author_homeserver($user,$domain);
  277:                         if ($server_status eq 'switchserver') {
  278:                             my $trolecode = 'au./'.$domain.'/';
  279:                             my $switchserver = '/adm/switchserver?otherserver='.$home.'&role='.$trolecode;
  280:                             $r->internal_redirect($switchserver);
  281:                         }
  282:                         last;
  283:                     }
  284:                     if (my ($castart,$caend) = ($env{'user.role.ca./'.$domain.'/'.$user} =~ /^(\d*)\.(\d*)$/)) {
  285:                         if (((($castart) && ($castart < $now)) || !$castart) && 
  286:                             ((!$caend) || (($caend) && ($caend > $now)))) {
  287:                             my ($server_status,$home) = &check_author_homeserver($user,$domain);
  288:                             if ($server_status eq 'switchserver') {
  289:                                 my $trolecode = 'ca./'.$domain.'/'.$user;
  290:                                 my $switchserver = '/adm/switchserver?otherserver='.$home.'&role='.$trolecode;
  291:                                 $r->internal_redirect($switchserver);
  292:                             }
  293:                             last;
  294:                         }
  295:                     }
  296:                     # Check if author blocked ca-access
  297:                     my %blocked=&Apache::lonnet::get('environment',['domcoord.author'],$domain,$user);
  298:                     if ($blocked{'domcoord.author'} eq 'blocked') {
  299:                         delete($env{$envkey});
  300:                         $env{'user.error.msg'}=':::1:User '.$user.' in domain '.$domain.' blocked domain coordinator access';
  301:                         last;
  302:                     }
  303:                     if ($dcroles{$domain}) {
  304:                         my ($server_status,$home) = &check_author_homeserver($user,$domain);
  305:                         if (($server_status eq 'ok') || ($server_status eq 'switchserver')) {
  306:                             &Apache::lonnet::check_adhoc_privs($domain,$user,$then,
  307:                                                                $refresh,$now,'ca');
  308:                             if ($server_status eq 'switchserver') {
  309:                                 my $trolecode = 'ca./'.$domain.'/'.$user; 
  310:                                 my $switchserver = '/adm/switchserver?'
  311:                                                   .'otherserver='.$home.'&role='.$trolecode;
  312:                                 $r->internal_redirect($switchserver);
  313:                             }
  314:                         } else {
  315:                             delete($env{$envkey});
  316:                         }
  317:                     } else {
  318:                         delete($env{$envkey});
  319:                     }
  320:                     last;
  321:                 }
  322:             }
  323:         }
  324:         if (($env{'form.cm'}) && ($env{'form.orgurl'})) { 
  325:             $r->internal_redirect($env{'form.orgurl'});
  326:         }
  327:         foreach $envkey (keys %env) {
  328:             next if ($envkey!~/^user\.role\./);
  329:             my ($where,$trolecode,$role,$tstatus,$tend,$tstart);
  330:             &Apache::lonnet::role_status($envkey,$then,$refresh,$now,\$role,\$where,
  331:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
  332:             if ($env{'form.'.$trolecode}) {
  333: 		if ($tstatus eq 'is') {
  334: 		    $where=~s/^\///;
  335: 		    my ($cdom,$cnum,$csec)=split(/\//,$where);
  336: # check for course groups
  337:                     my %coursegroups = &Apache::lonnet::get_active_groups(
  338:                           $env{'user.domain'},$env{'user.name'},$cdom, $cnum);
  339:                     my $cgrps = join(':',keys(%coursegroups));
  340: 
  341: # store role if recent_role list being kept
  342:                     if ($env{'environment.recentroles'}) {
  343:                         my %frozen_roles =
  344:                            &Apache::lonhtmlcommon::get_recent_frozen('roles',$env{'environment.recentrolesn'});
  345: 			&Apache::lonhtmlcommon::store_recent('roles',
  346: 							     $trolecode,' ',$frozen_roles{$trolecode});
  347:                     }
  348: 
  349: 
  350: # check for keyed access
  351: 		    if (($role eq 'st') && 
  352:                        ($env{'course.'.$cdom.'_'.$cnum.'.keyaccess'} eq 'yes')) {
  353: # who is key authority?
  354: 			my $authdom=$cdom;
  355: 			my $authnum=$cnum;
  356: 			if ($env{'course.'.$cdom.'_'.$cnum.'.keyauth'}) {
  357: 			    ($authnum,$authdom)=
  358: 				split(/:/,$env{'course.'.$cdom.'_'.$cnum.'.keyauth'});
  359: 			}
  360: # check with key authority
  361: 			unless (&Apache::lonnet::validate_access_key(
  362: 				     $env{'environment.key.'.$cdom.'_'.$cnum},
  363: 					     $authdom,$authnum)) {
  364: # there is no valid key
  365: 			     if ($env{'form.newkey'}) {
  366: # student attempts to register a new key
  367: 				 &Apache::loncommon::content_type($r,'text/html');
  368: 				 &Apache::loncommon::no_cache($r);
  369: 				 $r->send_http_header;
  370: 				 my $swinfo=&Apache::lonmenu::rawconfig();
  371: 				 my $start_page=&Apache::loncommon::start_page
  372: 				    ('Verifying Access Key to Unlock this Course');
  373: 				 my $end_page=&Apache::loncommon::end_page();
  374: 				 my $buttontext=&mt('Enter Course');
  375: 				 my $message=&mt('Successfully registered key');
  376: 				 my $assignresult=
  377: 				     &Apache::lonnet::assign_access_key(
  378: 						     $env{'form.newkey'},
  379: 						     $authdom,$authnum,
  380: 						     $cdom,$cnum,
  381:                                                      $env{'user.domain'},
  382: 						     $env{'user.name'},
  383:                                                      &mt('Assigned from [_1] at [_2] for [_3]'
  384:                                                         ,$ENV{'REMOTE_ADDR'}
  385:                                                         ,&Apache::lonlocal::locallocaltime()
  386:                                                         ,$trolecode)
  387:                                                      );
  388: 				 unless ($assignresult eq 'ok') {
  389: 				     $assignresult=~s/^error\:\s*//;
  390: 				     $message=&mt($assignresult).
  391: 				     '<br /><a href="/adm/logout">'.
  392: 				     &mt('Logout').'</a>';
  393: 				     $buttontext=&mt('Re-Enter Key');
  394: 				 }
  395: 				 $r->print(<<ENDENTEREDKEY);
  396: $start_page
  397: <script type="text/javascript">
  398: // <![CDATA[
  399: $swinfo
  400: // ]]>
  401: </script>
  402: <form action="" method="post">
  403: <input type="hidden" name="selectrole" value="1" />
  404: <input type="hidden" name="$trolecode" value="1" />
  405: <span class="LC_fontsize_large">$message</span><br />
  406: <input type="submit" value="$buttontext" />
  407: </form>
  408: $end_page
  409: ENDENTEREDKEY
  410:                                  return OK;
  411: 			     } else {
  412: # print form to enter a new key
  413: 				 &Apache::loncommon::content_type($r,'text/html');
  414: 				 &Apache::loncommon::no_cache($r);
  415: 				 $r->send_http_header;
  416: 				 my $swinfo=&Apache::lonmenu::rawconfig();
  417: 				 my $start_page=&Apache::loncommon::start_page
  418: 				    ('Enter Access Key to Unlock this Course');
  419: 				 my $end_page=&Apache::loncommon::end_page();
  420: 				 $r->print(<<ENDENTERKEY);
  421: $start_page
  422: <script type="text/javascript">
  423: // <![CDATA[
  424: $swinfo
  425: // ]]>
  426: </script>
  427: <form action="" method="post">
  428: <input type="hidden" name="selectrole" value="1" />
  429: <input type="hidden" name="$trolecode" value="1" />
  430: <input type="text" size="20" name="newkey" value="$env{'form.newkey'}" />
  431: <input type="submit" value="Enter key" />
  432: </form>
  433: $end_page
  434: ENDENTERKEY
  435: 				 return OK;
  436: 			     }
  437: 			 }
  438: 		     }
  439: 		    &Apache::lonnet::log($env{'user.domain'},
  440: 					 $env{'user.name'},
  441: 					 $env{'user.home'},
  442: 					 "Role ".$trolecode);
  443: 		    
  444: 		    &Apache::lonnet::appenv(
  445: 					   {'request.role'        => $trolecode,
  446: 					    'request.role.domain' => $cdom,
  447: 					    'request.course.sec'  => $csec,
  448:                                             'request.course.groups' => $cgrps});
  449:                     my $tadv=0;
  450: 
  451: 		    if (($cnum) && ($role ne 'ca') && ($role ne 'aa')) {
  452:                         my $msg;
  453:                         if (&Apache::lonnet::allowed('adv') eq 'F') { $tadv=1; }
  454:                         &Apache::lonnet::appenv({'request.role.adv'=>$tadv});
  455: 			my ($furl,$ferr)=
  456: 			    &Apache::lonuserstate::readmap($cdom.'/'.$cnum);
  457: 			if (($env{'form.orgurl'}) && 
  458: 			    ($env{'form.orgurl'}!~/^\/adm\/flip/)) {
  459: 			    my $dest=$env{'form.orgurl'};
  460:                             if ($env{'form.symb'}) {
  461:                                 if ($dest =~ /\?/) {
  462:                                     $dest .= '&';
  463:                                 } else {
  464:                                     $dest .= '?'
  465:                                 }
  466:                                 $dest .= 'symb='.$env{'form.symb'};
  467:                             }
  468:                             if (($ferr) && ($tadv)) {
  469: 				&error_page($r,$ferr,$dest);
  470: 			    } else {
  471: 				$r->internal_redirect($dest);
  472: 			    }
  473: 			    return OK;
  474: 			} else {
  475: 			    if (!$env{'request.course.id'}) {
  476: 				&Apache::lonnet::appenv(
  477: 				      {"request.course.id"  => $cdom.'_'.$cnum});
  478: 				$furl='/adm/roles?tryagain=1';
  479:                 $msg='<p><span class="LC_error">'
  480:                     .&mt('Could not initialize [_1] at this time.',
  481:                          $env{'course.'.$cdom.'_'.$cnum.'.description'})
  482:                     .'</span></p>'
  483:                     .'<p>'.&mt('Please try again.').'</p>'
  484:                     .'<p>'.$ferr.'</p>';
  485: 			    }
  486: 
  487: 			    if (($ferr) && ($tadv)) {
  488: 				&error_page($r,$ferr,$furl);
  489: 			    } else {
  490: 				# Check to see if the user is a CC entering a course 
  491: 				# for the first time
  492: 				my (undef, undef, $role, $courseid) = split(/\./, $envkey);
  493: 				if (substr($courseid, 0, 1) eq '/') {
  494: 				    $courseid = substr($courseid, 1);
  495: 				}
  496: 				$courseid =~ s/\//_/;
  497: 				if (($cdom ne 'gcitest') && (($role eq 'cc') || ($role eq 'co')) 
  498:                                     && ($env{'course.' . $courseid .'.course.helper.not.run'})) { 
  499: 				    $furl = "/adm/helper/course.initialization.helper";
  500: 				    # Send the user to the course they selected
  501: 				} elsif ($env{'request.course.id'}) {
  502:                                     if ($env{'form.destinationurl'}) {
  503:                                         my $dest = $env{'form.destinationurl'};
  504:                                         if ($env{'form.destsymb'} ne '') {
  505:                                             my $esc_symb = &HTML::Entities::encode($env{'form.destsymb'},'"<>&');
  506:                                             $dest .= '?symb='.$esc_symb;
  507:                                         }
  508:                                         &redirect_user($r,&mt('Entering [_1]',
  509:                                                       $env{'course.'.$courseid.'.description'}),
  510:                                                $dest,$msg,
  511:                                                $env{'environment.remotenavmap'});
  512:                                         return OK;
  513:                                     }
  514: 				    if (&Apache::lonnet::allowed('whn',
  515: 								 $env{'request.course.id'})
  516: 					|| &Apache::lonnet::allowed('whn',
  517: 								    $env{'request.course.id'}.'/'
  518: 								    .$env{'request.course.sec'})
  519: 					) {
  520: 					my $startpage = &courseloadpage($courseid);
  521: 					unless (($startpage eq 'firstres') || ($cdom eq 'gcitest')) {
  522: 					    $msg = &mt('Entering [_1] ...',
  523: 						       $env{'course.'.$courseid.'.description'});
  524: 					    &redirect_user($r,&mt('New in course'),
  525: 							   '/adm/whatsnew?refpage=start',$msg,
  526: 							   $env{'environment.remotenavmap'});
  527: 					    return OK;
  528: 					}
  529: 				    }
  530: 				}
  531: # Are we allowed to look at the first resource?
  532: 				if ($furl !~ m|^/adm/|) {
  533: # Guess not ...
  534: 				    $furl=&Apache::lonpageflip::first_accessible_resource();
  535: 				}
  536:                                 if (($cdom eq 'gcitest') && ($custommenu)) {
  537:                                     $furl = '/adm/navmaps';
  538:                                 }
  539:                                 $msg = &mt('Entering [_1] ...',
  540: 					   $env{'course.'.$courseid.'.description'});
  541: 				&redirect_user($r,&mt('Entering [_1]',
  542: 						      $env{'course.'.$courseid.'.description'}),
  543: 					       $furl,$msg,
  544: 					       $env{'environment.remotenavmap'});
  545: 			    }
  546: 			    return OK;
  547: 			}
  548: 		    }
  549:                     #
  550:                     # Send the user to the construction space they selected
  551:                     if ($role =~ /^(au|ca|aa)$/) {
  552:                         my $redirect_url = '/priv/';
  553:                         if ($role eq 'au') {
  554:                             $redirect_url.=$env{'user.name'};
  555:                         } else {
  556:                             $where =~ /\/(.*)$/;
  557:                             $redirect_url .= $1;
  558:                         }
  559:                         $redirect_url .= '/';
  560:                         &redirect_user($r,&mt('Entering Construction Space'),
  561:                                        $redirect_url);
  562:                         return OK;
  563:                     }
  564:                     if ($role eq 'dc') {
  565:                         my $redirect_url = '/adm/menu/';
  566:                         &redirect_user($r,&mt('Loading Domain Coordinator Menu'),
  567:                                        $redirect_url);
  568:                         return OK;
  569:                     }
  570:                     if ($role eq 'sc') {
  571:                         my $redirect_url = '/adm/grades?command=scantronupload';
  572:                         &redirect_user($r,&mt('Loading Data Upload Page'),
  573:                                        $redirect_url);
  574:                         return OK;
  575:                     }
  576: 		}
  577:             }
  578:         }
  579:     }
  580: 
  581: # =============================================================== No Roles Init
  582: 
  583:     &Apache::loncommon::content_type($r,'text/html');
  584:     &Apache::loncommon::no_cache($r);
  585:     $r->send_http_header;
  586:     return OK if $r->header_only;
  587: 
  588:     my ($crumbtext,$pagetitle,$recent,$show_course);
  589:     my $noscript='<span class="LC_error">'.&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.').'<br />'.&mt('As this is not the case, most functionality in the system will be unavailable.').'</span><br />';
  590:     if ($custommenu) {
  591:         my $start_page = &Apache::loncommon::start_page('Main Menu',undef,
  592:                                                         {'bread_crumbs' => 1});
  593:         $r->print(<<"ENDCUSTOM");
  594: $start_page
  595: <br />
  596: <noscript>
  597: $noscript
  598: </noscript>
  599: ENDCUSTOM
  600:     } else {
  601:         $crumbtext = 'User Roles';
  602:         $pagetitle = 'My Roles';
  603:         $recent = &mt('Recent Roles');
  604:         $show_course=&Apache::loncommon::show_course();
  605:         if ($show_course) {
  606:             $crumbtext = 'Courses';
  607:             $pagetitle = 'My Courses';
  608:             $recent = &mt('Recent Courses');
  609:         }
  610:         my $brcrum =[{href=>"/adm/roles",text=>$crumbtext}];
  611:         my $swinfo=&Apache::lonmenu::rawconfig();
  612:         my $start_page=&Apache::loncommon::start_page($pagetitle,undef,{bread_crumbs=>$brcrum});
  613:         my $standby=&mt('Role selected. Please stand by.');
  614:         $standby=~s/\n/\\n/g;
  615:         $r->print(<<ENDHEADER);
  616: $start_page
  617: <br />
  618: <noscript>
  619: $noscript
  620: </noscript>
  621: <script type="text/javascript">
  622: // <![CDATA[
  623: $swinfo
  624: window.focus();
  625: 
  626: active=true;
  627: 
  628: function enterrole (thisform,rolecode,buttonname) {
  629:     if (active) {
  630: 	active=false;
  631:         document.title='$standby';
  632:         window.status='$standby';
  633: 	thisform.newrole.value=rolecode;
  634: 	thisform.submit();
  635:     } else {
  636:        alert('$standby');
  637:     }   
  638: }
  639: // ]]>
  640: </script>
  641: ENDHEADER
  642:     }
  643: 
  644: # ------------------------------------------ Get Error Message from Environment
  645: 
  646:     my ($fn,$priv,$nochoose,$error,$msg)=split(/:/,$env{'user.error.msg'});
  647:     if ($env{'user.error.msg'}) {
  648: 	$r->log_reason(
  649:    "$msg for $env{'user.name'} domain $env{'user.domain'} access $priv",$fn);
  650:     }
  651: 
  652: # ------------------------------------------------- Can this user re-init, etc?
  653: 
  654:     my $advanced=$env{'user.adv'};
  655:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['tryagain']);
  656:     my $tryagain=$env{'form.tryagain'};
  657:     my $reinit=$env{'user.reinit'};
  658:     delete $env{'user.reinit'};
  659: 
  660: # -------------------------------------------------------- Generate Page Output
  661: # --------------------------------------------------------------- Error Header?
  662:     if ($error) {
  663:         $r->print("<h1>".&mt('LON-CAPA Access Control')."</h1>");
  664: 	$r->print("<!-- LONCAPAACCESSCONTROLERRORSCREEN --><hr /><pre>");
  665: 	if ($priv ne '') {
  666:             $r->print(&mt('Access  : ').&Apache::lonnet::plaintext($priv)."\n");
  667: 	}
  668: 	if ($fn ne '') {
  669:             $r->print(&mt('Resource: ').&Apache::lonenc::check_encrypt($fn)."\n");
  670: 	}
  671: 	if ($msg ne '') {
  672:             $r->print(&mt('Action  : ').$msg."\n");
  673: 	}
  674: 	$r->print("</pre><hr />");
  675: 	my $url=$fn;
  676: 	my $last;
  677: 	if (tie(my %hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
  678: 		&GDBM_READER(),0640)) {
  679: 	    $last=$hash{'last_known'};
  680: 	    untie(%hash);
  681: 	}
  682: 	if ($last) { $fn.='?symb='.&escape($last); }
  683: 
  684: 	&Apache::londocs::changewarning($r,undef,'You have modified your course recently, [_1] may fix this access problem.',
  685: 					&Apache::lonenc::check_encrypt($fn));
  686:     } else {
  687:         if ($env{'user.error.msg'}) {
  688:             if ($reinit) {
  689:                 $r->print(
  690:  '<h3><span class="LC_error">'.
  691:  &mt('As your session file for the course or community has expired, you will need to re-select it.').'</span></h3>');
  692:             } else {
  693: 	        $r->print(
  694:  '<h3><span class="LC_error">'.
  695:  &mt('You need to choose another user role or enter a specific course or community for this function.').
  696:  '</span></h3>');
  697: 	    }
  698:         }
  699:     }
  700: # -------------------------------------------------------- Choice or no choice?
  701:     if ($nochoose) {
  702: 	$r->print("<h2>".&mt('Sorry ...')."</h2>\n<span class='LC_error'>".
  703: 		  &mt('This action is currently not authorized.').'</span>'.
  704: 		  &Apache::loncommon::end_page());
  705: 	return OK;
  706:     } else {
  707:         if (($ENV{'REDIRECT_QUERY_STRING'}) && ($fn)) {
  708:     	    $fn.='?'.$ENV{'REDIRECT_QUERY_STRING'};
  709:         }
  710:         unless ($custommenu) {
  711:             $r->print('<form method="post" name="rolechoice" action="'.(($fn)?$fn:$r->uri).'">');
  712:             $r->print('<input type="hidden" name="orgurl" value="'.$fn.'" />');
  713:             $r->print('<input type="hidden" name="selectrole" value="1" />');
  714:             $r->print('<input type="hidden" name="newrole" value="" />');
  715:         }
  716:     }
  717: 
  718:     my (%roletext,%sortrole,%roleclass,%futureroles,%timezones);
  719:     my ($countactive,$countfuture,$inrole,$possiblerole) = 
  720:         &gather_roles($then,$refresh,$now,$reinit,$nochoose,\%roletext,\%sortrole,\%roleclass,
  721:                       \%futureroles,\%timezones);
  722: 
  723:     $refresh = $now;
  724:     &Apache::lonnet::appenv({'user.refresh.time'  => $refresh});
  725:     if ($custommenu) {
  726:         if ($env{'form.destinationurl'} eq '/adm/gci_info') {
  727:             $r->print(&gci_info_page()).
  728:             &Apache::loncommon::end_page();
  729:             return OK;
  730:         }
  731:         my %courses = &Apache::loncommon::existing_gcitest_courses();
  732:         $env{'browser.interface'}='faketextual';
  733:         $env{'environment.remote'}='off';
  734:         my $numcourses = keys(%courses);
  735:         my $switcher;
  736:         if ($numcourses > 0) {
  737:             $switcher = &Apache::lonmainmenu::gcitest_switcher(%courses);
  738:             my $current;
  739:             if ($env{'request.course.id'}) {
  740:                 $current = 'cc./'.$env{'course.'.$env{'request.course.id'}.'.domain'}.
  741:                            '/'.$env{'course.'.$env{'request.course.id'}.'.num'};
  742:             }
  743:             my $switcher_js = &Apache::lonmainmenu::gcitest_switcher_js($current,$numcourses);
  744:             $r->print(<<"ENDSCRIPT");
  745: <script type="text/javascript">
  746: // <![CDATA[
  747: $switcher_js
  748: // ]]>
  749: </script>
  750: ENDSCRIPT
  751:         }
  752:         $r->print(&Apache::lonmenu::inlinemenu('gcicustom',$switcher).
  753:                   &Apache::loncommon::end_page());
  754:         return OK;
  755:     } else {
  756:         if ($env{'form.destinationurl'} eq '/adm/gci_info') {
  757:             delete($env{'form.destinationurl'});
  758:         }
  759:     }
  760:     if ($env{'user.adv'}) {
  761:         $r->print('<p><label><input type="checkbox" name="showall"');
  762:         if ($env{'form.showall'}) { $r->print(' checked="checked" '); }
  763:         $r->print(' />'.&mt('Show all roles').'</label>'
  764:                  .' <input type="submit" value="'.&mt('Update display').'" />'
  765:                  .'</p>');
  766:     } else {
  767:         if ($countactive > 0) {
  768:             &queued_selfenrollment($r);
  769:             my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
  770:             my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&'); 
  771:             $r->print(
  772:                 '<p>'
  773:                .&mt('[_1]Visit the [_2]Course/Community Catalog[_3]'
  774:                    .' to view all [_4] LON-CAPA courses and communities.'
  775:                    ,'<b>'
  776:                    ,'<a href="/adm/coursecatalog?showdom='.$esc_dom.'">'
  777:                    ,'</a></b>',$domdesc)
  778:                .'<br />'
  779:                .&mt('If a course or community is [_1]not[_2] in your list of current courses and communities below,'
  780:                    .' you may be able to enroll if self-enrollment is permitted.'
  781:                    ,'<b>','</b>')
  782:                .'</p>'
  783:             );
  784:         }
  785:     }
  786: 
  787: # No active roles
  788:     if ($countactive==0) {
  789: 	if ($inrole) {
  790: 	    $r->print('<h2>'.&mt('Currently no additional roles, courses or communities').'</h2>');
  791: 	} else {
  792: 	    $r->print('<h2>'.&mt('Currently no active roles, courses or communities').'</h2>');
  793: 	}
  794:         &findcourse_advice($r);
  795:         &requestcourse_advice($r); 
  796: 	$r->print('</form>');
  797:         if ($countfuture) {
  798:             $r->print(&mt('The following [quant,_1,role,roles] will become active in the future:',$countfuture));
  799:             my $doheaders = &roletable_headers($r,\%roleclass,\%sortrole,
  800:                                                $nochoose);
  801:             &print_rolerows($r,$doheaders,\%roleclass,\%sortrole,\%dcroles,
  802:                             \%roletext);
  803:             my $tremark='';
  804:             my $tbg;
  805:             if ($env{'request.role'} eq 'cm') {
  806:                 $tbg="LC_roles_selected";
  807:                 $tremark=&mt('Currently selected.').' ';
  808:             } else {
  809:                 $tbg="LC_roles_is";
  810:             }
  811:             $r->print(&Apache::loncommon::start_data_table_row()
  812:                      .'<td class="'.$tbg.'">&nbsp;</td>'
  813:                      .'<td colspan="3">'
  814:                      .&mt('No role specified')
  815:                      .'</td>'
  816:                      .'<td>'.$tremark.'&nbsp;</td>'
  817:                      .&Apache::loncommon::end_data_table_row()
  818:             );
  819: 
  820:             $r->print(&Apache::loncommon::end_data_table());
  821:         }
  822:         $r->print(&Apache::loncommon::end_page());
  823: 	return OK;
  824:     } elsif ($countactive==1) { # Is there only one choice?
  825:         my $needs_switchserver;
  826:         if ($env{'user.author'}) {
  827:             $needs_switchserver = &check_needs_switchserver($possiblerole);
  828:         }
  829:         if ((!$needs_switchserver) && ($env{'request.role'} eq 'cm')) {
  830:             $r->print('<h3>'.&mt('Please stand by.').'</h3>'.
  831:                 '<input type="hidden" name="'.$possiblerole.'" value="1" />'.
  832:             '<noscript><br /><input type="submit" name="submit" value="'.&mt('Continue').'" /></noscript>');
  833:             $r->print("</form>\n");
  834:             $r->rflush();
  835:             $r->print('<script type="text/javascript">document.forms.rolechoice.submit();</script>');
  836:             $r->print(&Apache::loncommon::end_page());
  837:             return OK;
  838:         }
  839:         if ($needs_switchserver) {
  840:             $r->print("<h2>".&mt('Server Switch Required')."</h2>\n".
  841:                       &mt('Construction Space access is only available from '.
  842:                           'the home server of the corresponding Author.').'<br />'.
  843:                       &mt("Click the 'Switch Server' link to go there.").'<br />');
  844:         }
  845:     }
  846: # ----------------------------------------------------------------------- Table
  847:     unless ((!&Apache::loncommon::show_course()) || ($nochoose) || ($countactive==1)) {
  848: 	$r->print("<h2>".&mt('Select a Course to Enter')."</h2>\n");
  849:     }
  850:     if ($env{'form.destinationurl'}) {
  851:         $r->print('<input type="hidden" name="destinationurl" value="'.
  852:                   $env{'form.destinationurl'}.'" />');
  853:         if ($env{'form.destsymb'} ne '') {
  854:             $r->print('<input type="hidden" name="destsymb" value="'.
  855:                       $env{'form.destsymb'}.'" />');
  856:         }
  857:     }
  858:     my $doheaders = &roletable_headers($r,\%roleclass,\%sortrole,$nochoose);
  859:     if ($env{'environment.recentroles'}) {
  860:         my %recent_roles =
  861:                &Apache::lonhtmlcommon::get_recent('roles',$env{'environment.recentrolesn'});
  862: 	my $output='';
  863: 	foreach (sort(keys(%recent_roles))) {
  864: 	    if (ref($roletext{'user.role.'.$_}) eq 'ARRAY') {
  865: 		$output.= &Apache::loncommon::start_data_table_row().
  866:                           $roletext{'user.role.'.$_}->[0].
  867:                           &Apache::loncommon::end_data_table_row().
  868:                           &Apache::loncommon::continue_data_table_row().
  869:                           $roletext{'user.role.'.$_}->[1].
  870:                           &Apache::loncommon::end_data_table_row();
  871:                 if ($_ =~ m-dc\./($match_domain)/- 
  872: 		    && $dcroles{$1}) {
  873: 		    $output .= &adhoc_roles_row($1,'recent');
  874:                 }
  875: 	    } elsif ($numdc > 0) {
  876:                 unless ($_ =~/^error\:/) {
  877:                     $output.=&display_cc_role('user.role.'.$_);
  878:                 }
  879:             } 
  880: 	}
  881: 	if ($output) {
  882: 	    $r->print(&Apache::loncommon::start_data_table_empty_row()
  883:                      .'<td align="center" colspan="5">'
  884:                      .$recent
  885:                      .'</td>'
  886:                      .&Apache::loncommon::end_data_table_empty_row()
  887:             );
  888: 	    $r->print($output);
  889:             $doheaders ++;
  890: 	}
  891:     }
  892: 
  893:     if ($numdc > 0) {
  894:         $r->print(&coursepick_jscript());
  895:         $r->print(&Apache::loncommon::coursebrowser_javascript().
  896:                   &Apache::loncommon::authorbrowser_javascript());
  897:     }
  898:     &print_rolerows($r,$doheaders,\%roleclass,\%sortrole,\%dcroles,\%roletext);
  899:     if ($countactive > 1) {
  900:         my $tremark='';
  901:         my $tbg;
  902:         if ($env{'request.role'} eq 'cm') {
  903:             $tbg="LC_roles_selected";
  904:             $tremark=&mt('Currently selected.').' ';
  905:         } else {
  906:                 $tbg="LC_roles_is";
  907:         }
  908:         $r->print(&Apache::loncommon::start_data_table_row());
  909:         unless ($nochoose) {
  910: 	    if ($env{'request.role'} ne 'cm') {
  911: 	        $r->print('<td class="'.$tbg.'"><input type="submit" value="'.
  912: 		          &mt('Select').'" name="cm" /></td>');
  913: 	    } else {
  914: 	        $r->print('<td class="'.$tbg.'">&nbsp;</td>');
  915: 	    }
  916:         }
  917:         $r->print('<td colspan="3">'
  918:                  .&mt('No role specified')
  919:                  .'</td>'
  920:                  .'<td>'.$tremark.'&nbsp;</td>'
  921:                  .&Apache::loncommon::end_data_table_row()
  922:         );
  923:     } 
  924:     $r->print(&Apache::loncommon::end_data_table());
  925:     unless ($nochoose) {
  926: 	$r->print("</form>\n");
  927:     }
  928: # ------------------------------------------------------------ Privileges Info
  929:     if (($advanced) && (($env{'user.error.msg'}) || ($error))) {
  930: 	$r->print('<hr /><h2>'.&mt('Current Privileges').'</h2>');
  931: 	$r->print(&privileges_info());
  932:     }
  933:     $r->print(&Apache::lonnet::getannounce());
  934:     if ($advanced) {
  935:         my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&');
  936:         $r->print('<p><small><i>'
  937:                  .&mt('This LON-CAPA server is version [_1]',$r->dir_config('lonVersion'))
  938:                  .'</i><br />'
  939:                  .'<a href="/adm/logout">'.&mt('Logout').'</a>&nbsp;&nbsp;'
  940:                  .'<a href="/adm/coursecatalog?showdom='.$esc_dom.'">'
  941:                  .&mt('Course/Community Catalog')
  942:                  .'</a></small></p>');
  943:     }
  944:     $r->print(&Apache::loncommon::end_page());
  945:     return OK;
  946: }
  947: 
  948: sub gci_info_page {
  949:     return <<"END";
  950: <h2>Welcome to the Geoscience Concept Inventory WebCenter</h2>
  951: <p>
  952: Use the tabs to navigate the WebCenter and...
  953: <ul>
  954: <li>Review and comment on existing GCI questions</li>
  955: <li>Submit a GCI question of your own</li>
  956: <li>Create an online test for your students</li>
  957: </ul>
  958: </p>
  959: <p>For more information about writing and reviewing Concept Inventory questions
  960: please refer to the <a href="/res/gci/gci/internal/pdfs/GCIWorkbook.pdf">GCI Workbook</a>.
  961: 
  962: END
  963: }
  964: 
  965: sub gather_roles {
  966:     my ($then,$refresh,$now,$reinit,$nochoose,$roletext,$sortrole,$roleclass,$futureroles,$timezones) = @_;
  967:     my ($countactive,$countfuture,$inrole,$possiblerole) = (0,0,0,'');
  968:     my $advanced = $env{'user.adv'};
  969:     my $tryagain = $env{'form.tryagain'};
  970:     foreach my $envkey (sort(keys(%env))) {
  971:         my $button = 1;
  972:         my $switchserver='';
  973:         my ($role_text,$role_text_end,$sortkey);
  974:         if ($envkey=~/^user\.role\./) {
  975:             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
  976:             &Apache::lonnet::role_status($envkey,$then,$refresh,$now,\$role,\$where,
  977:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
  978:             next if (!defined($role) || $role eq '' || $role =~ /^gr/);
  979:             my $timezone = &role_timezone($where,$timezones);
  980:             $tremark='';
  981:             $tpstart='&nbsp;';
  982:             $tpend='&nbsp;';
  983:             if ($tstart) {
  984:                 $tpstart=&Apache::lonlocal::locallocaltime($tstart,$timezone);
  985:             }
  986:             if ($tend) {
  987:                 $tpend=&Apache::lonlocal::locallocaltime($tend,$timezone);
  988:             }
  989:             if ($env{'request.role'} eq $trolecode) {
  990:                 $tstatus='selected';
  991:             }
  992:             my $tbg;
  993:             if (($tstatus eq 'is')
  994:                 || ($tstatus eq 'selected')
  995:                 || ($tstatus eq 'future')
  996:                 || ($env{'form.showall'})) {
  997:                 if ($tstatus eq 'is') {
  998:                     $tbg='LC_roles_is';
  999:                     $possiblerole=$trolecode;
 1000:                     $countactive++;
 1001:                 } elsif ($tstatus eq 'future') {
 1002:                     $tbg='LC_roles_future';
 1003:                     $button=0;
 1004:                     $futureroles->{$trolecode} = $tstart.':'.$tend;
 1005:                     $countfuture ++;
 1006:                 } elsif ($tstatus eq 'expired') {
 1007:                     $tbg='LC_roles_expired';
 1008:                     $button=0;
 1009:                 } elsif ($tstatus eq 'will_not') {
 1010:                     $tbg='LC_roles_will_not';
 1011:                     $tremark.=&mt('Expired after logout.').' ';
 1012:                 } elsif ($tstatus eq 'selected') {
 1013:                     $tbg='LC_roles_selected';
 1014:                     $inrole=1;
 1015:                     $countactive++;
 1016:                     $tremark.=&mt('Currently selected.').' ';
 1017:                 }
 1018:                 my $trole;
 1019:                 if ($role =~ /^cr\//) {
 1020:                     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$role);
 1021:                     if ($tremark) { $tremark.='<br />'; }
 1022:                     $tremark.=&mt('Defined by [_1] at [_2].',$rauthor,$rdomain);
 1023:                 }
 1024:                 $trole=Apache::lonnet::plaintext($role);
 1025:                 my $ttype;
 1026:                 my $twhere;
 1027:                 my ($tdom,$trest,$tsection)=
 1028:                     split(/\//,Apache::lonnet::declutter($where));
 1029:                 # First, Co-Authorship roles
 1030:                 if (($role eq 'ca') || ($role eq 'aa')) {
 1031:                     my $home = &Apache::lonnet::homeserver($trest,$tdom);
 1032:                     my $allowed=0;
 1033:                     my @ids=&Apache::lonnet::current_machine_ids();
 1034:                     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 1035:                     if (!$allowed) {
 1036:                         $button=0;
 1037:                         $switchserver='otherserver='.$home.'&role='.$trolecode;
 1038:                     }
 1039:                     #next if ($home eq 'no_host');
 1040:                     $home = &Apache::lonnet::hostname($home);
 1041:                     $ttype='Construction Space';
 1042:                     $twhere=&mt('User').': '.$trest.'<br />'.&mt('Domain').
 1043:                         ': '.$tdom.'<br />'.
 1044:                         ' '.&mt('Server').':&nbsp;'.$home;
 1045:                     $env{'course.'.$tdom.'_'.$trest.'.description'}='ca';
 1046:                     $tremark.=&Apache::lonhtmlcommon::authorbombs('/res/'.$tdom.'/'.$trest.'/');
 1047:                     $sortkey=$role."$trest:$tdom";
 1048:                 } elsif ($role eq 'au') {
 1049:                     # Authors
 1050:                     my $home = &Apache::lonnet::homeserver
 1051:                         ($env{'user.name'},$env{'user.domain'});
 1052:                     my $allowed=0;
 1053:                     my @ids=&Apache::lonnet::current_machine_ids();
 1054:                     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 1055:                     if (!$allowed) {
 1056:                         $button=0;
 1057:                         $switchserver='otherserver='.$home.'&role='.$trolecode;
 1058:                     }
 1059:                     #next if ($home eq 'no_host');
 1060:                     $home = &Apache::lonnet::hostname($home);
 1061:                     $ttype='Construction Space';
 1062:                     $twhere=&mt('Domain').': '.$tdom.'<br />'.&mt('Server').
 1063:                         ':&nbsp;'.$home;
 1064:                     $env{'course.'.$tdom.'_'.$trest.'.description'}='ca';
 1065:                     $tremark.=&Apache::lonhtmlcommon::authorbombs('/res/'.$tdom.'/'.$env{'user.name'}.'/');
 1066:                     $sortkey=$role;
 1067:                 } elsif ($trest) {
 1068:                     my $tcourseid=$tdom.'_'.$trest;
 1069:                     $ttype = &Apache::loncommon::course_type($tcourseid);
 1070:                     $trole = &Apache::lonnet::plaintext($role,$ttype);
 1071:                     if ($env{'course.'.$tcourseid.'.description'}) {
 1072:                         $twhere=$env{'course.'.$tcourseid.'.description'};
 1073:                         $sortkey=$role."\0".$tdom."\0".$twhere."\0".$envkey;
 1074:                         unless ($twhere eq &mt('Currently not available')) {
 1075:                             $twhere.=' <span class="LC_fontsize_small">'.
 1076:         &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$trest,$tdom).
 1077:                                     '</span>';
 1078:                         }
 1079:                     } else {
 1080:                         my %newhash=&Apache::lonnet::coursedescription($tcourseid);
 1081:                         if (%newhash) {
 1082:                             $sortkey=$role."\0".$tdom."\0".$newhash{'description'}.
 1083:                                 "\0".$envkey;
 1084:                             $twhere=$newhash{'description'}.
 1085:                               ' <span class="LC_fontsize_small">'.
 1086:         &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$trest,$tdom).
 1087:                               '</span>';
 1088:                             $ttype = $newhash{'type'};
 1089:                             $trole = &Apache::lonnet::plaintext($role,$ttype);
 1090:                         } else {
 1091:                             $twhere=&mt('Currently not available');
 1092:                             $env{'course.'.$tcourseid.'.description'}=$twhere;
 1093:                             $sortkey=$role."\0".$tdom."\0".$twhere."\0".$envkey;
 1094:                             $ttype = 'Unavailable';
 1095:                         }
 1096:                     }
 1097:                     if ($tsection) {
 1098:                         $twhere.='<br />'.&mt('Section').': '.$tsection;
 1099:                     }
 1100:                     if ($role ne 'st') { $twhere.="<br />".&mt('Domain').":".$tdom; }
 1101:                 } elsif ($tdom) {
 1102:                     $ttype='Domain';
 1103:                     $twhere=$tdom;
 1104:                     $sortkey=$role.$twhere;
 1105:                 } else {
 1106:                     $ttype='System';
 1107:                     $twhere=&mt('system wide');
 1108:                     $sortkey=$role.$twhere;
 1109:                 }
 1110:                 ($role_text,$role_text_end) =
 1111:                     &build_roletext($trolecode,$tdom,$trest,$tstatus,$tryagain,
 1112:                                     $advanced,$tremark,$tbg,$trole,$twhere,$tpstart,
 1113:                                     $tpend,$nochoose,$button,$switchserver,$reinit);
 1114:                 $roletext->{$envkey}=[$role_text,$role_text_end];
 1115:                 if (!$sortkey) {$sortkey=$twhere."\0".$envkey;}
 1116:                 $sortrole->{$sortkey}=$envkey;
 1117:                 $roleclass->{$envkey}=$ttype;
 1118:             }
 1119:         }
 1120:     }
 1121:     return ($countactive,$countfuture,$inrole,$possiblerole);
 1122: }
 1123: 
 1124: sub role_timezone {
 1125:     my ($where,$timezones) = @_;
 1126:     my $timezone;
 1127:     if (ref($timezones) eq 'HASH') { 
 1128:         if ($where =~ m{^/($match_domain)/($match_courseid)}) {
 1129:             my $cdom = $1;
 1130:             my $cnum = $2;
 1131:             if ($cdom && $cnum) {
 1132:                 if (!exists($timezones->{$cdom.'_'.$cnum})) {
 1133:                     my %timehash =
 1134:                         &Apache::lonnet::get('environment',['timezone'],$cdom,$cnum);
 1135:                     if ($timehash{'timezone'} eq '') {
 1136:                         if (!exists($timezones->{$cdom})) {
 1137:                             my %domdefaults = 
 1138:                                 &Apache::lonnet::get_domain_defaults($cdom);
 1139:                             if ($domdefaults{'timezone_def'} eq '') {
 1140:                                 $timezones->{$cdom} = 'local';
 1141:                             } else {
 1142:                                 $timezones->{$cdom} = $domdefaults{'timezone_def'};
 1143:                             }
 1144:                         }
 1145:                         $timezones->{$cdom.'_'.$cnum} = $timezones->{$cdom};
 1146:                     } else {
 1147:                         $timezones->{$cdom.'_'.$cnum} = 
 1148:                             &Apache::lonlocal::gettimezone($timehash{'timezone'});
 1149:                     }
 1150:                 }
 1151:                 $timezone = $timezones->{$cdom.'_'.$cnum};
 1152:             }
 1153:         } else {
 1154:             my ($tdom) = ($where =~ m{^/($match_domain)});
 1155:             if ($tdom) {
 1156:                 if (!exists($timezones->{$tdom})) {
 1157:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($tdom);
 1158:                     if ($domdefaults{'timezone_def'} eq '') {
 1159:                         $timezones->{$tdom} = 'local';
 1160:                     } else {
 1161:                         $timezones->{$tdom} = $domdefaults{'timezone_def'};
 1162:                     }
 1163:                 }
 1164:                 $timezone = $timezones->{$tdom};
 1165:             }
 1166:         }
 1167:         if ($timezone eq 'local') {
 1168:             $timezone = undef;
 1169:         }
 1170:     }
 1171:     return $timezone;
 1172: }
 1173: 
 1174: sub roletable_headers {
 1175:     my ($r,$roleclass,$sortrole,$nochoose) = @_;
 1176:     my $doheaders;
 1177:     if ((ref($sortrole) eq 'HASH') && (ref($roleclass) eq 'HASH')) {
 1178:         $r->print('<br />'
 1179:                  .&Apache::loncommon::start_data_table()
 1180:                  .&Apache::loncommon::start_data_table_header_row()
 1181:         );
 1182:         if (!$nochoose) { $r->print('<th>&nbsp;</th>'); }
 1183:         $r->print('<th>'.&mt('User Role').'</th>'
 1184:                  .'<th>'.&mt('Extent').'</th>'
 1185:                  .'<th>'.&mt('Start').'</th>'
 1186:                  .'<th>'.&mt('End').'</th>'
 1187:                  .&Apache::loncommon::end_data_table_header_row()
 1188:         );
 1189:         $doheaders=-1;
 1190:         my @roletypes = &roletypes();
 1191:         foreach my $type (@roletypes) {
 1192:             my $haverole=0;
 1193:             foreach my $which (sort {uc($a) cmp uc($b)} (keys(%{$sortrole}))) {
 1194:                 if ($roleclass->{$sortrole->{$which}} =~ /^\Q$type\E/) {
 1195:                     $haverole=1;
 1196:                 }
 1197:             }
 1198:             if ($haverole) { $doheaders++; }
 1199:         }
 1200:     }
 1201:     return $doheaders;
 1202: }
 1203: 
 1204: sub roletypes {
 1205:     my @types = ('Domain','Construction Space','Course','Community','Unavailable','System');
 1206:     return @types; 
 1207: }
 1208: 
 1209: sub print_rolerows {
 1210:     my ($r,$doheaders,$roleclass,$sortrole,$dcroles,$roletext) = @_;
 1211:     if ((ref($roleclass) eq 'HASH') && (ref($sortrole) eq 'HASH')) {
 1212:         my @types = &roletypes();
 1213:         foreach my $type (@types) {
 1214:             my $output;
 1215:             foreach my $which (sort {uc($a) cmp uc($b)} (keys(%{$sortrole}))) {
 1216:                 if ($roleclass->{$sortrole->{$which}} =~ /^\Q$type\E/) {
 1217:                     if (ref($roletext) eq 'HASH') {
 1218:                         if (ref($roletext->{$sortrole->{$which}}) eq 'ARRAY') {
 1219:                             $output.= &Apache::loncommon::start_data_table_row().
 1220:                                       $roletext->{$sortrole->{$which}}->[0].
 1221:                                       &Apache::loncommon::end_data_table_row().
 1222:                                       &Apache::loncommon::continue_data_table_row().
 1223:                                       $roletext->{$sortrole->{$which}}->[1].
 1224:                                       &Apache::loncommon::end_data_table_row();
 1225:                         }
 1226:                         if ($sortrole->{$which} =~ m-dc\./($match_domain)/-) {
 1227:                             if (ref($dcroles) eq 'HASH') {
 1228:                                 if ($dcroles->{$1}) {
 1229:                                     $output .= &adhoc_roles_row($1,'');
 1230:                                 }
 1231:                             }
 1232:                         }
 1233:                     }
 1234:                 }
 1235:             }
 1236:             if ($output) {
 1237:                 if ($doheaders > 0) {
 1238:                     $r->print(&Apache::loncommon::start_data_table_empty_row()
 1239:                              .'<td align="center" colspan="5">'
 1240:                              .&mt($type)
 1241:                              .'</td>'
 1242:                              .&Apache::loncommon::end_data_table_empty_row()
 1243:                     );
 1244:                 }
 1245:                 $r->print($output);
 1246:             }
 1247:         }
 1248:     }
 1249: }
 1250: 
 1251: sub findcourse_advice {
 1252:     my ($r) = @_;
 1253:     my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
 1254:     my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&');
 1255:     if (&Apache::lonnet::auto_run(undef,$env{'user.domain'})) {
 1256:         $r->print(&mt('If you were expecting to see an active role listed for a particular course in the [_1] domain, it may be missing for one of the following reasons:',$domdesc).'
 1257: <ul>
 1258:  <li>'.&mt('The course has yet to be created.').'</li>
 1259:  <li>'.&mt('Automatic enrollment of registered students has not been enabled for the course.').'</li>
 1260:  <li>'.&mt('You are in a section of course for which automatic enrollment in the corresponding LON-CAPA course is not active.').'</li>
 1261:  <li>'.&mt('The start date for automated enrollment has yet to be reached.').'</li>
 1262:  <li>'.&mt('You registered for the course recently and there is a time lag between the time you register, and the time this information becomes available for the update of LON-CAPA course rosters.').'</li>
 1263:  </ul>');
 1264:     } else {
 1265:         $r->print(&mt('If you were expecting to see an active role listed for a particular course, that course may not have been created yet.').'<br />');
 1266:     }
 1267:     $r->print('<h3>'.&mt('Self-Enrollment').'</h3>'.
 1268:               '<p>'.&mt('The [_1]Course/Community Catalog[_2] provides information about all [_3] classes for which LON-CAPA courses have been created, as well as any communities in the domain.','<a href="/adm/coursecatalog?showdom='.$esc_dom.'">','</a>',$domdesc).'<br />');
 1269:     $r->print(&mt('You can search for courses and communities which permit self-enrollment, if you would like to enroll in one.').'</p>');
 1270:     &queued_selfenrollment($r);
 1271:     return;
 1272: }
 1273: 
 1274: sub requestcourse_advice {
 1275:     my ($r) = @_;
 1276:     my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
 1277:     my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&');
 1278:     my (%can_request,%request_doms);
 1279:     &Apache::lonnet::check_can_request($env{'user.domain'},\%can_request,\%request_doms);
 1280:     if (keys(%request_doms) > 0) {
 1281:         my ($types,$typename) = &Apache::loncommon::course_types();
 1282:         if ((ref($types) eq 'ARRAY') && (ref($typename) eq 'HASH')) { 
 1283:             $r->print('<h3>'.&mt('Request creation of a course or community').'</h3>'.
 1284:                       '<p>'.&mt('You have rights to request the creation of courses and/or communities in the following domain(s):').'<ul>');
 1285:             my (@reqdoms,@reqtypes);
 1286:             foreach my $type (sort(keys(%request_doms))) {
 1287:                 push(@reqtypes,$type); 
 1288:                 if (ref($request_doms{$type}) eq 'ARRAY') {
 1289:                     my $domstr = join(', ',map { &Apache::lonnet::domain($_) } sort(@{$request_doms{$type}}));
 1290:                     $r->print(
 1291:                         '<li>'
 1292:                        .&mt('[_1]'.$typename->{$type}.'[_2] in domain: [_3]',
 1293:                             '<i>',
 1294:                             '</i>',
 1295:                             '<b>'.$domstr.'</b>')
 1296:                        .'</li>'
 1297:                     );
 1298:                     foreach my $dom (@{$request_doms{$type}}) {
 1299:                         unless (grep(/^\Q$dom\E/,@reqdoms)) {
 1300:                             push(@reqdoms,$dom);
 1301:                         }
 1302:                     }
 1303:                 }
 1304:             }
 1305:             my @showtypes;
 1306:             foreach my $type (@{$types}) {
 1307:                 if (grep(/^\Q$type\E$/,@reqtypes)) {
 1308:                     push(@showtypes,$type);
 1309:                 }
 1310:             }
 1311:             my $requrl = '/adm/requestcourse';
 1312:             if (@reqdoms == 1) {
 1313:                 $requrl .= '?showdom='.$reqdoms[0];
 1314:             }
 1315:             if (@showtypes > 0) {
 1316:                 $requrl.=(($requrl=~/\?/)?'&':'?').'crstype='.$showtypes[0];
 1317:             }
 1318:             if (@reqdoms == 1 || @showtypes > 0) {
 1319:                 $requrl .= '&state=crstype&action=new';
 1320:             } 
 1321:             $r->print('</ul>'.&mt('Use the [_1]request form[_2] to submit a request for creation of a new course or community.','<a href="'.$requrl.'">','</a>').'</p>');
 1322:         }
 1323:     }
 1324:     return;
 1325: }
 1326: 
 1327: sub queued_selfenrollment {
 1328:     my ($r) = @_;
 1329:     my %selfenrollrequests = &Apache::lonnet::dump('selfenrollrequests');
 1330:     my %reqs_by_date;
 1331:     foreach my $item (keys(%selfenrollrequests)) {
 1332:         if (ref($selfenrollrequests{$item}) eq 'HASH') {
 1333:             if ($selfenrollrequests{$item}{'status'} eq 'request') {
 1334:                 if ($selfenrollrequests{$item}{'timestamp'}) {
 1335:                     push(@{$reqs_by_date{$selfenrollrequests{$item}{'timestamp'}}},$item);
 1336:                 }
 1337:             } 
 1338:         }
 1339:     }
 1340:     if (keys(%reqs_by_date)) {
 1341:         my $rolename = &Apache::lonnet::plaintext('st');
 1342:         $r->print('<b>'.&mt('Enrollment requests pending Course Coordinator approval').'</b><br />'.
 1343:                   &Apache::loncommon::start_data_table().
 1344:                   &Apache::loncommon::start_data_table_header_row().
 1345:                   '<th>'.&mt('Date requested').'</th><th>'.&mt('Course title').'</th>'.
 1346:                   '<th>'.&mt('User role').'</th><th>'.&mt('Section').'</th>'.
 1347:                  &Apache::loncommon::end_data_table_header_row());
 1348:         my @sorted = sort { $a <=> $b } (keys(%reqs_by_date));
 1349:         foreach my $item (@sorted) {
 1350:             if (ref($reqs_by_date{$item}) eq 'ARRAY') {
 1351:                 foreach my $crs (@{$reqs_by_date{$item}}) {
 1352:                     my %courseinfo = &Apache::lonnet::coursedescription($crs);
 1353:                     my $usec = $selfenrollrequests{$crs}{'section'};
 1354:                     if ($usec eq '') {
 1355:                         $usec = &mt('No section'); 
 1356:                     }
 1357:                     $r->print(&Apache::loncommon::start_data_table_row().
 1358:                              '<td>'.&Apache::lonlocal::locallocaltime($item).'</td>'.
 1359:                              '<td>'.$courseinfo{'description'}.'</td>'.
 1360:                              '<td>'.$rolename.'</td><td>'.$usec.'</td>'.
 1361:                              &Apache::loncommon::end_data_table_row());
 1362:                 }
 1363:             }
 1364:         }
 1365:         $r->print(&Apache::loncommon::end_data_table());
 1366:     }
 1367:     return;
 1368: }
 1369: 
 1370: sub privileges_info {
 1371:     my ($which) = @_;
 1372:     my $output;
 1373: 
 1374:     $which ||= $env{'request.role'};
 1375: 
 1376:     foreach my $envkey (sort(keys(%env))) {
 1377: 	next if ($envkey!~/^user\.priv\.\Q$which\E\.(.*)/);
 1378: 
 1379: 	my $where=$1;
 1380: 	my $ttype;
 1381: 	my $twhere;
 1382: 	my (undef,$tdom,$trest,$tsec)=split(m{/},$where);
 1383: 	if ($trest) {
 1384: 	    if ($env{'course.'.$tdom.'_'.$trest.'.description'} eq 'ca') {
 1385: 		$ttype='Construction Space';
 1386: 		$twhere='User: '.$trest.', Domain: '.$tdom;
 1387: 	    } else {
 1388: 		$ttype= &Apache::loncommon::course_type($tdom.'_'.$trest);
 1389: 		$twhere=$env{'course.'.$tdom.'_'.$trest.'.description'};
 1390: 		if ($tsec) {
 1391: 		    my $sec_type = 'Section';
 1392: 		    if (exists($env{"user.role.gr.$where"})) {
 1393: 			$sec_type = 'Group';
 1394: 		    }
 1395: 		    $twhere.=' ('.$sec_type.': '.$tsec.')';
 1396: 		}
 1397: 	    }
 1398: 	} elsif ($tdom) {
 1399: 	    $ttype='Domain';
 1400: 	    $twhere=$tdom;
 1401: 	} else {
 1402: 	    $ttype='System';
 1403: 	    $twhere='/';
 1404: 	}
 1405: 	$output .= "\n<h3>".&mt($ttype).': '.$twhere.'</h3>'."\n<ul>";
 1406: 	foreach my $priv (sort(split(/:/,$env{$envkey}))) {
 1407: 	    next if (!$priv);
 1408: 
 1409: 	    my ($prv,$restr)=split(/\&/,$priv);
 1410: 	    my $trestr='';
 1411: 	    if ($restr ne 'F') {
 1412: 		$trestr.=' ('.
 1413: 		    join(', ',
 1414: 			 map { &Apache::lonnet::plaintext($_) } 
 1415: 			     (split('',$restr))).') ';
 1416: 	    }
 1417: 	    $output .= "\n\t".
 1418: 		'<li>'.&Apache::lonnet::plaintext($prv).$trestr.'</li>';
 1419: 	}
 1420: 	$output .= "\n".'</ul>';
 1421:     }
 1422:     return $output;
 1423: }
 1424: 
 1425: sub build_roletext {
 1426:     my ($trolecode,$tdom,$trest,$tstatus,$tryagain,$advanced,$tremark,$tbg,$trole,$twhere,$tpstart,$tpend,$nochoose,$button,$switchserver,$reinit) = @_;
 1427:     my ($roletext,$roletext_end);
 1428:     my $is_dc=($trolecode =~ m/^dc\./);
 1429:     my $rowspan=($is_dc) ? ''
 1430:                          : ' rowspan="2" ';
 1431: 
 1432:     unless ($nochoose) {
 1433:         my $buttonname=$trolecode;
 1434:         $buttonname=~s/\W//g;
 1435:         if (!$button) {
 1436:             if ($switchserver) {
 1437:                 $roletext.='<td'.$rowspan.' class="'.$tbg.'">'
 1438:                           .'<a href="/adm/switchserver?'.$switchserver.'">'
 1439:                           .&mt('Switch Server')
 1440:                           .'</a></td>';
 1441:             } else {
 1442:                 $roletext.=('<td'.$rowspan.' class="'.$tbg.'">&nbsp;</td>');
 1443:             }
 1444:         } elsif ($tstatus eq 'is') {
 1445:             $roletext.='<td'.$rowspan.' class="'.$tbg.'">'.
 1446:                         '<input name="'.$buttonname.'" type="button" value="'.
 1447:                         &mt('Select').'" onclick="javascript:enterrole(this.form,\''.
 1448:                         $trolecode."','".$buttonname.'\');" /></td>';
 1449:         } elsif ($tryagain) {
 1450:             $roletext.=
 1451:                 '<td'.$rowspan.' class="'.$tbg.'">'.
 1452:                 '<input name="'.$buttonname.'" type="button" value="'.
 1453:                 &mt('Try Selecting Again').'" onclick="javascript:enterrole(this.form,\''.
 1454:                         $trolecode."','".$buttonname.'\');" /></td>';
 1455:         } elsif ($advanced) {
 1456:             $roletext.=
 1457:                 '<td'.$rowspan.' class="'.$tbg.'">'.
 1458:                 '<input name="'.$buttonname.'" type="button" value="'.
 1459:                 &mt('Re-Initialize').'" onclick="javascript:enterrole(this.form,\''.
 1460:                         $trolecode."','".$buttonname.'\');" /></td>';
 1461:         } elsif ($reinit) {
 1462:             $roletext.= 
 1463:                 '<td'.$rowspan.' class="'.$tbg.'">'.
 1464:                 '<input name="'.$buttonname.'" type="button" value="'.
 1465:                 &mt('Re-Select').'" onclick="javascript:enterrole(this.form,\''.
 1466:                         $trolecode."','".$buttonname.'\');" /></td>';
 1467:         } else {
 1468:             $roletext.=
 1469:                 '<td'.$rowspan.' class="'.$tbg.'">'.
 1470:                 '<input name="'.$buttonname.'" type="button" value="'.
 1471:                 &mt('Re-Select').'" onclick="javascript:enterrole(this.form,\''.
 1472:                         $trolecode."','".$buttonname.'\');" /></td>';
 1473:         }
 1474:     }
 1475:     if ($trolecode !~ m/^(dc|ca|au|aa)\./) {
 1476: 	$tremark.=&Apache::lonannounce::showday(time,1,
 1477: 			 &Apache::lonannounce::readcalendar($tdom.'_'.$trest));
 1478:     }
 1479:     $roletext.='<td>'.$trole.'</td>'
 1480:               .'<td>'.$twhere.'</td>'
 1481:               .'<td>'.$tpstart.'</td>'
 1482:               .'<td>'.$tpend.'</td>';
 1483:     if (!$is_dc) {
 1484:         $roletext_end = '<td colspan="4">'.
 1485:                         $tremark.'&nbsp;'.
 1486:                         '</td>';
 1487:     }
 1488:     return ($roletext,$roletext_end);
 1489: }
 1490: 
 1491: sub check_needs_switchserver {
 1492:     my ($possiblerole) = @_;
 1493:     my $needs_switchserver;
 1494:     my ($role,$where) = split(/\./,$possiblerole,2);
 1495:     my (undef,$tdom,$twho) = split(/\//,$where);
 1496:     my ($server_status,$home);
 1497:     if (($role eq 'ca') || ($role eq 'aa')) {
 1498:         ($server_status,$home) = &check_author_homeserver($twho,$tdom);
 1499:     } else {
 1500:         ($server_status,$home) = &check_author_homeserver($env{'user.name'},
 1501:                                                           $env{'user.domain'});
 1502:     }
 1503:     if ($server_status eq 'switchserver') {
 1504:         $needs_switchserver = 1;
 1505:     }
 1506:     return $needs_switchserver;
 1507: }
 1508: 
 1509: sub check_author_homeserver {
 1510:     my ($uname,$udom)=@_;
 1511:     if (($uname eq '') || ($udom eq '')) {
 1512:         return ('fail','');
 1513:     }
 1514:     my $home = &Apache::lonnet::homeserver($uname,$udom);
 1515:     if (&Apache::lonnet::host_domain($home) ne $udom) {
 1516:         return ('fail',$home);
 1517:     }
 1518:     my @ids=&Apache::lonnet::current_machine_ids();
 1519:     if (grep(/^\Q$home\E$/,@ids)) {
 1520:         return ('ok',$home);
 1521:     } else {
 1522:         return ('switchserver',$home);
 1523:     }
 1524: }
 1525: 
 1526: sub check_fordc {
 1527:     my ($dcroles,$then) = @_;
 1528:     my $numdc = 0;
 1529:     if ($env{'user.adv'}) {
 1530:         foreach my $envkey (sort keys %env) {
 1531:             if ($envkey=~/^user\.role\.dc\.\/($match_domain)\/$/) {
 1532:                 my $dcdom = $1;
 1533:                 my $livedc = 1;
 1534:                 my ($tstart,$tend)=split(/\./,$env{$envkey});
 1535:                 if ($tstart && $tstart>$then) { $livedc = 0; }
 1536:                 if ($tend   && $tend  <$then) { $livedc = 0; }
 1537:                 if ($livedc) {
 1538:                     $$dcroles{$dcdom} = $envkey;
 1539:                     $numdc++;
 1540:                 }
 1541:             }
 1542:         }
 1543:     }
 1544:     return $numdc;
 1545: }
 1546: 
 1547: sub adhoc_course_role {
 1548:     my ($refresh,$then) = @_;
 1549:     my ($cdom,$cnum,$crstype);
 1550:     $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1551:     $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1552:     $crstype = &Apache::loncommon::course_type();
 1553:     if (&check_forcc($cdom,$cnum,$refresh,$then,$crstype)) {
 1554:         my $setprivs;
 1555:         if (!defined($env{'user.role.'.$env{'form.switchrole'}})) {
 1556:             $setprivs = 1;
 1557:         } else {
 1558:             my ($start,$end) = split(/\./,$env{'user.role.'.$env{'form.switchrole'}});
 1559:             if (($start && ($start>$refresh || $start == -1)) ||
 1560:                 ($end && $end<$then)) {
 1561:                 $setprivs = 1;
 1562:             }
 1563:         }
 1564:         if ($setprivs) {
 1565:             if ($env{'form.switchrole'} =~ m-^(in|ta|ep|ad|st|cr)([\w/]*)\./\Q$cdom\E/\Q$cnum\E/?(\w*)$-) {
 1566:                 my $role = $1;
 1567:                 my $custom_role = $2;
 1568:                 my $usec = $3;
 1569:                 if ($role eq 'cr') {
 1570:                     if ($custom_role =~ m-^/$match_domain/$match_username/\w+$-) {
 1571:                         $role .= $custom_role;
 1572:                     } else {
 1573:                         return;
 1574:                     }
 1575:                 }
 1576:                 my (%userroles,%newrole,%newgroups,%group_privs);
 1577:                 my %cgroups =
 1578:                     &Apache::lonnet::get_active_groups($env{'user.domain'},
 1579:                                             $env{'user.name'},$cdom,$cnum);
 1580:                 foreach my $group (keys(%cgroups)) {
 1581:                     $group_privs{$group} =
 1582:                         $env{'user.priv.cc./'.$cdom.'/'.$cnum.'./'.$cdom.'/'.$cnum.'/'.$group};
 1583:                 }
 1584:                 $newgroups{'/'.$cdom.'/'.$cnum} = \%group_privs;
 1585:                 my $area = '/'.$cdom.'/'.$cnum;
 1586:                 my $spec = $role.'.'.$area;
 1587:                 if ($usec ne '') {
 1588:                     $spec .= '/'.$usec;
 1589:                     $area .= '/'.$usec;
 1590:                 }
 1591:                 &Apache::lonnet::standard_roleprivs(\%newrole,$role,$cdom,$spec,$cnum,$area);
 1592:                 &Apache::lonnet::set_userprivs(\%userroles,\%newrole,\%newgroups);
 1593:                 my $adhocstart = $refresh-1;
 1594:                 $userroles{'user.role.'.$spec} = $adhocstart.'.';
 1595:                 &Apache::lonnet::appenv(\%userroles,[$role,'cm']);
 1596:             }
 1597:         }
 1598:     }
 1599:     return;
 1600: }
 1601: 
 1602: sub check_forcc {
 1603:     my ($cdom,$cnum,$refresh,$then,$crstype) = @_;
 1604:     my ($is_cc,$ccrole);
 1605:     if ($crstype eq 'Community') {
 1606:         $ccrole = 'co';
 1607:     } else {
 1608:         $ccrole = 'cc';
 1609:     }
 1610:     if ($cdom ne '' && $cnum ne '') {
 1611:         if (&Apache::lonnet::is_course($cdom,$cnum)) {
 1612:             my $envkey = 'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum;
 1613:             if (defined($env{$envkey})) {
 1614:                 $is_cc = 1;
 1615:                 my ($tstart,$tend)=split(/\./,$env{$envkey});
 1616:                 if ($tstart && $tstart>$refresh) { $is_cc = 0; }
 1617:                 if ($tend   && $tend  <$then) { $is_cc = 0; }
 1618:             }
 1619:         }
 1620:     }
 1621:     return $is_cc;
 1622: }
 1623: 
 1624: sub courselink {
 1625:     my ($dcdom,$rowtype) = @_;
 1626:     my $courseform=&Apache::loncommon::selectcourse_link
 1627:                    ('rolechoice','dccourse'.$rowtype.'_'.$dcdom,
 1628:                     'dcdomain'.$rowtype.'_'.$dcdom,'coursedesc'.$rowtype.'_'.
 1629:                     $dcdom,$dcdom,undef,'Course/Community');
 1630:     my $hiddenitems = '<input type="hidden" name="dcdomain'.$rowtype.'_'.$dcdom.'" value="'.$dcdom.'" />'.
 1631:                       '<input type="hidden" name="origdom'.$rowtype.'_'.$dcdom.'" value="'.$dcdom.'" />'.
 1632:                       '<input type="hidden" name="dccourse'.$rowtype.'_'.$dcdom.'" value="" />'.
 1633:                       '<input type="hidden" name="coursedesc'.$rowtype.'_'.$dcdom.'" value="" />';
 1634:     return $courseform.$hiddenitems;
 1635: }
 1636: 
 1637: sub coursepick_jscript {
 1638:     my %lt = &Apache::lonlocal::texthash(
 1639:                   plsu => "Please use the 'Select Course/Community' link to open a separate pick course window where you may select the course or community you wish to enter.",
 1640:                   youc => 'You can only use this screen to select courses and communities in the current domain.',
 1641:              );
 1642:     my $verify_script = <<"END";
 1643: <script type="text/javascript">
 1644: // <![CDATA[
 1645: function verifyCoursePick(caller) {
 1646:     var numbutton = getIndex(caller)
 1647:     var pickedCourse = document.rolechoice.elements[numbutton+4].value
 1648:     var pickedDomain = document.rolechoice.elements[numbutton+2].value
 1649:     if (document.rolechoice.elements[numbutton+2].value == document.rolechoice.elements[numbutton+3].value) {
 1650:         if (pickedCourse != '') {
 1651:             if (numbutton != -1) {
 1652:                 var courseTarget = "cc./"+pickedDomain+"/"+pickedCourse
 1653:                 document.rolechoice.elements[numbutton+1].name = courseTarget
 1654:                 document.rolechoice.submit()
 1655:             }
 1656:         }
 1657:         else {
 1658:             alert("$lt{'plsu'}");
 1659:         }
 1660:     }
 1661:     else {
 1662:         alert("$lt{'youc'}")
 1663:     }
 1664: }
 1665: function getIndex(caller) {
 1666:     for (var i=0;i<document.rolechoice.elements.length;i++) {
 1667:         if (document.rolechoice.elements[i] == caller) {
 1668:             return i;
 1669:         }
 1670:     }
 1671:     return -1;
 1672: }
 1673: // ]]>
 1674: </script>
 1675: END
 1676:     return $verify_script;
 1677: }
 1678: 
 1679: sub coauthorlink {
 1680:     my ($dcdom,$rowtype) = @_;
 1681:     my $coauthorform=&Apache::loncommon::selectauthor_link('rolechoice',$dcdom);
 1682:     my $hiddenitems = '<input type="hidden" name="adhoccauname'.$rowtype.'_'.$dcdom.'" value="" />';
 1683:     return $coauthorform.$hiddenitems;
 1684: }
 1685: 
 1686: sub display_cc_role {
 1687:     my $rolekey = shift;
 1688:     my ($roletext,$roletext_end);
 1689:     my $advanced = $env{'user.adv'};
 1690:     my $tryagain = $env{'form.tryagain'};
 1691:     unless ($rolekey =~/^error\:/) {
 1692:         if ($rolekey =~ m{^user\.role\.(cc|co)\./($match_domain)/($match_courseid)$}) {
 1693:             my $ccrole = $1;
 1694:             my $tcourseid = $2.'_'.$3;
 1695:             my $trolecode = $1.'./'.$2.'/'.$3;
 1696:             my $twhere;
 1697:             my $ttype;
 1698:             my $tbg='LC_roles_is';
 1699:             my %newhash=&Apache::lonnet::coursedescription($tcourseid);
 1700:             if (%newhash) {
 1701:                 $twhere=$newhash{'description'}.
 1702:                         ' <span style="LC_fontsize_small">'.
 1703:                         &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$2,$1).
 1704:                         '</span>';
 1705:                 $ttype = $newhash{'type'};
 1706:             } else {
 1707:                 $twhere=&mt('Currently not available');
 1708:                 $env{'course.'.$tcourseid.'.description'}=$twhere;
 1709:             }
 1710:             my $trole = &Apache::lonnet::plaintext($ccrole,$ttype);
 1711:             $twhere.="<br />".&mt('Domain').":".$1;
 1712:             ($roletext,$roletext_end) = &build_roletext($trolecode,$1,$2,'is',$tryagain,$advanced,'',$tbg,$trole,$twhere,'','','',1,'');
 1713:         }
 1714:     }
 1715:     return ($roletext,$roletext_end);
 1716: }
 1717: 
 1718: sub adhoc_roles_row {
 1719:     my ($dcdom,$rowtype) = @_;
 1720:     my $output = &Apache::loncommon::continue_data_table_row()
 1721:                  .' <td colspan="5">'
 1722:                  .&mt('[_1]Ad hoc[_2] roles in domain [_3] --'
 1723:                      ,'<span class="LC_cusr_emph">','</span>',$dcdom)
 1724:                  .' ';
 1725:     my $selectcclink = &courselink($dcdom,$rowtype);
 1726:     my $ccrole = &Apache::lonnet::plaintext('co',undef,undef,1);
 1727:     my $carole = &Apache::lonnet::plaintext('ca');
 1728:     my $selectcalink = &coauthorlink($dcdom,$rowtype);
 1729:     $output.=$ccrole.': '.$selectcclink
 1730:             .' | '.$carole.': '.$selectcalink
 1731:             .&Apache::loncommon::end_data_table_row();
 1732:     return $output;
 1733: }
 1734: 
 1735: sub recent_filename {
 1736:     my $area=shift;
 1737:     return 'nohist_recent_'.&escape($area);
 1738: }
 1739: 
 1740: sub courseloadpage {
 1741:     my ($courseid) = @_;
 1742:     my $startpage;
 1743:     my %entry_settings = &Apache::lonnet::get('nohist_whatsnew',
 1744: 					      [$courseid.':courseinit']);
 1745:     my ($tmp) = %entry_settings;
 1746:     unless ($tmp =~ /^error: 2 /) {
 1747:         $startpage = $entry_settings{$courseid.':courseinit'};
 1748:     }
 1749:     if ($startpage eq '') {
 1750:         if (exists($env{'environment.course_init_display'})) {
 1751:             $startpage = $env{'environment.course_init_display'};
 1752:         }
 1753:     }
 1754:     return $startpage;
 1755: }
 1756: 
 1757: 1;
 1758: __END__
 1759: 
 1760: =head1 NAME
 1761: 
 1762: Apache::lonroles - User Roles Screen
 1763: 
 1764: =head1 SYNOPSIS
 1765: 
 1766: Invoked by /etc/httpd/conf/srm.conf:
 1767: 
 1768:  <Location /adm/roles>
 1769:  PerlAccessHandler       Apache::lonacc
 1770:  SetHandler perl-script
 1771:  PerlHandler Apache::lonroles
 1772:  ErrorDocument     403 /adm/login
 1773:  ErrorDocument	  500 /adm/errorhandler
 1774:  </Location>
 1775: 
 1776: =head1 OVERVIEW
 1777: 
 1778: =head2 Choosing Roles
 1779: 
 1780: C<lonroles> is a handler that allows a user to switch roles in
 1781: mid-session. LON-CAPA attempts to work with "No Role Specified", the
 1782: default role that a user has before selecting a role, as widely as
 1783: possible, but certain handlers for example need specification which
 1784: course they should act on, etc. Both in this scenario, and when the
 1785: handler determines via C<lonnet>'s C<&allowed> function that a certain
 1786: action is not allowed, C<lonroles> is used as error handler. This
 1787: allows the user to select another role which may have permission to do
 1788: what they were trying to do. C<lonroles> can also be accessed via the
 1789: B<CRS> button in the Remote Control. 
 1790: 
 1791: =begin latex
 1792: 
 1793: \begin{figure}
 1794: \begin{center}
 1795: \includegraphics[width=0.45\paperwidth,keepaspectratio]{Sample_Roles_Screen}
 1796:   \caption{\label{Sample_Roles_Screen}Sample Roles Screen} 
 1797: \end{center}
 1798: \end{figure}
 1799: 
 1800: =end latex
 1801: 
 1802: =head2 Role Initialization
 1803: 
 1804: The privileges for a user are established at login time and stored in the session environment. As a consequence, a new role does not become active till the next login. Handlers are able to query for privileges using C<lonnet>'s C<&allowed> function. When a user first logs in, their role is the "common" role, which means that they have the sum of all of their privileges. During a session it might become necessary to choose a particular role, which as a consequence also limits the user to only the privileges in that particular role.
 1805: 
 1806: =head1 INTRODUCTION
 1807: 
 1808: This module enables a user to select what role he wishes to
 1809: operate under (instructor, student, teaching assistant, course
 1810: coordinator, etc).  These roles are pre-established by the actions
 1811: of upper-level users.
 1812: 
 1813: This is part of the LearningOnline Network with CAPA project
 1814: described at http://www.lon-capa.org.
 1815: 
 1816: =head1 HANDLER SUBROUTINE
 1817: 
 1818: This routine is called by Apache and mod_perl.
 1819: 
 1820: =over 4
 1821: 
 1822: =item *
 1823: 
 1824: Roles Initialization (yes/no)
 1825: 
 1826: =item *
 1827: 
 1828: Get Error Message from Environment
 1829: 
 1830: =item *
 1831: 
 1832: Who is this?
 1833: 
 1834: =item *
 1835: 
 1836: Generate Page Output
 1837: 
 1838: =item *
 1839: 
 1840: Choice or no choice
 1841: 
 1842: =item *
 1843: 
 1844: Table
 1845: 
 1846: =item *
 1847: 
 1848: Privileges
 1849: 
 1850: =back
 1851: 
 1852: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>