File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.269.2.29: download - view: text, annotated - select for diffs
Wed Nov 9 17:48:38 2016 UTC (7 years, 7 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.321, 1.322

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

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