File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.240.2.4: download - view: text, annotated - select for diffs
Sun Dec 20 04:11:27 2009 UTC (14 years, 8 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3.
 - Eliminate duplicate code.
 - Set request.role.adv before calling lonuserstate::readmap() so order
    randomized when CC is viewing as a student (if randomorder set for folder).

    1: # The LearningOnline Network with CAPA
    2: # User Roles Screen
    3: #
    4: # $Id: lonroles.pm,v 1.240.2.4 2009/12/20 04:11:27 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. C<lonroles> can also be accessed via the
   61: B<CRS> button in the Remote Control. 
   62: 
   63: =begin latex
   64: 
   65: \begin{figure}
   66: \begin{center}
   67: \includegraphics[width=0.45\paperwidth,keepaspectratio]{Sample_Roles_Screen}
   68:   \caption{\label{Sample_Roles_Screen}Sample Roles Screen} 
   69: \end{center}
   70: \end{figure}
   71: 
   72: =end latex
   73: 
   74: =head2 Role Initialization
   75: 
   76: 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.
   77: 
   78: =head1 INTRODUCTION
   79: 
   80: This module enables a user to select what role he wishes to
   81: operate under (instructor, student, teaching assistant, course
   82: coordinator, etc).  These roles are pre-established by the actions
   83: of upper-level users.
   84: 
   85: This is part of the LearningOnline Network with CAPA project
   86: described at http://www.lon-capa.org.
   87: 
   88: =head1 HANDLER SUBROUTINE
   89: 
   90: This routine is called by Apache and mod_perl.
   91: 
   92: =over 4
   93: 
   94: =item *
   95: 
   96: Roles Initialization (yes/no)
   97: 
   98: =item *
   99: 
  100: Get Error Message from Environment
  101: 
  102: =item *
  103: 
  104: Who is this?
  105: 
  106: =item *
  107: 
  108: Generate Page Output
  109: 
  110: =item *
  111: 
  112: Choice or no choice
  113: 
  114: =item *
  115: 
  116: Table
  117: 
  118: =item *
  119: 
  120: Privileges
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: 
  127: package Apache::lonroles;
  128: 
  129: use strict;
  130: use Apache::lonnet;
  131: use Apache::lonuserstate();
  132: use Apache::Constants qw(:common);
  133: use Apache::File();
  134: use Apache::lonmenu;
  135: use Apache::loncommon;
  136: use Apache::lonhtmlcommon;
  137: use Apache::lonannounce;
  138: use Apache::lonlocal;
  139: use Apache::lonpageflip();
  140: use Apache::lonnavdisplay();
  141: use Apache::lonmainmenu();
  142: use GDBM_File;
  143: use LONCAPA qw(:DEFAULT :match);
  144: use HTML::Entities;
  145:  
  146: 
  147: sub redirect_user {
  148:     my ($r,$title,$url,$msg,$launch_nav) = @_;
  149:     $msg = $title if (! defined($msg));
  150:     &Apache::loncommon::content_type($r,'text/html');
  151:     &Apache::loncommon::no_cache($r);
  152:     $r->send_http_header;
  153:     my $swinfo=&Apache::lonmenu::rawconfig();
  154:     my $navwindow;
  155:     if ($launch_nav eq 'on') {
  156: 	$navwindow.=&Apache::lonnavdisplay::launch_win('now',undef,undef,
  157: 						       ($url =~ m-^/adm/whatsnew-));
  158:     } else {
  159: 	$navwindow.=&Apache::lonnavmaps::close();
  160:     }
  161: 
  162:     # Breadcrumbs
  163:     my $brcrum = [{'href' => $url,
  164:                    'text' => 'Switching Role'},];
  165:     my $start_page = &Apache::loncommon::start_page('Switching Role',undef,
  166:                                                     {'redirect' => [1,$url],
  167:                                                      'bread_crumbs' => $brcrum,});
  168:     my $end_page   = &Apache::loncommon::end_page();
  169: 
  170: # Note to style police: 
  171: # This must only replace the spaces, nothing else, or it bombs elsewhere.
  172:     $url=~s/ /\%20/g;
  173:     $r->print(<<ENDREDIR);
  174: $start_page
  175: <script type="text/javascript">
  176: // <![CDATA[
  177: $swinfo
  178: // ]]>
  179: </script>
  180: $navwindow
  181: <p>$msg</p>
  182: $end_page
  183: ENDREDIR
  184:     return;
  185: }
  186: 
  187: sub error_page {
  188:     my ($r,$error,$dest)=@_;
  189:     &Apache::loncommon::content_type($r,'text/html');
  190:     &Apache::loncommon::no_cache($r);
  191:     $r->send_http_header;
  192:     return OK if $r->header_only;
  193:     # Breadcrumbs
  194:     my $brcrum = [{'href' => $dest,
  195:                    'text' => 'Problems during Course Initialization'},];
  196:     $r->print(&Apache::loncommon::start_page('Problems during Course Initialization',
  197:                                              undef,
  198:                                              {'bread_crumbs' => $brcrum,})
  199:     );
  200:     $r->print(
  201:         '<script type="text/javascript">'.
  202:         '// <![CDATA['.
  203:         &Apache::lonmenu::rawconfig().
  204:         '// ]]>'.
  205:         '</script>'.
  206: 	      '<p class="LC_error">'.&mt('The following problems occurred:').
  207:           '<br />'.
  208: 	      $error.
  209: 	      '</p><br /><a href="'.$dest.'">'.&mt('Continue').'</a>'
  210:     );
  211:     $r->print(&Apache::loncommon::end_page());
  212: }
  213: 
  214: sub handler {
  215: 
  216:     my $r = shift;
  217: 
  218:     my $now=time;
  219:     my $then=$env{'user.login.time'};
  220:     my $refresh=$env{'user.refresh.time'};
  221:     if (!$refresh) {
  222:         $refresh = $then;
  223:     }
  224:     my $envkey;
  225:     my %dcroles = ();
  226:     my $numdc = &check_fordc(\%dcroles,$then);
  227:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
  228:     my $custommenu = &Apache::loncommon::needs_gci_custom();
  229: 
  230: # ================================================================== Roles Init
  231:     if ($env{'form.selectrole'}) {
  232: 
  233:         my $locknum=&Apache::lonnet::get_locks();
  234:         if ($locknum) { return 409; }
  235: 
  236:         if ($env{'form.newrole'}) {
  237:             $env{'form.'.$env{'form.newrole'}}=1;
  238: 	}
  239: 	if ($env{'request.course.id'}) {
  240:             # Check if user is CC trying to select a course role
  241:             if ($env{'form.switchrole'}) {
  242:                 if (!defined($env{'user.role.'.$env{'form.switchrole'}})) {
  243:                     &adhoc_course_role($refresh,$then);
  244:                 }
  245:             }
  246: 	    my %temp=('logout_'.$env{'request.course.id'} => time);
  247: 	    &Apache::lonnet::put('email_status',\%temp);
  248: 	    &Apache::lonnet::delenv('user.state.'.$env{'request.course.id'});
  249: 	}
  250: 	&Apache::lonnet::appenv({"request.course.id"   => '',
  251: 			 	 "request.course.fn"   => '',
  252: 				 "request.course.uri"  => '',
  253: 				 "request.course.sec"  => '',
  254: 				 "request.role"        => 'cm',
  255:                                  "request.role.adv"    => $env{'user.adv'},
  256: 				 "request.role.domain" => $env{'user.domain'}});
  257: # Check if user is a DC trying to enter a course or author space and needs privs to be created
  258:         if ($numdc > 0) {
  259:             foreach my $envkey (keys %env) {
  260: # Is this an ad-hoc Coordinator role?
  261:                 if (my ($ccrole,$domain,$coursenum) =
  262: 		    ($envkey =~ m-^form\.(cc|co)\./($match_domain)/($match_courseid)$-)) {
  263:                     if ($dcroles{$domain}) {
  264:                         &Apache::lonnet::check_adhoc_privs($domain,$coursenum,
  265:                                                            $then,$refresh,$now,$ccrole);
  266:                     }
  267:                     last;
  268:                 }
  269: # Is this an ad-hoc CA-role?
  270:                 if (my ($domain,$user) =
  271: 		    ($envkey =~ m-^form\.ca\./($match_domain)/($match_username)$-)) {
  272:                     if (($domain eq $env{'user.domain'}) && ($user eq $env{'user.name'})) {
  273:                         delete($env{$envkey});
  274:                         $env{'form.au./'.$domain.'/'} = 1;
  275:                         my ($server_status,$home) = &check_author_homeserver($user,$domain);
  276:                         if ($server_status eq 'switchserver') {
  277:                             my $trolecode = 'au./'.$domain.'/';
  278:                             my $switchserver = '/adm/switchserver?otherserver='.$home.'&role='.$trolecode;
  279:                             $r->internal_redirect($switchserver);
  280:                         }
  281:                         last;
  282:                     }
  283:                     if (my ($castart,$caend) = ($env{'user.role.ca./'.$domain.'/'.$user} =~ /^(\d*)\.(\d*)$/)) {
  284:                         if (((($castart) && ($castart < $now)) || !$castart) && 
  285:                             ((!$caend) || (($caend) && ($caend > $now)))) {
  286:                             my ($server_status,$home) = &check_author_homeserver($user,$domain);
  287:                             if ($server_status eq 'switchserver') {
  288:                                 my $trolecode = 'ca./'.$domain.'/'.$user;
  289:                                 my $switchserver = '/adm/switchserver?otherserver='.$home.'&role='.$trolecode;
  290:                                 $r->internal_redirect($switchserver);
  291:                             }
  292:                             last;
  293:                         }
  294:                     }
  295:                     # Check if author blocked ca-access
  296:                     my %blocked=&Apache::lonnet::get('environment',['domcoord.author'],$domain,$user);
  297:                     if ($blocked{'domcoord.author'} eq 'blocked') {
  298:                         delete($env{$envkey});
  299:                         $env{'user.error.msg'}=':::1:User '.$user.' in domain '.$domain.' blocked domain coordinator access';
  300:                         last;
  301:                     }
  302:                     if ($dcroles{$domain}) {
  303:                         my ($server_status,$home) = &check_author_homeserver($user,$domain);
  304:                         if (($server_status eq 'ok') || ($server_status eq 'switchserver')) {
  305:                             &Apache::lonnet::check_adhoc_privs($domain,$user,$then,
  306:                                                                $refresh,$now,'ca');
  307:                             if ($server_status eq 'switchserver') {
  308:                                 my $trolecode = 'ca./'.$domain.'/'.$user; 
  309:                                 my $switchserver = '/adm/switchserver?'
  310:                                                   .'otherserver='.$home.'&role='.$trolecode;
  311:                                 $r->internal_redirect($switchserver);
  312:                             }
  313:                         } else {
  314:                             delete($env{$envkey});
  315:                         }
  316:                     } else {
  317:                         delete($env{$envkey});
  318:                     }
  319:                     last;
  320:                 }
  321:             }
  322:         }
  323:         if (($env{'form.cm'}) && ($env{'form.orgurl'})) { 
  324:             $r->internal_redirect($env{'form.orgurl'});
  325:         }
  326:         foreach $envkey (keys %env) {
  327:             next if ($envkey!~/^user\.role\./);
  328:             my ($where,$trolecode,$role,$tstatus,$tend,$tstart);
  329:             &Apache::lonnet::role_status($envkey,$then,$refresh,$now,\$role,\$where,
  330:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
  331:             if ($env{'form.'.$trolecode}) {
  332: 		if ($tstatus eq 'is') {
  333: 		    $where=~s/^\///;
  334: 		    my ($cdom,$cnum,$csec)=split(/\//,$where);
  335: # check for course groups
  336:                     my %coursegroups = &Apache::lonnet::get_active_groups(
  337:                           $env{'user.domain'},$env{'user.name'},$cdom, $cnum);
  338:                     my $cgrps = join(':',keys(%coursegroups));
  339: 
  340: # store role if recent_role list being kept
  341:                     if ($env{'environment.recentroles'}) {
  342:                         my %frozen_roles =
  343:                            &Apache::lonhtmlcommon::get_recent_frozen('roles',$env{'environment.recentrolesn'});
  344: 			&Apache::lonhtmlcommon::store_recent('roles',
  345: 							     $trolecode,' ',$frozen_roles{$trolecode});
  346:                     }
  347: 
  348: 
  349: # check for keyed access
  350: 		    if (($role eq 'st') && 
  351:                        ($env{'course.'.$cdom.'_'.$cnum.'.keyaccess'} eq 'yes')) {
  352: # who is key authority?
  353: 			my $authdom=$cdom;
  354: 			my $authnum=$cnum;
  355: 			if ($env{'course.'.$cdom.'_'.$cnum.'.keyauth'}) {
  356: 			    ($authnum,$authdom)=
  357: 				split(/:/,$env{'course.'.$cdom.'_'.$cnum.'.keyauth'});
  358: 			}
  359: # check with key authority
  360: 			unless (&Apache::lonnet::validate_access_key(
  361: 				     $env{'environment.key.'.$cdom.'_'.$cnum},
  362: 					     $authdom,$authnum)) {
  363: # there is no valid key
  364: 			     if ($env{'form.newkey'}) {
  365: # student attempts to register a new key
  366: 				 &Apache::loncommon::content_type($r,'text/html');
  367: 				 &Apache::loncommon::no_cache($r);
  368: 				 $r->send_http_header;
  369: 				 my $swinfo=&Apache::lonmenu::rawconfig();
  370: 				 my $start_page=&Apache::loncommon::start_page
  371: 				    ('Verifying Access Key to Unlock this Course');
  372: 				 my $end_page=&Apache::loncommon::end_page();
  373: 				 my $buttontext=&mt('Enter Course');
  374: 				 my $message=&mt('Successfully registered key');
  375: 				 my $assignresult=
  376: 				     &Apache::lonnet::assign_access_key(
  377: 						     $env{'form.newkey'},
  378: 						     $authdom,$authnum,
  379: 						     $cdom,$cnum,
  380:                                                      $env{'user.domain'},
  381: 						     $env{'user.name'},
  382:                                                      &mt('Assigned from [_1] at [_2] for [_3]'
  383:                                                         ,$ENV{'REMOTE_ADDR'}
  384:                                                         ,&Apache::lonlocal::locallocaltime()
  385:                                                         ,$trolecode)
  386:                                                      );
  387: 				 unless ($assignresult eq 'ok') {
  388: 				     $assignresult=~s/^error\:\s*//;
  389: 				     $message=&mt($assignresult).
  390: 				     '<br /><a href="/adm/logout">'.
  391: 				     &mt('Logout').'</a>';
  392: 				     $buttontext=&mt('Re-Enter Key');
  393: 				 }
  394: 				 $r->print(<<ENDENTEREDKEY);
  395: $start_page
  396: <script type="text/javascript">
  397: // <![CDATA[
  398: $swinfo
  399: // ]]>
  400: </script>
  401: <form action="" method="post">
  402: <input type="hidden" name="selectrole" value="1" />
  403: <input type="hidden" name="$trolecode" value="1" />
  404: <span class="LC_fontsize_large">$message</span><br />
  405: <input type="submit" value="$buttontext" />
  406: </form>
  407: $end_page
  408: ENDENTEREDKEY
  409:                                  return OK;
  410: 			     } else {
  411: # print form to enter a new key
  412: 				 &Apache::loncommon::content_type($r,'text/html');
  413: 				 &Apache::loncommon::no_cache($r);
  414: 				 $r->send_http_header;
  415: 				 my $swinfo=&Apache::lonmenu::rawconfig();
  416: 				 my $start_page=&Apache::loncommon::start_page
  417: 				    ('Enter Access Key to Unlock this Course');
  418: 				 my $end_page=&Apache::loncommon::end_page();
  419: 				 $r->print(<<ENDENTERKEY);
  420: $start_page
  421: <script type="text/javascript">
  422: // <![CDATA[
  423: $swinfo
  424: // ]]>
  425: </script>
  426: <form action="" method="post">
  427: <input type="hidden" name="selectrole" value="1" />
  428: <input type="hidden" name="$trolecode" value="1" />
  429: <input type="text" size="20" name="newkey" value="$env{'form.newkey'}" />
  430: <input type="submit" value="Enter key" />
  431: </form>
  432: $end_page
  433: ENDENTERKEY
  434: 				 return OK;
  435: 			     }
  436: 			 }
  437: 		     }
  438: 		    &Apache::lonnet::log($env{'user.domain'},
  439: 					 $env{'user.name'},
  440: 					 $env{'user.home'},
  441: 					 "Role ".$trolecode);
  442: 		    
  443: 		    &Apache::lonnet::appenv(
  444: 					   {'request.role'        => $trolecode,
  445: 					    'request.role.domain' => $cdom,
  446: 					    'request.course.sec'  => $csec,
  447:                                             'request.course.groups' => $cgrps});
  448:                     my $tadv=0;
  449: 
  450: 		    if (($cnum) && ($role ne 'ca') && ($role ne 'aa')) {
  451:                         my $msg;
  452:                         if (&Apache::lonnet::allowed('adv') eq 'F') { $tadv=1; }
  453:                         &Apache::lonnet::appenv({'request.role.adv'=>$tadv});
  454: 			my ($furl,$ferr)=
  455: 			    &Apache::lonuserstate::readmap($cdom.'/'.$cnum);
  456: 			if (($env{'form.orgurl'}) && 
  457: 			    ($env{'form.orgurl'}!~/^\/adm\/flip/)) {
  458: 			    my $dest=$env{'form.orgurl'};
  459:                             if ($env{'form.symb'}) {
  460:                                 if ($dest =~ /\?/) {
  461:                                     $dest .= '&';
  462:                                 } else {
  463:                                     $dest .= '?'
  464:                                 }
  465:                                 $dest .= 'symb='.$env{'form.symb'};
  466:                             }
  467:                             if (($ferr) && ($tadv)) {
  468: 				&error_page($r,$ferr,$dest);
  469: 			    } else {
  470: 				$r->internal_redirect($dest);
  471: 			    }
  472: 			    return OK;
  473: 			} else {
  474: 			    if (!$env{'request.course.id'}) {
  475: 				&Apache::lonnet::appenv(
  476: 				      {"request.course.id"  => $cdom.'_'.$cnum});
  477: 				$furl='/adm/roles?tryagain=1';
  478:                 $msg='<p><span class="LC_error">'
  479:                     .&mt('Could not initialize [_1] at this time.',
  480:                          $env{'course.'.$cdom.'_'.$cnum.'.description'})
  481:                     .'</span></p>'
  482:                     .'<p>'.&mt('Please try again.').'</p>'
  483:                     .'<p>'.$ferr.'</p>';
  484: 			    }
  485: 
  486: 			    if (($ferr) && ($tadv)) {
  487: 				&error_page($r,$ferr,$furl);
  488: 			    } else {
  489: 				# Check to see if the user is a CC entering a course 
  490: 				# for the first time
  491: 				my (undef, undef, $role, $courseid) = split(/\./, $envkey);
  492: 				if (substr($courseid, 0, 1) eq '/') {
  493: 				    $courseid = substr($courseid, 1);
  494: 				}
  495: 				$courseid =~ s/\//_/;
  496: 				if (($cdom ne 'gcitest') && (($role eq 'cc') || ($role eq 'co')) 
  497:                                     && ($env{'course.' . $courseid .'.course.helper.not.run'})) { 
  498: 				    $furl = "/adm/helper/course.initialization.helper";
  499: 				    # Send the user to the course they selected
  500: 				} elsif ($env{'request.course.id'}) {
  501:                                     if ($env{'form.destinationurl'}) {
  502:                                         my $dest = $env{'form.destinationurl'};
  503:                                         if ($env{'form.destsymb'} ne '') {
  504:                                             my $esc_symb = &HTML::Entities::encode($env{'form.destsymb'},'"<>&');
  505:                                             $dest .= '?symb='.$esc_symb;
  506:                                         }
  507:                                         &redirect_user($r,&mt('Entering [_1]',
  508:                                                       $env{'course.'.$courseid.'.description'}),
  509:                                                $dest,$msg,
  510:                                                $env{'environment.remotenavmap'});
  511:                                         return OK;
  512:                                     }
  513: 				    if (&Apache::lonnet::allowed('whn',
  514: 								 $env{'request.course.id'})
  515: 					|| &Apache::lonnet::allowed('whn',
  516: 								    $env{'request.course.id'}.'/'
  517: 								    .$env{'request.course.sec'})
  518: 					) {
  519: 					my $startpage = &courseloadpage($courseid);
  520: 					unless (($startpage eq 'firstres') || ($cdom eq 'gcitest')) {
  521: 					    $msg = &mt('Entering [_1] ...',
  522: 						       $env{'course.'.$courseid.'.description'});
  523: 					    &redirect_user($r,&mt('New in course'),
  524: 							   '/adm/whatsnew?refpage=start',$msg,
  525: 							   $env{'environment.remotenavmap'});
  526: 					    return OK;
  527: 					}
  528: 				    }
  529: 				}
  530: # Are we allowed to look at the first resource?
  531: 				if ($furl !~ m|^/adm/|) {
  532: # Guess not ...
  533: 				    $furl=&Apache::lonpageflip::first_accessible_resource();
  534: 				}
  535:                                 if (($cdom eq 'gcitest') && ($custommenu)) {
  536:                                     $furl = '/adm/navmaps';
  537:                                 }
  538:                                 $msg = &mt('Entering [_1] ...',
  539: 					   $env{'course.'.$courseid.'.description'});
  540: 				&redirect_user($r,&mt('Entering [_1]',
  541: 						      $env{'course.'.$courseid.'.description'}),
  542: 					       $furl,$msg,
  543: 					       $env{'environment.remotenavmap'});
  544: 			    }
  545: 			    return OK;
  546: 			}
  547: 		    }
  548:                     #
  549:                     # Send the user to the construction space they selected
  550:                     if ($role =~ /^(au|ca|aa)$/) {
  551:                         my $redirect_url = '/priv/';
  552:                         if ($role eq 'au') {
  553:                             $redirect_url.=$env{'user.name'};
  554:                         } else {
  555:                             $where =~ /\/(.*)$/;
  556:                             $redirect_url .= $1;
  557:                         }
  558:                         $redirect_url .= '/';
  559:                         &redirect_user($r,&mt('Entering Construction Space'),
  560:                                        $redirect_url);
  561:                         return OK;
  562:                     }
  563:                     if ($role eq 'dc') {
  564:                         my $redirect_url = '/adm/menu/';
  565:                         &redirect_user($r,&mt('Loading Domain Coordinator Menu'),
  566:                                        $redirect_url);
  567:                         return OK;
  568:                     }
  569:                     if ($role eq 'sc') {
  570:                         my $redirect_url = '/adm/grades?command=scantronupload';
  571:                         &redirect_user($r,&mt('Loading Data Upload Page'),
  572:                                        $redirect_url);
  573:                         return OK;
  574:                     }
  575: 		}
  576:             }
  577:         }
  578:     }
  579: 
  580: # =============================================================== No Roles Init
  581: 
  582:     &Apache::loncommon::content_type($r,'text/html');
  583:     &Apache::loncommon::no_cache($r);
  584:     $r->send_http_header;
  585:     return OK if $r->header_only;
  586: 
  587:     my ($crumbtext,$pagetitle,$recent,$show_course);
  588:     my $noscript='<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 />';
  589:     if ($custommenu) {
  590:         my $start_page = &Apache::loncommon::start_page('Main Menu',undef,
  591:                                                         {'bread_crumbs' => 1});
  592:         $r->print(<<"ENDCUSTOM");
  593: $start_page
  594: <br />
  595: <noscript>
  596: $noscript
  597: </noscript>
  598: ENDCUSTOM
  599:     } else {
  600:         $crumbtext = 'User Roles';
  601:         $pagetitle = 'My Roles';
  602:         $recent = &mt('Recent Roles');
  603:         $show_course=&Apache::loncommon::show_course();
  604:         if ($show_course) {
  605:             $crumbtext = 'Courses';
  606:             $pagetitle = 'My Courses';
  607:             $recent = &mt('Recent Courses');
  608:         }
  609:         my $brcrum =[{href=>"/adm/roles",text=>$crumbtext}];
  610:         my $swinfo=&Apache::lonmenu::rawconfig();
  611:         my $start_page=&Apache::loncommon::start_page($pagetitle,undef,{bread_crumbs=>$brcrum});
  612:         my $standby=&mt('Role selected. Please stand by.');
  613:         $standby=~s/\n/\\n/g;
  614:         $r->print(<<ENDHEADER);
  615: $start_page
  616: <br />
  617: <noscript>
  618: $noscript
  619: </noscript>
  620: <script type="text/javascript">
  621: // <![CDATA[
  622: $swinfo
  623: window.focus();
  624: 
  625: active=true;
  626: 
  627: function enterrole (thisform,rolecode,buttonname) {
  628:     if (active) {
  629: 	active=false;
  630:         document.title='$standby';
  631:         window.status='$standby';
  632: 	thisform.newrole.value=rolecode;
  633: 	thisform.submit();
  634:     } else {
  635:        alert('$standby');
  636:     }   
  637: }
  638: // ]]>
  639: </script>
  640: ENDHEADER
  641:     }
  642: 
  643: # ------------------------------------------ Get Error Message from Environment
  644: 
  645:     my ($fn,$priv,$nochoose,$error,$msg)=split(/:/,$env{'user.error.msg'});
  646:     if ($env{'user.error.msg'}) {
  647: 	$r->log_reason(
  648:    "$msg for $env{'user.name'} domain $env{'user.domain'} access $priv",$fn);
  649:     }
  650: 
  651: # ------------------------------------------------- Can this user re-init, etc?
  652: 
  653:     my $advanced=$env{'user.adv'};
  654:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['tryagain']);
  655:     my $tryagain=$env{'form.tryagain'};
  656:     my $reinit=$env{'user.reinit'};
  657:     delete $env{'user.reinit'};
  658: 
  659: # -------------------------------------------------------- Generate Page Output
  660: # --------------------------------------------------------------- Error Header?
  661:     if ($error) {
  662:         $r->print("<h1>".&mt('LON-CAPA Access Control')."</h1>");
  663: 	$r->print("<!-- LONCAPAACCESSCONTROLERRORSCREEN --><hr /><pre>");
  664: 	if ($priv ne '') {
  665:             $r->print(&mt('Access  : ').&Apache::lonnet::plaintext($priv)."\n");
  666: 	}
  667: 	if ($fn ne '') {
  668:             $r->print(&mt('Resource: ').&Apache::lonenc::check_encrypt($fn)."\n");
  669: 	}
  670: 	if ($msg ne '') {
  671:             $r->print(&mt('Action  : ').$msg."\n");
  672: 	}
  673: 	$r->print("</pre><hr />");
  674: 	my $url=$fn;
  675: 	my $last;
  676: 	if (tie(my %hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
  677: 		&GDBM_READER(),0640)) {
  678: 	    $last=$hash{'last_known'};
  679: 	    untie(%hash);
  680: 	}
  681: 	if ($last) { $fn.='?symb='.&escape($last); }
  682: 
  683: 	&Apache::londocs::changewarning($r,undef,'You have modified your course recently, [_1] may fix this access problem.',
  684: 					&Apache::lonenc::check_encrypt($fn));
  685:     } else {
  686:         if ($env{'user.error.msg'}) {
  687:             if ($reinit) {
  688:                 $r->print(
  689:  '<h3><span class="LC_error">'.
  690:  &mt('As your session file for the course or community has expired, you will need to re-select it.').'</span></h3>');
  691:             } else {
  692: 	        $r->print(
  693:  '<h3><span class="LC_error">'.
  694:  &mt('You need to choose another user role or enter a specific course or community for this function.').
  695:  '</span></h3>');
  696: 	    }
  697:         }
  698:     }
  699: # -------------------------------------------------------- Choice or no choice?
  700:     if ($nochoose) {
  701: 	$r->print("<h2>".&mt('Sorry ...')."</h2>\n<span class='LC_error'>".
  702: 		  &mt('This action is currently not authorized.').'</span>'.
  703: 		  &Apache::loncommon::end_page());
  704: 	return OK;
  705:     } else {
  706:         if (($ENV{'REDIRECT_QUERY_STRING'}) && ($fn)) {
  707:     	    $fn.='?'.$ENV{'REDIRECT_QUERY_STRING'};
  708:         }
  709:         unless ($custommenu) {
  710:             $r->print('<form method="post" name="rolechoice" action="'.(($fn)?$fn:$r->uri).'">');
  711:             $r->print('<input type="hidden" name="orgurl" value="'.$fn.'" />');
  712:             $r->print('<input type="hidden" name="selectrole" value="1" />');
  713:             $r->print('<input type="hidden" name="newrole" value="" />');
  714:         }
  715:     }
  716: 
  717:     my (%roletext,%sortrole,%roleclass,%futureroles,%timezones);
  718:     my ($countactive,$countfuture,$inrole,$possiblerole) = 
  719:         &gather_roles($then,$refresh,$now,$reinit,$nochoose,\%roletext,\%sortrole,\%roleclass,
  720:                       \%futureroles,\%timezones);
  721: 
  722:     $refresh = $now;
  723:     &Apache::lonnet::appenv({'user.refresh.time'  => $refresh});
  724:     if ($custommenu) {
  725:         my %courses = &Apache::loncommon::existing_gcitest_courses();
  726:         $env{'browser.interface'}='faketextual';
  727:         $env{'environment.remote'}='off';
  728:         my $numcourses = keys(%courses);
  729:         my $switcher;
  730:         if ($numcourses > 0) {
  731:             $switcher = &Apache::lonmainmenu::gcitest_switcher(%courses);
  732:             my $current;
  733:             if ($env{'request.course.id'}) {
  734:                 $current = 'cc./'.$env{'course.'.$env{'request.course.id'}.'.domain'}.
  735:                            '/'.$env{'course.'.$env{'request.course.id'}.'.num'};
  736:             }
  737:             my $switcher_js = &Apache::lonmainmenu::gcitest_switcher_js($current,$numcourses);
  738:             $r->print(<<"ENDSCRIPT");
  739: <script type="text/javascript">
  740: // <![CDATA[
  741: $switcher_js
  742: // ]]>
  743: </script>
  744: ENDSCRIPT
  745:         }
  746:         $r->print(&Apache::lonmenu::inlinemenu('gcicustom',$switcher).
  747:                   &Apache::loncommon::end_page());
  748:         return OK;
  749:     }
  750:     if ($env{'user.adv'}) {
  751:         $r->print('<p><label><input type="checkbox" name="showall"');
  752:         if ($env{'form.showall'}) { $r->print(' checked="checked" '); }
  753:         $r->print(' />'.&mt('Show all roles').'</label>'
  754:                  .' <input type="submit" value="'.&mt('Update display').'" />'
  755:                  .'</p>');
  756:     } else {
  757:         if ($countactive > 0) {
  758:             &queued_selfenrollment($r);
  759:             my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
  760:             my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&'); 
  761:             $r->print(
  762:                 '<p>'
  763:                .&mt('[_1]Visit the [_2]Course/Community Catalog[_3]'
  764:                    .' to view all [_4] LON-CAPA courses and communities.'
  765:                    ,'<b>'
  766:                    ,'<a href="/adm/coursecatalog?showdom='.$esc_dom.'">'
  767:                    ,'</a></b>',$domdesc)
  768:                .'<br />'
  769:                .&mt('If a course or community is [_1]not[_2] in your list of current courses and communities below,'
  770:                    .' you may be able to enroll if self-enrollment is permitted.'
  771:                    ,'<b>','</b>')
  772:                .'</p>'
  773:             );
  774:         }
  775:     }
  776: 
  777: # No active roles
  778:     if ($countactive==0) {
  779: 	if ($inrole) {
  780: 	    $r->print('<h2>'.&mt('Currently no additional roles, courses or communities').'</h2>');
  781: 	} else {
  782: 	    $r->print('<h2>'.&mt('Currently no active roles, courses or communities').'</h2>');
  783: 	}
  784:         &findcourse_advice($r);
  785:         &requestcourse_advice($r); 
  786: 	$r->print('</form>');
  787:         if ($countfuture) {
  788:             $r->print(&mt('The following [quant,_1,role,roles] will become active in the future:',$countfuture));
  789:             my $doheaders = &roletable_headers($r,\%roleclass,\%sortrole,
  790:                                                $nochoose);
  791:             &print_rolerows($r,$doheaders,\%roleclass,\%sortrole,\%dcroles,
  792:                             \%roletext);
  793:             my $tremark='';
  794:             my $tbg;
  795:             if ($env{'request.role'} eq 'cm') {
  796:                 $tbg="LC_roles_selected";
  797:                 $tremark=&mt('Currently selected.').' ';
  798:             } else {
  799:                 $tbg="LC_roles_is";
  800:             }
  801:             $r->print(&Apache::loncommon::start_data_table_row()
  802:                      .'<td class="'.$tbg.'">&nbsp;</td>'
  803:                      .'<td colspan="3">'
  804:                      .&mt('No role specified')
  805:                      .'</td>'
  806:                      .'<td>'.$tremark.'&nbsp;</td>'
  807:                      .&Apache::loncommon::end_data_table_row()
  808:             );
  809: 
  810:             $r->print(&Apache::loncommon::end_data_table());
  811:         }
  812:         $r->print(&Apache::loncommon::end_page());
  813: 	return OK;
  814:     } elsif ($countactive==1) { # Is there only one choice?
  815:         my $needs_switchserver;
  816:         if ($env{'user.author'}) {
  817:             $needs_switchserver = &check_needs_switchserver($possiblerole);
  818:         }
  819:         if ((!$needs_switchserver) && ($env{'request.role'} eq 'cm')) {
  820:             $r->print('<h3>'.&mt('Please stand by.').'</h3>'.
  821:                 '<input type="hidden" name="'.$possiblerole.'" value="1" />'.
  822:             '<noscript><br /><input type="submit" name="submit" value="'.&mt('Continue').'" /></noscript>');
  823:             $r->print("</form>\n");
  824:             $r->rflush();
  825:             $r->print('<script type="text/javascript">document.forms.rolechoice.submit();</script>');
  826:             $r->print(&Apache::loncommon::end_page());
  827:             return OK;
  828:         }
  829:         if ($needs_switchserver) {
  830:             $r->print("<h2>".&mt('Server Switch Required')."</h2>\n".
  831:                       &mt('Construction Space access is only available from '.
  832:                           'the home server of the corresponding Author.').'<br />'.
  833:                       &mt("Click the 'Switch Server' link to go there.").'<br />');
  834:         }
  835:     }
  836: # ----------------------------------------------------------------------- Table
  837:     unless ((!&Apache::loncommon::show_course()) || ($nochoose) || ($countactive==1)) {
  838: 	$r->print("<h2>".&mt('Select a Course to Enter')."</h2>\n");
  839:     }
  840:     if ($env{'form.destinationurl'}) {
  841:         $r->print('<input type="hidden" name="destinationurl" value="'.
  842:                   $env{'form.destinationurl'}.'" />');
  843:         if ($env{'form.destsymb'} ne '') {
  844:             $r->print('<input type="hidden" name="destsymb" value="'.
  845:                       $env{'form.destsymb'}.'" />');
  846:         }
  847:     }
  848:     my $doheaders = &roletable_headers($r,\%roleclass,\%sortrole,$nochoose);
  849:     if ($env{'environment.recentroles'}) {
  850:         my %recent_roles =
  851:                &Apache::lonhtmlcommon::get_recent('roles',$env{'environment.recentrolesn'});
  852: 	my $output='';
  853: 	foreach (sort(keys(%recent_roles))) {
  854: 	    if (ref($roletext{'user.role.'.$_}) eq 'ARRAY') {
  855: 		$output.= &Apache::loncommon::start_data_table_row().
  856:                           $roletext{'user.role.'.$_}->[0].
  857:                           &Apache::loncommon::end_data_table_row().
  858:                           &Apache::loncommon::continue_data_table_row().
  859:                           $roletext{'user.role.'.$_}->[1].
  860:                           &Apache::loncommon::end_data_table_row();
  861:                 if ($_ =~ m-dc\./($match_domain)/- 
  862: 		    && $dcroles{$1}) {
  863: 		    $output .= &adhoc_roles_row($1,'recent');
  864:                 }
  865: 	    } elsif ($numdc > 0) {
  866:                 unless ($_ =~/^error\:/) {
  867:                     $output.=&display_cc_role('user.role.'.$_);
  868:                 }
  869:             } 
  870: 	}
  871: 	if ($output) {
  872: 	    $r->print(&Apache::loncommon::start_data_table_empty_row()
  873:                      .'<td align="center" colspan="5">'
  874:                      .$recent
  875:                      .'</td>'
  876:                      .&Apache::loncommon::end_data_table_empty_row()
  877:             );
  878: 	    $r->print($output);
  879:             $doheaders ++;
  880: 	}
  881:     }
  882: 
  883:     if ($numdc > 0) {
  884:         $r->print(&coursepick_jscript());
  885:         $r->print(&Apache::loncommon::coursebrowser_javascript().
  886:                   &Apache::loncommon::authorbrowser_javascript());
  887:     }
  888:     &print_rolerows($r,$doheaders,\%roleclass,\%sortrole,\%dcroles,\%roletext);
  889:     if ($countactive > 1) {
  890:         my $tremark='';
  891:         my $tbg;
  892:         if ($env{'request.role'} eq 'cm') {
  893:             $tbg="LC_roles_selected";
  894:             $tremark=&mt('Currently selected.').' ';
  895:         } else {
  896:                 $tbg="LC_roles_is";
  897:         }
  898:         $r->print(&Apache::loncommon::start_data_table_row());
  899:         unless ($nochoose) {
  900: 	    if ($env{'request.role'} ne 'cm') {
  901: 	        $r->print('<td class="'.$tbg.'"><input type="submit" value="'.
  902: 		          &mt('Select').'" name="cm" /></td>');
  903: 	    } else {
  904: 	        $r->print('<td class="'.$tbg.'">&nbsp;</td>');
  905: 	    }
  906:         }
  907:         $r->print('<td colspan="3">'
  908:                  .&mt('No role specified')
  909:                  .'</td>'
  910:                  .'<td>'.$tremark.'&nbsp;</td>'
  911:                  .&Apache::loncommon::end_data_table_row()
  912:         );
  913:     } 
  914:     $r->print(&Apache::loncommon::end_data_table());
  915:     unless ($nochoose) {
  916: 	$r->print("</form>\n");
  917:     }
  918: # ------------------------------------------------------------ Privileges Info
  919:     if (($advanced) && (($env{'user.error.msg'}) || ($error))) {
  920: 	$r->print('<hr /><h2>'.&mt('Current Privileges').'</h2>');
  921: 	$r->print(&privileges_info());
  922:     }
  923:     $r->print(&Apache::lonnet::getannounce());
  924:     if ($advanced) {
  925:         my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&');
  926:         $r->print('<p><small><i>'
  927:                  .&mt('This LON-CAPA server is version [_1]',$r->dir_config('lonVersion'))
  928:                  .'</i><br />'
  929:                  .'<a href="/adm/logout">'.&mt('Logout').'</a>&nbsp;&nbsp;'
  930:                  .'<a href="/adm/coursecatalog?showdom='.$esc_dom.'">'
  931:                  .&mt('Course/Community Catalog')
  932:                  .'</a></small></p>');
  933:     }
  934:     $r->print(&Apache::loncommon::end_page());
  935:     return OK;
  936: }
  937: 
  938: sub gather_roles {
  939:     my ($then,$refresh,$now,$reinit,$nochoose,$roletext,$sortrole,$roleclass,$futureroles,$timezones) = @_;
  940:     my ($countactive,$countfuture,$inrole,$possiblerole) = (0,0,0,'');
  941:     my $advanced = $env{'user.adv'};
  942:     my $tryagain = $env{'form.tryagain'};
  943:     foreach my $envkey (sort(keys(%env))) {
  944:         my $button = 1;
  945:         my $switchserver='';
  946:         my ($role_text,$role_text_end,$sortkey);
  947:         if ($envkey=~/^user\.role\./) {
  948:             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
  949:             &Apache::lonnet::role_status($envkey,$then,$refresh,$now,\$role,\$where,
  950:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
  951:             next if (!defined($role) || $role eq '' || $role =~ /^gr/);
  952:             my $timezone = &role_timezone($where,$timezones);
  953:             $tremark='';
  954:             $tpstart='&nbsp;';
  955:             $tpend='&nbsp;';
  956:             if ($tstart) {
  957:                 $tpstart=&Apache::lonlocal::locallocaltime($tstart,$timezone);
  958:             }
  959:             if ($tend) {
  960:                 $tpend=&Apache::lonlocal::locallocaltime($tend,$timezone);
  961:             }
  962:             if ($env{'request.role'} eq $trolecode) {
  963:                 $tstatus='selected';
  964:             }
  965:             my $tbg;
  966:             if (($tstatus eq 'is')
  967:                 || ($tstatus eq 'selected')
  968:                 || ($tstatus eq 'future')
  969:                 || ($env{'form.showall'})) {
  970:                 if ($tstatus eq 'is') {
  971:                     $tbg='LC_roles_is';
  972:                     $possiblerole=$trolecode;
  973:                     $countactive++;
  974:                 } elsif ($tstatus eq 'future') {
  975:                     $tbg='LC_roles_future';
  976:                     $button=0;
  977:                     $futureroles->{$trolecode} = $tstart.':'.$tend;
  978:                     $countfuture ++;
  979:                 } elsif ($tstatus eq 'expired') {
  980:                     $tbg='LC_roles_expired';
  981:                     $button=0;
  982:                 } elsif ($tstatus eq 'will_not') {
  983:                     $tbg='LC_roles_will_not';
  984:                     $tremark.=&mt('Expired after logout.').' ';
  985:                 } elsif ($tstatus eq 'selected') {
  986:                     $tbg='LC_roles_selected';
  987:                     $inrole=1;
  988:                     $countactive++;
  989:                     $tremark.=&mt('Currently selected.').' ';
  990:                 }
  991:                 my $trole;
  992:                 if ($role =~ /^cr\//) {
  993:                     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$role);
  994:                     if ($tremark) { $tremark.='<br />'; }
  995:                     $tremark.=&mt('Defined by [_1] at [_2].',$rauthor,$rdomain);
  996:                 }
  997:                 $trole=Apache::lonnet::plaintext($role);
  998:                 my $ttype;
  999:                 my $twhere;
 1000:                 my ($tdom,$trest,$tsection)=
 1001:                     split(/\//,Apache::lonnet::declutter($where));
 1002:                 # First, Co-Authorship roles
 1003:                 if (($role eq 'ca') || ($role eq 'aa')) {
 1004:                     my $home = &Apache::lonnet::homeserver($trest,$tdom);
 1005:                     my $allowed=0;
 1006:                     my @ids=&Apache::lonnet::current_machine_ids();
 1007:                     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 1008:                     if (!$allowed) {
 1009:                         $button=0;
 1010:                         $switchserver='otherserver='.$home.'&role='.$trolecode;
 1011:                     }
 1012:                     #next if ($home eq 'no_host');
 1013:                     $home = &Apache::lonnet::hostname($home);
 1014:                     $ttype='Construction Space';
 1015:                     $twhere=&mt('User').': '.$trest.'<br />'.&mt('Domain').
 1016:                         ': '.$tdom.'<br />'.
 1017:                         ' '.&mt('Server').':&nbsp;'.$home;
 1018:                     $env{'course.'.$tdom.'_'.$trest.'.description'}='ca';
 1019:                     $tremark.=&Apache::lonhtmlcommon::authorbombs('/res/'.$tdom.'/'.$trest.'/');
 1020:                     $sortkey=$role."$trest:$tdom";
 1021:                 } elsif ($role eq 'au') {
 1022:                     # Authors
 1023:                     my $home = &Apache::lonnet::homeserver
 1024:                         ($env{'user.name'},$env{'user.domain'});
 1025:                     my $allowed=0;
 1026:                     my @ids=&Apache::lonnet::current_machine_ids();
 1027:                     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 1028:                     if (!$allowed) {
 1029:                         $button=0;
 1030:                         $switchserver='otherserver='.$home.'&role='.$trolecode;
 1031:                     }
 1032:                     #next if ($home eq 'no_host');
 1033:                     $home = &Apache::lonnet::hostname($home);
 1034:                     $ttype='Construction Space';
 1035:                     $twhere=&mt('Domain').': '.$tdom.'<br />'.&mt('Server').
 1036:                         ':&nbsp;'.$home;
 1037:                     $env{'course.'.$tdom.'_'.$trest.'.description'}='ca';
 1038:                     $tremark.=&Apache::lonhtmlcommon::authorbombs('/res/'.$tdom.'/'.$env{'user.name'}.'/');
 1039:                     $sortkey=$role;
 1040:                 } elsif ($trest) {
 1041:                     my $tcourseid=$tdom.'_'.$trest;
 1042:                     $ttype = &Apache::loncommon::course_type($tcourseid);
 1043:                     $trole = &Apache::lonnet::plaintext($role,$ttype);
 1044:                     if ($env{'course.'.$tcourseid.'.description'}) {
 1045:                         $twhere=$env{'course.'.$tcourseid.'.description'};
 1046:                         $sortkey=$role."\0".$tdom."\0".$twhere."\0".$envkey;
 1047:                         unless ($twhere eq &mt('Currently not available')) {
 1048:                             $twhere.=' <span class="LC_fontsize_small">'.
 1049:         &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$trest,$tdom).
 1050:                                     '</span>';
 1051:                         }
 1052:                     } else {
 1053:                         my %newhash=&Apache::lonnet::coursedescription($tcourseid);
 1054:                         if (%newhash) {
 1055:                             $sortkey=$role."\0".$tdom."\0".$newhash{'description'}.
 1056:                                 "\0".$envkey;
 1057:                             $twhere=$newhash{'description'}.
 1058:                               ' <span class="LC_fontsize_small">'.
 1059:         &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$trest,$tdom).
 1060:                               '</span>';
 1061:                             $ttype = $newhash{'type'};
 1062:                             $trole = &Apache::lonnet::plaintext($role,$ttype);
 1063:                         } else {
 1064:                             $twhere=&mt('Currently not available');
 1065:                             $env{'course.'.$tcourseid.'.description'}=$twhere;
 1066:                             $sortkey=$role."\0".$tdom."\0".$twhere."\0".$envkey;
 1067:                             $ttype = 'Unavailable';
 1068:                         }
 1069:                     }
 1070:                     if ($tsection) {
 1071:                         $twhere.='<br />'.&mt('Section').': '.$tsection;
 1072:                     }
 1073:                     if ($role ne 'st') { $twhere.="<br />".&mt('Domain').":".$tdom; }
 1074:                 } elsif ($tdom) {
 1075:                     $ttype='Domain';
 1076:                     $twhere=$tdom;
 1077:                     $sortkey=$role.$twhere;
 1078:                 } else {
 1079:                     $ttype='System';
 1080:                     $twhere=&mt('system wide');
 1081:                     $sortkey=$role.$twhere;
 1082:                 }
 1083:                 ($role_text,$role_text_end) =
 1084:                     &build_roletext($trolecode,$tdom,$trest,$tstatus,$tryagain,
 1085:                                     $advanced,$tremark,$tbg,$trole,$twhere,$tpstart,
 1086:                                     $tpend,$nochoose,$button,$switchserver,$reinit);
 1087:                 $roletext->{$envkey}=[$role_text,$role_text_end];
 1088:                 if (!$sortkey) {$sortkey=$twhere."\0".$envkey;}
 1089:                 $sortrole->{$sortkey}=$envkey;
 1090:                 $roleclass->{$envkey}=$ttype;
 1091:             }
 1092:         }
 1093:     }
 1094:     return ($countactive,$countfuture,$inrole,$possiblerole);
 1095: }
 1096: 
 1097: sub role_timezone {
 1098:     my ($where,$timezones) = @_;
 1099:     my $timezone;
 1100:     if (ref($timezones) eq 'HASH') { 
 1101:         if ($where =~ m{^/($match_domain)/($match_courseid)}) {
 1102:             my $cdom = $1;
 1103:             my $cnum = $2;
 1104:             if ($cdom && $cnum) {
 1105:                 if (!exists($timezones->{$cdom.'_'.$cnum})) {
 1106:                     my %timehash =
 1107:                         &Apache::lonnet::get('environment',['timezone'],$cdom,$cnum);
 1108:                     if ($timehash{'timezone'} eq '') {
 1109:                         if (!exists($timezones->{$cdom})) {
 1110:                             my %domdefaults = 
 1111:                                 &Apache::lonnet::get_domain_defaults($cdom);
 1112:                             if ($domdefaults{'timezone_def'} eq '') {
 1113:                                 $timezones->{$cdom} = 'local';
 1114:                             } else {
 1115:                                 $timezones->{$cdom} = $domdefaults{'timezone_def'};
 1116:                             }
 1117:                         }
 1118:                         $timezones->{$cdom.'_'.$cnum} = $timezones->{$cdom};
 1119:                     } else {
 1120:                         $timezones->{$cdom.'_'.$cnum} = 
 1121:                             &Apache::lonlocal::gettimezone($timehash{'timezone'});
 1122:                     }
 1123:                 }
 1124:                 $timezone = $timezones->{$cdom.'_'.$cnum};
 1125:             }
 1126:         } else {
 1127:             my ($tdom) = ($where =~ m{^/($match_domain)});
 1128:             if ($tdom) {
 1129:                 if (!exists($timezones->{$tdom})) {
 1130:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($tdom);
 1131:                     if ($domdefaults{'timezone_def'} eq '') {
 1132:                         $timezones->{$tdom} = 'local';
 1133:                     } else {
 1134:                         $timezones->{$tdom} = $domdefaults{'timezone_def'};
 1135:                     }
 1136:                 }
 1137:                 $timezone = $timezones->{$tdom};
 1138:             }
 1139:         }
 1140:         if ($timezone eq 'local') {
 1141:             $timezone = undef;
 1142:         }
 1143:     }
 1144:     return $timezone;
 1145: }
 1146: 
 1147: sub roletable_headers {
 1148:     my ($r,$roleclass,$sortrole,$nochoose) = @_;
 1149:     my $doheaders;
 1150:     if ((ref($sortrole) eq 'HASH') && (ref($roleclass) eq 'HASH')) {
 1151:         $r->print('<br />'
 1152:                  .&Apache::loncommon::start_data_table()
 1153:                  .&Apache::loncommon::start_data_table_header_row()
 1154:         );
 1155:         if (!$nochoose) { $r->print('<th>&nbsp;</th>'); }
 1156:         $r->print('<th>'.&mt('User Role').'</th>'
 1157:                  .'<th>'.&mt('Extent').'</th>'
 1158:                  .'<th>'.&mt('Start').'</th>'
 1159:                  .'<th>'.&mt('End').'</th>'
 1160:                  .&Apache::loncommon::end_data_table_header_row()
 1161:         );
 1162:         $doheaders=-1;
 1163:         my @roletypes = &roletypes();
 1164:         foreach my $type (@roletypes) {
 1165:             my $haverole=0;
 1166:             foreach my $which (sort {uc($a) cmp uc($b)} (keys(%{$sortrole}))) {
 1167:                 if ($roleclass->{$sortrole->{$which}} =~ /^\Q$type\E/) {
 1168:                     $haverole=1;
 1169:                 }
 1170:             }
 1171:             if ($haverole) { $doheaders++; }
 1172:         }
 1173:     }
 1174:     return $doheaders;
 1175: }
 1176: 
 1177: sub roletypes {
 1178:     my @types = ('Domain','Construction Space','Course','Community','Unavailable','System');
 1179:     return @types; 
 1180: }
 1181: 
 1182: sub print_rolerows {
 1183:     my ($r,$doheaders,$roleclass,$sortrole,$dcroles,$roletext) = @_;
 1184:     if ((ref($roleclass) eq 'HASH') && (ref($sortrole) eq 'HASH')) {
 1185:         my @types = &roletypes();
 1186:         foreach my $type (@types) {
 1187:             my $output;
 1188:             foreach my $which (sort {uc($a) cmp uc($b)} (keys(%{$sortrole}))) {
 1189:                 if ($roleclass->{$sortrole->{$which}} =~ /^\Q$type\E/) {
 1190:                     if (ref($roletext) eq 'HASH') {
 1191:                         if (ref($roletext->{$sortrole->{$which}}) eq 'ARRAY') {
 1192:                             $output.= &Apache::loncommon::start_data_table_row().
 1193:                                       $roletext->{$sortrole->{$which}}->[0].
 1194:                                       &Apache::loncommon::end_data_table_row().
 1195:                                       &Apache::loncommon::continue_data_table_row().
 1196:                                       $roletext->{$sortrole->{$which}}->[1].
 1197:                                       &Apache::loncommon::end_data_table_row();
 1198:                         }
 1199:                         if ($sortrole->{$which} =~ m-dc\./($match_domain)/-) {
 1200:                             if (ref($dcroles) eq 'HASH') {
 1201:                                 if ($dcroles->{$1}) {
 1202:                                     $output .= &adhoc_roles_row($1,'');
 1203:                                 }
 1204:                             }
 1205:                         }
 1206:                     }
 1207:                 }
 1208:             }
 1209:             if ($output) {
 1210:                 if ($doheaders > 0) {
 1211:                     $r->print(&Apache::loncommon::start_data_table_empty_row()
 1212:                              .'<td align="center" colspan="5">'
 1213:                              .&mt($type)
 1214:                              .'</td>'
 1215:                              .&Apache::loncommon::end_data_table_empty_row()
 1216:                     );
 1217:                 }
 1218:                 $r->print($output);
 1219:             }
 1220:         }
 1221:     }
 1222: }
 1223: 
 1224: sub findcourse_advice {
 1225:     my ($r) = @_;
 1226:     my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
 1227:     my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&');
 1228:     if (&Apache::lonnet::auto_run(undef,$env{'user.domain'})) {
 1229:         $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).'
 1230: <ul>
 1231:  <li>'.&mt('The course has yet to be created.').'</li>
 1232:  <li>'.&mt('Automatic enrollment of registered students has not been enabled for the course.').'</li>
 1233:  <li>'.&mt('You are in a section of course for which automatic enrollment in the corresponding LON-CAPA course is not active.').'</li>
 1234:  <li>'.&mt('The start date for automated enrollment has yet to be reached.').'</li>
 1235:  <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>
 1236:  </ul>');
 1237:     } else {
 1238:         $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 />');
 1239:     }
 1240:     $r->print('<h3>'.&mt('Self-Enrollment').'</h3>'.
 1241:               '<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 />');
 1242:     $r->print(&mt('You can search for courses and communities which permit self-enrollment, if you would like to enroll in one.').'</p>');
 1243:     &queued_selfenrollment($r);
 1244:     return;
 1245: }
 1246: 
 1247: sub requestcourse_advice {
 1248:     my ($r) = @_;
 1249:     my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
 1250:     my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&');
 1251:     my (%can_request,%request_doms);
 1252:     &Apache::lonnet::check_can_request($env{'user.domain'},\%can_request,\%request_doms);
 1253:     if (keys(%request_doms) > 0) {
 1254:         my ($types,$typename) = &Apache::loncommon::course_types();
 1255:         if ((ref($types) eq 'ARRAY') && (ref($typename) eq 'HASH')) { 
 1256:             $r->print('<h3>'.&mt('Request creation of a course or community').'</h3>'.
 1257:                       '<p>'.&mt('You have rights to request the creation of courses and/or communities in the following domain(s):').'<ul>');
 1258:             my (@reqdoms,@reqtypes);
 1259:             foreach my $type (sort(keys(%request_doms))) {
 1260:                 push(@reqtypes,$type); 
 1261:                 if (ref($request_doms{$type}) eq 'ARRAY') {
 1262:                     my $domstr = join(', ',map { &Apache::lonnet::domain($_) } sort(@{$request_doms{$type}}));
 1263:                     $r->print(
 1264:                         '<li>'
 1265:                        .&mt('[_1]'.$typename->{$type}.'[_2] in domain: [_3]',
 1266:                             '<i>',
 1267:                             '</i>',
 1268:                             '<b>'.$domstr.'</b>')
 1269:                        .'</li>'
 1270:                     );
 1271:                     foreach my $dom (@{$request_doms{$type}}) {
 1272:                         unless (grep(/^\Q$dom\E/,@reqdoms)) {
 1273:                             push(@reqdoms,$dom);
 1274:                         }
 1275:                     }
 1276:                 }
 1277:             }
 1278:             my @showtypes;
 1279:             foreach my $type (@{$types}) {
 1280:                 if (grep(/^\Q$type\E$/,@reqtypes)) {
 1281:                     push(@showtypes,$type);
 1282:                 }
 1283:             }
 1284:             my $requrl = '/adm/requestcourse';
 1285:             if (@reqdoms == 1) {
 1286:                 $requrl .= '?showdom='.$reqdoms[0];
 1287:             }
 1288:             if (@showtypes > 0) {
 1289:                 $requrl.=(($requrl=~/\?/)?'&':'?').'crstype='.$showtypes[0];
 1290:             }
 1291:             if (@reqdoms == 1 || @showtypes > 0) {
 1292:                 $requrl .= '&state=crstype&action=new';
 1293:             } 
 1294:             $r->print('</ul>'.&mt('Use the [_1]request form[_2] to submit a request for creation of a new course or community.','<a href="'.$requrl.'">','</a>').'</p>');
 1295:         }
 1296:     }
 1297:     return;
 1298: }
 1299: 
 1300: sub queued_selfenrollment {
 1301:     my ($r) = @_;
 1302:     my %selfenrollrequests = &Apache::lonnet::dump('selfenrollrequests');
 1303:     my %reqs_by_date;
 1304:     foreach my $item (keys(%selfenrollrequests)) {
 1305:         if (ref($selfenrollrequests{$item}) eq 'HASH') {
 1306:             if ($selfenrollrequests{$item}{'status'} eq 'request') {
 1307:                 if ($selfenrollrequests{$item}{'timestamp'}) {
 1308:                     push(@{$reqs_by_date{$selfenrollrequests{$item}{'timestamp'}}},$item);
 1309:                 }
 1310:             } 
 1311:         }
 1312:     }
 1313:     if (keys(%reqs_by_date)) {
 1314:         my $rolename = &Apache::lonnet::plaintext('st');
 1315:         $r->print('<b>'.&mt('Enrollment requests pending Course Coordinator approval').'</b><br />'.
 1316:                   &Apache::loncommon::start_data_table().
 1317:                   &Apache::loncommon::start_data_table_header_row().
 1318:                   '<th>'.&mt('Date requested').'</th><th>'.&mt('Course title').'</th>'.
 1319:                   '<th>'.&mt('User role').'</th><th>'.&mt('Section').'</th>'.
 1320:                  &Apache::loncommon::end_data_table_header_row());
 1321:         my @sorted = sort { $a <=> $b } (keys(%reqs_by_date));
 1322:         foreach my $item (@sorted) {
 1323:             if (ref($reqs_by_date{$item}) eq 'ARRAY') {
 1324:                 foreach my $crs (@{$reqs_by_date{$item}}) {
 1325:                     my %courseinfo = &Apache::lonnet::coursedescription($crs);
 1326:                     my $usec = $selfenrollrequests{$crs}{'section'};
 1327:                     if ($usec eq '') {
 1328:                         $usec = &mt('No section'); 
 1329:                     }
 1330:                     $r->print(&Apache::loncommon::start_data_table_row().
 1331:                              '<td>'.&Apache::lonlocal::locallocaltime($item).'</td>'.
 1332:                              '<td>'.$courseinfo{'description'}.'</td>'.
 1333:                              '<td>'.$rolename.'</td><td>'.$usec.'</td>'.
 1334:                              &Apache::loncommon::end_data_table_row());
 1335:                 }
 1336:             }
 1337:         }
 1338:         $r->print(&Apache::loncommon::end_data_table());
 1339:     }
 1340:     return;
 1341: }
 1342: 
 1343: sub privileges_info {
 1344:     my ($which) = @_;
 1345:     my $output;
 1346: 
 1347:     $which ||= $env{'request.role'};
 1348: 
 1349:     foreach my $envkey (sort(keys(%env))) {
 1350: 	next if ($envkey!~/^user\.priv\.\Q$which\E\.(.*)/);
 1351: 
 1352: 	my $where=$1;
 1353: 	my $ttype;
 1354: 	my $twhere;
 1355: 	my (undef,$tdom,$trest,$tsec)=split(m{/},$where);
 1356: 	if ($trest) {
 1357: 	    if ($env{'course.'.$tdom.'_'.$trest.'.description'} eq 'ca') {
 1358: 		$ttype='Construction Space';
 1359: 		$twhere='User: '.$trest.', Domain: '.$tdom;
 1360: 	    } else {
 1361: 		$ttype= &Apache::loncommon::course_type($tdom.'_'.$trest);
 1362: 		$twhere=$env{'course.'.$tdom.'_'.$trest.'.description'};
 1363: 		if ($tsec) {
 1364: 		    my $sec_type = 'Section';
 1365: 		    if (exists($env{"user.role.gr.$where"})) {
 1366: 			$sec_type = 'Group';
 1367: 		    }
 1368: 		    $twhere.=' ('.$sec_type.': '.$tsec.')';
 1369: 		}
 1370: 	    }
 1371: 	} elsif ($tdom) {
 1372: 	    $ttype='Domain';
 1373: 	    $twhere=$tdom;
 1374: 	} else {
 1375: 	    $ttype='System';
 1376: 	    $twhere='/';
 1377: 	}
 1378: 	$output .= "\n<h3>".&mt($ttype).': '.$twhere.'</h3>'."\n<ul>";
 1379: 	foreach my $priv (sort(split(/:/,$env{$envkey}))) {
 1380: 	    next if (!$priv);
 1381: 
 1382: 	    my ($prv,$restr)=split(/\&/,$priv);
 1383: 	    my $trestr='';
 1384: 	    if ($restr ne 'F') {
 1385: 		$trestr.=' ('.
 1386: 		    join(', ',
 1387: 			 map { &Apache::lonnet::plaintext($_) } 
 1388: 			     (split('',$restr))).') ';
 1389: 	    }
 1390: 	    $output .= "\n\t".
 1391: 		'<li>'.&Apache::lonnet::plaintext($prv).$trestr.'</li>';
 1392: 	}
 1393: 	$output .= "\n".'</ul>';
 1394:     }
 1395:     return $output;
 1396: }
 1397: 
 1398: sub build_roletext {
 1399:     my ($trolecode,$tdom,$trest,$tstatus,$tryagain,$advanced,$tremark,$tbg,$trole,$twhere,$tpstart,$tpend,$nochoose,$button,$switchserver,$reinit) = @_;
 1400:     my ($roletext,$roletext_end);
 1401:     my $is_dc=($trolecode =~ m/^dc\./);
 1402:     my $rowspan=($is_dc) ? ''
 1403:                          : ' rowspan="2" ';
 1404: 
 1405:     unless ($nochoose) {
 1406:         my $buttonname=$trolecode;
 1407:         $buttonname=~s/\W//g;
 1408:         if (!$button) {
 1409:             if ($switchserver) {
 1410:                 $roletext.='<td'.$rowspan.' class="'.$tbg.'">'
 1411:                           .'<a href="/adm/switchserver?'.$switchserver.'">'
 1412:                           .&mt('Switch Server')
 1413:                           .'</a></td>';
 1414:             } else {
 1415:                 $roletext.=('<td'.$rowspan.' class="'.$tbg.'">&nbsp;</td>');
 1416:             }
 1417:         } elsif ($tstatus eq 'is') {
 1418:             $roletext.='<td'.$rowspan.' class="'.$tbg.'">'.
 1419:                         '<input name="'.$buttonname.'" type="button" value="'.
 1420:                         &mt('Select').'" onclick="javascript:enterrole(this.form,\''.
 1421:                         $trolecode."','".$buttonname.'\');" /></td>';
 1422:         } elsif ($tryagain) {
 1423:             $roletext.=
 1424:                 '<td'.$rowspan.' class="'.$tbg.'">'.
 1425:                 '<input name="'.$buttonname.'" type="button" value="'.
 1426:                 &mt('Try Selecting Again').'" onclick="javascript:enterrole(this.form,\''.
 1427:                         $trolecode."','".$buttonname.'\');" /></td>';
 1428:         } elsif ($advanced) {
 1429:             $roletext.=
 1430:                 '<td'.$rowspan.' class="'.$tbg.'">'.
 1431:                 '<input name="'.$buttonname.'" type="button" value="'.
 1432:                 &mt('Re-Initialize').'" onclick="javascript:enterrole(this.form,\''.
 1433:                         $trolecode."','".$buttonname.'\');" /></td>';
 1434:         } elsif ($reinit) {
 1435:             $roletext.= 
 1436:                 '<td'.$rowspan.' class="'.$tbg.'">'.
 1437:                 '<input name="'.$buttonname.'" type="button" value="'.
 1438:                 &mt('Re-Select').'" onclick="javascript:enterrole(this.form,\''.
 1439:                         $trolecode."','".$buttonname.'\');" /></td>';
 1440:         } else {
 1441:             $roletext.=
 1442:                 '<td'.$rowspan.' class="'.$tbg.'">'.
 1443:                 '<input name="'.$buttonname.'" type="button" value="'.
 1444:                 &mt('Re-Select').'" onclick="javascript:enterrole(this.form,\''.
 1445:                         $trolecode."','".$buttonname.'\');" /></td>';
 1446:         }
 1447:     }
 1448:     if ($trolecode !~ m/^(dc|ca|au|aa)\./) {
 1449: 	$tremark.=&Apache::lonannounce::showday(time,1,
 1450: 			 &Apache::lonannounce::readcalendar($tdom.'_'.$trest));
 1451:     }
 1452:     $roletext.='<td>'.$trole.'</td>'
 1453:               .'<td>'.$twhere.'</td>'
 1454:               .'<td>'.$tpstart.'</td>'
 1455:               .'<td>'.$tpend.'</td>';
 1456:     if (!$is_dc) {
 1457:         $roletext_end = '<td colspan="4">'.
 1458:                         $tremark.'&nbsp;'.
 1459:                         '</td>';
 1460:     }
 1461:     return ($roletext,$roletext_end);
 1462: }
 1463: 
 1464: sub check_needs_switchserver {
 1465:     my ($possiblerole) = @_;
 1466:     my $needs_switchserver;
 1467:     my ($role,$where) = split(/\./,$possiblerole,2);
 1468:     my (undef,$tdom,$twho) = split(/\//,$where);
 1469:     my ($server_status,$home);
 1470:     if (($role eq 'ca') || ($role eq 'aa')) {
 1471:         ($server_status,$home) = &check_author_homeserver($twho,$tdom);
 1472:     } else {
 1473:         ($server_status,$home) = &check_author_homeserver($env{'user.name'},
 1474:                                                           $env{'user.domain'});
 1475:     }
 1476:     if ($server_status eq 'switchserver') {
 1477:         $needs_switchserver = 1;
 1478:     }
 1479:     return $needs_switchserver;
 1480: }
 1481: 
 1482: sub check_author_homeserver {
 1483:     my ($uname,$udom)=@_;
 1484:     if (($uname eq '') || ($udom eq '')) {
 1485:         return ('fail','');
 1486:     }
 1487:     my $home = &Apache::lonnet::homeserver($uname,$udom);
 1488:     if (&Apache::lonnet::host_domain($home) ne $udom) {
 1489:         return ('fail',$home);
 1490:     }
 1491:     my @ids=&Apache::lonnet::current_machine_ids();
 1492:     if (grep(/^\Q$home\E$/,@ids)) {
 1493:         return ('ok',$home);
 1494:     } else {
 1495:         return ('switchserver',$home);
 1496:     }
 1497: }
 1498: 
 1499: sub check_fordc {
 1500:     my ($dcroles,$then) = @_;
 1501:     my $numdc = 0;
 1502:     if ($env{'user.adv'}) {
 1503:         foreach my $envkey (sort keys %env) {
 1504:             if ($envkey=~/^user\.role\.dc\.\/($match_domain)\/$/) {
 1505:                 my $dcdom = $1;
 1506:                 my $livedc = 1;
 1507:                 my ($tstart,$tend)=split(/\./,$env{$envkey});
 1508:                 if ($tstart && $tstart>$then) { $livedc = 0; }
 1509:                 if ($tend   && $tend  <$then) { $livedc = 0; }
 1510:                 if ($livedc) {
 1511:                     $$dcroles{$dcdom} = $envkey;
 1512:                     $numdc++;
 1513:                 }
 1514:             }
 1515:         }
 1516:     }
 1517:     return $numdc;
 1518: }
 1519: 
 1520: sub adhoc_course_role {
 1521:     my ($refresh,$then) = @_;
 1522:     my ($cdom,$cnum,$crstype);
 1523:     $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 1524:     $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 1525:     $crstype = &Apache::loncommon::course_type();
 1526:     if (&check_forcc($cdom,$cnum,$refresh,$then,$crstype)) {
 1527:         my $setprivs;
 1528:         if (!defined($env{'user.role.'.$env{'form.switchrole'}})) {
 1529:             $setprivs = 1;
 1530:         } else {
 1531:             my ($start,$end) = split(/\./,$env{'user.role.'.$env{'form.switchrole'}});
 1532:             if (($start && ($start>$refresh || $start == -1)) ||
 1533:                 ($end && $end<$then)) {
 1534:                 $setprivs = 1;
 1535:             }
 1536:         }
 1537:         if ($setprivs) {
 1538:             if ($env{'form.switchrole'} =~ m-^(in|ta|ep|ad|st|cr)([\w/]*)\./\Q$cdom\E/\Q$cnum\E/?(\w*)$-) {
 1539:                 my $role = $1;
 1540:                 my $custom_role = $2;
 1541:                 my $usec = $3;
 1542:                 if ($role eq 'cr') {
 1543:                     if ($custom_role =~ m-^/$match_domain/$match_username/\w+$-) {
 1544:                         $role .= $custom_role;
 1545:                     } else {
 1546:                         return;
 1547:                     }
 1548:                 }
 1549:                 my (%userroles,%newrole,%newgroups,%group_privs);
 1550:                 my %cgroups =
 1551:                     &Apache::lonnet::get_active_groups($env{'user.domain'},
 1552:                                             $env{'user.name'},$cdom,$cnum);
 1553:                 foreach my $group (keys(%cgroups)) {
 1554:                     $group_privs{$group} =
 1555:                         $env{'user.priv.cc./'.$cdom.'/'.$cnum.'./'.$cdom.'/'.$cnum.'/'.$group};
 1556:                 }
 1557:                 $newgroups{'/'.$cdom.'/'.$cnum} = \%group_privs;
 1558:                 my $area = '/'.$cdom.'/'.$cnum;
 1559:                 my $spec = $role.'.'.$area;
 1560:                 if ($usec ne '') {
 1561:                     $spec .= '/'.$usec;
 1562:                     $area .= '/'.$usec;
 1563:                 }
 1564:                 &Apache::lonnet::standard_roleprivs(\%newrole,$role,$cdom,$spec,$cnum,$area);
 1565:                 &Apache::lonnet::set_userprivs(\%userroles,\%newrole,\%newgroups);
 1566:                 my $adhocstart = $refresh-1;
 1567:                 $userroles{'user.role.'.$spec} = $adhocstart.'.';
 1568:                 &Apache::lonnet::appenv(\%userroles,[$role,'cm']);
 1569:             }
 1570:         }
 1571:     }
 1572:     return;
 1573: }
 1574: 
 1575: sub check_forcc {
 1576:     my ($cdom,$cnum,$refresh,$then,$crstype) = @_;
 1577:     my ($is_cc,$ccrole);
 1578:     if ($crstype eq 'Community') {
 1579:         $ccrole = 'co';
 1580:     } else {
 1581:         $ccrole = 'cc';
 1582:     }
 1583:     if ($cdom ne '' && $cnum ne '') {
 1584:         if (&Apache::lonnet::is_course($cdom,$cnum)) {
 1585:             my $envkey = 'user.role.'.$ccrole.'./'.$cdom.'/'.$cnum;
 1586:             if (defined($env{$envkey})) {
 1587:                 $is_cc = 1;
 1588:                 my ($tstart,$tend)=split(/\./,$env{$envkey});
 1589:                 if ($tstart && $tstart>$refresh) { $is_cc = 0; }
 1590:                 if ($tend   && $tend  <$then) { $is_cc = 0; }
 1591:             }
 1592:         }
 1593:     }
 1594:     return $is_cc;
 1595: }
 1596: 
 1597: sub courselink {
 1598:     my ($dcdom,$rowtype) = @_;
 1599:     my $courseform=&Apache::loncommon::selectcourse_link
 1600:                    ('rolechoice','dccourse'.$rowtype.'_'.$dcdom,
 1601:                     'dcdomain'.$rowtype.'_'.$dcdom,'coursedesc'.$rowtype.'_'.
 1602:                     $dcdom,$dcdom,undef,'Course/Community');
 1603:     my $hiddenitems = '<input type="hidden" name="dcdomain'.$rowtype.'_'.$dcdom.'" value="'.$dcdom.'" />'.
 1604:                       '<input type="hidden" name="origdom'.$rowtype.'_'.$dcdom.'" value="'.$dcdom.'" />'.
 1605:                       '<input type="hidden" name="dccourse'.$rowtype.'_'.$dcdom.'" value="" />'.
 1606:                       '<input type="hidden" name="coursedesc'.$rowtype.'_'.$dcdom.'" value="" />';
 1607:     return $courseform.$hiddenitems;
 1608: }
 1609: 
 1610: sub coursepick_jscript {
 1611:     my %lt = &Apache::lonlocal::texthash(
 1612:                   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.",
 1613:                   youc => 'You can only use this screen to select courses and communities in the current domain.',
 1614:              );
 1615:     my $verify_script = <<"END";
 1616: <script type="text/javascript">
 1617: // <![CDATA[
 1618: function verifyCoursePick(caller) {
 1619:     var numbutton = getIndex(caller)
 1620:     var pickedCourse = document.rolechoice.elements[numbutton+4].value
 1621:     var pickedDomain = document.rolechoice.elements[numbutton+2].value
 1622:     if (document.rolechoice.elements[numbutton+2].value == document.rolechoice.elements[numbutton+3].value) {
 1623:         if (pickedCourse != '') {
 1624:             if (numbutton != -1) {
 1625:                 var courseTarget = "cc./"+pickedDomain+"/"+pickedCourse
 1626:                 document.rolechoice.elements[numbutton+1].name = courseTarget
 1627:                 document.rolechoice.submit()
 1628:             }
 1629:         }
 1630:         else {
 1631:             alert("$lt{'plsu'}");
 1632:         }
 1633:     }
 1634:     else {
 1635:         alert("$lt{'youc'}")
 1636:     }
 1637: }
 1638: function getIndex(caller) {
 1639:     for (var i=0;i<document.rolechoice.elements.length;i++) {
 1640:         if (document.rolechoice.elements[i] == caller) {
 1641:             return i;
 1642:         }
 1643:     }
 1644:     return -1;
 1645: }
 1646: // ]]>
 1647: </script>
 1648: END
 1649:     return $verify_script;
 1650: }
 1651: 
 1652: sub coauthorlink {
 1653:     my ($dcdom,$rowtype) = @_;
 1654:     my $coauthorform=&Apache::loncommon::selectauthor_link('rolechoice',$dcdom);
 1655:     my $hiddenitems = '<input type="hidden" name="adhoccauname'.$rowtype.'_'.$dcdom.'" value="" />';
 1656:     return $coauthorform.$hiddenitems;
 1657: }
 1658: 
 1659: sub display_cc_role {
 1660:     my $rolekey = shift;
 1661:     my ($roletext,$roletext_end);
 1662:     my $advanced = $env{'user.adv'};
 1663:     my $tryagain = $env{'form.tryagain'};
 1664:     unless ($rolekey =~/^error\:/) {
 1665:         if ($rolekey =~ m{^user\.role\.(cc|co)\./($match_domain)/($match_courseid)$}) {
 1666:             my $ccrole = $1;
 1667:             my $tcourseid = $2.'_'.$3;
 1668:             my $trolecode = $1.'./'.$2.'/'.$3;
 1669:             my $twhere;
 1670:             my $ttype;
 1671:             my $tbg='LC_roles_is';
 1672:             my %newhash=&Apache::lonnet::coursedescription($tcourseid);
 1673:             if (%newhash) {
 1674:                 $twhere=$newhash{'description'}.
 1675:                         ' <span style="LC_fontsize_small">'.
 1676:                         &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$2,$1).
 1677:                         '</span>';
 1678:                 $ttype = $newhash{'type'};
 1679:             } else {
 1680:                 $twhere=&mt('Currently not available');
 1681:                 $env{'course.'.$tcourseid.'.description'}=$twhere;
 1682:             }
 1683:             my $trole = &Apache::lonnet::plaintext($ccrole,$ttype);
 1684:             $twhere.="<br />".&mt('Domain').":".$1;
 1685:             ($roletext,$roletext_end) = &build_roletext($trolecode,$1,$2,'is',$tryagain,$advanced,'',$tbg,$trole,$twhere,'','','',1,'');
 1686:         }
 1687:     }
 1688:     return ($roletext,$roletext_end);
 1689: }
 1690: 
 1691: sub adhoc_roles_row {
 1692:     my ($dcdom,$rowtype) = @_;
 1693:     my $output = &Apache::loncommon::continue_data_table_row()
 1694:                  .' <td colspan="5">'
 1695:                  .&mt('[_1]Ad hoc[_2] roles in domain [_3] --'
 1696:                      ,'<span class="LC_cusr_emph">','</span>',$dcdom)
 1697:                  .' ';
 1698:     my $selectcclink = &courselink($dcdom,$rowtype);
 1699:     my $ccrole = &Apache::lonnet::plaintext('co',undef,undef,1);
 1700:     my $carole = &Apache::lonnet::plaintext('ca');
 1701:     my $selectcalink = &coauthorlink($dcdom,$rowtype);
 1702:     $output.=$ccrole.': '.$selectcclink
 1703:             .' | '.$carole.': '.$selectcalink
 1704:             .&Apache::loncommon::end_data_table_row();
 1705:     return $output;
 1706: }
 1707: 
 1708: sub recent_filename {
 1709:     my $area=shift;
 1710:     return 'nohist_recent_'.&escape($area);
 1711: }
 1712: 
 1713: sub courseloadpage {
 1714:     my ($courseid) = @_;
 1715:     my $startpage;
 1716:     my %entry_settings = &Apache::lonnet::get('nohist_whatsnew',
 1717: 					      [$courseid.':courseinit']);
 1718:     my ($tmp) = %entry_settings;
 1719:     unless ($tmp =~ /^error: 2 /) {
 1720:         $startpage = $entry_settings{$courseid.':courseinit'};
 1721:     }
 1722:     if ($startpage eq '') {
 1723:         if (exists($env{'environment.course_init_display'})) {
 1724:             $startpage = $env{'environment.course_init_display'};
 1725:         }
 1726:     }
 1727:     return $startpage;
 1728: }
 1729: 
 1730: 1;
 1731: __END__
 1732: 
 1733: =head1 NAME
 1734: 
 1735: Apache::lonroles - User Roles Screen
 1736: 
 1737: =head1 SYNOPSIS
 1738: 
 1739: Invoked by /etc/httpd/conf/srm.conf:
 1740: 
 1741:  <Location /adm/roles>
 1742:  PerlAccessHandler       Apache::lonacc
 1743:  SetHandler perl-script
 1744:  PerlHandler Apache::lonroles
 1745:  ErrorDocument     403 /adm/login
 1746:  ErrorDocument	  500 /adm/errorhandler
 1747:  </Location>
 1748: 
 1749: =head1 OVERVIEW
 1750: 
 1751: =head2 Choosing Roles
 1752: 
 1753: C<lonroles> is a handler that allows a user to switch roles in
 1754: mid-session. LON-CAPA attempts to work with "No Role Specified", the
 1755: default role that a user has before selecting a role, as widely as
 1756: possible, but certain handlers for example need specification which
 1757: course they should act on, etc. Both in this scenario, and when the
 1758: handler determines via C<lonnet>'s C<&allowed> function that a certain
 1759: action is not allowed, C<lonroles> is used as error handler. This
 1760: allows the user to select another role which may have permission to do
 1761: what they were trying to do. C<lonroles> can also be accessed via the
 1762: B<CRS> button in the Remote Control. 
 1763: 
 1764: =begin latex
 1765: 
 1766: \begin{figure}
 1767: \begin{center}
 1768: \includegraphics[width=0.45\paperwidth,keepaspectratio]{Sample_Roles_Screen}
 1769:   \caption{\label{Sample_Roles_Screen}Sample Roles Screen} 
 1770: \end{center}
 1771: \end{figure}
 1772: 
 1773: =end latex
 1774: 
 1775: =head2 Role Initialization
 1776: 
 1777: 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.
 1778: 
 1779: =head1 INTRODUCTION
 1780: 
 1781: This module enables a user to select what role he wishes to
 1782: operate under (instructor, student, teaching assistant, course
 1783: coordinator, etc).  These roles are pre-established by the actions
 1784: of upper-level users.
 1785: 
 1786: This is part of the LearningOnline Network with CAPA project
 1787: described at http://www.lon-capa.org.
 1788: 
 1789: =head1 HANDLER SUBROUTINE
 1790: 
 1791: This routine is called by Apache and mod_perl.
 1792: 
 1793: =over 4
 1794: 
 1795: =item *
 1796: 
 1797: Roles Initialization (yes/no)
 1798: 
 1799: =item *
 1800: 
 1801: Get Error Message from Environment
 1802: 
 1803: =item *
 1804: 
 1805: Who is this?
 1806: 
 1807: =item *
 1808: 
 1809: Generate Page Output
 1810: 
 1811: =item *
 1812: 
 1813: Choice or no choice
 1814: 
 1815: =item *
 1816: 
 1817: Table
 1818: 
 1819: =item *
 1820: 
 1821: Privileges
 1822: 
 1823: =back
 1824: 
 1825: =cut

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