File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.240.2.15: download - view: text, annotated - select for diffs
Mon Aug 9 23:39:59 2010 UTC (13 years, 9 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3.  For Concept Tests:
  - Keep track of last course "login"
  - Keep track of submission count by students in Concep Tests.
  - New What's New item - Last login for users (day, week, month, ever).
  - Eliminate columns for groups and clickers for classlist display.
  - Add new columns for last login and test status (completed, incomplete, unattempted).

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

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