File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.336: download - view: text, annotated - select for diffs
Tue Jan 9 15:44:43 2018 UTC (6 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Include use of "Check for changes" link as mechanism to update roles list,
  in case where an unprivileged user has no roles listed.

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

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