File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.312: download - view: text, annotated - select for diffs
Tue Jun 9 21:22:44 2015 UTC (9 years ago) by damieng
Branches: MAIN
CVS tags: HEAD
fixed bug 6782, and escaped most localized messages used in Javascript blocks to make sure bugs like that do not happen again

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

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