File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.240.2.9: download - view: text, annotated - select for diffs
Fri Jan 15 05:30:21 2010 UTC (14 years, 5 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3.
  - Backport 1.241.

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

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