File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.323: download - view: text, annotated - select for diffs
Mon Jan 2 19:44:11 2017 UTC (7 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Ad hoc roles for helpdesk personnel.
  - Domain configuration for:
    - which user(s) with dh role in domain may use each ad hoc role.
      - set by institutional status, or by include specific people, or by
        exclude specific people.
    - assign role description (displayed on Roles page, and at top left of
      page, when role active).
    - assign role order (numerical).
  - Course configuration (available for editing by course owner, and viewing
    by co-owner(s).
    - can override domain defaults for which dh role users can use ad hoc role(s)
      in course.
    - can override domain defaults set for course-level privileges for ad hoc
      role(s).

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

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