File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.240.2.18: download - view: text, annotated - select for diffs
Wed Oct 6 18:46:53 2010 UTC (13 years, 8 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3.
  - Substitute the term 'Concept Tests' for 'Roles' when appropriate.

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

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