File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.343: download - view: text, annotated - select for diffs
Tue Feb 4 01:27:04 2020 UTC (4 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Suggest use of "Check for changes" link as way to update roles list, when
  an unprivileged user has no roles listed, and it is more than 10 minutes
  since last check (or log-in).

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

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