File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.304: download - view: text, annotated - select for diffs
Tue May 20 20:36:16 2014 UTC (10 years, 1 month ago) by musolffc
Branches: MAIN
CVS tags: HEAD
Calls critical_redirect() to check for critical messages

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

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