File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.269.2.28: download - view: text, annotated - select for diffs
Thu Oct 27 22:53:48 2016 UTC (7 years, 8 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.319, 1.320

    1: # The LearningOnline Network with CAPA
    2: # User Roles Screen
    3: #
    4: # $Id: lonroles.pm,v 1.269.2.28 2016/10/27 22:53:48 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.
   61: 
   62: =begin latex
   63: 
   64: \begin{figure}
   65: \begin{center}
   66: \includegraphics[width=0.45\paperwidth,keepaspectratio]{Sample_Roles_Screen}
   67:   \caption{\label{Sample_Roles_Screen}Sample Roles Screen} 
   68: \end{center}
   69: \end{figure}
   70: 
   71: =end latex
   72: 
   73: =head2 Role Initialization
   74: 
   75: 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.
   76: 
   77: =head1 INTRODUCTION
   78: 
   79: This module enables a user to select what role he wishes to
   80: operate under (instructor, student, teaching assistant, course
   81: coordinator, etc).  These roles are pre-established by the actions
   82: of upper-level users.
   83: 
   84: This is part of the LearningOnline Network with CAPA project
   85: described at http://www.lon-capa.org.
   86: 
   87: =head1 HANDLER SUBROUTINE
   88: 
   89: This routine is called by Apache and mod_perl.
   90: 
   91: =over 4
   92: 
   93: =item *
   94: 
   95: Roles Initialization (yes/no)
   96: 
   97: =item *
   98: 
   99: Get Error Message from Environment
  100: 
  101: =item *
  102: 
  103: Who is this?
  104: 
  105: =item *
  106: 
  107: Generate Page Output
  108: 
  109: =item *
  110: 
  111: Choice or no choice
  112: 
  113: =item *
  114: 
  115: Table
  116: 
  117: =item *
  118: 
  119: Privileges
  120: 
  121: =back
  122: 
  123: =cut
  124: 
  125: 
  126: package Apache::lonroles;
  127: 
  128: use strict;
  129: use Apache::lonnet;
  130: use Apache::lonuserstate();
  131: use Apache::Constants qw(:common REDIRECT);
  132: use Apache::File();
  133: use Apache::lonmenu;
  134: use Apache::loncommon;
  135: use Apache::lonhtmlcommon;
  136: use Apache::lonannounce;
  137: use Apache::lonlocal;
  138: use Apache::lonpageflip();
  139: use Apache::lonnavdisplay();
  140: use Apache::loncoursequeueadmin;
  141: use Apache::longroup;
  142: use Apache::lonrss;
  143: use GDBM_File;
  144: use LONCAPA qw(:DEFAULT :match);
  145: use HTML::Entities;
  146:  
  147: 
  148: sub redirect_user {
  149:     my ($r,$title,$url,$msg) = @_;
  150:     $msg = $title if (! defined($msg));
  151:     &Apache::loncommon::content_type($r,'text/html');
  152:     &Apache::loncommon::no_cache($r);
  153:     $r->send_http_header;
  154:     my $swinfo=&Apache::lonmenu::rawconfig();
  155: 
  156:     # Breadcrumbs
  157:     my $brcrum = [{'href' => $url,
  158:                    'text' => 'Switching Role'},];
  159:     my $start_page = &Apache::loncommon::start_page('Switching Role',undef,
  160:                                                     {'redirect' => [1,$url],
  161:                                                      'bread_crumbs' => $brcrum,});
  162:     my $end_page   = &Apache::loncommon::end_page();
  163: 
  164: # Note to style police: 
  165: # This must only replace the spaces, nothing else, or it bombs elsewhere.
  166:     $url=~s/ /\%20/g;
  167:     $r->print(<<ENDREDIR);
  168: $start_page
  169: <script type="text/javascript">
  170: // <![CDATA[
  171: $swinfo
  172: // ]]>
  173: </script>
  174: <p>$msg</p>
  175: $end_page
  176: ENDREDIR
  177:     return;
  178: }
  179: 
  180: sub error_page {
  181:     my ($r,$error,$dest)=@_;
  182:     &Apache::loncommon::content_type($r,'text/html');
  183:     &Apache::loncommon::no_cache($r);
  184:     $r->send_http_header;
  185:     return OK if $r->header_only;
  186:     # Breadcrumbs
  187:     my $brcrum = [{'href' => $dest,
  188:                    'text' => 'Problems during Course Initialization'},];
  189:     $r->print(&Apache::loncommon::start_page('Problems during Course Initialization',
  190:                                              undef,
  191:                                              {'bread_crumbs' => $brcrum,})
  192:     );
  193:     $r->print(
  194:         '<script type="text/javascript">'.
  195:         '// <![CDATA['.
  196:         &Apache::lonmenu::rawconfig().
  197:         '// ]]>'.
  198:         '</script>'.
  199: 	      '<p class="LC_error">'.&mt('The following problems occurred:').
  200:           '<br />'.
  201: 	      $error.
  202: 	      '</p><br /><a href="'.$dest.'">'.&mt('Continue').'</a>'
  203:     );
  204:     $r->print(&Apache::loncommon::end_page());
  205: }
  206: 
  207: sub handler {
  208: 
  209:     my $r = shift;
  210: 
  211:     # Check for critical messages and redirect if present.
  212:     my ($redirect,$url) = &Apache::loncommon::critical_redirect(300);
  213:     if ($redirect) {
  214:         &Apache::loncommon::content_type($r,'text/html');
  215:         $r->header_out(Location => $url);
  216:         return REDIRECT;
  217:     }
  218: 
  219:     my $now=time;
  220:     my $then=$env{'user.login.time'};
  221:     my $refresh=$env{'user.refresh.time'};
  222:     my $update=$env{'user.update.time'};
  223:     if (!$refresh) {
  224:         $refresh = $then;
  225:     }
  226:     if (!$update) {
  227:         $update = $then;
  228:     }
  229: 
  230:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
  231: 
  232: # -------------------------------------------------- Check if setting hot list
  233:     my $hotlist;
  234:     if ($env{'form.action'} eq 'verify_and_change_rolespref') {
  235:         $hotlist = &Apache::lonpreferences::verify_and_change_rolespref($r);
  236:     }
  237: 
  238: # -------------------------------------------------------- Check for new roles
  239:     my $updateresult;
  240:     if ($env{'form.state'} eq 'doupdate') {
  241:         my $show_course=&Apache::loncommon::show_course();
  242:         my $checkingtxt;
  243:         if ($show_course) {
  244:             $checkingtxt = &mt('Checking for new courses ...');
  245:         } else {
  246:             $checkingtxt = &mt('Checking for new roles ...');
  247:         }
  248:         $updateresult = $checkingtxt;
  249:         $updateresult .= &update_session_roles();
  250:         &Apache::lonnet::appenv({'user.update.time'  => $now});
  251:         $update = $now;
  252:         &Apache::loncoursequeueadmin::reqauthor_check();
  253:     }
  254: 
  255: # -------------------------------------------------- Check for author requests
  256:     my $reqauthor;
  257:     if ($env{'form.state'} eq 'requestauthor') {
  258:        $reqauthor = &Apache::loncoursequeueadmin::process_reqauthor(\$update);
  259:     }
  260: 
  261:     my $envkey;
  262:     my %dcroles = ();
  263:     my %dhroles = ();
  264:     my ($numdc,$numdh,$numadhoc) = &check_for_adhoc(\%dcroles,\%dhroles,$update,$then);
  265:     my $loncaparev = $r->dir_config('lonVersion');
  266: 
  267: # ================================================================== Roles Init
  268:     if ($env{'form.selectrole'}) {
  269: 
  270:         my $locknum=&Apache::lonnet::get_locks();
  271:         if ($locknum) { return 409; }
  272: 
  273:         my $custom_adhoc;
  274:         if ($env{'form.newrole'}) {
  275:             $env{'form.'.$env{'form.newrole'}}=1;
  276: # Check if this is a Domain Helpdesk role trying to enter a course
  277:             if ($env{'form.newrole'} =~ m{^cr/($match_domain)/\1\-domainconfig/\w+\./\1/$match_courseid$}) {
  278:                 if ($dhroles{$1}) {
  279:                     $custom_adhoc = 1;
  280:                 }
  281:             }
  282: 	}
  283: 	if ($env{'request.course.id'}) {
  284:             # Check if user is CC trying to select a course role
  285:             if ($env{'form.switchrole'}) {
  286:                 my $switch_is_active;
  287:                 if (defined($env{'user.role.'.$env{'form.switchrole'}})) {
  288:                     my ($start,$end) = split(/\./,$env{'user.role.'.$env{'form.switchrole'}});
  289:                     if (!$end || $end > $now) {
  290:                         if (!$start || $start < $update) {
  291:                             $switch_is_active = 1;
  292:                         }
  293:                     }
  294:                 }
  295:                 unless ($switch_is_active) {
  296:                     &adhoc_course_role($refresh,$update,$then);
  297:                 }
  298:             }
  299: 	    my %temp=('logout_'.$env{'request.course.id'} => time);
  300: 	    &Apache::lonnet::put('email_status',\%temp);
  301: 	    &Apache::lonnet::delenv('user.state.'.$env{'request.course.id'});
  302: 	}
  303: 	&Apache::lonnet::appenv({"request.course.id"           => '',
  304: 			 	 "request.course.fn"           => '',
  305: 				 "request.course.uri"          => '',
  306: 				 "request.course.sec"          => '',
  307:                                  "request.course.tied"         => '',
  308:                                  "request.course.timechecked"  => '',
  309: 				 "request.role"                => 'cm',
  310:                                  "request.role.adv"            => $env{'user.adv'},
  311: 				 "request.role.domain"         => $env{'user.domain'}});
  312: # Check if Domain Helpdesk role trying to enter a course needs privs to be created
  313:         if ($env{'form.newrole'} =~ m{^cr/($match_domain)/\1\-domainconfig/(\w+)\./\1/($match_courseid)$}) {
  314:             my $cdom = $1;
  315:             my $rolename = $2;
  316:             my $cnum = $3;
  317:             if ($custom_adhoc) {
  318:                 my %adhocroles = &Apache::lonnet::userenvironment($env{'user.domain'},$env{'user.name'},
  319:                                                                   'adhocroles.'.$cdom);
  320:                 if (keys(%adhocroles)) {
  321:                     my @adhoc = split(',',$adhocroles{'adhocroles.'.$cdom});
  322:                     if (grep(/^\Q$rolename\E$/,@adhoc)) {
  323:                         if (&Apache::lonnet::check_adhoc_privs($cdom,$cnum,$update,$refresh,$now,
  324:                                                                "cr/$cdom/$cdom".'-domainconfig/'.$rolename)) {
  325:                             &Apache::lonnet::appenv({"environment.internal.$cdom.$cnum.cr/$cdom/$cdom".'-domainconfig/'."$rolename.adhoc" => time});
  326:                         }
  327:                     }
  328:                 }
  329:             }
  330:         } elsif (($numdc > 0) || ($numdh > 0)) {
  331: # Check if user is a DC trying to enter a course or author space and needs privs to be created
  332: # Check if user is a DH trying to enter a course and needs privs to be created
  333:             foreach my $envkey (keys(%env)) {
  334:                 if ($numdc) {
  335: # Is this an ad-hoc Coordinator role?
  336:                     if (my ($ccrole,$domain,$coursenum) =
  337: 		        ($envkey =~ m-^form\.(cc|co)\./($match_domain)/($match_courseid)$-)) {
  338:                         if ($dcroles{$domain}) {
  339:                             if (&Apache::lonnet::check_adhoc_privs($domain,$coursenum,
  340:                                                                    $update,$refresh,$now,$ccrole)) {
  341:                                 &Apache::lonnet::appenv({"environment.internal.$domain.$coursenum.$ccrole.adhoc" => time});
  342:                             }
  343:                         }
  344:                         last;
  345:                     }
  346: # Is this an ad-hoc CA-role?
  347:                     if (my ($domain,$user) =
  348: 		        ($envkey =~ m-^form\.ca\./($match_domain)/($match_username)$-)) {
  349:                         if (($domain eq $env{'user.domain'}) && ($user eq $env{'user.name'})) {
  350:                             delete($env{$envkey});
  351:                             $env{'form.au./'.$domain.'/'} = 1;
  352:                             my ($server_status,$home) = &check_author_homeserver($user,$domain);
  353:                             if ($server_status eq 'switchserver') {
  354:                                 my $trolecode = 'au./'.$domain.'/';
  355:                                 my $switchserver = '/adm/switchserver?otherserver='.$home.'&amp;role='.$trolecode;
  356:                                 $r->internal_redirect($switchserver);
  357:                                 return OK;
  358:                             }
  359:                             last;
  360:                         }
  361:                         if (my ($castart,$caend) = ($env{'user.role.ca./'.$domain.'/'.$user} =~ /^(\d*)\.(\d*)$/)) {
  362:                             if (((($castart) && ($castart < $now)) || !$castart) && 
  363:                                 ((!$caend) || (($caend) && ($caend > $now)))) {
  364:                                 my ($server_status,$home) = &check_author_homeserver($user,$domain);
  365:                                 if ($server_status eq 'switchserver') {
  366:                                     my $trolecode = 'ca./'.$domain.'/'.$user;
  367:                                     my $switchserver = '/adm/switchserver?otherserver='.$home.'&amp;role='.$trolecode;
  368:                                     $r->internal_redirect($switchserver);
  369:                                     return OK;
  370:                                 }
  371:                                 last;
  372:                             }
  373:                         }
  374:                         # Check if author blocked ca-access
  375:                         my %blocked=&Apache::lonnet::get('environment',['domcoord.author'],$domain,$user);
  376:                         if ($blocked{'domcoord.author'} eq 'blocked') {
  377:                             delete($env{$envkey});
  378:                             $env{'user.error.msg'}=':::1:User '.$user.' in domain '.$domain.' blocked domain coordinator access';
  379:                             last;
  380:                         }
  381:                         if ($dcroles{$domain}) {
  382:                             my ($server_status,$home) = &check_author_homeserver($user,$domain);
  383:                             if (($server_status eq 'ok') || ($server_status eq 'switchserver')) {
  384:                                 &Apache::lonnet::check_adhoc_privs($domain,$user,$update,
  385:                                                                    $refresh,$now,'ca');
  386:                                 if ($server_status eq 'switchserver') {
  387:                                     my $trolecode = 'ca./'.$domain.'/'.$user; 
  388:                                     my $switchserver = '/adm/switchserver?'
  389:                                                       .'otherserver='.$home.'&amp;role='.$trolecode;
  390:                                     $r->internal_redirect($switchserver);
  391:                                     return OK;
  392:                                 }
  393:                             } else {
  394:                                 delete($env{$envkey});
  395:                             }
  396:                         } else {
  397:                             delete($env{$envkey});
  398:                         }
  399:                         last;
  400:                     }
  401:                 }
  402:                 if ($numdh) {
  403: # Is this an ad hoc custom role in a course/community?
  404:                     if (my ($domain,$rolename,$coursenum) = ($envkey =~ m{^form\.cr/($match_domain)/\1\-domainconfig/(\w+)\./\1/($match_courseid)$})) {
  405:                         if ($dhroles{$domain}) {
  406:                             my @adhoc;
  407:                             if ($env{'environment.adhocroles.'.$domain}) {
  408:                                 @adhoc = split(',',$env{'environment.adhocroles.'.$domain});
  409:                             } else {
  410:                                 my %adhocroles = &Apache::lonnet::userenvironment($env{'user.domain'},$env{'user.name'},
  411:                                                                                   'adhocroles.'.$domain);
  412:                                 if (keys(%adhocroles)) {
  413:                                     @adhoc = split(',',$adhocroles{'adhocroles.'.$domain});
  414:                                 }
  415:                             }
  416:                             if ((@adhoc > 0) && ($rolename ne '')) {
  417:                                 if (grep(/^\Q$rolename\E$/,@adhoc)) {
  418:                                     if (&Apache::lonnet::check_adhoc_privs($domain,$coursenum,$update,$refresh,$now,
  419:                                                                            "cr/$domain/$domain".'-domainconfig/'.$rolename)) {
  420:                                         &Apache::lonnet::appenv({"environment.internal.$domain.$coursenum.cr/$domain/$domain".
  421:                                                                  '-domainconfig/'."$rolename.adhoc" => time});
  422:                                     }
  423:                                 } else {
  424:                                     delete($env{$envkey});
  425:                                 }
  426:                             } else {
  427:                                 delete($env{$envkey});
  428:                             }
  429:                         } else {
  430:                             delete($env{$envkey});
  431:                         }
  432:                         last;
  433:                     }
  434:                 } 
  435:             }
  436:         }
  437: 
  438:         foreach $envkey (keys(%env)) {
  439:             next if ($envkey!~/^user\.role\./);
  440:             my ($where,$trolecode,$role,$tstatus,$tend,$tstart);
  441:             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
  442:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
  443:             if ($env{'form.'.$trolecode}) {
  444: 		if ($tstatus eq 'is') {
  445: 		    $where=~s/^\///;
  446: 		    my ($cdom,$cnum,$csec)=split(/\//,$where);
  447:                     if (($cnum) && ($role ne 'ca') && ($role ne 'aa')) {
  448:                         my $home = $env{'course.'.$cdom.'_'.$cnum.'.home'};
  449:                         my @ids = &Apache::lonnet::current_machine_ids();
  450:                         unless ($loncaparev eq '' && $home && grep(/^\Q$home\E$/,@ids)) {
  451:                             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
  452:                             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
  453:                                 my ($switchserver,$switchwarning) =
  454:                                     &Apache::loncommon::check_release_required($loncaparev,$cdom.'_'.$cnum,$trolecode,
  455:                                                                                $curr_reqd_hash{'internal.releaserequired'});
  456:                                 if ($switchwarning ne '' || $switchserver ne '') {
  457:                                     &Apache::loncommon::content_type($r,'text/html');
  458:                                     &Apache::loncommon::no_cache($r);
  459:                                     $r->send_http_header;
  460:                                     $r->print(&Apache::loncommon::check_release_result($switchwarning,$switchserver));
  461:                                     return OK;
  462:                                 }
  463:                             }
  464:                         }
  465:                     }
  466: # check for course groups
  467:                     my %coursegroups = &Apache::lonnet::get_active_groups(
  468:                           $env{'user.domain'},$env{'user.name'},$cdom, $cnum);
  469:                     my $cgrps = join(':',keys(%coursegroups));
  470: 
  471: # store role if recent_role list being kept
  472:                     if ($env{'environment.recentroles'}) {
  473:                         my %frozen_roles =
  474:                            &Apache::lonhtmlcommon::get_recent_frozen('roles',$env{'environment.recentrolesn'});
  475: 			&Apache::lonhtmlcommon::store_recent('roles',
  476: 							     $trolecode,' ',$frozen_roles{$trolecode});
  477:                     }
  478: 
  479: 
  480: # check for keyed access
  481: 		    if (($role eq 'st') && 
  482:                        ($env{'course.'.$cdom.'_'.$cnum.'.keyaccess'} eq 'yes')) {
  483: # who is key authority?
  484: 			my $authdom=$cdom;
  485: 			my $authnum=$cnum;
  486: 			if ($env{'course.'.$cdom.'_'.$cnum.'.keyauth'}) {
  487: 			    ($authnum,$authdom)=
  488: 				split(/:/,$env{'course.'.$cdom.'_'.$cnum.'.keyauth'});
  489: 			}
  490: # check with key authority
  491: 			unless (&Apache::lonnet::validate_access_key(
  492: 				     $env{'environment.key.'.$cdom.'_'.$cnum},
  493: 					     $authdom,$authnum)) {
  494: # there is no valid key
  495: 			     if ($env{'form.newkey'}) {
  496: # student attempts to register a new key
  497: 				 &Apache::loncommon::content_type($r,'text/html');
  498: 				 &Apache::loncommon::no_cache($r);
  499: 				 $r->send_http_header;
  500: 				 my $swinfo=&Apache::lonmenu::rawconfig();
  501: 				 my $start_page=&Apache::loncommon::start_page
  502: 				    ('Verifying Access Key to Unlock this Course');
  503: 				 my $end_page=&Apache::loncommon::end_page();
  504: 				 my $buttontext=&mt('Enter Course');
  505: 				 my $message=&mt('Successfully registered key');
  506: 				 my $assignresult=
  507: 				     &Apache::lonnet::assign_access_key(
  508: 						     $env{'form.newkey'},
  509: 						     $authdom,$authnum,
  510: 						     $cdom,$cnum,
  511:                                                      $env{'user.domain'},
  512: 						     $env{'user.name'},
  513:                                                      &mt('Assigned from [_1] at [_2] for [_3]'
  514:                                                         ,$ENV{'REMOTE_ADDR'}
  515:                                                         ,&Apache::lonlocal::locallocaltime()
  516:                                                         ,$trolecode)
  517:                                                      );
  518: 				 unless ($assignresult eq 'ok') {
  519: 				     $assignresult=~s/^error\:\s*//;
  520: 				     $message=&mt($assignresult).
  521: 				     '<br /><a href="/adm/logout">'.
  522: 				     &mt('Logout').'</a>';
  523: 				     $buttontext=&mt('Re-Enter Key');
  524: 				 }
  525: 				 $r->print(<<ENDENTEREDKEY);
  526: $start_page
  527: <script type="text/javascript">
  528: // <![CDATA[
  529: $swinfo
  530: // ]]>
  531: </script>
  532: <form action="" method="post">
  533: <input type="hidden" name="selectrole" value="1" />
  534: <input type="hidden" name="$trolecode" value="1" />
  535: <span class="LC_fontsize_large">$message</span><br />
  536: <input type="submit" value="$buttontext" />
  537: </form>
  538: $end_page
  539: ENDENTEREDKEY
  540:                                  return OK;
  541: 			     } else {
  542: # print form to enter a new key
  543: 				 &Apache::loncommon::content_type($r,'text/html');
  544: 				 &Apache::loncommon::no_cache($r);
  545: 				 $r->send_http_header;
  546: 				 my $swinfo=&Apache::lonmenu::rawconfig();
  547: 				 my $start_page=&Apache::loncommon::start_page
  548: 				    ('Enter Access Key to Unlock this Course');
  549: 				 my $end_page=&Apache::loncommon::end_page();
  550: 				 $r->print(<<ENDENTERKEY);
  551: $start_page
  552: <script type="text/javascript">
  553: // <![CDATA[
  554: $swinfo
  555: // ]]>
  556: </script>
  557: <form action="" method="post">
  558: <input type="hidden" name="selectrole" value="1" />
  559: <input type="hidden" name="$trolecode" value="1" />
  560: <input type="text" size="20" name="newkey" value="$env{'form.newkey'}" />
  561: <input type="submit" value="Enter key" />
  562: </form>
  563: $end_page
  564: ENDENTERKEY
  565: 				 return OK;
  566: 			     }
  567: 			 }
  568: 		     }
  569: 		    &Apache::lonnet::log($env{'user.domain'},
  570: 					 $env{'user.name'},
  571: 					 $env{'user.home'},
  572: 					 "Role ".$trolecode);
  573: 		    
  574: 		    &Apache::lonnet::appenv(
  575: 					   {'request.role'        => $trolecode,
  576: 					    'request.role.domain' => $cdom,
  577: 					    'request.course.sec'  => $csec,
  578:                                             'request.course.groups' => $cgrps});
  579:                     my $tadv=0;
  580: 
  581: 		    if (($cnum) && ($role ne 'ca') && ($role ne 'aa')) {
  582:                         my $msg;
  583:                         my ($furl,$ferr)=
  584:                             &Apache::lonuserstate::readmap($cdom.'/'.$cnum);
  585:                         unless ($ferr) {
  586:                             unless (($env{'form.switchrole'}) ||
  587:                                     ($env{"environment.internal.$cdom.$cnum.$role.adhoc"})) {
  588:                                 &Apache::lonnet::put('nohist_crslastlogin',
  589:                                     {$env{'user.name'}.':'.$env{'user.domain'}.
  590:                                      ':'.$csec.':'.$role => $now},$cdom,$cnum);
  591:                             }
  592:                             my ($feeds,$syllabus_time);
  593:                             &Apache::lonrss::advertisefeeds($cnum,$cdom,undef,\$feeds);
  594:                             &Apache::lonnet::appenv({'request.course.feeds' => $feeds});
  595:                             &Apache::lonnet::get_numsuppfiles($cnum,$cdom,1);
  596:                             unless ($env{'course.'.$cdom.'_'.$cnum.'.updatedsyllabus'}) {
  597:                                 unless (($env{'course.'.$cdom.'_'.$cnum.'.externalsyllabus'}) ||
  598:                                         ($env{'course.'.$cdom.'_'.$cnum.'.uploadedsyllabus'})) {
  599:                                     my %syllabus=&Apache::lonnet::dump('syllabus',$cdom,$cnum);
  600:                                     $syllabus_time = $syllabus{'uploaded.lastmodified'};
  601:                                     if ($syllabus_time) {
  602:                                         &Apache::lonnet::appenv({'request.course.syllabustime' => $syllabus_time});
  603:                                     }
  604:                                 }
  605:                             }
  606:                         }
  607: 			if (($env{'form.orgurl'}) && 
  608: 			    ($env{'form.orgurl'}!~/^\/adm\/flip/) &&
  609:                             ($env{'form.orgurl'} ne '/adm/roles')) {
  610: 			    my $dest=$env{'form.orgurl'};
  611:                             if ($env{'form.symb'}) {
  612:                                 if ($dest =~ /\?/) {
  613:                                     $dest .= '&';
  614:                                 } else {
  615:                                     $dest .= '?';
  616:                                 }
  617:                                 $dest .= 'symb='.$env{'form.symb'};
  618:                             }
  619: 			    if (&Apache::lonnet::allowed('adv') eq 'F') { $tadv=1; }
  620: 			    &Apache::lonnet::appenv({'request.role.adv'=>$tadv});
  621:                             if (($ferr) && ($tadv)) {
  622: 				&error_page($r,$ferr,$dest);
  623: 			    } else {
  624:                                 if ($dest =~ m{^/adm/coursedocs\?folderpath}) {
  625:                                     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) { 
  626:                                         my $chome = &Apache::lonnet::homeserver($cnum,$cdom);
  627:                                         &Apache::loncommon::update_content_constraints($cdom,$cnum,$chome,
  628:                                                                                        $cdom.'_'.$cnum);
  629:                                     }
  630:                                 }
  631: 				$r->internal_redirect($dest);
  632: 			    }
  633: 			    return OK;
  634: 			} else {
  635: 			    if (!$env{'request.course.id'}) {
  636: 				&Apache::lonnet::appenv(
  637: 				      {"request.course.id"  => $cdom.'_'.$cnum});
  638: 				$furl='/adm/roles?tryagain=1';
  639:                 $msg='<p><span class="LC_error">'
  640:                     .&mt('Could not initialize [_1] at this time.',
  641:                          $env{'course.'.$cdom.'_'.$cnum.'.description'})
  642:                     .'</span></p>'
  643:                     .'<p>'.&mt('Please try again.').'</p>'
  644:                     .'<p>'.$ferr.'</p>';
  645: 			    }
  646: 			    if (&Apache::lonnet::allowed('adv') eq 'F') { $tadv=1; }
  647: 			    &Apache::lonnet::appenv({'request.role.adv'=>$tadv});
  648: 
  649: 			    if (($ferr) && ($tadv)) {
  650: 				&error_page($r,$ferr,$furl);
  651: 			    } else {
  652: 				# Check to see if the user is a CC entering a course 
  653: 				# for the first time
  654: 				if ((($role eq 'cc') || ($role eq 'co')) 
  655:                                     && ($env{'course.'.$cdom.'_'.$cnum.'.course.helper.not.run'})) { 
  656: 				    $furl = "/adm/helper/course.initialization.helper";
  657: 				    # Send the user to the course they selected
  658: 				} elsif ($env{'request.course.id'}) {
  659:                                     my ($dest,$destsymb,$checkenc);
  660:                                     $dest = $env{'form.destinationurl'};
  661:                                     $destsymb = $env{'form.destsymb'};
  662:                                     if ($dest ne '') {
  663:                                         if ($env{'form.switchrole'}) {
  664:                                             if ($destsymb ne '') {
  665:                                                 if ($destsymb !~ m{^/enc/}) {
  666:                                                     unless ($env{'request.role.adv'}) {
  667:                                                         $checkenc = 1;
  668:                                                     }
  669:                                                 }
  670:                                             }
  671:                                             if ($dest =~ m{^/enc/}) {
  672:                                                 if ($env{'request.role.adv'}) {
  673:                                                     $dest = &Apache::lonenc::unencrypted($dest);
  674:                                                     if ($destsymb eq '') {
  675:                                                         ($destsymb) = ($dest =~ /(?:\?|\&)symb=([^\&]*)/); 
  676:                                                         $destsymb = &unescape($destsymb);
  677:                                                     }
  678:                                                 }
  679:                                             } else {
  680:                                                 if ($destsymb eq '') {
  681:                                                     ($destsymb) = ($dest =~ /(?:\?|\&)symb=([^\&]+)/);
  682:                                                     $destsymb = &unescape($destsymb);
  683:                                                 }
  684:                                                 unless ($env{'request.role.adv'}) {
  685:                                                     $checkenc = 1;
  686:                                                 }
  687:                                             }
  688:                                             if (($checkenc) && ($destsymb ne '')) {
  689:                                                 my ($encstate,$unencsymb,$res);
  690:                                                 $unencsymb = &Apache::lonnet::symbclean($destsymb);
  691:                                                 (undef,undef,$res) = &Apache::lonnet::decode_symb($unencsymb);
  692:                                                 &Apache::lonnet::symbverify($unencsymb,$res,\$encstate);
  693:                                                 if ($encstate) {
  694:                                                     if (($dest ne '') && ($dest !~ m{^/enc/})) {
  695:                                                         $dest=&Apache::lonenc::encrypted($dest);
  696:                                                     }
  697:                                                 }
  698:                                             }
  699:                                         }
  700:                                         unless (($dest =~ m{^/enc/}) || ($dest =~ /(\?|\&)symb=.+___\d+___.+/)) { 
  701:                                             if (($destsymb ne '') && ($destsymb !~ m{^/enc/})) {
  702:                                                 my $esc_symb = &escape($destsymb);
  703:                                                 $dest .= '?symb='.$esc_symb;
  704:                                             }
  705:                                         }
  706:                                         &redirect_user($r, &mt('Entering [_1]',
  707:                                                        $env{'course.'.$cdom.'_'.$cnum.'.description'}),
  708:                                                        $dest, $msg);
  709:                                         return OK;
  710:                                     }
  711: 				    if (&Apache::lonnet::allowed('whn',
  712: 								 $env{'request.course.id'})
  713: 					|| &Apache::lonnet::allowed('whn',
  714: 								    $env{'request.course.id'}.'/'
  715: 								    .$env{'request.course.sec'})
  716: 					) {
  717: 					my $startpage = &courseloadpage($env{'request.course.id'});
  718: 					unless ($startpage eq 'firstres') {         
  719: 					    $msg = &mt('Entering [_1] ...',
  720: 						       $env{'course.'.$env{'request.course.id'}.'.description'});
  721: 					    &redirect_user($r, &mt('New in course'),
  722:                                        '/adm/whatsnew?refpage=start', $msg);
  723: 					    return OK;
  724: 					}
  725: 				    }
  726: 				}
  727:                                 # Are we allowed to look at the first resource?
  728:                                 my $access;
  729:                                 if ($furl =~ m{^(/adm/wrapper|)/ext/}) {
  730:                                     # If it's an external resource,
  731:                                     # strip off the symb argument and possible query
  732:                                     my ($exturl,$symb) = ($furl =~ m{^(.+)(?:\?|\&)symb=(.+)$});
  733:                                     # Unencode $symb
  734:                                     $symb = &unescape($symb);
  735:                                     # Then check for permission
  736:                                     $access = &Apache::lonnet::allowed('bre',$exturl,$symb);
  737:                                 # For other resources just check for permission
  738:                                 } else {
  739:                                     $access = &Apache::lonnet::allowed('bre',$furl);
  740:                                 }
  741:                                 if (!$access) {
  742:                                     $furl = &Apache::lonpageflip::first_accessible_resource();
  743:                                 } elsif ($access eq 'B') {
  744:                                     $furl = '/adm/navmaps?showOnlyHomework=1';
  745:                                 }
  746:                                 $msg = &mt('Entering [_1] ...',
  747: 					   $env{'course.'.$cdom.'_'.$cnum.'.description'});
  748: 				&redirect_user($r, &mt('Entering [_1]',
  749:                                $env{'course.'.$cdom.'_'.$cnum.'.description'}),
  750:                                $furl, $msg);
  751: 			    }
  752: 			    return OK;
  753: 			}
  754: 		    }
  755:                     #
  756:                     # Send the user to the construction space they selected
  757:                     if ($role =~ /^(au|ca|aa)$/) {
  758:                         my $redirect_url = '/priv/';
  759:                         if ($role eq 'au') {
  760:                             $redirect_url.=$env{'user.domain'}.'/'.$env{'user.name'};
  761:                         } else {
  762:                             $redirect_url .= $where;
  763:                         }
  764:                         $redirect_url .= '/';
  765:                         &redirect_user($r,&mt('Entering Authoring Space'),
  766:                                        $redirect_url);
  767:                         return OK;
  768:                     }
  769:                     if ($role eq 'dc') {
  770:                         my $redirect_url = '/adm/menu/';
  771:                         &redirect_user($r,&mt('Loading Domain Coordinator Menu'),
  772:                                        $redirect_url);
  773:                         return OK;
  774:                     }
  775:                     if ($role eq 'dh') {
  776:                         my $redirect_url = '/adm/menu/';
  777:                         &redirect_user($r,&mt('Loading Domain Helpdesk Menu'),
  778:                                        $redirect_url);
  779:                         return OK;
  780:                     }
  781:                     if ($role eq 'sc') {
  782:                         my $redirect_url = '/adm/grades?command=scantronupload';
  783:                         &redirect_user($r,&mt('Loading Data Upload Page'),
  784:                                        $redirect_url);
  785:                         return OK;
  786:                     }
  787: 		}
  788:             }
  789:         }
  790:     }
  791: 
  792: 
  793: # =============================================================== No Roles Init
  794: 
  795:     &Apache::loncommon::content_type($r,'text/html');
  796:     &Apache::loncommon::no_cache($r);
  797:     $r->send_http_header;
  798:     return OK if $r->header_only;
  799: 
  800:     my $crumbtext = 'User Roles';
  801:     my $pagetitle = 'My Roles';
  802:     my $recent = &mt('Recent Roles');
  803:     my $standby = &mt('Role selected. Please stand by.');
  804:     my $show_course=&Apache::loncommon::show_course();
  805:     if ($show_course) {
  806:         $crumbtext = 'Courses';
  807:         $pagetitle = 'My Courses';
  808:         $recent = &mt('Recent Courses');
  809:         $standby = &mt('Course selected. Please stand by.');
  810:     }
  811:     my $brcrum =[{href=>"/adm/roles",text=>$crumbtext}];
  812: 
  813:     my %roles_in_env;
  814:     my $showcount = &roles_from_env(\%roles_in_env,$update); 
  815: 
  816:     my $swinfo=&Apache::lonmenu::rawconfig();
  817:     my %domdefs=&Apache::lonnet::get_domain_defaults($env{'user.domain'}); 
  818:     my $cattype = 'std';
  819:     if ($domdefs{'catauth'}) {
  820:         $cattype = $domdefs{'catauth'};
  821:     }
  822:     my $funcs = &get_roles_functions($showcount,$cattype);
  823:     my $crumbsright;
  824:     if ($env{'browser.mobile'}) {
  825:         $crumbsright = $funcs;
  826:         undef($funcs);
  827:     }
  828:     my $start_page=&Apache::loncommon::start_page($pagetitle,undef,{bread_crumbs=>$brcrum,
  829:                                                                     bread_crumbs_component=>$crumbsright});
  830:     &js_escape(\$standby);
  831:     my $noscript='<br /><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 />';
  832: 
  833:     $r->print(<<ENDHEADER);
  834: $start_page
  835: $funcs
  836: <noscript>
  837: $noscript
  838: </noscript>
  839: <script type="text/javascript">
  840: // <![CDATA[
  841: $swinfo
  842: window.focus();
  843: 
  844: active=true;
  845: 
  846: function enterrole (thisform,rolecode,buttonname) {
  847:     if (active) {
  848: 	active=false;
  849:         document.title='$standby';
  850:         window.status='$standby';
  851: 	thisform.newrole.value=rolecode;
  852: 	thisform.submit();
  853:     } else {
  854:        alert('$standby');
  855:     }
  856: }
  857: 
  858: function rolesView (caller) {
  859:     if ((caller == 'showall') || (caller == 'noshowall')) {
  860:         document.rolechoice.display.value = caller;
  861:     } else {
  862:         if ((caller == 'doupdate') || (caller == 'requestauthor') ||
  863:             (caller == 'queued')) {
  864:             document.rolechoice.state.value = caller;
  865:         }
  866:     }
  867:     document.rolechoice.selectrole.value='';
  868:     document.rolechoice.submit();
  869: }
  870: 
  871: // ]]>
  872: </script>
  873: ENDHEADER
  874: 
  875: # ------------------------------------------ Get Error Message from Environment
  876: 
  877:     my ($fn,$priv,$nochoose,$error,$msg)=split(/:/,$env{'user.error.msg'});
  878:     if ($env{'user.error.msg'}) {
  879: 	$r->log_reason(
  880:    "$msg for $env{'user.name'} domain $env{'user.domain'} access $priv",$fn);
  881:     }
  882: 
  883: # ------------------------------------------------- Can this user re-init, etc?
  884: 
  885:     my $advanced=$env{'user.adv'};
  886:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['tryagain']);
  887:     my $tryagain=$env{'form.tryagain'};
  888:     my $reinit=$env{'user.reinit'};
  889:     delete $env{'user.reinit'};
  890: 
  891: # -------------------------------------------------------- Generate Page Output
  892: # --------------------------------------------------------------- Error Header?
  893:     if ($error) {
  894:         $r->print("<h1>".&mt('LON-CAPA Access Control')."</h1>");
  895: 	$r->print("<!-- LONCAPAACCESSCONTROLERRORSCREEN --><hr /><pre>");
  896: 	if ($priv ne '') {
  897:             $r->print(&mt('Access  : ').&Apache::lonnet::plaintext($priv)."\n");
  898: 	}
  899: 	if ($fn ne '') {
  900:             $r->print(&mt('Resource: ').&Apache::lonenc::check_encrypt($fn)."\n");
  901: 	}
  902: 	if ($msg ne '') {
  903:             $r->print(&mt('Action  : ').$msg."\n");
  904: 	}
  905: 	$r->print("</pre><hr />");
  906: 	my $url=$fn;
  907: 	my $last;
  908: 	if (tie(my %hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
  909: 		&GDBM_READER(),0640)) {
  910: 	    $last=$hash{'last_known'};
  911: 	    untie(%hash);
  912: 	}
  913: 	if ($last) { $fn.='?symb='.&escape($last); }
  914: 
  915: 	&Apache::londocs::changewarning($r,undef,'You have modified your course recently, [_1] may fix this access problem.',
  916: 					&Apache::lonenc::check_encrypt($fn));
  917:     } else {
  918:         if ($env{'user.error.msg'}) {
  919:             if ($reinit) {
  920:                 $r->print(
  921:  '<h3><span class="LC_error">'.
  922:  &mt('As your session file for the course or community has expired, you will need to re-select it.').'</span></h3>');
  923:             } else {
  924: 	        $r->print(
  925:  '<h3><span class="LC_error">'.
  926:  &mt('You need to choose another user role or enter a specific course or community for this function.').
  927:  '</span></h3>');
  928: 	    }
  929:         }
  930:     }
  931:     if ($nochoose) {
  932: 	$r->print("<h2>".&mt('Sorry ...')."</h2>\n<span class='LC_error'>".
  933: 		  &mt('This action is currently not authorized.').'</span>'.
  934: 		  &Apache::loncommon::end_page());
  935: 	return OK;
  936:     } else {
  937:         if ($updateresult || $reqauthor || $hotlist) {
  938:             my $showresult = '<div>';
  939:             if ($updateresult) {
  940:                 $showresult .= &Apache::lonhtmlcommon::confirm_success($updateresult);
  941:             }
  942:             if ($reqauthor) {
  943:                 $showresult .= &Apache::lonhtmlcommon::confirm_success($reqauthor);
  944:             }
  945:             if ($hotlist) {
  946:                 $showresult .= $hotlist;
  947:             }
  948:             $showresult .= '</div>';
  949:             $r->print($showresult);
  950:         } elsif ($env{'form.state'} eq 'queued') {
  951:             $r->print(&get_queued());
  952:         }
  953:         if (($ENV{'REDIRECT_QUERY_STRING'}) && ($fn)) {
  954:     	    $fn.='?'.$ENV{'REDIRECT_QUERY_STRING'};
  955:         }
  956:         my $display = ($env{'form.display'} =~ /^(showall)$/);
  957:         $r->print('<form method="post" name="rolechoice" action="'.(($fn)?$fn:$r->uri).'">');
  958:         $r->print('<input type="hidden" name="orgurl" value="'.$fn.'" />');
  959:         $r->print('<input type="hidden" name="selectrole" value="1" />');
  960:         $r->print('<input type="hidden" name="newrole" value="" />');
  961:         $r->print('<input type="hidden" name="display" value="'.$display.'" />');
  962:         $r->print('<input type="hidden" name="state" value="" />');
  963:     }
  964:     $r->rflush();
  965: 
  966:     my (%roletext,%sortrole,%roleclass,%futureroles,%timezones);
  967:     my ($countactive,$countfuture,$inrole,$possiblerole) = 
  968:         &gather_roles($update,$refresh,$now,$reinit,$nochoose,\%roles_in_env,\%roletext,
  969:                       \%sortrole,\%roleclass,\%futureroles,\%timezones,$loncaparev);
  970:     $refresh = $now;
  971:     &Apache::lonnet::appenv({'user.refresh.time'  => $refresh});
  972:     if ((($cattype eq 'std') || ($cattype eq 'domonly')) && (!$env{'user.adv'})) {
  973:         if ($countactive > 0) {
  974:             my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
  975:             my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&'); 
  976:             $r->print(
  977:                 '<p>'
  978:                .&mt('[_1]Visit the [_2]Course/Community Catalog[_3][_4]'
  979:                    .' to view all [_5] LON-CAPA courses and communities.'
  980:                    ,'<b>'
  981:                    ,'<a href="/adm/coursecatalog?showdom='.$esc_dom.'">'
  982:                    ,'</a>'
  983:                    ,'</b>'
  984:                    ,'"'.$domdesc.'"')
  985:                .'<br />'
  986:                .&mt('If a course or community is [_1]not[_2] in your list of current courses and communities below,'
  987:                    .' you may be able to enroll if self-enrollment is permitted.'
  988:                    ,'<b>','</b>')
  989:                .'</p>'
  990:             );
  991:         }
  992:     }
  993: 
  994: # No active roles
  995:     if ($countactive==0) {
  996:         &requestcourse_advice($r,$cattype,$inrole); 
  997: 	$r->print('</form>');
  998:         if ($countfuture) {
  999:             $r->print(&mt('The following [quant,_1,role,roles] will become active in the future:',$countfuture));
 1000:             my $doheaders = &roletable_headers($r,\%roleclass,\%sortrole,
 1001:                                                $nochoose);
 1002:             &print_rolerows($r,$doheaders,\%roleclass,\%sortrole,\%dcroles,
 1003:                             \%roletext);
 1004:             my $tremark='';
 1005:             my $tbg;
 1006:             if ($env{'request.role'} eq 'cm') {
 1007:                 $tbg="LC_roles_selected";
 1008:                 $tremark=&mt('Currently selected.').' ';
 1009:             } else {
 1010:                 $tbg="LC_roles_is";
 1011:             }
 1012:             $r->print(&Apache::loncommon::start_data_table_row()
 1013:                      .'<td class="'.$tbg.'">&nbsp;</td>'
 1014:                      .'<td colspan="3">'
 1015:                      .&mt('No role specified')
 1016:                      .'</td>'
 1017:                      .'<td>'.$tremark.'&nbsp;</td>'
 1018:                      .&Apache::loncommon::end_data_table_row()
 1019:             );
 1020: 
 1021:             $r->print(&Apache::loncommon::end_data_table());
 1022:         }
 1023:         $r->print(&Apache::loncommon::end_page());
 1024: 	return OK;
 1025:     }
 1026: # ----------------------------------------------------------------------- Table
 1027: 
 1028:     if (($numdc > 0) || (($numdh > 0) && ($numadhoc > 0))) {
 1029:         $r->print(&coursepick_jscript());
 1030:         $r->print(&Apache::loncommon::coursebrowser_javascript().
 1031:                   &Apache::loncommon::authorbrowser_javascript());
 1032:     }
 1033: 
 1034:     unless ((!&Apache::loncommon::show_course()) || ($nochoose) || ($countactive==1)) {
 1035: 	$r->print("<h2>".&mt('Select a Course to Enter')."</h2>\n");
 1036:     }
 1037:     if ($env{'form.destinationurl'}) {
 1038:         $r->print('<input type="hidden" name="destinationurl" value="'.
 1039:                   $env{'form.destinationurl'}.'" />');
 1040:         if ($env{'form.destsymb'} ne '') {
 1041:             $r->print('<input type="hidden" name="destsymb" value="'.
 1042:                       $env{'form.destsymb'}.'" />');
 1043:         }
 1044:     }
 1045: 
 1046:     my $doheaders = &roletable_headers($r,\%roleclass,\%sortrole,$nochoose);
 1047:     if ($env{'environment.recentroles'}) {
 1048:         my %recent_roles =
 1049:                &Apache::lonhtmlcommon::get_recent('roles',$env{'environment.recentrolesn'});
 1050: 	my $output='';
 1051: 	foreach my $role (sort(keys(%recent_roles))) {
 1052: 	    if (ref($roletext{'user.role.'.$role}) eq 'ARRAY') {
 1053: 		$output.= &Apache::loncommon::start_data_table_row().
 1054:                           $roletext{'user.role.'.$role}->[0].
 1055:                           &Apache::loncommon::end_data_table_row();
 1056:                 if ($roletext{'user.role.'.$role}->[1] ne '') {
 1057:                     $output .= &Apache::loncommon::continue_data_table_row().
 1058:                                $roletext{'user.role.'.$role}->[1].
 1059:                                &Apache::loncommon::end_data_table_row();
 1060:                 }
 1061:                 if ($role =~ m{^dc\./($match_domain)/$} 
 1062: 		    && $dcroles{$1}) {
 1063: 		    $output .= &adhoc_roles_row($1,'recent');
 1064:                 } elsif ($role =~ m{^dh\./($match_domain)/$}
 1065:                          && ($env{'environment.adhocroles.'.$1} ne '')) {
 1066:                     $output .= &adhoc_customroles_row($1,'recent');
 1067:                 }
 1068: 	    } elsif ($numdc > 0) {
 1069:                 unless ($role =~/^error\:/) {
 1070:                     my ($roletext,$role_text_end) = &display_cc_role('user.role.'.$role);
 1071:                     if ($roletext) {
 1072:                         $output.= &Apache::loncommon::start_data_table_row().
 1073:                                   $roletext.
 1074:                                   &Apache::loncommon::end_data_table_row();
 1075:                         if ($role_text_end) {
 1076:                             $output .= &Apache::loncommon::continue_data_table_row().
 1077:                                        $role_text_end.
 1078:                                        &Apache::loncommon::end_data_table_row();
 1079:                         }
 1080:                     }
 1081:                 }
 1082:             }
 1083: 	}
 1084: 	if ($output) {
 1085: 	    $r->print(&Apache::loncommon::start_data_table_empty_row()
 1086:                      .'<td align="center" colspan="5">'
 1087:                      .$recent
 1088:                      .'</td>'
 1089:                      .&Apache::loncommon::end_data_table_empty_row()
 1090:             );
 1091: 	    $r->print($output);
 1092:             $doheaders ++;
 1093: 	}
 1094:     }
 1095:     &print_rolerows($r,$doheaders,\%roleclass,\%sortrole,\%dcroles,\%roletext);
 1096:     if ($countactive > 1) {
 1097:         my $tremark='';
 1098:         my $tbg;
 1099:         if ($env{'request.role'} eq 'cm') {
 1100:             $tbg="LC_roles_selected";
 1101:             $tremark=&mt('Currently selected.').' ';
 1102:         } else {
 1103:                 $tbg="LC_roles_is";
 1104:         }
 1105:         $r->print(&Apache::loncommon::start_data_table_row());
 1106:         unless ($nochoose) {
 1107: 	    if ($env{'request.role'} ne 'cm') {
 1108: 	        $r->print('<td class="'.$tbg.'"><input type="submit" value="'.
 1109: 		          &mt('Select').'" name="cm" /></td>');
 1110: 	    } else {
 1111: 	        $r->print('<td class="'.$tbg.'">&nbsp;</td>');
 1112: 	    }
 1113:         }
 1114:         $r->print('<td colspan="3">'
 1115:                  .&mt('No role specified')
 1116:                  .'</td>'
 1117:                  .'<td>'.$tremark.'&nbsp;</td>'
 1118:                  .&Apache::loncommon::end_data_table_row()
 1119:         );
 1120:     } 
 1121:     $r->print(&Apache::loncommon::end_data_table());
 1122:     unless ($nochoose) {
 1123: 	$r->print("</form>\n");
 1124:     }
 1125: # ------------------------------------------------------------ Privileges Info
 1126:     if (($advanced) && (($env{'user.error.msg'}) || ($error))) {
 1127: 	$r->print('<hr /><h2>'.&mt('Current Privileges').'</h2>');
 1128: 	$r->print(&privileges_info());
 1129:     }
 1130:     my $announcements = &Apache::lonnet::getannounce();
 1131:     $r->print(
 1132:         '<br />'.
 1133:         '<h2>'.&mt('Announcements').'</h2>'.
 1134:         $announcements
 1135:     ) unless (!$announcements);
 1136:     if ($advanced) {
 1137:         my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&');
 1138:         $r->print('<p><small><i>'
 1139:                  .&mt('This LON-CAPA server is version [_1]',$r->dir_config('lonVersion'))
 1140:                  .'</i></small></p>');
 1141:     }
 1142:     $r->print(&Apache::loncommon::end_page());
 1143:     return OK;
 1144: }
 1145: 
 1146: sub roles_from_env {
 1147:     my ($roleshash,$update) = @_;
 1148:     my $count = 0;
 1149:     if (ref($roleshash) eq 'HASH') {
 1150:         foreach my $envkey (keys(%env)) {
 1151:             if ($envkey =~ m{^user\.role\.(\w+)[./]}) {
 1152:                 next if ($1 eq 'gr');
 1153:                 $roleshash->{$envkey} = $env{$envkey};
 1154:                 my ($start,$end) = split(/\./,$env{$envkey});
 1155:                 unless ($end && $end<$update) {
 1156:                     $count ++;
 1157:                 }
 1158:             }
 1159:         }
 1160:     }
 1161:     return $count;
 1162: }
 1163: 
 1164: sub gather_roles {
 1165:     my ($update,$refresh,$now,$reinit,$nochoose,$roles_in_env,$roletext,$sortrole,$roleclass,$futureroles,
 1166:         $timezones,$loncaparev) = @_;
 1167:     my ($countactive,$countfuture,$inrole,$possiblerole) = (0,0,0,'');
 1168:     my $advanced = $env{'user.adv'};
 1169:     my $tryagain = $env{'form.tryagain'};
 1170:     my @ids = &Apache::lonnet::current_machine_ids();
 1171:     if (ref($roles_in_env) eq 'HASH') {
 1172:         foreach my $envkey (sort(keys(%{$roles_in_env}))) {
 1173:             my $button = 1;
 1174:             my $switchserver='';
 1175:             my $switchwarning;
 1176:             my ($role_text,$role_text_end,$sortkey,$role,$where,$trolecode,$tstart,
 1177:                 $tend,$tremark,$tstatus,$tpstart,$tpend);
 1178:             &Apache::lonnet::role_status($envkey,$update,$refresh,$now,\$role,\$where,
 1179:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
 1180:             next if (!defined($role) || $role eq '' || $role =~ /^gr/);
 1181:             $tremark='';
 1182:             $tpstart='&nbsp;';
 1183:             $tpend='&nbsp;';
 1184:             if ($env{'request.role'} eq $trolecode) {
 1185:                 $tstatus='selected';
 1186:             }
 1187:             my $tbg;
 1188:             if (($tstatus eq 'is')
 1189:                 || ($tstatus eq 'selected')
 1190:                 || ($tstatus eq 'future')
 1191:                 || ($env{'form.display'} eq 'showall')) {
 1192:                 my $timezone = &role_timezone($where,$timezones);
 1193:                 if ($tstart) {
 1194:                     $tpstart=&Apache::lonlocal::locallocaltime($tstart,$timezone);
 1195:                 }
 1196:                 if ($tend) {
 1197:                     $tpend=&Apache::lonlocal::locallocaltime($tend,$timezone);
 1198:                 }
 1199:                 if ($tstatus eq 'is') {
 1200:                     $tbg='LC_roles_is';
 1201:                     $possiblerole=$trolecode;
 1202:                     $countactive++;
 1203:                 } elsif ($tstatus eq 'future') {
 1204:                     $tbg='LC_roles_future';
 1205:                     $button=0;
 1206:                     $futureroles->{$trolecode} = $tstart.':'.$tend;
 1207:                     $countfuture ++;
 1208:                 } elsif ($tstatus eq 'expired') {
 1209:                     $tbg='LC_roles_expired';
 1210:                     $button=0;
 1211:                 } elsif ($tstatus eq 'will_not') {
 1212:                     $tbg='LC_roles_will_not';
 1213:                     $tremark.=&mt('Expired after logout.').' ';
 1214:                 } elsif ($tstatus eq 'selected') {
 1215:                     $tbg='LC_roles_selected';
 1216:                     $inrole=1;
 1217:                     $countactive++;
 1218:                     $tremark.=&mt('Currently selected.').' ';
 1219:                 }
 1220:                 my $trole;
 1221:                 if ($role =~ /^cr\//) {
 1222:                     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$role);
 1223:                     if ($tremark) { $tremark.='<br />'; }
 1224:                     $tremark.=&mt('Custom role defined by [_1].',$rauthor.':'.$rdomain);
 1225:                 }
 1226:                 $trole=Apache::lonnet::plaintext($role);
 1227:                 my $ttype;
 1228:                 my $twhere;
 1229:                 my ($tdom,$trest,$tsection)=
 1230:                     split(/\//,Apache::lonnet::declutter($where));
 1231:                 # First, Co-Authorship roles
 1232:                 if (($role eq 'ca') || ($role eq 'aa')) {
 1233:                     my $home = &Apache::lonnet::homeserver($trest,$tdom);
 1234:                     my $allowed=0;
 1235:                     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 1236:                     if (!$allowed) {
 1237:                         $button=0;
 1238:                         $switchserver='otherserver='.$home.'&amp;role='.$trolecode;
 1239:                     }
 1240:                     #next if ($home eq 'no_host');
 1241:                     $home = &Apache::lonnet::hostname($home);
 1242:                     $ttype='Authoring Space';
 1243:                     $twhere=&mt('User').': '.$trest.'<br />'.&mt('Domain').
 1244:                         ': '.$tdom.'<br />'.
 1245:                         ' '.&mt('Server').':&nbsp;'.$home;
 1246:                     $env{'course.'.$tdom.'_'.$trest.'.description'}='ca';
 1247:                     $tremark.=&Apache::lonhtmlcommon::authorbombs('/res/'.$tdom.'/'.$trest.'/');
 1248:                     $sortkey=$role."$trest:$tdom";
 1249:                 } elsif ($role eq 'au') {
 1250:                     # Authors
 1251:                     my $home = &Apache::lonnet::homeserver
 1252:                         ($env{'user.name'},$env{'user.domain'});
 1253:                     my $allowed=0;
 1254:                     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 1255:                     if (!$allowed) {
 1256:                         $button=0;
 1257:                         $switchserver='otherserver='.$home.'&amp;role='.$trolecode;
 1258:                     }
 1259:                     #next if ($home eq 'no_host');
 1260:                     $home = &Apache::lonnet::hostname($home);
 1261:                     $ttype='Authoring Space';
 1262:                     $twhere=&mt('Domain').': '.$tdom.'<br />'.&mt('Server').
 1263:                         ':&nbsp;'.$home;
 1264:                     $env{'course.'.$tdom.'_'.$trest.'.description'}='ca';
 1265:                     $tremark.=&Apache::lonhtmlcommon::authorbombs('/res/'.$tdom.'/'.$env{'user.name'}.'/');
 1266:                     $sortkey=$role;
 1267:                 } elsif ($trest) {
 1268:                     my $tcourseid=$tdom.'_'.$trest;
 1269:                     $ttype = &Apache::loncommon::course_type($tcourseid);
 1270:                     $trole = &Apache::lonnet::plaintext($role,$ttype,$tcourseid);
 1271:                     if ($env{'course.'.$tcourseid.'.description'}) {
 1272:                         my $home=$env{'course.'.$tcourseid.'.home'};
 1273:                         $twhere=$env{'course.'.$tcourseid.'.description'};
 1274:                         $sortkey=$role."\0".$tdom."\0".$twhere."\0".$envkey;
 1275:                         $twhere = &HTML::Entities::encode($twhere,'"<>&');
 1276:                         unless ($twhere eq &mt('Currently not available')) {
 1277:                             $twhere.=' <span class="LC_fontsize_small">'.
 1278:         &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$trest,$tdom).
 1279:                                     '</span>';
 1280:                             unless ($home && grep(/^\Q$home\E$/,@ids) && $loncaparev eq '') {
 1281:                                 my $required = $env{'course.'.$tcourseid.'.internal.releaserequired'};
 1282:                                 if ($required ne '') {
 1283:                                     ($switchserver,$switchwarning) = 
 1284:                                         &Apache::loncommon::check_release_required($loncaparev,$tcourseid,$trolecode,$required);
 1285:                                     if ($switchserver || $switchwarning) {
 1286:                                         $button = 0;
 1287:                                     }
 1288:                                 }
 1289:                             }
 1290:                         }
 1291:                     } else {
 1292:                         my %newhash=&Apache::lonnet::coursedescription($tcourseid);
 1293:                         if (%newhash) {
 1294:                             $sortkey=$role."\0".$tdom."\0".$newhash{'description'}.
 1295:                                 "\0".$envkey;
 1296:                             $twhere=&HTML::Entities::encode($newhash{'description'},'"<>&').
 1297:                                     ' <span class="LC_fontsize_small">'.
 1298:                                      &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$trest,$tdom).
 1299:                                     '</span>';
 1300:                             $ttype = $newhash{'type'};
 1301:                             $trole = &Apache::lonnet::plaintext($role,$ttype,$tcourseid);
 1302:                             my $home = $newhash{'home'};
 1303:                             unless ($home && grep(/^\Q$home\E$/,@ids) && $loncaparev eq '') {
 1304:                                 my $required = $newhash{'internal.releaserequired'};
 1305:                                 if ($required ne '') {
 1306:                                     ($switchserver,$switchwarning) =
 1307:                                         &Apache::loncommon::check_release_required($loncaparev,$tcourseid,$trolecode,$required);
 1308:                                     if ($switchserver || $switchwarning) {
 1309:                                         $button = 0;
 1310:                                     }
 1311:                                 }
 1312:                             }
 1313:                         } else {
 1314:                             $twhere=&mt('Currently not available');
 1315:                             $env{'course.'.$tcourseid.'.description'}=$twhere;
 1316:                             $sortkey=$role."\0".$tdom."\0".$twhere."\0".$envkey;
 1317:                             $ttype = 'Unavailable';
 1318:                         }
 1319:                     }
 1320:                     if ($tsection) {
 1321:                         $twhere.='<br />'.&mt('Section').': '.$tsection;
 1322:                     }
 1323:                     if ($role ne 'st') { $twhere.="<br />".&mt('Domain').":".$tdom; }
 1324:                 } elsif ($tdom) {
 1325:                     $ttype='Domain';
 1326:                     $twhere=$tdom;
 1327:                     $sortkey=$role.$twhere;
 1328:                 } else {
 1329:                     $ttype='System';
 1330:                     $twhere=&mt('system wide');
 1331:                     $sortkey=$role.$twhere;
 1332:                 }
 1333:                 ($role_text,$role_text_end) =
 1334:                     &build_roletext($trolecode,$tdom,$trest,$tstatus,$tryagain,
 1335:                                     $advanced,$tremark,$tbg,$trole,$twhere,$tpstart,
 1336:                                     $tpend,$nochoose,$button,$switchserver,$reinit,$switchwarning);
 1337:                 $roletext->{$envkey}=[$role_text,$role_text_end];
 1338:                 if (!$sortkey) {$sortkey=$twhere."\0".$envkey;}
 1339:                 $sortrole->{$sortkey}=$envkey;
 1340:                 $roleclass->{$envkey}=$ttype;
 1341:             }
 1342:         }
 1343:     }
 1344:     return ($countactive,$countfuture,$inrole,$possiblerole);
 1345: }
 1346: 
 1347: sub role_timezone {
 1348:     my ($where,$timezones) = @_;
 1349:     my $timezone;
 1350:     if (ref($timezones) eq 'HASH') { 
 1351:         if ($where =~ m{^/($match_domain)/($match_courseid)}) {
 1352:             my $cdom = $1;
 1353:             my $cnum = $2;
 1354:             if ($cdom && $cnum) {
 1355:                 if (!exists($timezones->{$cdom.'_'.$cnum})) {
 1356:                     my $tz;
 1357:                     if ($env{'course.'.$cdom.'_'.$cnum.'.description'}) {
 1358:                         $tz = $env{'course.'.$cdom.'_'.$cnum.'.timezone'};
 1359:                     } else {
 1360:                         my %timehash =
 1361:                             &Apache::lonnet::get('environment',['timezone'],$cdom,$cnum);
 1362:                         $tz = $timehash{'timezone'};
 1363:                     }
 1364:                     if ($tz eq '') {
 1365:                         if (!exists($timezones->{$cdom})) {
 1366:                             my %domdefaults = 
 1367:                                 &Apache::lonnet::get_domain_defaults($cdom);
 1368:                             if ($domdefaults{'timezone_def'} eq '') {
 1369:                                 $timezones->{$cdom} = 'local';
 1370:                             } else {
 1371:                                 $timezones->{$cdom} = $domdefaults{'timezone_def'};
 1372:                             }
 1373:                         }
 1374:                         $timezones->{$cdom.'_'.$cnum} = $timezones->{$cdom};
 1375:                     } else {
 1376:                         $timezones->{$cdom.'_'.$cnum} = 
 1377:                             &Apache::lonlocal::gettimezone($tz);
 1378:                     }
 1379:                 }
 1380:                 $timezone = $timezones->{$cdom.'_'.$cnum};
 1381:             }
 1382:         } else {
 1383:             my ($tdom) = ($where =~ m{^/($match_domain)});
 1384:             if ($tdom) {
 1385:                 if (!exists($timezones->{$tdom})) {
 1386:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($tdom);
 1387:                     if ($domdefaults{'timezone_def'} eq '') {
 1388:                         $timezones->{$tdom} = 'local';
 1389:                     } else {
 1390:                         $timezones->{$tdom} = $domdefaults{'timezone_def'};
 1391:                     }
 1392:                 }
 1393:                 $timezone = $timezones->{$tdom};
 1394:             }
 1395:         }
 1396:         if ($timezone eq 'local') {
 1397:             $timezone = undef;
 1398:         }
 1399:     }
 1400:     return $timezone;
 1401: }
 1402: 
 1403: sub roletable_headers {
 1404:     my ($r,$roleclass,$sortrole,$nochoose) = @_;
 1405:     my $doheaders;
 1406:     if ((ref($sortrole) eq 'HASH') && (ref($roleclass) eq 'HASH')) {
 1407:         $r->print('<br />'
 1408:                  .&Apache::loncommon::start_data_table('LC_textsize_mobile')
 1409:                  .&Apache::loncommon::start_data_table_header_row()
 1410:         );
 1411:         if (!$nochoose) { $r->print('<th>&nbsp;</th>'); }
 1412:         $r->print('<th>'.&mt('User Role').'</th>'
 1413:                  .'<th>'.&mt('Extent').'</th>'
 1414:                  .'<th>'.&mt('Start').'</th>'
 1415:                  .'<th>'.&mt('End').'</th>'
 1416:                  .&Apache::loncommon::end_data_table_header_row()
 1417:         );
 1418:         $doheaders=-1;
 1419:         my @roletypes = &roletypes();
 1420:         foreach my $type (@roletypes) {
 1421:             my $haverole=0;
 1422:             foreach my $which (sort {uc($a) cmp uc($b)} (keys(%{$sortrole}))) {
 1423:                 if ($roleclass->{$sortrole->{$which}} =~ /^\Q$type\E/) {
 1424:                     $haverole=1;
 1425:                 }
 1426:             }
 1427:             if ($haverole) { $doheaders++; }
 1428:         }
 1429:     }
 1430:     return $doheaders;
 1431: }
 1432: 
 1433: sub roletypes {
 1434:     my @types = ('Domain','Authoring Space','Course','Community','Unavailable','System');
 1435:     return @types; 
 1436: }
 1437: 
 1438: sub print_rolerows {
 1439:     my ($r,$doheaders,$roleclass,$sortrole,$dcroles,$roletext) = @_;
 1440:     if ((ref($roleclass) eq 'HASH') && (ref($sortrole) eq 'HASH')) {
 1441:         my @types = &roletypes();
 1442:         foreach my $type (@types) {
 1443:             my $output;
 1444:             foreach my $which (sort {uc($a) cmp uc($b)} (keys(%{$sortrole}))) {
 1445:                 if ($roleclass->{$sortrole->{$which}} =~ /^\Q$type\E/) {
 1446:                     if (ref($roletext) eq 'HASH') {
 1447:                         if (ref($roletext->{$sortrole->{$which}}) eq 'ARRAY') {
 1448:                             $output.= &Apache::loncommon::start_data_table_row().
 1449:                                       $roletext->{$sortrole->{$which}}->[0].
 1450:                                       &Apache::loncommon::end_data_table_row();
 1451:                             if ($roletext->{$sortrole->{$which}}->[1] ne '') {
 1452:                                 $output .= &Apache::loncommon::continue_data_table_row().
 1453:                                            $roletext->{$sortrole->{$which}}->[1].
 1454:                                            &Apache::loncommon::end_data_table_row();
 1455:                             }
 1456:                         }
 1457:                         if ($sortrole->{$which} =~ m{^user\.role\.dc\./($match_domain)/}) {
 1458:                             if (ref($dcroles) eq 'HASH') {
 1459:                                 if ($dcroles->{$1}) {
 1460:                                     $output .= &adhoc_roles_row($1,'');
 1461:                                 }
 1462:                             }
 1463:                         } elsif (($sortrole->{$which} =~ m{^user\.role\.dh\./($match_domain)/}) &&
 1464:                                  ($env{'environment.adhocroles.'.$1} ne '')) {
 1465:                             $output .= &adhoc_customroles_row($1,'');
 1466:                         }
 1467:                     }
 1468:                 }
 1469:             }
 1470:             if ($output) {
 1471:                 if ($doheaders > 0) {
 1472:                     $r->print(&Apache::loncommon::start_data_table_empty_row()
 1473:                              .'<td align="center" colspan="5">'
 1474:                              .&mt($type)
 1475:                              .'</td>'
 1476:                              .&Apache::loncommon::end_data_table_empty_row()
 1477:                     );
 1478:                 }
 1479:                 $r->print($output);
 1480:             }
 1481:         }
 1482:     }
 1483: }
 1484: 
 1485: sub findcourse_advice {
 1486:     my ($r,$cattype) = @_;
 1487:     my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
 1488:     my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&');
 1489:     if (&Apache::lonnet::auto_run(undef,$env{'user.domain'})) {
 1490:         $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).'
 1491: <ul>
 1492:  <li>'.&mt('The course has yet to be created.').'</li>
 1493:  <li>'.&mt('Automatic enrollment of registered students has not been enabled for the course.').'</li>
 1494:  <li>'.&mt('You are in a section of course for which automatic enrollment in the corresponding LON-CAPA course is not active.').'</li>
 1495:  <li>'.&mt('The start date for automated enrollment has yet to be reached.').'</li>
 1496:  <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>
 1497:  </ul>');
 1498:     } else {
 1499:         $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 />');
 1500:     }
 1501:     if (($cattype eq 'std') || ($cattype eq 'domonly')) {
 1502:         $r->print('<h3>'.&mt('Self-Enrollment').'</h3>'.
 1503:                   '<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 />');
 1504:         $r->print(&mt('You can search for courses and communities which permit self-enrollment, if you would like to enroll in one.').'</p>'.
 1505:         &Apache::loncoursequeueadmin::queued_selfenrollment());
 1506:     }
 1507:     return;
 1508: }
 1509: 
 1510: sub requestcourse_advice {
 1511:     my ($r,$cattype,$inrole) = @_;
 1512:     my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
 1513:     my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&');
 1514:     my (%can_request,%request_doms,$output);
 1515:     &Apache::lonnet::check_can_request($env{'user.domain'},\%can_request,\%request_doms);
 1516:     if (keys(%request_doms) > 0) {
 1517:         my ($types,$typename) = &Apache::loncommon::course_types();
 1518:         if ((ref($types) eq 'ARRAY') && (ref($typename) eq 'HASH')) { 
 1519:             my (@reqdoms,@reqtypes);
 1520:             foreach my $type (sort(keys(%request_doms))) {
 1521:                 push(@reqtypes,$type); 
 1522:                 if (ref($request_doms{$type}) eq 'ARRAY') {
 1523:                     my $domstr = join(', ',map { &Apache::lonnet::domain($_) } sort(@{$request_doms{$type}}));
 1524:                     $output .=
 1525:                         '<li>'
 1526:                        .&mt('[_1]'.$typename->{$type}.'[_2] in domain: [_3]',
 1527:                             '<i>',
 1528:                             '</i>',
 1529:                             '<b>'.$domstr.'</b>')
 1530:                        .'</li>';
 1531:                     foreach my $dom (@{$request_doms{$type}}) {
 1532:                         unless (grep(/^\Q$dom\E/,@reqdoms)) {
 1533:                             push(@reqdoms,$dom);
 1534:                         }
 1535:                     }
 1536:                 }
 1537:             }
 1538:             my @showtypes;
 1539:             foreach my $type (@{$types}) {
 1540:                 if (grep(/^\Q$type\E$/,@reqtypes)) {
 1541:                     push(@showtypes,$type);
 1542:                 }
 1543:             }
 1544:             my $requrl = '/adm/requestcourse';
 1545:             if (@reqdoms == 1) {
 1546:                 $requrl .= '?showdom='.$reqdoms[0];
 1547:             }
 1548:             if (@showtypes > 0) {
 1549:                 $requrl.=(($requrl=~/\?/)?'&':'?').'crstype='.$showtypes[0];
 1550:             }
 1551:             if (@reqdoms == 1 || @showtypes > 0) {
 1552:                 $requrl .= '&state=crstype&action=new';
 1553:             }
 1554:             if ($output) {
 1555:                 $r->print('<h3>'.&mt('Request creation of a course or community').'</h3>'.
 1556:                           '<p>'.
 1557:                           &mt('You have rights to request the creation of courses and/or communities in the following domain(s):').
 1558:                           '<ul>'.
 1559:                           $output.
 1560:                           '</ul>'.
 1561:                           &mt('Use the [_1]request form[_2] to submit a request for creation of a new course or community.',
 1562:                               '<a href="'.$requrl.'">','</a>').
 1563:                           '</p>');
 1564:             }
 1565:         }
 1566:     } elsif (!$env{'user.adv'}) {
 1567:        if ($inrole) {
 1568:             $r->print('<h3>'.&mt('Currently no additional roles, courses or communities').'</h3>');
 1569:         } else {
 1570:             $r->print('<h3>'.&mt('Currently no active roles, courses or communities').'</h3>');
 1571:         }
 1572:         &findcourse_advice($r,$cattype);
 1573:     }
 1574:     return;
 1575: }
 1576: 
 1577: sub privileges_info {
 1578:     my ($which) = @_;
 1579:     my $output;
 1580: 
 1581:     $which ||= $env{'request.role'};
 1582: 
 1583:     foreach my $envkey (sort(keys(%env))) {
 1584: 	next if ($envkey!~/^user\.priv\.\Q$which\E\.(.*)/);
 1585: 
 1586: 	my $where=$1;
 1587: 	my $ttype;
 1588: 	my $twhere;
 1589: 	my (undef,$tdom,$trest,$tsec)=split(m{/},$where);
 1590: 	if ($trest) {
 1591: 	    if ($env{'course.'.$tdom.'_'.$trest.'.description'} eq 'ca') {
 1592: 		$ttype='Authoring Space';
 1593: 		$twhere='User: '.$trest.', Domain: '.$tdom;
 1594: 	    } else {
 1595: 		$ttype= &Apache::loncommon::course_type($tdom.'_'.$trest);
 1596: 		$twhere=$env{'course.'.$tdom.'_'.$trest.'.description'};
 1597: 		if ($tsec) {
 1598: 		    my $sec_type = 'Section';
 1599: 		    if (exists($env{"user.role.gr.$where"})) {
 1600: 			$sec_type = 'Group';
 1601: 		    }
 1602: 		    $twhere.=' ('.$sec_type.': '.$tsec.')';
 1603: 		}
 1604: 	    }
 1605: 	} elsif ($tdom) {
 1606: 	    $ttype='Domain';
 1607: 	    $twhere=$tdom;
 1608: 	} else {
 1609: 	    $ttype='System';
 1610: 	    $twhere='/';
 1611: 	}
 1612: 	$output .= "\n<h3>".&mt($ttype).': '.$twhere.'</h3>'."\n<ul>";
 1613: 	foreach my $priv (sort(split(/:/,$env{$envkey}))) {
 1614: 	    next if (!$priv);
 1615: 
 1616: 	    my ($prv,$restr)=split(/\&/,$priv);
 1617: 	    my $trestr='';
 1618: 	    if ($restr ne 'F') {
 1619: 		$trestr.=' ('.
 1620: 		    join(', ',
 1621: 			 map { &Apache::lonnet::plaintext($_) } 
 1622: 			     (split('',$restr))).') ';
 1623: 	    }
 1624: 	    $output .= "\n\t".
 1625: 		'<li>'.&Apache::lonnet::plaintext($prv).$trestr.'</li>';
 1626: 	}
 1627: 	$output .= "\n".'</ul>';
 1628:     }
 1629:     return $output;
 1630: }
 1631: 
 1632: sub build_roletext {
 1633:     my ($trolecode,$tdom,$trest,$tstatus,$tryagain,$advanced,$tremark,$tbg,$trole,$twhere,$tpstart,$tpend,$nochoose,$button,$switchserver,$reinit,$switchwarning) = @_;
 1634:     my ($roletext,$roletext_end);
 1635:     my $is_dc=($trolecode =~ m/^dc\./);
 1636:     my $rowspan=($is_dc) ? ''
 1637:                          : ' rowspan="2" ';
 1638: 
 1639:     unless ($nochoose) {
 1640:         my $buttonname=$trolecode;
 1641:         $buttonname=~s/\W//g;
 1642:         if (!$button) {
 1643:             if ($switchserver) {
 1644:                 $roletext.='<td'.$rowspan.' class="'.$tbg.'">'
 1645:                           .'<a href="/adm/switchserver?'.$switchserver.'">'
 1646:                           .&mt('Switch Server')
 1647:                           .'</a></td>';
 1648:             } else {
 1649:                 $roletext.=('<td'.$rowspan.' class="'.$tbg.'">&nbsp;</td>');
 1650:             }
 1651:             if ($switchwarning) {
 1652:                 if ($tremark eq '') {
 1653:                     $tremark = $switchwarning;
 1654:                 } else {
 1655:                     $tremark .= '<br />'.$switchwarning;
 1656:                 }
 1657:             }
 1658:         } elsif ($tstatus eq 'is') {
 1659:             $roletext.='<td'.$rowspan.' class="'.$tbg.'">'.
 1660:                         '<input name="'.$buttonname.'" type="button" value="'.
 1661:                         &mt('Select').'" onclick="javascript:enterrole(this.form,\''.
 1662:                         $trolecode."','".$buttonname.'\');" /></td>';
 1663:         } elsif ($tryagain) {
 1664:             $roletext.=
 1665:                 '<td'.$rowspan.' class="'.$tbg.'">'.
 1666:                 '<input name="'.$buttonname.'" type="button" value="'.
 1667:                 &mt('Try Selecting Again').'" onclick="javascript:enterrole(this.form,\''.
 1668:                         $trolecode."','".$buttonname.'\');" /></td>';
 1669:         } elsif ($advanced) {
 1670:             $roletext.=
 1671:                 '<td'.$rowspan.' class="'.$tbg.'">'.
 1672:                 '<input name="'.$buttonname.'" type="button" value="'.
 1673:                 &mt('Re-Initialize').'" onclick="javascript:enterrole(this.form,\''.
 1674:                         $trolecode."','".$buttonname.'\');" /></td>';
 1675:         } elsif ($reinit) {
 1676:             $roletext.= 
 1677:                 '<td'.$rowspan.' class="'.$tbg.'">'.
 1678:                 '<input name="'.$buttonname.'" type="button" value="'.
 1679:                 &mt('Re-Select').'" onclick="javascript:enterrole(this.form,\''.
 1680:                         $trolecode."','".$buttonname.'\');" /></td>';
 1681:         } else {
 1682:             $roletext.=
 1683:                 '<td'.$rowspan.' class="'.$tbg.'">'.
 1684:                 '<input name="'.$buttonname.'" type="button" value="'.
 1685:                 &mt('Re-Select').'" onclick="javascript:enterrole(this.form,\''.
 1686:                         $trolecode."','".$buttonname.'\');" /></td>';
 1687:         }
 1688:     }
 1689:     if ($trolecode !~ m/^(dc|ca|au|aa)\./) {
 1690: 	$tremark.=&Apache::lonannounce::showday(time,1,
 1691: 			 &Apache::lonannounce::readcalendar($tdom.'_'.$trest));
 1692:     }
 1693:     $roletext.='<td>'.$trole.'</td>'
 1694:               .'<td>'.$twhere.'</td>'
 1695:               .'<td>'.$tpstart.'</td>'
 1696:               .'<td>'.$tpend.'</td>';
 1697:     if (!$is_dc) {
 1698:         $roletext_end = '<td colspan="4">'.
 1699:                         $tremark.'&nbsp;'.
 1700:                         '</td>';
 1701:     }
 1702:     return ($roletext,$roletext_end);
 1703: }
 1704: 
 1705: sub check_author_homeserver {
 1706:     my ($uname,$udom)=@_;
 1707:     if (($uname eq '') || ($udom eq '')) {
 1708:         return ('fail','');
 1709:     }
 1710:     my $home = &Apache::lonnet::homeserver($uname,$udom);
 1711:     if (&Apache::lonnet::host_domain($home) ne $udom) {
 1712:         return ('fail',$home);
 1713:     }
 1714:     my @ids=&Apache::lonnet::current_machine_ids();
 1715:     if (grep(/^\Q$home\E$/,@ids)) {
 1716:         return ('ok',$home);
 1717:     } else {
 1718:         return ('switchserver',$home);
 1719:     }
 1720: }
 1721: 
 1722: sub check_for_adhoc {
 1723:     my ($dcroles,$dhroles,$update,$then) = @_;
 1724:     my $numdc = 0;
 1725:     my $numdh = 0;
 1726:     my $numadhoc = 0;
 1727:     my $num_custom_adhoc = 0;
 1728:     if ($env{'user.adv'}) {
 1729:         foreach my $envkey (sort(keys(%env))) {
 1730:             if ($envkey=~/^user\.role\.(dc|dh)\.\/($match_domain)\/$/) {
 1731:                 my $role = $1;
 1732:                 my $roledom = $2;
 1733:                 my $liverole = 1;
 1734:                 my ($tstart,$tend)=split(/\./,$env{$envkey});
 1735:                 my $limit = $update;
 1736:                 if ((($role eq 'dc') && ($env{'request.role'} eq 'dc./'.$roledom.'/')) ||
 1737:                     (($role eq 'dh') && ($env{'request.role'} eq 'dh./'.$roledom.'/'))) {
 1738:                     $limit = $then;
 1739:                 }
 1740:                 if ($tstart && $tstart>$limit) { $liverole = 0; }
 1741:                 if ($tend   && $tend  <$limit) { $liverole = 0; }
 1742:                 if ($liverole) {
 1743:                     if ($role eq 'dc') {
 1744:                         $dcroles->{$roledom} = $envkey;
 1745:                         $numdc++;
 1746:                     } else {
 1747:                         $dhroles->{$roledom} = $envkey;
 1748:                         if ($env{'environment.adhocroles.'.$roledom} ne '') {
 1749:                             $numadhoc ++;
 1750:                         }
 1751:                         $numdh++;
 1752:                     }
 1753:                 }
 1754:             }
 1755:         }
 1756:     }
 1757:     return ($numdc,$numdh,$numadhoc);
 1758: }
 1759: 
 1760: sub adhoc_course_role {
 1761:     my ($refresh,$update,$then) = @_;
 1762:     my ($cdom,$cnum,$crstype);
 1763:     $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1764:     $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1765:     $crstype = &Apache::loncommon::course_type();
 1766:     if (&check_forcc($cdom,$cnum,$refresh,$update,$then,$crstype)) {
 1767:         my $setprivs;
 1768:         if (!defined($env{'user.role.'.$env{'form.switchrole'}})) {
 1769:             $setprivs = 1;
 1770:         } else {
 1771:             my ($start,$end) = split(/\./,$env{'user.role.'.$env{'form.switchrole'}});
 1772:             if (($start && ($start>$refresh || $start == -1)) ||
 1773:                 ($end && $end<$update)) {
 1774:                 $setprivs = 1;
 1775:             }
 1776:         }
 1777:         unless ($setprivs) {
 1778:             if (!exists($env{'user.priv.'.$env{'form.switchrole'}.'./'})) {
 1779:                 $setprivs = 1;
 1780:             }
 1781:         }
 1782:         if ($setprivs) {
 1783:             if ($env{'form.switchrole'} =~ m-^(in|ta|ep|ad|st|cr)(.*?)\./\Q$cdom\E/\Q$cnum\E/?(\w*)$-) {
 1784:                 my $role = $1;
 1785:                 my $custom_role = $2;
 1786:                 my $usec = $3;
 1787:                 if ($role eq 'cr') {
 1788:                     if ($custom_role =~ m-^/$match_domain/$match_username/\w+$-) {
 1789:                         $role .= $custom_role;
 1790:                     } else {
 1791:                         return;
 1792:                     }
 1793:                 }
 1794:                 my (%userroles,%newrole,%newgroups,%group_privs);
 1795:                 my %cgroups =
 1796:                     &Apache::lonnet::get_active_groups($env{'user.domain'},
 1797:                                             $env{'user.name'},$cdom,$cnum);
 1798:                 foreach my $group (keys(%cgroups)) {
 1799:                     $group_privs{$group} =
 1800:                         $env{'user.priv.cc./'.$cdom.'/'.$cnum.'./'.$cdom.'/'.$cnum.'/'.$group};
 1801:                 }
 1802:                 $newgroups{'/'.$cdom.'/'.$cnum} = \%group_privs;
 1803:                 my $area = '/'.$cdom.'/'.$cnum;
 1804:                 my $spec = $role.'.'.$area;
 1805:                 if ($usec ne '') {
 1806:                     $spec .= '/'.$usec;
 1807:                     $area .= '/'.$usec;
 1808:                 }
 1809:                 if ($role =~ /^cr/) {
 1810:                     &Apache::lonnet::custom_roleprivs(\%newrole,$role,$cdom,$cnum,$spec,$area);
 1811:                 } else {
 1812:                     &Apache::lonnet::standard_roleprivs(\%newrole,$role,$cdom,$spec,$cnum,$area);
 1813:                 }
 1814:                 &Apache::lonnet::set_userprivs(\%userroles,\%newrole,\%newgroups);
 1815:                 my $adhocstart = $refresh-1;
 1816:                 $userroles{'user.role.'.$spec} = $adhocstart.'.';
 1817:                 &Apache::lonnet::appenv(\%userroles,[$role,'cm']);
 1818:             }
 1819:         }
 1820:     }
 1821:     return;
 1822: }
 1823: 
 1824: sub check_forcc {
 1825:     my ($cdom,$cnum,$refresh,$update,$then,$crstype) = @_;
 1826:     my ($is_cc,$ccrole);
 1827:     if ($crstype eq 'Community') {
 1828:         $ccrole = 'co';
 1829:     } else {
 1830:         $ccrole = 'cc';
 1831:     }
 1832:     if (&Apache::lonnet::is_course($cdom,$cnum)) {
 1833:         my $envkey = 'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum;
 1834:         if (defined($env{$envkey})) {
 1835:             $is_cc = 1;
 1836:             my ($tstart,$tend)=split(/\./,$env{$envkey});
 1837:             my $limit = $update;
 1838:             if ($env{'request.role'} eq $ccrole.'./'.$cdom.'/'.$cnum) {
 1839:                 $limit = $then;
 1840:             }
 1841:             if ($tstart && $tstart>$refresh) { $is_cc = 0; }
 1842:             if ($tend   && $tend  <$limit) { $is_cc = 0; }
 1843:         }
 1844:     }
 1845:     return $is_cc;
 1846: }
 1847: 
 1848: sub courselink {
 1849:     my ($roledom,$rowtype,$role) = @_;
 1850:     my $courseform=&Apache::loncommon::selectcourse_link
 1851:                    ('rolechoice','course'.$rowtype.'_'.$roledom.'_'.$role,
 1852:                     'domain'.$rowtype.'_'.$roledom.'_'.$role,
 1853:                     'coursedesc'.$rowtype.'_'.$roledom.'_'.$role,
 1854:                     $roledom.':'.$role,undef,'Course/Community');
 1855:     my $hiddenitems = '<input type="hidden" name="domain'.$rowtype.'_'.$roledom.'_'.$role.'" value="'.$roledom.'" />'.
 1856:                       '<input type="hidden" name="origdom'.$rowtype.'_'.$roledom.'_'.$role.'" value="'.$roledom.'" />'.
 1857:                       '<input type="hidden" name="course'.$rowtype.'_'.$roledom.'_'.$role.'" value="" />'.
 1858:                       '<input type="hidden" name="coursedesc'.$rowtype.'_'.$roledom.'_'.$role.'" value="" />';
 1859:     return $courseform.$hiddenitems;
 1860: }
 1861: 
 1862: sub coursepick_jscript {
 1863:     my %js_lt = &Apache::lonlocal::texthash(
 1864:                   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.",
 1865:                   youc => 'You can only use this screen to select courses and communities in the current domain.',
 1866:              );
 1867:     &js_escape(\%js_lt);
 1868:     my $verify_script = <<"END";
 1869: <script type="text/javascript">
 1870: // <![CDATA[
 1871: function verifyCoursePick(caller) {
 1872:     var numbutton = getIndex(caller)
 1873:     var pickedCourse = document.rolechoice.elements[numbutton+4].value
 1874:     var pickedDomain = document.rolechoice.elements[numbutton+2].value
 1875:     if (document.rolechoice.elements[numbutton+2].value == document.rolechoice.elements[numbutton+3].value) {
 1876:         if (pickedCourse != '') {
 1877:             if (numbutton != -1) {
 1878:                 var courseTarget = "cc./"+pickedDomain+"/"+pickedCourse
 1879:                 document.rolechoice.elements[numbutton+1].name = courseTarget
 1880:                 document.rolechoice.submit()
 1881:             }
 1882:         }
 1883:         else {
 1884:             alert("$js_lt{'plsu'}");
 1885:         }
 1886:     }
 1887:     else {
 1888:         alert("$js_lt{'youc'}")
 1889:     }
 1890: }
 1891: function getIndex(caller) {
 1892:     for (var i=0;i<document.rolechoice.elements.length;i++) {
 1893:         if (document.rolechoice.elements[i] == caller) {
 1894:             return i;
 1895:         }
 1896:     }
 1897:     return -1;
 1898: }
 1899: // ]]>
 1900: </script>
 1901: END
 1902:     return $verify_script;
 1903: }
 1904: 
 1905: sub coauthorlink {
 1906:     my ($dcdom,$rowtype) = @_;
 1907:     my $coauthorform=&Apache::loncommon::selectauthor_link('rolechoice',$dcdom);
 1908:     my $hiddenitems = '<input type="hidden" name="adhoccauname'.$rowtype.'_'.$dcdom.'" value="" />';
 1909:     return $coauthorform.$hiddenitems;
 1910: }
 1911: 
 1912: sub display_cc_role {
 1913:     my $rolekey = shift;
 1914:     my ($roletext,$roletext_end);
 1915:     my $advanced = $env{'user.adv'};
 1916:     my $tryagain = $env{'form.tryagain'};
 1917:     unless ($rolekey =~/^error\:/) {
 1918:         if ($rolekey =~ m{^user\.role\.(cc|co)\./($match_domain)/($match_courseid)$}) {
 1919:             my $ccrole = $1;
 1920:             my $tdom = $2;
 1921:             my $trest = $3;
 1922:             my $tcourseid = $tdom.'_'.$trest;
 1923:             my $trolecode = $ccrole.'./'.$tdom.'/'.$trest;
 1924:             my $twhere;
 1925:             my $ttype;
 1926:             my $tbg='LC_roles_is';
 1927:             my %newhash=&Apache::lonnet::coursedescription($tcourseid);
 1928:             if (%newhash) {
 1929:                 $twhere=$newhash{'description'}.
 1930:                         ' <span class="LC_fontsize_small">'.
 1931:                         &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$trest,$tdom).
 1932:                         '</span>';
 1933:                 $ttype = $newhash{'type'};
 1934:             } else {
 1935:                 $twhere=&mt('Currently not available');
 1936:                 $env{'course.'.$tcourseid.'.description'}=$twhere;
 1937:             }
 1938:             my $trole = &Apache::lonnet::plaintext($ccrole,$ttype,$tcourseid);
 1939:             $twhere.="<br />".&mt('Domain').":".$tdom;
 1940:             ($roletext,$roletext_end) = &build_roletext($trolecode,$tdom,$trest,'is',$tryagain,$advanced,'',$tbg,$trole,$twhere,'','','',1,'');
 1941:         }
 1942:     }
 1943:     return ($roletext,$roletext_end);
 1944: }
 1945: 
 1946: sub adhoc_roles_row {
 1947:     my ($dcdom,$rowtype) = @_;
 1948:     my $output = &Apache::loncommon::continue_data_table_row()
 1949:                  .' <td colspan="5" class="LC_textsize_mobile">'
 1950:                  .&mt('[_1]Ad hoc[_2] roles in domain [_3] --'
 1951:                      ,'<span class="LC_cusr_emph">','</span>',$dcdom)
 1952:                  .' ';
 1953:     my $role = 'cc';
 1954:     my $selectcclink = &courselink($dcdom,$rowtype,$role);
 1955:     my $ccrole = &Apache::lonnet::plaintext('co',undef,undef,1);
 1956:     my $carole = &Apache::lonnet::plaintext('ca');
 1957:     my $selectcalink = &coauthorlink($dcdom,$rowtype);
 1958:     $output.=$ccrole.': '.$selectcclink
 1959:             .' | '.$carole.': '.$selectcalink.'</td>'
 1960:             .&Apache::loncommon::end_data_table_row();
 1961:     return $output;
 1962: }
 1963: 
 1964: sub adhoc_customroles_row {
 1965:     my ($dhdom,$rowtype) = @_;
 1966:     my $output = &Apache::loncommon::continue_data_table_row()
 1967:                  .' <td colspan="5" class="LC_textsize_mobile">'
 1968:                  .&mt('[_1]Ad hoc[_2] course/community roles in domain [_3] --',
 1969:                       '<span class="LC_cusr_emph">','</span>',$dhdom);
 1970:     my @customroles = split(/,/,$env{'environment.adhocroles.'.$dhdom});
 1971:     my $count = 0;
 1972:     foreach my $role (@customroles) {
 1973:         next if (($role eq '') || ($role =~ /\W/));
 1974:         $output .= ' '.$role.': '.&courselink($dhdom,$rowtype,$role).' |';
 1975:         $count ++;
 1976:     }
 1977:     if ($count) {
 1978:         return $output;
 1979:     }
 1980:     return;
 1981: }
 1982: 
 1983: sub recent_filename {
 1984:     my $area=shift;
 1985:     return 'nohist_recent_'.&escape($area);
 1986: }
 1987: 
 1988: sub courseloadpage {
 1989:     my ($courseid) = @_;
 1990:     my $startpage;
 1991:     my %entry_settings = &Apache::lonnet::get('nohist_whatsnew',
 1992: 					      [$courseid.':courseinit']);
 1993:     my ($tmp) = %entry_settings;
 1994:     unless ($tmp =~ /^error: 2 /) {
 1995:         $startpage = $entry_settings{$courseid.':courseinit'};
 1996:     }
 1997:     if ($startpage eq '') {
 1998:         if (exists($env{'environment.course_init_display'})) {
 1999:             $startpage = $env{'environment.course_init_display'};
 2000:         }
 2001:     }
 2002:     return $startpage;
 2003: }
 2004: 
 2005: sub update_session_roles {
 2006:     my $then=$env{'user.login.time'};
 2007:     my $refresh=$env{'user.refresh.time'};
 2008:     if (!$refresh) {
 2009:         $refresh = $then;
 2010:     }
 2011:     my $update = $env{'user.update.time'};
 2012:     if (!$update) {
 2013:         $update = $then;
 2014:     }
 2015:     my $now = time;
 2016:     my %roleshash =
 2017:         &Apache::lonnet::get_my_roles('','','userroles',
 2018:                                       ['active','future','previous'],
 2019:                                       undef,undef,1);
 2020:     my ($msg,@newsec,$oldsec,$currrole_expired,@changed_roles,
 2021:         %changed_groups,%dbroles,%deletedroles,%allroles,%allgroups,
 2022:         %userroles,%checkedgroup,%crprivs,$hasgroups,%rolechange,
 2023:         %groupchange,%newrole,%newgroup,%customprivchg,%groups_roles,
 2024:         @rolecodes);
 2025:     my @possroles = ('cr','st','ta','ad','ep','in','co','cc');
 2026:     my %courseroles;
 2027:     foreach my $item (keys(%roleshash)) {
 2028:         my ($uname,$udom,$role,$remainder) = split(/:/,$item,4);
 2029:         my ($tstart,$tend) = split(/:/,$roleshash{$item});
 2030:         my ($section,$group,@group_privs);
 2031:         if ($role =~ m{^gr/(\w*)$}) {
 2032:             $role = 'gr';
 2033:             my $priv = $1;
 2034:             next if ($tstart eq '-1');
 2035:             if (&curr_role_status($tstart,$tend,$refresh,$now) eq 'active') {
 2036:                 if ($priv ne '') {
 2037:                     push(@group_privs,$priv);
 2038:                 }
 2039:             }
 2040:             if ($remainder =~ /:/) {
 2041:                 (my $additional_privs,$group) =
 2042:                     ($remainder =~ /^([\w:]+):([^:]+)$/);
 2043:                 if ($additional_privs ne '') {
 2044:                     if (&curr_role_status($tstart,$tend,$refresh,$now) eq 'active') {
 2045:                         push(@group_privs,split(/:/,$additional_privs));
 2046:                         @group_privs = sort(@group_privs);
 2047:                     }
 2048:                 }
 2049:             } else {
 2050:                 $group = $remainder;
 2051:             }
 2052:         } else {
 2053:             $section = $remainder;
 2054:         }
 2055:         my $where = "/$udom/$uname";
 2056:         if ($section ne '') {
 2057:             $where .= "/$section";
 2058:         } elsif ($group ne '') {
 2059:             $where .= "/$group";
 2060:         }
 2061:         my $rolekey = "$role.$where";
 2062:         my $envkey = "user.role.$rolekey";
 2063:         $dbroles{$envkey} = 1;
 2064:         if (($env{'request.role'} eq $rolekey) && ($role ne 'st')) {
 2065:             if (&curr_role_status($tstart,$tend,$refresh,$now) ne 'active') {
 2066:                 $currrole_expired = 1;
 2067:             }
 2068:         }
 2069:         if ($env{$envkey} eq '') {
 2070:             my $status_in_db =
 2071:                 &curr_role_status($tstart,$tend,$now,$now);
 2072:                 &gather_roleprivs(\%allroles,\%allgroups,\%userroles,$where,$role,$tstart,$tend,$status_in_db);
 2073:             if (($role eq 'st') && ($env{'request.role'} =~ m{^\Q$role\E\.\Q/$udom/$uname\E})) {
 2074:                 if ($status_in_db eq 'active') {
 2075:                     if ($section eq '') {
 2076:                         push(@newsec,'none');
 2077:                     } else {
 2078:                         push(@newsec,$section);
 2079:                     }
 2080:                 }
 2081:             } else {
 2082:                 unless (grep(/^\Q$role\E$/,@changed_roles)) {
 2083:                     push(@changed_roles,$role);
 2084:                 }
 2085:                 if ($status_in_db ne 'previous') {
 2086:                     if ($role eq 'gr') {
 2087:                         $newgroup{$rolekey} = $status_in_db;
 2088:                         if ($status_in_db eq 'active') {
 2089:                             unless (ref($courseroles{$udom}) eq 'HASH') {
 2090:                                 %{$courseroles{$udom}} =
 2091:                                     &Apache::lonnet::get_my_roles('','','userroles',
 2092:                                                                   ['active'],\@possroles,
 2093:                                                                   [$udom],1);
 2094:                             }
 2095:                             &Apache::lonnet::get_groups_roles($udom,$uname,
 2096:                                                               $courseroles{$udom},
 2097:                                                               \@rolecodes,\%groups_roles);
 2098:                         }
 2099:                     } else {
 2100:                         $newrole{$rolekey} = $status_in_db;
 2101:                     }
 2102:                 }
 2103:             }
 2104:         } else {
 2105:             my ($currstart,$currend) = split(/\./,$env{$envkey});
 2106:             if ($role eq 'gr') {
 2107:                 if (&curr_role_status($currstart,$currend,$refresh,$update) ne 'previous') {
 2108:                     $hasgroups = 1;
 2109:                 }
 2110:             }
 2111:             if (($currstart ne $tstart) || ($currend ne $tend)) {
 2112:                 my $status_in_env =
 2113:                     &curr_role_status($currstart,$currend,$refresh,$update);
 2114:                 my $status_in_db =
 2115:                     &curr_role_status($tstart,$tend,$now,$now);
 2116:                 if ($status_in_env ne $status_in_db) {
 2117:                     if ($status_in_env eq 'active') {
 2118:                         if ($role eq 'st') {
 2119:                             if ($env{'request.role'} eq $rolekey) {
 2120:                                 my $switchsection;
 2121:                                 unless (ref($courseroles{$udom}) eq 'HASH') {
 2122:                                     %{$courseroles{$udom}} =
 2123:                                         &Apache::lonnet::get_my_roles('','','userroles',
 2124:                                                                       ['active'],
 2125:                                                                       \@possroles,[$udom],1);
 2126:                                 }
 2127:                                 foreach my $crsrole (keys(%{$courseroles{$udom}})) {
 2128:                                     if ($crsrole =~ /^\Q$uname\E:\Q$udom\E:st/) {
 2129:                                         $switchsection = 1;
 2130:                                         last;
 2131:                                     }
 2132:                                 }
 2133:                                 if ($switchsection) {
 2134:                                     if ($section eq '') {
 2135:                                         $oldsec = 'none';
 2136:                                     } else {
 2137:                                         $oldsec = $section;
 2138:                                     }
 2139:                                     &gather_roleprivs(\%allroles,\%allgroups,\%userroles,$where,$role,$tstart,$tend,$status_in_db);
 2140:                                 } else {
 2141:                                     $currrole_expired = 1;
 2142:                                     next;
 2143:                                 }
 2144:                             }
 2145:                         }
 2146:                         unless ($rolekey eq $env{'request.role'}) {
 2147:                             if ($role eq 'gr') {
 2148:                                 &Apache::lonnet::delete_env_groupprivs($where,\%courseroles,\@possroles);
 2149:                             } else {
 2150:                                 &Apache::lonnet::delenv("user.priv.$rolekey",undef,[$role]);
 2151:                                 &Apache::lonnet::delenv("user.priv.cm.$where",undef,['cm']);
 2152:                             }
 2153:                             &gather_roleprivs(\%allroles,\%allgroups,\%userroles,$where,$role,$tstart,$tend,$status_in_db);
 2154:                         }
 2155:                     } elsif ($status_in_db eq 'active') {
 2156:                         if (($role eq 'st') &&
 2157:                             ($env{'request.role'} =~ m{^\Q$role\E\.\Q/$udom/$uname\E})) {
 2158:                             if ($section eq '') {
 2159:                                 push(@newsec,'none');
 2160:                             } else {
 2161:                                 push(@newsec,$section);
 2162:                             }
 2163:                         } elsif ($role eq 'gr') {
 2164:                             unless (ref($courseroles{$udom}) eq 'HASH') {
 2165:                                 %{$courseroles{$udom}} =
 2166:                                     &Apache::lonnet::get_my_roles('','','userroles',
 2167:                                                                   ['active'],
 2168:                                                                   \@possroles,[$udom],1);
 2169:                             }
 2170:                             &Apache::lonnet::get_groups_roles($udom,$uname,
 2171:                                                               $courseroles{$udom},
 2172:                                                               \@rolecodes,\%groups_roles);
 2173:                         }
 2174:                         &gather_roleprivs(\%allroles,\%allgroups,\%userroles,$where,$role,$tstart,$tend,$status_in_db);
 2175:                     }
 2176:                     unless (grep(/^\Q$role\E$/,@changed_roles)) {
 2177:                         push(@changed_roles,$role);
 2178:                     }
 2179:                     if ($role eq 'gr') {
 2180:                         $groupchange{"/$udom/$uname"}{$group} = $status_in_db;
 2181:                     } else {
 2182:                         $rolechange{$rolekey} = $status_in_db;
 2183:                     }
 2184:                 }
 2185:             } else {
 2186:                 if ($role eq 'gr') {
 2187:                     unless ($checkedgroup{$where}) {
 2188:                         my $status_in_db =
 2189:                             &curr_role_status($tstart,$tend,$refresh,$now);
 2190:                         if ($tstart eq '-1') {
 2191:                             $status_in_db = 'deleted';
 2192:                         }
 2193:                         unless (ref($courseroles{$udom}) eq 'HASH') {
 2194:                             %{$courseroles{$udom}} =
 2195:                                 &Apache::lonnet::get_my_roles('','','userroles',
 2196:                                                               ['active'],
 2197:                                                               \@possroles,[$udom],1);
 2198:                         }
 2199:                         if (ref($courseroles{$udom}) eq 'HASH') {
 2200:                             foreach my $item (keys(%{$courseroles{$udom}})) {
 2201:                                 next unless ($item =~ /^\Q$uname\E/);
 2202:                                 my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 2203:                                 my $area = '/'.$cdom.'/'.$cnum;
 2204:                                 if ($crssec ne '') {
 2205:                                     $area .= '/'.$crssec;
 2206:                                 }
 2207:                                 my $crsrolekey = $crsrole.'.'.$area;
 2208:                                 my $currprivs = $env{'user.priv.'.$crsrole.'.'.$area.'.'.$where};
 2209:                                 $currprivs =~ s/^://;
 2210:                                 $currprivs =~ s/\&F$//;
 2211:                                 my @curr_grp_privs = split(/\&F:/,$currprivs);
 2212:                                 @curr_grp_privs = sort(@curr_grp_privs);
 2213:                                 my @diffs;
 2214:                                 if (@group_privs > 0 || @curr_grp_privs > 0) {
 2215:                                     @diffs = &Apache::loncommon::compare_arrays(\@group_privs,\@curr_grp_privs);
 2216:                                 }
 2217:                                 if (@diffs == 0) {
 2218:                                     last;
 2219:                                 } else {
 2220:                                     unless(grep(/^\Qgr\E$/,@rolecodes)) {
 2221:                                         push(@rolecodes,'gr');
 2222:                                     }
 2223:                                     &gather_roleprivs(\%allroles,\%allgroups,
 2224:                                                       \%userroles,$where,$role,
 2225:                                                       $tstart,$tend,$status_in_db);
 2226:                                     if ($status_in_db eq 'active') {
 2227:                                         &Apache::lonnet::get_groups_roles($udom,$uname,
 2228:                                                                           $courseroles{$udom},
 2229:                                                                           \@rolecodes,\%groups_roles);
 2230:                                     }
 2231:                                     $changed_groups{$udom.'_'.$uname}{$group} = $status_in_db;
 2232:                                     last;
 2233:                                 }
 2234:                             }
 2235:                         }
 2236:                         $checkedgroup{$where} = 1;
 2237:                     }
 2238:                 } elsif ($role =~ /^cr/) {
 2239:                     my $status_in_db =
 2240:                         &curr_role_status($tstart,$tend,$refresh,$now);
 2241:                     my ($rdummy,$rest) = split(/\//,$role,2);
 2242:                     my %currpriv;
 2243:                     unless (exists($crprivs{$rest})) {
 2244:                         my ($rdomain,$rauthor,$rrole)=split(/\//,$rest);
 2245:                         my $homsvr=&Apache::lonnet::homeserver($rauthor,$rdomain);
 2246:                         if (&Apache::lonnet::hostname($homsvr) ne '') {
 2247:                             my ($rdummy,$roledef)=
 2248:                             &Apache::lonnet::get('roles',["rolesdef_$rrole"],
 2249:                                                  $rdomain,$rauthor);
 2250:                             if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2251:                                 my $i = 0;
 2252:                                 my @scopes = ('sys','dom','crs');
 2253:                                 my @privs = split(/\_/,$roledef);
 2254:                                 foreach my $priv (@privs) {
 2255:                                     my ($blank,@prv) = split(/:/,$priv);
 2256:                                     @prv = map { $_ .= (/\&\w+$/ ? '':'&F') } @prv;
 2257:                                     if (@prv) {
 2258:                                         $priv = ':'.join(':',sort(@prv));
 2259:                                     }
 2260:                                     $crprivs{$rest}{$scopes[$i]} = $priv;
 2261:                                     $i++;
 2262:                                 }
 2263:                             }
 2264:                         }
 2265:                     }
 2266:                     my $status_in_env =
 2267:                         &curr_role_status($currstart,$currend,$refresh,$update);
 2268:                     if ($status_in_env eq 'active') {
 2269:                         $currpriv{sys} = $env{"user.priv.$rolekey./"};
 2270:                         $currpriv{dom} = $env{"user.priv.$rolekey./$udom/"};
 2271:                         $currpriv{crs} = $env{"user.priv.$rolekey.$where"};
 2272:                         if (keys(%crprivs)) {
 2273:                             if (($crprivs{$rest}{sys} ne $currpriv{sys}) ||
 2274:                                 ($crprivs{$rest}{dom} ne $currpriv{dom})
 2275:  ||
 2276:                                 ($crprivs{$rest}{crs} ne $currpriv{crs})) {
 2277:                                 &gather_roleprivs(\%allroles,\%allgroups,
 2278:                                                   \%userroles,$where,$role,
 2279:                                                   $tstart,$tend,$status_in_db);
 2280:                                 unless (grep(/^\Q$role\E$/,@changed_roles)) {
 2281:                                     push(@changed_roles,$role);
 2282:                                 }
 2283:                                 $customprivchg{$rolekey} = $status_in_env;
 2284:                             }
 2285:                         }
 2286:                     }
 2287:                 }
 2288:             }
 2289:         }
 2290:     }
 2291:     foreach my $envkey (keys(%env)) {
 2292:         next unless ($envkey =~ /^user\.role\./);
 2293:         next if ($dbroles{$envkey});
 2294:         next if ($envkey eq 'user.role.'.$env{'request.role'});
 2295:         my ($currstart,$currend) = split(/\./,$env{$envkey});
 2296:         my $status_in_env =
 2297:             &curr_role_status($currstart,$currend,$refresh,$update);
 2298:         my ($rolekey) = ($envkey =~ /^user\.role\.(.+)$/);
 2299:         my ($role,$rest)=split(m{\./},$rolekey,2);
 2300:         $rest = '/'.$rest; 
 2301:         if (&Apache::lonnet::delenv($envkey,undef,[$role])) {
 2302:             if ($status_in_env eq 'active') {
 2303:                 if ($role eq 'gr') {
 2304:                     &Apache::lonnet::delete_env_groupprivs($rest,\%courseroles,
 2305:                                                            \@possroles);
 2306:                 } else {
 2307:                     &Apache::lonnet::delenv("user.priv.$rolekey",undef,[$role]);
 2308:                     &Apache::lonnet::delenv("user.priv.cm.$rest",undef,['cm']);
 2309:                 }
 2310:                 unless (grep(/^\Q$role\E$/,@changed_roles)) {
 2311:                     push(@changed_roles,$role);
 2312:                 }
 2313:                 $deletedroles{$rolekey} = 1;
 2314:             }
 2315:         }
 2316:     }
 2317:     if (($oldsec) && (@newsec > 0)) {
 2318:         if (@newsec > 1) {
 2319:             $msg = '<p class="LC_warning">'.&mt('The section has changed for your current role. Log-out and log-in again to select a role for the new section.').'</p>';
 2320:         } else {
 2321:             my $newrole = $env{'request.role'};
 2322:             if ($newsec[0] eq 'none') {
 2323:                 $newrole =~ s{(/[^/])$}{};
 2324:             } elsif ($oldsec eq 'none') {
 2325:                 $newrole .= '/'.$newsec[0];
 2326:             } else {
 2327:                 $newrole =~ s{([^/]+)$}{$newsec[0]};
 2328:             }
 2329:             my $coursedesc = $env{'course.'.$env{'request.course.id'}.'.description'};
 2330:             my ($curr_role) = ($env{'request.role'} =~ m{^(\w+)\./$match_domain/$match_courseid});
 2331:             my %temp=('logout_'.$env{'request.course.id'} => time);
 2332:             &Apache::lonnet::put('email_status',\%temp);
 2333:             &Apache::lonnet::delenv('user.state.'.$env{'request.course.id'});
 2334:             &Apache::lonnet::appenv({"request.course.id"   => '',
 2335:                                      "request.course.fn"   => '',
 2336:                                      "request.course.uri"  => '',
 2337:                                      "request.course.sec"  => '',
 2338:                                      "request.role"        => 'cm',
 2339:                                      "request.role.adv"    => $env{'user.adv'},
 2340:                                      "request.role.domain" => $env{'user.domain'}});
 2341:             my $rolename = &Apache::loncommon::plainname($curr_role);
 2342:             $msg = '<p><form name="reselectrole" action="/adm/roles" method="post" />'.
 2343:                    '<input type="hidden" name="newrole" value="" />'.
 2344:                    '<input type="hidden" name="selectrole" value="1" />'.
 2345:                    '<span class="LC_info">'.
 2346:                    &mt('Your section has changed for your current [_1] role in [_2].',$rolename,$coursedesc).'</span><br />';
 2347:             my $button = '<input type="button" name="sectionchanged" value="'.
 2348:                          &mt('Re-Select').'" onclick="javascript:enterrole(this.form,'."'$newrole','sectionchanged'".')" />';
 2349:             if ($newsec[0] eq 'none') {
 2350:                 $msg .= &mt('[_1] to continue with your new section-less role.',$button);
 2351:             } else {
 2352:                 $msg .= &mt('[_1] to continue with your new role in section ([_2]).',$button,$newsec[0]);
 2353:             }
 2354:             $msg .= '</form></p>';
 2355:         }
 2356:     } elsif ($currrole_expired) {
 2357:         $msg .= '<p class="LC_warning">';
 2358:         if (&Apache::loncommon::show_course()) {
 2359:             $msg .= &mt('Your role in the current course has expired.');
 2360:         } else {
 2361:             $msg .= &mt('Your current role has expired.');
 2362:         }
 2363:         $msg .= '<br />'.&mt('However you can continue to use this role until you logout, click the "Re-Select" button, or your session has been idle for more than 24 hours.').'</p>';
 2364:     }
 2365:     &Apache::lonnet::set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 2366:     my ($curr_is_adv,$curr_role_adv,$curr_author,$curr_role_author);
 2367:     $curr_author = $env{'user.author'};
 2368:     if (($env{'request.role'} =~/^au/) || ($env{'request.role'} =~/^ca/) ||
 2369:         ($env{'request.role'} =~/^aa/)) {
 2370:         $curr_role_author=1;
 2371:     }
 2372:     $curr_is_adv = $env{'user.adv'};
 2373:     $curr_role_adv = $env{'request.role.adv'};
 2374:     if (keys(%userroles) > 0) {
 2375:         foreach my $role (@changed_roles) {
 2376:             unless(grep(/^\Q$role\E$/,@rolecodes)) {
 2377:                 push(@rolecodes,$role);
 2378:             }
 2379:         }
 2380:         unless(grep(/^\Qcm\E$/,@rolecodes)) {
 2381:             push(@rolecodes,'cm');
 2382:         }
 2383:         &Apache::lonnet::appenv(\%userroles,\@rolecodes);
 2384:     }
 2385:     my %newenv;
 2386:     if (&Apache::lonnet::is_advanced_user($env{'user.domain'},$env{'user.name'})) {
 2387:         unless ($curr_is_adv) {
 2388:             $newenv{'user.adv'} = 1;
 2389:         }
 2390:     } elsif ($curr_is_adv && !$curr_role_adv) {
 2391:         &Apache::lonnet::delenv('user.adv');
 2392:     }
 2393:     my %authorroleshash =
 2394:         &Apache::lonnet::get_my_roles('','','userroles',['active'],['au','ca','aa']);
 2395:     if (keys(%authorroleshash)) {
 2396:         unless ($curr_author) {
 2397:             $newenv{'user.author'} = 1;
 2398:         }
 2399:     } elsif ($curr_author && !$curr_role_author) {
 2400:         &Apache::lonnet::delenv('user.author');
 2401:     }
 2402:     if ($env{'request.course.id'}) {
 2403:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 2404:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 2405:         my (@activecrsgroups,$crsgroupschanged);
 2406:         if ($env{'request.course.groups'}) {
 2407:             @activecrsgroups = split(/:/,$env{'request.course.groups'});
 2408:             foreach my $item (keys(%deletedroles)) {
 2409:                 if ($item =~ m{^gr\./\Q$cdom\E/\Q$cnum\E/(\w+)$}) {
 2410:                     if (grep(/^\Q$1\E$/,@activecrsgroups)) {
 2411:                         $crsgroupschanged = 1;
 2412:                         last;
 2413:                     }
 2414:                 }
 2415:             }
 2416:         }
 2417:         unless ($crsgroupschanged) {
 2418:             foreach my $item (keys(%newgroup)) {
 2419:                 if ($item =~ m{^gr\./\Q$cdom\E/\Q$cnum\E/(\w+)$}) {
 2420:                     if ($newgroup{$item} eq 'active') {
 2421:                         $crsgroupschanged = 1;
 2422:                         last;
 2423:                     }
 2424:                 }
 2425:             }
 2426:         }
 2427:         if ((ref($changed_groups{$env{'request.course.id'}}) eq 'HASH') ||
 2428:             (ref($groupchange{"/$cdom/$cnum"}) eq 'HASH') ||
 2429:             ($crsgroupschanged)) {
 2430:             my %grouproles =  &Apache::lonnet::get_my_roles('','','userroles',
 2431:                                                             ['active'],['gr'],[$cdom],1);
 2432:             my @activegroups;
 2433:             foreach my $item (keys(%grouproles)) {
 2434:                 next unless($item =~ /^\Q$cnum\E:\Q$cdom\E/);
 2435:                 my $group;
 2436:                 my ($crsn,$crsd,$role,$remainder) = split(/:/,$item,4);
 2437:                 if ($remainder =~ /:/) {
 2438:                     (my $other,$group) = ($remainder =~ /^([\w:]+):([^:]+)$/);
 2439:                 } else {
 2440:                     $group = $remainder;
 2441:                 }
 2442:                 if ($group ne '') {
 2443:                     push(@activegroups,$group);
 2444:                 }
 2445:             }
 2446:             $newenv{'request.course.groups'} = join(':',@activegroups);
 2447:         }
 2448:     }
 2449:     if (keys(%newenv)) {
 2450:         &Apache::lonnet::appenv(\%newenv);
 2451:     }
 2452:     if (!@changed_roles || !(keys(%changed_groups))) {
 2453:         my ($rolesmsg,$groupsmsg);
 2454:         if (!@changed_roles) {
 2455:             if (&Apache::loncommon::show_course()) {
 2456:                 $rolesmsg = &mt('No new courses or communities');
 2457:             } else {
 2458:                 $rolesmsg = &mt('No role changes');
 2459:             }
 2460:         }
 2461:         if ($hasgroups && !(keys(%changed_groups)) && !(grep(/gr/,@changed_roles))) {
 2462:             $groupsmsg = &mt('No changes in course/community groups');
 2463:         }
 2464:         if (!@changed_roles && !(keys(%changed_groups))) {
 2465:             if (($msg ne '') || ($groupsmsg ne '')) {
 2466:                 $msg .= '<ul>';
 2467:                 if ($rolesmsg) {
 2468:                     $msg .= '<li>'.$rolesmsg.'</li>';
 2469:                 }
 2470:                 if ($groupsmsg) {
 2471:                     $msg .= '<li>'.$groupsmsg.'</li>';
 2472:                 }
 2473:                 $msg .= '</ul>';
 2474:             } else {
 2475:                 $msg = '&nbsp;<span class="LC_cusr_emph">'.$rolesmsg.'</span><br />';
 2476:             }
 2477:             return $msg;
 2478:         }
 2479:     }
 2480:     my $changemsg;
 2481:     if (@changed_roles > 0) {
 2482:         if (keys(%newgroup) > 0) {
 2483:             my $groupmsg;
 2484:             my (%curr_groups,%groupdescs,$currcrs);
 2485:             foreach my $item (sort(keys(%newgroup))) {
 2486:                 if (&is_active_course($item,$refresh,$update,\%roleshash)) {
 2487:                     if ($item =~ m{^gr\./($match_domain/$match_courseid)/(\w+)$}) {
 2488:                         my ($cdom,$cnum) = split(/\//,$1);
 2489:                         my $group = $2;
 2490:                         if ($currcrs ne $cdom.'_'.$cnum) {
 2491:                             if ($currcrs) {
 2492:                                 $groupmsg .= '</ul><li>';
 2493:                             }
 2494:                             $groupmsg .= '<li><b>'.
 2495:                                          $env{'course.'.$cdom.'_'.$cnum.'.description'}.'</b><ul>';
 2496:                             $currcrs = $cdom.'_'.$cnum;
 2497:                         }
 2498:                         my $groupdesc;
 2499:                         unless (ref($curr_groups{$cdom.'_'.$cnum}) eq 'HASH') {
 2500:                             %{$curr_groups{$cdom.'_'.$cnum}} =
 2501:                                 &Apache::longroup::coursegroups($cdom,$cnum);
 2502:                         }
 2503:                         unless ((ref($groupdescs{$cdom.'_'.$cnum}) eq 'HASH') &&
 2504:                             ($groupdescs{$cdom.'_'.$cnum}{$group})) {
 2505: 
 2506:                             my %groupinfo =
 2507:                                 &Apache::longroup::get_group_settings($curr_groups{$cdom.'_'.$cnum}{$group});
 2508:                             $groupdescs{$cdom.'_'.$cnum}{$group} =
 2509:                                 &unescape($groupinfo{'description'});
 2510:                         }
 2511:                         $groupdesc = $groupdescs{$cdom.'_'.$cnum}{$group};
 2512:                         if ($groupdesc) {
 2513:                             $groupmsg .= '<li>'.
 2514:                                          &mt('[_1] with status: [_2].',
 2515:                                          '<b>'.$groupdesc.'</b>',$newgroup{$item}).'</li>';
 2516:                         }
 2517:                     }
 2518:                 }
 2519:                 if ($groupmsg) {
 2520:                     $groupmsg .= '</ul></li>';
 2521:                 }
 2522:             }
 2523:             if ($groupmsg) {
 2524:                 $changemsg .= '<li>'.
 2525:                               &mt('Courses with new groups').'</li>'.
 2526:                               '<ul>'.$groupmsg.'</ul></li>';
 2527:             }
 2528:         }
 2529:         if (keys(%newrole) > 0) {
 2530:             my $newmsg;
 2531:             foreach my $item (sort(keys(%newrole))) {
 2532:                 my $desc = &role_desc($item,$update,$refresh,$now);
 2533:                 if ($desc) {
 2534:                     $newmsg .= '<li>'.
 2535:                                &mt('[_1] with status: [_2].',
 2536:                                $desc,&mt($newrole{$item})).'</li>';
 2537:                 }
 2538:             }
 2539:             if ($newmsg) {
 2540:                 $changemsg .= '<li>'.&mt('New roles').
 2541:                               '<ul>'.$newmsg.'</ul>'.
 2542:                               '</li>';
 2543:             }
 2544:         }
 2545:         if (keys(%customprivchg) > 0) {
 2546:             my $privmsg;
 2547:             foreach my $item (sort(keys(%customprivchg))) {
 2548:                 my $desc = &role_desc($item,$update,$refresh,$now);
 2549:                 if ($desc) {
 2550:                     $privmsg .= '<li>'.$desc.'</li>';
 2551:                 }
 2552:             }
 2553:             if ($privmsg) {
 2554:                 $changemsg .= '<li>'.
 2555:                               &mt('Custom roles with privilege changes').
 2556:                               '<ul>'.$privmsg.'</ul>'.
 2557:                               '</li>';
 2558:              }
 2559:         }
 2560:         if (keys(%rolechange) > 0) {
 2561:             my $rolemsg;
 2562:             foreach my $item (sort(keys(%rolechange))) {
 2563:                 my $desc = &role_desc($item,$update,$refresh,$now);  
 2564:                 if ($desc) {
 2565:                     $rolemsg .= '<li>'.
 2566:                                 &mt('[_1] status now: [_2].',$desc,
 2567:                                 $rolechange{$item}).'</li>';
 2568:                 }
 2569:             }
 2570:             if ($rolemsg) {
 2571:                 $changemsg .= '<li>'.
 2572:                               &mt('Existing roles with status changes').'</li>'.
 2573:                               '<ul>'.$rolemsg.'</ul>'.
 2574:                               '</li>';
 2575:             }
 2576:         }
 2577:         if (keys(%deletedroles) > 0) {
 2578:             my $delmsg;
 2579:             foreach my $item (sort(keys(%deletedroles))) {
 2580:                 my $desc = &role_desc($item,$update,$refresh,$now);
 2581:                 if ($desc) {
 2582:                     $delmsg .= '<li>'.$desc.'</li>';
 2583:                 }
 2584:             }
 2585:             if ($delmsg) {
 2586:                 $changemsg .= '<li>'.
 2587:                               &mt('Existing roles now expired').'</li>'.
 2588:                               '<ul>'.$delmsg.'</ul>'.
 2589:                               '</li>';
 2590:             }
 2591:         }
 2592:     }
 2593:     if ((keys(%changed_groups) > 0) || (keys(%groupchange) > 0)) {
 2594:         my $groupchgmsg;
 2595:         foreach my $key (sort(keys(%changed_groups))) {
 2596:             my $crs = 'gr/'.$key;
 2597:             $crs =~ s/_/\//;
 2598:             if (&is_active_course($crs,$refresh,$update,\%roleshash)) {
 2599:                 if (ref($changed_groups{$key}) eq 'HASH') {
 2600:                     my @showgroups;
 2601:                     foreach my $group (sort(keys(%{$changed_groups{$key}}))) {
 2602:                         if ($changed_groups{$key}{$group} eq 'active') {
 2603:                             push(@showgroups,$group);
 2604:                         }
 2605:                     }
 2606:                     if (@showgroups > 0) {
 2607:                         $groupchgmsg .= '<li>'.
 2608:                                         &mt('Course: [_1], groups: [_2].',$key,
 2609:                                         join(', ',@showgroups)).
 2610:                                         '</li>';
 2611:                     }
 2612:                 }
 2613:             }
 2614:         }
 2615:         if (keys(%groupchange) > 0) {
 2616:             $groupchgmsg .= '<li>'.
 2617:                           &mt('Existing course/community groups with status changes').'</li>'.
 2618:                           '<ul>';
 2619:             foreach my $crs (sort(keys(%groupchange))) {
 2620:                 my $cid = $crs;
 2621:                 $cid=~s{^/}{};
 2622:                 $cid=~s{/}{_};
 2623:                 my $crsdesc = $env{'course.'.$cid.'.description'};
 2624:                 my $cdom = $env{'course.'.$cid.'.domain'};
 2625:                 my $cnum = $env{'course.'.$cid.'.num'};
 2626:                 my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
 2627:                 my %groupdesc;
 2628:                 if (ref($groupchange{$crs}) eq 'HASH') {
 2629:                     $groupchgmsg .= '<li>'.&mt('Course/Community: [_1]','<b>'.$crsdesc.'</b><ul>');
 2630:                     foreach my $group (sort(keys(%{$groupchange{$crs}}))) {
 2631:                         unless ($groupdesc{$group}) {
 2632:                             my %groupinfo = &Apache::longroup::get_group_settings($curr_groups{$group});
 2633:                             $groupdesc{$group} =  &unescape($groupinfo{'description'});
 2634:                         }
 2635:                         $groupchgmsg .= '<li>'.&mt('Group: [_1] status now: [_2].','<b>'.$groupdesc{$group}.'</b>',$groupchange{$crs}{$group}).'</li>';
 2636:                     }
 2637:                     $groupchgmsg .= '</ul></li>';
 2638:                 }
 2639:             }
 2640:             $groupchgmsg .= '</ul></li>';
 2641:         }
 2642:         if ($groupchgmsg) {
 2643:             $changemsg .= '<li>'.
 2644:                           &mt('Courses with changes in groups').'</li>'.
 2645:                           '<ul>'.$groupchgmsg.'</ul></li>';
 2646:         }
 2647:     }
 2648:     if ($changemsg) {
 2649:         $msg .= '<ul>'.$changemsg.'</ul>';
 2650:     } else {
 2651:         if (&Apache::loncommon::show_course()) {
 2652:             $msg = &mt('No new courses or communities');
 2653:         } else {
 2654:             $msg = &mt('No role changes');
 2655:         }
 2656:     }
 2657:     return $msg;
 2658: }
 2659: 
 2660: sub role_desc {
 2661:     my ($item,$update,$refresh,$now) = @_;
 2662:     my ($where,$trolecode,$role,$tstatus,$tend,$tstart,$twhere,
 2663:         $trole,$tremark);
 2664:     &Apache::lonnet::role_status('user.role.'.$item,$update,$refresh,
 2665:                                  $now,\$role,\$where,\$trolecode,
 2666:                                  \$tstatus,\$tstart,\$tend);
 2667:     return unless ($role);
 2668:     if ($role =~ /^cr\//) {
 2669:         my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$role);
 2670:         $tremark = &mt('Custom role defined by [_1].',$rauthor.':'.$rdomain);
 2671:     }
 2672:     $trole=Apache::lonnet::plaintext($role);
 2673:     my ($tdom,$trest,$tsection)=
 2674:         split(/\//,Apache::lonnet::declutter($where));
 2675:     if (($role eq 'ca') || ($role eq 'aa')) {
 2676:         my $home = &Apache::lonnet::homeserver($trest,$tdom);
 2677:         $home = &Apache::lonnet::hostname($home);
 2678:         $twhere=&mt('User').':&nbsp;'.$trest.'&nbsp; '.&mt('Domain').
 2679:                 ':&nbsp;'.$tdom.'&nbsp; '.&mt('Server').':&nbsp;'.$home;
 2680:     } elsif ($role eq 'au') {
 2681:         my $home = &Apache::lonnet::homeserver
 2682:                        ($env{'user.name'},$env{'user.domain'});
 2683:         $home = &Apache::lonnet::hostname($home);
 2684:         $twhere=&mt('Domain').':&nbsp;'.$tdom.'&nbsp; '.&mt('Server').
 2685:                         ':&nbsp;'.$home;
 2686:     } elsif ($trest) {
 2687:         my $tcourseid=$tdom.'_'.$trest;
 2688:         my $crstype = &Apache::loncommon::course_type($tcourseid);
 2689:         $trole = &Apache::lonnet::plaintext($role,$crstype,$tcourseid);
 2690:         if ($env{'course.'.$tcourseid.'.description'}) {
 2691:             $twhere=$env{'course.'.$tcourseid.'.description'};
 2692:         } else {
 2693:             my %newhash=&Apache::lonnet::coursedescription($tcourseid);
 2694:             if (%newhash) {
 2695:                 $twhere=$newhash{'description'};
 2696:             } else {
 2697:                 $twhere=&mt('Currently not available');
 2698:             }
 2699:         }
 2700:         if ($tsection) {
 2701:             $twhere.= '&nbsp; '.&mt('Section').':&nbsp;'.$tsection;
 2702:         }
 2703:         if ($role ne 'st') {
 2704:             $twhere.= '&nbsp; '.&mt('Domain').':&nbsp;'.$tdom;
 2705:         }
 2706:     } elsif ($tdom) {
 2707:         $twhere = &mt('Domain').':&nbsp;'.$tdom;
 2708:     }
 2709:     my $output;
 2710:     if ($trole) {
 2711:         $output = $trole;
 2712:         if ($twhere) {
 2713:             $output .= " -- $twhere";
 2714:         }
 2715:         if ($tremark) {
 2716:             $output .= '<br />'.$tremark;
 2717:         }
 2718:     }
 2719:     return $output;
 2720: }
 2721: 
 2722: sub curr_role_status {
 2723:     my ($start,$end,$refresh,$update) = @_;
 2724:     if (($start) && ($start<0)) { return 'deleted' };
 2725:     my $status = 'active';
 2726:     if (($end) && ($end<=$update)) {
 2727:         $status = 'previous';
 2728:     }
 2729:     if (($start) && ($refresh<$start)) {
 2730:         $status = 'future';
 2731:     }
 2732:     return $status;
 2733: }
 2734: 
 2735: sub gather_roleprivs {
 2736:     my ($allroles,$allgroups,$userroles,$area,$role,$tstart,$tend,$status) = @_;
 2737:     return unless ((ref($allroles) eq 'HASH') && (ref($allgroups) eq 'HASH') && (ref($userroles) eq 'HASH'));
 2738:     if (($area ne '') && ($role ne '')) {
 2739:         &Apache::lonnet::userrolelog($role,$env{'user.name'},$env{'user.domain'},
 2740:                                      $area,$tstart,$tend);
 2741:         my $spec=$role.'.'.$area;
 2742:         $userroles->{'user.role.'.$spec} = $tstart.'.'.$tend;
 2743:         my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2744:         if ($status eq 'active') { 
 2745:             if ($role =~ /^cr\//) {
 2746:                 &Apache::lonnet::custom_roleprivs($allroles,$role,$tdomain,$trest,$spec,$area);
 2747:             } elsif ($role eq 'gr') {
 2748:                 my %rolehash = &Apache::lonnet::get('roles',[$area.'_'.$role],
 2749:                                                     $env{'user.domain'},
 2750:                                                     $env{'user.name'});
 2751:                 my ($trole) = split(/_/,$rolehash{$area.'_'.$role},2);
 2752:                 (undef,my $group_privs) = split(/\//,$trole);
 2753:                 $group_privs = &unescape($group_privs);
 2754:                 &Apache::lonnet::group_roleprivs($allgroups,$area,$group_privs,$tend,$tstart);
 2755:             } else {
 2756:                 &Apache::lonnet::standard_roleprivs($allroles,$role,$tdomain,$spec,$trest,$area);
 2757:             }
 2758:         }
 2759:     }
 2760:     return;
 2761: }
 2762: 
 2763: sub is_active_course {
 2764:     my ($rolekey,$refresh,$update,$roleshashref) = @_;
 2765:     return unless(ref($roleshashref) eq 'HASH');
 2766:     my ($role,$cdom,$cnum) = split(/\//,$rolekey);
 2767:     my $is_active;
 2768:     foreach my $key (keys(%{$roleshashref})) {
 2769:         if ($key =~ /^\Q$cnum\E:\Q$cdom\E:/) {
 2770:             my ($tstart,$tend) = split(/:/,$roleshashref->{$key});
 2771:             my $status = &curr_role_status($tstart,$tend,$refresh,$update);
 2772:             if ($status eq 'active') {
 2773:                 $is_active = 1;
 2774:                 last;
 2775:             }
 2776:         }
 2777:     }
 2778:     return $is_active;
 2779: }
 2780: 
 2781: sub get_roles_functions {
 2782:     my ($rolescount,$cattype) = @_;
 2783:     my @links;
 2784:     push(@links,["javascript:rolesView('doupdate');",'start-here-22x22',&mt('Check for changes')]);
 2785:     if ($env{'environment.canrequest.author'}) {
 2786:         unless (&Apache::loncoursequeueadmin::is_active_author()) {
 2787:             push(@links,["javascript:rolesView('requestauthor');",'list-add-22x22',&mt('Request author role')]);
 2788:         }
 2789:     }
 2790:     if (($rolescount > 3) || ($env{'environment.recentroles'})) {
 2791:         push(@links,['/adm/preferences?action=changerolespref&amp;returnurl=/adm/roles','role_hotlist-22x22',&mt('Hotlist')]);
 2792:     }
 2793:     if (&Apache::lonmenu::check_for_rcrs()) {
 2794:         push(@links,['/adm/requestcourse','rcrs-22x22',&mt('Request course')]);
 2795:     }
 2796:     if ($env{'form.state'} eq 'queued') {
 2797:         push(@links,["javascript:rolesView('noqueued');",'selfenrl-queue-22x22',&mt('Hide queued')]);
 2798:     } else {
 2799:         push(@links,["javascript:rolesView('queued');",'selfenrl-queue-22x22',&mt('Show queued')]);
 2800:     }
 2801:     if ($env{'user.adv'}) {
 2802:         if ($env{'form.display'} eq 'showall') {
 2803:             push(@links,["javascript:rolesView('noshowall');",'edit-redo-22x22',&mt('Exclude expired')]);
 2804:         } else {
 2805:             push(@links,["javascript:rolesView('showall');",'edit-undo-22x22',&mt('Include expired')]);
 2806:         }
 2807:     }
 2808:     unless ($cattype eq 'none') {
 2809:         push(@links,['/adm/coursecatalog','ccat-22x22',&mt('Course catalog')]);
 2810:     }
 2811:     my $funcs;
 2812:     if ($env{'browser.mobile'}) {
 2813:         my @functions;
 2814:         foreach my $link (@links) {
 2815:             push(@functions,[$link->[0],$link->[2]]);
 2816:         }
 2817:         my $title = 'Display options';
 2818:         if ($env{'user.adv'}) {
 2819:             $title = 'Roles options';
 2820:         }
 2821:         $funcs = &Apache::lonmenu::create_submenu('','',$title,\@functions,1,'LC_breadcrumbs_hoverable');
 2822:         $funcs = '<ol class="LC_primary_menu LC_floatright">'.$funcs.'</ol>';
 2823:     } else {
 2824:         $funcs = &Apache::lonhtmlcommon::start_funclist();
 2825:         foreach my $link (@links) {
 2826:             $funcs .= &Apache::lonhtmlcommon::add_item_funclist(
 2827:                           '<a href="'.$link->[0].'" class="LC_menubuttons_link">'.
 2828:                           '<img src="/res/adm/pages/'.$link->[1].'.png" class="LC_icon" alt="'.$link->[2].'" />'.
 2829:                           $link->[2].'</a>');
 2830:         }
 2831:         $funcs .= &Apache::lonhtmlcommon::end_funclist();
 2832:         $funcs = &Apache::loncommon::head_subbox($funcs);
 2833:     }
 2834:     return $funcs;
 2835: }
 2836: 
 2837: sub get_queued {
 2838:     my ($output,%reqcrs);
 2839:     my ($types,$typenames) = &Apache::loncommon::course_types();
 2840:     my %statusinfo = &Apache::lonnet::dump('courserequests',$env{'user.domain'},
 2841:                                            $env{'user.name'},'^status:');
 2842:     foreach my $key (keys(%statusinfo)) {
 2843:         next unless (($statusinfo{$key} eq 'approval') || ($statusinfo{$key} eq 'pending'));
 2844:         (undef,my($cdom,$cnum)) = split(/:/,$key);
 2845:         my $requestkey = $cdom.'_'.$cnum;
 2846:         if ($requestkey =~ /^($match_domain)_($match_courseid)$/) {
 2847:             my %history = &Apache::lonnet::restore($requestkey,'courserequests',
 2848:                                                    $env{'user.domain'},$env{'user.name'});
 2849:             next if ((exists($history{'status'})) && ($history{'status'} eq 'created'));
 2850:             my $reqtime = $history{'reqtime'};
 2851:             my $lastupdate = $history{'timestamp'};
 2852:             my $showtype = $history{'crstype'};
 2853:             if (defined($typenames->{$history{'crstype'}})) {
 2854:                 $showtype = $typenames->{$history{'crstype'}};
 2855:             }
 2856:             my $description;
 2857:             if (ref($history{'details'}) eq 'HASH') {
 2858:                 $description = $history{details}{'cdescr'};
 2859:             }
 2860:             @{$reqcrs{$reqtime}} = ($description,$showtype);
 2861:         }
 2862:     }
 2863:     my @sortedtimes = sort {$a <=> $b} (keys(%reqcrs));
 2864:     if (@sortedtimes > 0) {
 2865:         $output .= '<p><b>'.&mt('Course/Community requests').'</b><br />'.
 2866:                    &Apache::loncommon::start_data_table().
 2867:                    &Apache::loncommon::start_data_table_header_row().
 2868:                    '<th>'.&mt('Date requested').'</th>'.
 2869:                    '<th>'.&mt('Course title').'</th>'.
 2870:                    '<th>'.&mt('Course type').'</th>';
 2871:                    &Apache::loncommon::end_data_table_header_row();
 2872:         foreach my $reqtime (@sortedtimes) {
 2873:             next unless (ref($reqcrs{$reqtime}) eq 'ARRAY');
 2874:             $output .= &Apache::loncommon::start_data_table_row().
 2875:                        '<td>'.&Apache::lonlocal::locallocaltime($reqtime).'</td>'.
 2876:                        '<td>'.join('</td><td>',@{$reqcrs{$reqtime}}).'</td>'.
 2877:                        &Apache::loncommon::end_data_table_row();
 2878:         }
 2879:         $output .= &Apache::loncommon::end_data_table().
 2880:                    '<br /></p>';
 2881:     }
 2882:     my $queuedselfenroll = &Apache::loncoursequeueadmin::queued_selfenrollment(1);
 2883:     if ($queuedselfenroll) {
 2884:         $output .= '<p><b>'.&mt('Enrollment requests').'</b><br />'.
 2885:                    $queuedselfenroll.'<br /></p>';
 2886:     }
 2887:     if ($env{'environment.canrequest.author'}) {
 2888:         unless (&Apache::loncoursequeueadmin::is_active_author()) {
 2889:             my $requestauthor;
 2890:             my ($status,$timestamp) = split(/:/,$env{'environment.requestauthorqueued'});
 2891:             if (($status eq 'approval') || ($status eq 'approved')) {
 2892:                 $output .= '<p><b>'.&mt('Author role request').'</b><br />';
 2893:                 if ($status eq 'approval') {
 2894:                     $output .= &mt('A request for Authoring Space submitted on [_1] is awaiting approval',
 2895:                                   &Apache::lonlocal::locallocaltime($timestamp));
 2896:                 } elsif ($status eq 'approved') {
 2897:                     my %roleshash =
 2898:                         &Apache::lonnet::get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',
 2899:                                                       ['active'],['au'],[$env{'user.domain'}]);
 2900:                     if (keys(%roleshash)) {
 2901:                         $output .= '<span class="LC_info">'.
 2902:                                    &mt('Your request for an author role has been approved.').'<br />'.
 2903:                                    &mt('Use the "Check for changes" link to update your list of roles.').
 2904:                                    '</span>';
 2905:                     }
 2906:                 }
 2907:                 $output .= '</p>';
 2908:             }
 2909:         }
 2910:     }
 2911:     unless ($output) {
 2912:         if ($env{'environment.canrequest.author'} || $env{'environment.canrequest.official'} ||
 2913:             $env{'environment.canrequest.unofficial'} || $env{'environment.canrequest.community'}) {
 2914:             $output = &mt('No requests for courses, communities or authoring currently queued');
 2915:         } else {
 2916:             $output = &mt('No enrollment requests currently queued awaiting approval');
 2917:         }
 2918:     }
 2919:     return '<div class="LC_left_float"><fieldset><legend>'.&mt('Queued requests').'</legend>'.
 2920:            $output.'</fieldset></div><br clear="all" />';
 2921: }
 2922: 
 2923: 1;
 2924: __END__
 2925: 
 2926: =head1 NAME
 2927: 
 2928: Apache::lonroles - User Roles Screen
 2929: 
 2930: =head1 SYNOPSIS
 2931: 
 2932: Invoked by /etc/httpd/conf/srm.conf:
 2933: 
 2934:  <Location /adm/roles>
 2935:  PerlAccessHandler       Apache::lonacc
 2936:  SetHandler perl-script
 2937:  PerlHandler Apache::lonroles
 2938:  ErrorDocument     403 /adm/login
 2939:  ErrorDocument	  500 /adm/errorhandler
 2940:  </Location>
 2941: 
 2942: =head1 OVERVIEW
 2943: 
 2944: =head2 Choosing Roles
 2945: 
 2946: C<lonroles> is a handler that allows a user to switch roles in
 2947: mid-session. LON-CAPA attempts to work with "No Role Specified", the
 2948: default role that a user has before selecting a role, as widely as
 2949: possible, but certain handlers for example need specification which
 2950: course they should act on, etc. Both in this scenario, and when the
 2951: handler determines via C<lonnet>'s C<&allowed> function that a certain
 2952: action is not allowed, C<lonroles> is used as error handler. This
 2953: allows the user to select another role which may have permission to do
 2954: what they were trying to do.
 2955: 
 2956: =begin latex
 2957: 
 2958: \begin{figure}
 2959: \begin{center}
 2960: \includegraphics[width=0.45\paperwidth,keepaspectratio]{Sample_Roles_Screen}
 2961:   \caption{\label{Sample_Roles_Screen}Sample Roles Screen} 
 2962: \end{center}
 2963: \end{figure}
 2964: 
 2965: =end latex
 2966: 
 2967: =head2 Role Initialization
 2968: 
 2969: 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.
 2970: 
 2971: =head1 INTRODUCTION
 2972: 
 2973: This module enables a user to select what role he wishes to
 2974: operate under (instructor, student, teaching assistant, course
 2975: coordinator, etc).  These roles are pre-established by the actions
 2976: of upper-level users.
 2977: 
 2978: This is part of the LearningOnline Network with CAPA project
 2979: described at http://www.lon-capa.org.
 2980: 
 2981: =head1 HANDLER SUBROUTINE
 2982: 
 2983: This routine is called by Apache and mod_perl.
 2984: 
 2985: =over 4
 2986: 
 2987: =item *
 2988: 
 2989: Roles Initialization (yes/no)
 2990: 
 2991: =item *
 2992: 
 2993: Get Error Message from Environment
 2994: 
 2995: =item *
 2996: 
 2997: Who is this?
 2998: 
 2999: =item *
 3000: 
 3001: Generate Page Output
 3002: 
 3003: =item *
 3004: 
 3005: Choice or no choice
 3006: 
 3007: =item *
 3008: 
 3009: Table
 3010: 
 3011: =item *
 3012: 
 3013: Privileges
 3014: 
 3015: =back
 3016: 
 3017: =cut

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