File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.269.2.34: download - view: text, annotated - select for diffs
Fri May 19 19:53:00 2017 UTC (6 years, 11 months ago) by raeburn
Branches: version_2_11_X
CVS tags: version_2_11_2_uiuc, version_2_11_2_msu, version_2_11_2_educog, version_2_11_2
- For 2.11
  - Backport 1.330, 1.331

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

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