File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.338: download - view: text, annotated - select for diffs
Mon May 28 23:26:12 2018 UTC (5 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LON-CAPA as LTI Provider
  - Support LTI Extension: Context Memberships Service, whereby launch of
    Consumer can trigger Provider to request course roster.
  - Code moved from ltiauth.pm to routines in ltiutils.pm:
    &get_lc_roles(), &create_user() and &enrolluser(); &create_passwd() routine
    also moved.
  - Code moved from &parse_roster() to &get_roster() in ltiutils.pm.
  - New routines: &batchaddroster(), &datechange_check(), &store_passbackurl()
    added to support roster updates, (including saving user-specific values
    for: lis_result_sourcedid, used for passback of grades to Consumer.

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

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