File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.240.2.3: download - view: text, annotated - select for diffs
Tue Dec 15 05:04:17 2009 UTC (14 years, 6 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3.
 - For GCI users:
  - Replace standard roles screen with custom main menu.
  - First item displayed for CCs after selecting Concept Test is Course Contents instead of What's New?

    1: # The LearningOnline Network with CAPA
    2: # User Roles Screen
    3: #
    4: # $Id: lonroles.pm,v 1.240.2.3 2009/12/15 05:04:17 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonroles - User Roles Screen
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: Invoked by /etc/httpd/conf/srm.conf:
   39: 
   40:  <Location /adm/roles>
   41:  PerlAccessHandler       Apache::lonacc
   42:  SetHandler perl-script
   43:  PerlHandler Apache::lonroles
   44:  ErrorDocument     403 /adm/login
   45:  ErrorDocument	  500 /adm/errorhandler
   46:  </Location>
   47: 
   48: =head1 OVERVIEW
   49: 
   50: =head2 Choosing Roles
   51: 
   52: C<lonroles> is a handler that allows a user to switch roles in
   53: mid-session. LON-CAPA attempts to work with "No Role Specified", the
   54: default role that a user has before selecting a role, as widely as
   55: possible, but certain handlers for example need specification which
   56: course they should act on, etc. Both in this scenario, and when the
   57: handler determines via C<lonnet>'s C<&allowed> function that a certain
   58: action is not allowed, C<lonroles> is used as error handler. This
   59: allows the user to select another role which may have permission to do
   60: what they were trying to do. C<lonroles> can also be accessed via the
   61: B<CRS> button in the Remote Control. 
   62: 
   63: =begin latex
   64: 
   65: \begin{figure}
   66: \begin{center}
   67: \includegraphics[width=0.45\paperwidth,keepaspectratio]{Sample_Roles_Screen}
   68:   \caption{\label{Sample_Roles_Screen}Sample Roles Screen} 
   69: \end{center}
   70: \end{figure}
   71: 
   72: =end latex
   73: 
   74: =head2 Role Initialization
   75: 
   76: The privileges for a user are established at login time and stored in the session environment. As a consequence, a new role does not become active till the next login. Handlers are able to query for privileges using C<lonnet>'s C<&allowed> function. When a user first logs in, their role is the "common" role, which means that they have the sum of all of their privileges. During a session it might become necessary to choose a particular role, which as a consequence also limits the user to only the privileges in that particular role.
   77: 
   78: =head1 INTRODUCTION
   79: 
   80: This module enables a user to select what role he wishes to
   81: operate under (instructor, student, teaching assistant, course
   82: coordinator, etc).  These roles are pre-established by the actions
   83: of upper-level users.
   84: 
   85: This is part of the LearningOnline Network with CAPA project
   86: described at http://www.lon-capa.org.
   87: 
   88: =head1 HANDLER SUBROUTINE
   89: 
   90: This routine is called by Apache and mod_perl.
   91: 
   92: =over 4
   93: 
   94: =item *
   95: 
   96: Roles Initialization (yes/no)
   97: 
   98: =item *
   99: 
  100: Get Error Message from Environment
  101: 
  102: =item *
  103: 
  104: Who is this?
  105: 
  106: =item *
  107: 
  108: Generate Page Output
  109: 
  110: =item *
  111: 
  112: Choice or no choice
  113: 
  114: =item *
  115: 
  116: Table
  117: 
  118: =item *
  119: 
  120: Privileges
  121: 
  122: =back
  123: 
  124: =cut
  125: 
  126: 
  127: package Apache::lonroles;
  128: 
  129: use strict;
  130: use Apache::lonnet;
  131: use Apache::lonuserstate();
  132: use Apache::Constants qw(:common);
  133: use Apache::File();
  134: use Apache::lonmenu;
  135: use Apache::loncommon;
  136: use Apache::lonhtmlcommon;
  137: use Apache::lonannounce;
  138: use Apache::lonlocal;
  139: use Apache::lonpageflip();
  140: use Apache::lonnavdisplay();
  141: use Apache::lonmainmenu();
  142: use GDBM_File;
  143: use LONCAPA qw(:DEFAULT :match);
  144: use HTML::Entities;
  145:  
  146: 
  147: sub redirect_user {
  148:     my ($r,$title,$url,$msg,$launch_nav) = @_;
  149:     $msg = $title if (! defined($msg));
  150:     &Apache::loncommon::content_type($r,'text/html');
  151:     &Apache::loncommon::no_cache($r);
  152:     $r->send_http_header;
  153:     my $swinfo=&Apache::lonmenu::rawconfig();
  154:     my $navwindow;
  155:     if ($launch_nav eq 'on') {
  156: 	$navwindow.=&Apache::lonnavdisplay::launch_win('now',undef,undef,
  157: 						       ($url =~ m-^/adm/whatsnew-));
  158:     } else {
  159: 	$navwindow.=&Apache::lonnavmaps::close();
  160:     }
  161: 
  162:     # Breadcrumbs
  163:     my $brcrum = [{'href' => $url,
  164:                    'text' => 'Switching Role'},];
  165:     my $start_page = &Apache::loncommon::start_page('Switching Role',undef,
  166:                                                     {'redirect' => [1,$url],
  167:                                                      'bread_crumbs' => $brcrum,});
  168:     my $end_page   = &Apache::loncommon::end_page();
  169: 
  170: # Note to style police: 
  171: # This must only replace the spaces, nothing else, or it bombs elsewhere.
  172:     $url=~s/ /\%20/g;
  173:     $r->print(<<ENDREDIR);
  174: $start_page
  175: <script type="text/javascript">
  176: // <![CDATA[
  177: $swinfo
  178: // ]]>
  179: </script>
  180: $navwindow
  181: <p>$msg</p>
  182: $end_page
  183: ENDREDIR
  184:     return;
  185: }
  186: 
  187: sub error_page {
  188:     my ($r,$error,$dest)=@_;
  189:     &Apache::loncommon::content_type($r,'text/html');
  190:     &Apache::loncommon::no_cache($r);
  191:     $r->send_http_header;
  192:     return OK if $r->header_only;
  193:     # Breadcrumbs
  194:     my $brcrum = [{'href' => $dest,
  195:                    'text' => 'Problems during Course Initialization'},];
  196:     $r->print(&Apache::loncommon::start_page('Problems during Course Initialization',
  197:                                              undef,
  198:                                              {'bread_crumbs' => $brcrum,})
  199:     );
  200:     $r->print(
  201:         '<script type="text/javascript">'.
  202:         '// <![CDATA['.
  203:         &Apache::lonmenu::rawconfig().
  204:         '// ]]>'.
  205:         '</script>'.
  206: 	      '<p class="LC_error">'.&mt('The following problems occurred:').
  207:           '<br />'.
  208: 	      $error.
  209: 	      '</p><br /><a href="'.$dest.'">'.&mt('Continue').'</a>'
  210:     );
  211:     $r->print(&Apache::loncommon::end_page());
  212: }
  213: 
  214: sub handler {
  215: 
  216:     my $r = shift;
  217: 
  218:     my $now=time;
  219:     my $then=$env{'user.login.time'};
  220:     my $refresh=$env{'user.refresh.time'};
  221:     if (!$refresh) {
  222:         $refresh = $then;
  223:     }
  224:     my $envkey;
  225:     my %dcroles = ();
  226:     my $numdc = &check_fordc(\%dcroles,$then);
  227:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'});
  228:     my $custommenu = &Apache::loncommon::needs_gci_custom();
  229: 
  230: # ================================================================== Roles Init
  231:     if ($env{'form.selectrole'}) {
  232: 
  233:         my $locknum=&Apache::lonnet::get_locks();
  234:         if ($locknum) { return 409; }
  235: 
  236:         if ($env{'form.newrole'}) {
  237:             $env{'form.'.$env{'form.newrole'}}=1;
  238: 	}
  239: 	if ($env{'request.course.id'}) {
  240:             # Check if user is CC trying to select a course role
  241:             if ($env{'form.switchrole'}) {
  242:                 if (!defined($env{'user.role.'.$env{'form.switchrole'}})) {
  243:                     &adhoc_course_role($refresh,$then);
  244:                 }
  245:             }
  246: 	    my %temp=('logout_'.$env{'request.course.id'} => time);
  247: 	    &Apache::lonnet::put('email_status',\%temp);
  248: 	    &Apache::lonnet::delenv('user.state.'.$env{'request.course.id'});
  249: 	}
  250: 	&Apache::lonnet::appenv({"request.course.id"   => '',
  251: 			 	 "request.course.fn"   => '',
  252: 				 "request.course.uri"  => '',
  253: 				 "request.course.sec"  => '',
  254: 				 "request.role"        => 'cm',
  255:                                  "request.role.adv"    => $env{'user.adv'},
  256: 				 "request.role.domain" => $env{'user.domain'}});
  257: # Check if user is a DC trying to enter a course or author space and needs privs to be created
  258:         if ($numdc > 0) {
  259:             foreach my $envkey (keys %env) {
  260: # Is this an ad-hoc Coordinator role?
  261:                 if (my ($ccrole,$domain,$coursenum) =
  262: 		    ($envkey =~ m-^form\.(cc|co)\./($match_domain)/($match_courseid)$-)) {
  263:                     if ($dcroles{$domain}) {
  264:                         &Apache::lonnet::check_adhoc_privs($domain,$coursenum,
  265:                                                            $then,$refresh,$now,$ccrole);
  266:                     }
  267:                     last;
  268:                 }
  269: # Is this an ad-hoc CA-role?
  270:                 if (my ($domain,$user) =
  271: 		    ($envkey =~ m-^form\.ca\./($match_domain)/($match_username)$-)) {
  272:                     if (($domain eq $env{'user.domain'}) && ($user eq $env{'user.name'})) {
  273:                         delete($env{$envkey});
  274:                         $env{'form.au./'.$domain.'/'} = 1;
  275:                         my ($server_status,$home) = &check_author_homeserver($user,$domain);
  276:                         if ($server_status eq 'switchserver') {
  277:                             my $trolecode = 'au./'.$domain.'/';
  278:                             my $switchserver = '/adm/switchserver?otherserver='.$home.'&role='.$trolecode;
  279:                             $r->internal_redirect($switchserver);
  280:                         }
  281:                         last;
  282:                     }
  283:                     if (my ($castart,$caend) = ($env{'user.role.ca./'.$domain.'/'.$user} =~ /^(\d*)\.(\d*)$/)) {
  284:                         if (((($castart) && ($castart < $now)) || !$castart) && 
  285:                             ((!$caend) || (($caend) && ($caend > $now)))) {
  286:                             my ($server_status,$home) = &check_author_homeserver($user,$domain);
  287:                             if ($server_status eq 'switchserver') {
  288:                                 my $trolecode = 'ca./'.$domain.'/'.$user;
  289:                                 my $switchserver = '/adm/switchserver?otherserver='.$home.'&role='.$trolecode;
  290:                                 $r->internal_redirect($switchserver);
  291:                             }
  292:                             last;
  293:                         }
  294:                     }
  295:                     # Check if author blocked ca-access
  296:                     my %blocked=&Apache::lonnet::get('environment',['domcoord.author'],$domain,$user);
  297:                     if ($blocked{'domcoord.author'} eq 'blocked') {
  298:                         delete($env{$envkey});
  299:                         $env{'user.error.msg'}=':::1:User '.$user.' in domain '.$domain.' blocked domain coordinator access';
  300:                         last;
  301:                     }
  302:                     if ($dcroles{$domain}) {
  303:                         my ($server_status,$home) = &check_author_homeserver($user,$domain);
  304:                         if (($server_status eq 'ok') || ($server_status eq 'switchserver')) {
  305:                             &Apache::lonnet::check_adhoc_privs($domain,$user,$then,
  306:                                                                $refresh,$now,'ca');
  307:                             if ($server_status eq 'switchserver') {
  308:                                 my $trolecode = 'ca./'.$domain.'/'.$user; 
  309:                                 my $switchserver = '/adm/switchserver?'
  310:                                                   .'otherserver='.$home.'&role='.$trolecode;
  311:                                 $r->internal_redirect($switchserver);
  312:                             }
  313:                         } else {
  314:                             delete($env{$envkey});
  315:                         }
  316:                     } else {
  317:                         delete($env{$envkey});
  318:                     }
  319:                     last;
  320:                 }
  321:             }
  322:         }
  323:         if (($env{'form.cm'}) && ($env{'form.orgurl'})) { 
  324:             $r->internal_redirect($env{'form.orgurl'});
  325:         }
  326:         foreach $envkey (keys %env) {
  327:             next if ($envkey!~/^user\.role\./);
  328:             my ($where,$trolecode,$role,$tstatus,$tend,$tstart);
  329:             &Apache::lonnet::role_status($envkey,$then,$refresh,$now,\$role,\$where,
  330:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
  331:             if ($env{'form.'.$trolecode}) {
  332: 		if ($tstatus eq 'is') {
  333: 		    $where=~s/^\///;
  334: 		    my ($cdom,$cnum,$csec)=split(/\//,$where);
  335: # check for course groups
  336:                     my %coursegroups = &Apache::lonnet::get_active_groups(
  337:                           $env{'user.domain'},$env{'user.name'},$cdom, $cnum);
  338:                     my $cgrps = join(':',keys(%coursegroups));
  339: 
  340: # store role if recent_role list being kept
  341:                     if ($env{'environment.recentroles'}) {
  342:                         my %frozen_roles =
  343:                            &Apache::lonhtmlcommon::get_recent_frozen('roles',$env{'environment.recentrolesn'});
  344: 			&Apache::lonhtmlcommon::store_recent('roles',
  345: 							     $trolecode,' ',$frozen_roles{$trolecode});
  346:                     }
  347: 
  348: 
  349: # check for keyed access
  350: 		    if (($role eq 'st') && 
  351:                        ($env{'course.'.$cdom.'_'.$cnum.'.keyaccess'} eq 'yes')) {
  352: # who is key authority?
  353: 			my $authdom=$cdom;
  354: 			my $authnum=$cnum;
  355: 			if ($env{'course.'.$cdom.'_'.$cnum.'.keyauth'}) {
  356: 			    ($authnum,$authdom)=
  357: 				split(/:/,$env{'course.'.$cdom.'_'.$cnum.'.keyauth'});
  358: 			}
  359: # check with key authority
  360: 			unless (&Apache::lonnet::validate_access_key(
  361: 				     $env{'environment.key.'.$cdom.'_'.$cnum},
  362: 					     $authdom,$authnum)) {
  363: # there is no valid key
  364: 			     if ($env{'form.newkey'}) {
  365: # student attempts to register a new key
  366: 				 &Apache::loncommon::content_type($r,'text/html');
  367: 				 &Apache::loncommon::no_cache($r);
  368: 				 $r->send_http_header;
  369: 				 my $swinfo=&Apache::lonmenu::rawconfig();
  370: 				 my $start_page=&Apache::loncommon::start_page
  371: 				    ('Verifying Access Key to Unlock this Course');
  372: 				 my $end_page=&Apache::loncommon::end_page();
  373: 				 my $buttontext=&mt('Enter Course');
  374: 				 my $message=&mt('Successfully registered key');
  375: 				 my $assignresult=
  376: 				     &Apache::lonnet::assign_access_key(
  377: 						     $env{'form.newkey'},
  378: 						     $authdom,$authnum,
  379: 						     $cdom,$cnum,
  380:                                                      $env{'user.domain'},
  381: 						     $env{'user.name'},
  382:                                                      &mt('Assigned from [_1] at [_2] for [_3]'
  383:                                                         ,$ENV{'REMOTE_ADDR'}
  384:                                                         ,&Apache::lonlocal::locallocaltime()
  385:                                                         ,$trolecode)
  386:                                                      );
  387: 				 unless ($assignresult eq 'ok') {
  388: 				     $assignresult=~s/^error\:\s*//;
  389: 				     $message=&mt($assignresult).
  390: 				     '<br /><a href="/adm/logout">'.
  391: 				     &mt('Logout').'</a>';
  392: 				     $buttontext=&mt('Re-Enter Key');
  393: 				 }
  394: 				 $r->print(<<ENDENTEREDKEY);
  395: $start_page
  396: <script type="text/javascript">
  397: // <![CDATA[
  398: $swinfo
  399: // ]]>
  400: </script>
  401: <form action="" method="post">
  402: <input type="hidden" name="selectrole" value="1" />
  403: <input type="hidden" name="$trolecode" value="1" />
  404: <span class="LC_fontsize_large">$message</span><br />
  405: <input type="submit" value="$buttontext" />
  406: </form>
  407: $end_page
  408: ENDENTEREDKEY
  409:                                  return OK;
  410: 			     } else {
  411: # print form to enter a new key
  412: 				 &Apache::loncommon::content_type($r,'text/html');
  413: 				 &Apache::loncommon::no_cache($r);
  414: 				 $r->send_http_header;
  415: 				 my $swinfo=&Apache::lonmenu::rawconfig();
  416: 				 my $start_page=&Apache::loncommon::start_page
  417: 				    ('Enter Access Key to Unlock this Course');
  418: 				 my $end_page=&Apache::loncommon::end_page();
  419: 				 $r->print(<<ENDENTERKEY);
  420: $start_page
  421: <script type="text/javascript">
  422: // <![CDATA[
  423: $swinfo
  424: // ]]>
  425: </script>
  426: <form action="" method="post">
  427: <input type="hidden" name="selectrole" value="1" />
  428: <input type="hidden" name="$trolecode" value="1" />
  429: <input type="text" size="20" name="newkey" value="$env{'form.newkey'}" />
  430: <input type="submit" value="Enter key" />
  431: </form>
  432: $end_page
  433: ENDENTERKEY
  434: 				 return OK;
  435: 			     }
  436: 			 }
  437: 		     }
  438: 		    &Apache::lonnet::log($env{'user.domain'},
  439: 					 $env{'user.name'},
  440: 					 $env{'user.home'},
  441: 					 "Role ".$trolecode);
  442: 		    
  443: 		    &Apache::lonnet::appenv(
  444: 					   {'request.role'        => $trolecode,
  445: 					    'request.role.domain' => $cdom,
  446: 					    'request.course.sec'  => $csec,
  447:                                             'request.course.groups' => $cgrps});
  448:                     my $tadv=0;
  449: 
  450: 		    if (($cnum) && ($role ne 'ca') && ($role ne 'aa')) {
  451:                         my $msg;
  452: 			my ($furl,$ferr)=
  453: 			    &Apache::lonuserstate::readmap($cdom.'/'.$cnum);
  454: 			if (($env{'form.orgurl'}) && 
  455: 			    ($env{'form.orgurl'}!~/^\/adm\/flip/)) {
  456: 			    my $dest=$env{'form.orgurl'};
  457:                             if ($env{'form.symb'}) {
  458:                                 if ($dest =~ /\?/) {
  459:                                     $dest .= '&';
  460:                                 } else {
  461:                                     $dest .= '?'
  462:                                 }
  463:                                 $dest .= 'symb='.$env{'form.symb'};
  464:                             }
  465: 			    if (&Apache::lonnet::allowed('adv') eq 'F') { $tadv=1; }
  466: 			    &Apache::lonnet::appenv({'request.role.adv'=>$tadv});
  467:                             if (($ferr) && ($tadv)) {
  468: 				&error_page($r,$ferr,$dest);
  469: 			    } else {
  470: 				$r->internal_redirect($dest);
  471: 			    }
  472: 			    return OK;
  473: 			} else {
  474: 			    if (!$env{'request.course.id'}) {
  475: 				&Apache::lonnet::appenv(
  476: 				      {"request.course.id"  => $cdom.'_'.$cnum});
  477: 				$furl='/adm/roles?tryagain=1';
  478:                 $msg='<p><span class="LC_error">'
  479:                     .&mt('Could not initialize [_1] at this time.',
  480:                          $env{'course.'.$cdom.'_'.$cnum.'.description'})
  481:                     .'</span></p>'
  482:                     .'<p>'.&mt('Please try again.').'</p>'
  483:                     .'<p>'.$ferr.'</p>';
  484: 			    }
  485: 			    if (&Apache::lonnet::allowed('adv') eq 'F') { $tadv=1; }
  486: 			    &Apache::lonnet::appenv({'request.role.adv'=>$tadv});
  487: 
  488: 			    if (($ferr) && ($tadv)) {
  489: 				&error_page($r,$ferr,$furl);
  490: 			    } else {
  491: 				# Check to see if the user is a CC entering a course 
  492: 				# for the first time
  493: 				my (undef, undef, $role, $courseid) = split(/\./, $envkey);
  494: 				if (substr($courseid, 0, 1) eq '/') {
  495: 				    $courseid = substr($courseid, 1);
  496: 				}
  497: 				$courseid =~ s/\//_/;
  498: 				if (($cdom ne 'gcitest') && (($role eq 'cc') || ($role eq 'co')) 
  499:                                     && ($env{'course.' . $courseid .'.course.helper.not.run'})) { 
  500: 				    $furl = "/adm/helper/course.initialization.helper";
  501: 				    # Send the user to the course they selected
  502: 				} elsif ($env{'request.course.id'}) {
  503:                                     if ($env{'form.destinationurl'}) {
  504:                                         my $dest = $env{'form.destinationurl'};
  505:                                         if ($env{'form.destsymb'} ne '') {
  506:                                             my $esc_symb = &HTML::Entities::encode($env{'form.destsymb'},'"<>&');
  507:                                             $dest .= '?symb='.$esc_symb;
  508:                                         }
  509:                                         &redirect_user($r,&mt('Entering [_1]',
  510:                                                       $env{'course.'.$courseid.'.description'}),
  511:                                                $dest,$msg,
  512:                                                $env{'environment.remotenavmap'});
  513:                                         return OK;
  514:                                     }
  515: 				    if (&Apache::lonnet::allowed('whn',
  516: 								 $env{'request.course.id'})
  517: 					|| &Apache::lonnet::allowed('whn',
  518: 								    $env{'request.course.id'}.'/'
  519: 								    .$env{'request.course.sec'})
  520: 					) {
  521: 					my $startpage = &courseloadpage($courseid);
  522: 					unless (($startpage eq 'firstres') || ($cdom eq 'gcitest')) {
  523: 					    $msg = &mt('Entering [_1] ...',
  524: 						       $env{'course.'.$courseid.'.description'});
  525: 					    &redirect_user($r,&mt('New in course'),
  526: 							   '/adm/whatsnew?refpage=start',$msg,
  527: 							   $env{'environment.remotenavmap'});
  528: 					    return OK;
  529: 					}
  530: 				    }
  531: 				}
  532: # Are we allowed to look at the first resource?
  533: 				if ($furl !~ m|^/adm/|) {
  534: # Guess not ...
  535: 				    $furl=&Apache::lonpageflip::first_accessible_resource();
  536: 				}
  537:                                 if (($cdom eq 'gcitest') && ($custommenu)) {
  538:                                     $furl = '/adm/navmaps';
  539:                                 }
  540:                                 $msg = &mt('Entering [_1] ...',
  541: 					   $env{'course.'.$courseid.'.description'});
  542: 				&redirect_user($r,&mt('Entering [_1]',
  543: 						      $env{'course.'.$courseid.'.description'}),
  544: 					       $furl,$msg,
  545: 					       $env{'environment.remotenavmap'});
  546: 			    }
  547: 			    return OK;
  548: 			}
  549: 		    }
  550:                     #
  551:                     # Send the user to the construction space they selected
  552:                     if ($role =~ /^(au|ca|aa)$/) {
  553:                         my $redirect_url = '/priv/';
  554:                         if ($role eq 'au') {
  555:                             $redirect_url.=$env{'user.name'};
  556:                         } else {
  557:                             $where =~ /\/(.*)$/;
  558:                             $redirect_url .= $1;
  559:                         }
  560:                         $redirect_url .= '/';
  561:                         &redirect_user($r,&mt('Entering Construction Space'),
  562:                                        $redirect_url);
  563:                         return OK;
  564:                     }
  565:                     if ($role eq 'dc') {
  566:                         my $redirect_url = '/adm/menu/';
  567:                         &redirect_user($r,&mt('Loading Domain Coordinator Menu'),
  568:                                        $redirect_url);
  569:                         return OK;
  570:                     }
  571:                     if ($role eq 'sc') {
  572:                         my $redirect_url = '/adm/grades?command=scantronupload';
  573:                         &redirect_user($r,&mt('Loading Data Upload Page'),
  574:                                        $redirect_url);
  575:                         return OK;
  576:                     }
  577: 		}
  578:             }
  579:         }
  580:     }
  581: 
  582: # =============================================================== No Roles Init
  583: 
  584:     &Apache::loncommon::content_type($r,'text/html');
  585:     &Apache::loncommon::no_cache($r);
  586:     $r->send_http_header;
  587:     return OK if $r->header_only;
  588: 
  589:     my ($crumbtext,$pagetitle,$recent,$show_course);
  590:     my $noscript='<span class="LC_error">'.&mt('Use of LON-CAPA requires Javascript to be enabled in your web browser.').'<br />'.&mt('As this is not the case, most functionality in the system will be unavailable.').'</span><br />';
  591:     if ($custommenu) {
  592:         my $start_page = &Apache::loncommon::start_page('Main Menu',undef,
  593:                                                         {'bread_crumbs' => 1});
  594:         $r->print(<<"ENDCUSTOM");
  595: $start_page
  596: <br />
  597: <noscript>
  598: $noscript
  599: </noscript>
  600: ENDCUSTOM
  601:     } else {
  602:         $crumbtext = 'User Roles';
  603:         $pagetitle = 'My Roles';
  604:         $recent = &mt('Recent Roles');
  605:         $show_course=&Apache::loncommon::show_course();
  606:         if ($show_course) {
  607:             $crumbtext = 'Courses';
  608:             $pagetitle = 'My Courses';
  609:             $recent = &mt('Recent Courses');
  610:         }
  611:         my $brcrum =[{href=>"/adm/roles",text=>$crumbtext}];
  612:         my $swinfo=&Apache::lonmenu::rawconfig();
  613:         my $start_page=&Apache::loncommon::start_page($pagetitle,undef,{bread_crumbs=>$brcrum});
  614:         my $standby=&mt('Role selected. Please stand by.');
  615:         $standby=~s/\n/\\n/g;
  616:         $r->print(<<ENDHEADER);
  617: $start_page
  618: <br />
  619: <noscript>
  620: $noscript
  621: </noscript>
  622: <script type="text/javascript">
  623: // <![CDATA[
  624: $swinfo
  625: window.focus();
  626: 
  627: active=true;
  628: 
  629: function enterrole (thisform,rolecode,buttonname) {
  630:     if (active) {
  631: 	active=false;
  632:         document.title='$standby';
  633:         window.status='$standby';
  634: 	thisform.newrole.value=rolecode;
  635: 	thisform.submit();
  636:     } else {
  637:        alert('$standby');
  638:     }   
  639: }
  640: // ]]>
  641: </script>
  642: ENDHEADER
  643:     }
  644: 
  645: # ------------------------------------------ Get Error Message from Environment
  646: 
  647:     my ($fn,$priv,$nochoose,$error,$msg)=split(/:/,$env{'user.error.msg'});
  648:     if ($env{'user.error.msg'}) {
  649: 	$r->log_reason(
  650:    "$msg for $env{'user.name'} domain $env{'user.domain'} access $priv",$fn);
  651:     }
  652: 
  653: # ------------------------------------------------- Can this user re-init, etc?
  654: 
  655:     my $advanced=$env{'user.adv'};
  656:     &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},['tryagain']);
  657:     my $tryagain=$env{'form.tryagain'};
  658:     my $reinit=$env{'user.reinit'};
  659:     delete $env{'user.reinit'};
  660: 
  661: # -------------------------------------------------------- Generate Page Output
  662: # --------------------------------------------------------------- Error Header?
  663:     if ($error) {
  664:         $r->print("<h1>".&mt('LON-CAPA Access Control')."</h1>");
  665: 	$r->print("<!-- LONCAPAACCESSCONTROLERRORSCREEN --><hr /><pre>");
  666: 	if ($priv ne '') {
  667:             $r->print(&mt('Access  : ').&Apache::lonnet::plaintext($priv)."\n");
  668: 	}
  669: 	if ($fn ne '') {
  670:             $r->print(&mt('Resource: ').&Apache::lonenc::check_encrypt($fn)."\n");
  671: 	}
  672: 	if ($msg ne '') {
  673:             $r->print(&mt('Action  : ').$msg."\n");
  674: 	}
  675: 	$r->print("</pre><hr />");
  676: 	my $url=$fn;
  677: 	my $last;
  678: 	if (tie(my %hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
  679: 		&GDBM_READER(),0640)) {
  680: 	    $last=$hash{'last_known'};
  681: 	    untie(%hash);
  682: 	}
  683: 	if ($last) { $fn.='?symb='.&escape($last); }
  684: 
  685: 	&Apache::londocs::changewarning($r,undef,'You have modified your course recently, [_1] may fix this access problem.',
  686: 					&Apache::lonenc::check_encrypt($fn));
  687:     } else {
  688:         if ($env{'user.error.msg'}) {
  689:             if ($reinit) {
  690:                 $r->print(
  691:  '<h3><span class="LC_error">'.
  692:  &mt('As your session file for the course or community has expired, you will need to re-select it.').'</span></h3>');
  693:             } else {
  694: 	        $r->print(
  695:  '<h3><span class="LC_error">'.
  696:  &mt('You need to choose another user role or enter a specific course or community for this function.').
  697:  '</span></h3>');
  698: 	    }
  699:         }
  700:     }
  701: # -------------------------------------------------------- Choice or no choice?
  702:     if ($nochoose) {
  703: 	$r->print("<h2>".&mt('Sorry ...')."</h2>\n<span class='LC_error'>".
  704: 		  &mt('This action is currently not authorized.').'</span>'.
  705: 		  &Apache::loncommon::end_page());
  706: 	return OK;
  707:     } else {
  708:         if (($ENV{'REDIRECT_QUERY_STRING'}) && ($fn)) {
  709:     	    $fn.='?'.$ENV{'REDIRECT_QUERY_STRING'};
  710:         }
  711:         unless ($custommenu) {
  712:             $r->print('<form method="post" name="rolechoice" action="'.(($fn)?$fn:$r->uri).'">');
  713:             $r->print('<input type="hidden" name="orgurl" value="'.$fn.'" />');
  714:             $r->print('<input type="hidden" name="selectrole" value="1" />');
  715:             $r->print('<input type="hidden" name="newrole" value="" />');
  716:         }
  717:     }
  718: 
  719:     my (%roletext,%sortrole,%roleclass,%futureroles,%timezones);
  720:     my ($countactive,$countfuture,$inrole,$possiblerole) = 
  721:         &gather_roles($then,$refresh,$now,$reinit,$nochoose,\%roletext,\%sortrole,\%roleclass,
  722:                       \%futureroles,\%timezones);
  723: 
  724:     $refresh = $now;
  725:     &Apache::lonnet::appenv({'user.refresh.time'  => $refresh});
  726:     if ($custommenu) {
  727:         my %courses = &Apache::loncommon::existing_gcitest_courses();
  728:         $env{'browser.interface'}='faketextual';
  729:         $env{'environment.remote'}='off';
  730:         my $numcourses = keys(%courses);
  731:         my $switcher;
  732:         if ($numcourses > 0) {
  733:             $switcher = &Apache::lonmainmenu::gcitest_switcher(%courses);
  734:             my $current;
  735:             if ($env{'request.course.id'}) {
  736:                 $current = 'cc./'.$env{'course.'.$env{'request.course.id'}.'.domain'}.
  737:                            '/'.$env{'course.'.$env{'request.course.id'}.'.num'};
  738:             }
  739:             my $switcher_js = &Apache::lonmainmenu::gcitest_switcher_js($current,$numcourses);
  740:             $r->print(<<"ENDSCRIPT");
  741: <script type="text/javascript">
  742: // <![CDATA[
  743: $switcher_js
  744: // ]]>
  745: </script>
  746: ENDSCRIPT
  747:         }
  748:         $r->print(&Apache::lonmenu::inlinemenu('gcicustom',$switcher).
  749:                   &Apache::loncommon::end_page());
  750:         return OK;
  751:     }
  752:     if ($env{'user.adv'}) {
  753:         $r->print('<p><label><input type="checkbox" name="showall"');
  754:         if ($env{'form.showall'}) { $r->print(' checked="checked" '); }
  755:         $r->print(' />'.&mt('Show all roles').'</label>'
  756:                  .' <input type="submit" value="'.&mt('Update display').'" />'
  757:                  .'</p>');
  758:     } else {
  759:         if ($countactive > 0) {
  760:             &queued_selfenrollment($r);
  761:             my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
  762:             my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&'); 
  763:             $r->print(
  764:                 '<p>'
  765:                .&mt('[_1]Visit the [_2]Course/Community Catalog[_3]'
  766:                    .' to view all [_4] LON-CAPA courses and communities.'
  767:                    ,'<b>'
  768:                    ,'<a href="/adm/coursecatalog?showdom='.$esc_dom.'">'
  769:                    ,'</a></b>',$domdesc)
  770:                .'<br />'
  771:                .&mt('If a course or community is [_1]not[_2] in your list of current courses and communities below,'
  772:                    .' you may be able to enroll if self-enrollment is permitted.'
  773:                    ,'<b>','</b>')
  774:                .'</p>'
  775:             );
  776:         }
  777:     }
  778: 
  779: # No active roles
  780:     if ($countactive==0) {
  781: 	if ($inrole) {
  782: 	    $r->print('<h2>'.&mt('Currently no additional roles, courses or communities').'</h2>');
  783: 	} else {
  784: 	    $r->print('<h2>'.&mt('Currently no active roles, courses or communities').'</h2>');
  785: 	}
  786:         &findcourse_advice($r);
  787:         &requestcourse_advice($r); 
  788: 	$r->print('</form>');
  789:         if ($countfuture) {
  790:             $r->print(&mt('The following [quant,_1,role,roles] will become active in the future:',$countfuture));
  791:             my $doheaders = &roletable_headers($r,\%roleclass,\%sortrole,
  792:                                                $nochoose);
  793:             &print_rolerows($r,$doheaders,\%roleclass,\%sortrole,\%dcroles,
  794:                             \%roletext);
  795:             my $tremark='';
  796:             my $tbg;
  797:             if ($env{'request.role'} eq 'cm') {
  798:                 $tbg="LC_roles_selected";
  799:                 $tremark=&mt('Currently selected.').' ';
  800:             } else {
  801:                 $tbg="LC_roles_is";
  802:             }
  803:             $r->print(&Apache::loncommon::start_data_table_row()
  804:                      .'<td class="'.$tbg.'">&nbsp;</td>'
  805:                      .'<td colspan="3">'
  806:                      .&mt('No role specified')
  807:                      .'</td>'
  808:                      .'<td>'.$tremark.'&nbsp;</td>'
  809:                      .&Apache::loncommon::end_data_table_row()
  810:             );
  811: 
  812:             $r->print(&Apache::loncommon::end_data_table());
  813:         }
  814:         $r->print(&Apache::loncommon::end_page());
  815: 	return OK;
  816:     } elsif ($countactive==1) { # Is there only one choice?
  817:         my $needs_switchserver;
  818:         if ($env{'user.author'}) {
  819:             $needs_switchserver = &check_needs_switchserver($possiblerole);
  820:         }
  821:         if ((!$needs_switchserver) && ($env{'request.role'} eq 'cm')) {
  822:             $r->print('<h3>'.&mt('Please stand by.').'</h3>'.
  823:                 '<input type="hidden" name="'.$possiblerole.'" value="1" />'.
  824:             '<noscript><br /><input type="submit" name="submit" value="'.&mt('Continue').'" /></noscript>');
  825:             $r->print("</form>\n");
  826:             $r->rflush();
  827:             $r->print('<script type="text/javascript">document.forms.rolechoice.submit();</script>');
  828:             $r->print(&Apache::loncommon::end_page());
  829:             return OK;
  830:         }
  831:         if ($needs_switchserver) {
  832:             $r->print("<h2>".&mt('Server Switch Required')."</h2>\n".
  833:                       &mt('Construction Space access is only available from '.
  834:                           'the home server of the corresponding Author.').'<br />'.
  835:                       &mt("Click the 'Switch Server' link to go there.").'<br />');
  836:         }
  837:     }
  838: # ----------------------------------------------------------------------- Table
  839:     unless ((!&Apache::loncommon::show_course()) || ($nochoose) || ($countactive==1)) {
  840: 	$r->print("<h2>".&mt('Select a Course to Enter')."</h2>\n");
  841:     }
  842:     if ($env{'form.destinationurl'}) {
  843:         $r->print('<input type="hidden" name="destinationurl" value="'.
  844:                   $env{'form.destinationurl'}.'" />');
  845:         if ($env{'form.destsymb'} ne '') {
  846:             $r->print('<input type="hidden" name="destsymb" value="'.
  847:                       $env{'form.destsymb'}.'" />');
  848:         }
  849:     }
  850:     my $doheaders = &roletable_headers($r,\%roleclass,\%sortrole,$nochoose);
  851:     if ($env{'environment.recentroles'}) {
  852:         my %recent_roles =
  853:                &Apache::lonhtmlcommon::get_recent('roles',$env{'environment.recentrolesn'});
  854: 	my $output='';
  855: 	foreach (sort(keys(%recent_roles))) {
  856: 	    if (ref($roletext{'user.role.'.$_}) eq 'ARRAY') {
  857: 		$output.= &Apache::loncommon::start_data_table_row().
  858:                           $roletext{'user.role.'.$_}->[0].
  859:                           &Apache::loncommon::end_data_table_row().
  860:                           &Apache::loncommon::continue_data_table_row().
  861:                           $roletext{'user.role.'.$_}->[1].
  862:                           &Apache::loncommon::end_data_table_row();
  863:                 if ($_ =~ m-dc\./($match_domain)/- 
  864: 		    && $dcroles{$1}) {
  865: 		    $output .= &adhoc_roles_row($1,'recent');
  866:                 }
  867: 	    } elsif ($numdc > 0) {
  868:                 unless ($_ =~/^error\:/) {
  869:                     $output.=&display_cc_role('user.role.'.$_);
  870:                 }
  871:             } 
  872: 	}
  873: 	if ($output) {
  874: 	    $r->print(&Apache::loncommon::start_data_table_empty_row()
  875:                      .'<td align="center" colspan="5">'
  876:                      .$recent
  877:                      .'</td>'
  878:                      .&Apache::loncommon::end_data_table_empty_row()
  879:             );
  880: 	    $r->print($output);
  881:             $doheaders ++;
  882: 	}
  883:     }
  884: 
  885:     if ($numdc > 0) {
  886:         $r->print(&coursepick_jscript());
  887:         $r->print(&Apache::loncommon::coursebrowser_javascript().
  888:                   &Apache::loncommon::authorbrowser_javascript());
  889:     }
  890:     &print_rolerows($r,$doheaders,\%roleclass,\%sortrole,\%dcroles,\%roletext);
  891:     if ($countactive > 1) {
  892:         my $tremark='';
  893:         my $tbg;
  894:         if ($env{'request.role'} eq 'cm') {
  895:             $tbg="LC_roles_selected";
  896:             $tremark=&mt('Currently selected.').' ';
  897:         } else {
  898:                 $tbg="LC_roles_is";
  899:         }
  900:         $r->print(&Apache::loncommon::start_data_table_row());
  901:         unless ($nochoose) {
  902: 	    if ($env{'request.role'} ne 'cm') {
  903: 	        $r->print('<td class="'.$tbg.'"><input type="submit" value="'.
  904: 		          &mt('Select').'" name="cm" /></td>');
  905: 	    } else {
  906: 	        $r->print('<td class="'.$tbg.'">&nbsp;</td>');
  907: 	    }
  908:         }
  909:         $r->print('<td colspan="3">'
  910:                  .&mt('No role specified')
  911:                  .'</td>'
  912:                  .'<td>'.$tremark.'&nbsp;</td>'
  913:                  .&Apache::loncommon::end_data_table_row()
  914:         );
  915:     } 
  916:     $r->print(&Apache::loncommon::end_data_table());
  917:     unless ($nochoose) {
  918: 	$r->print("</form>\n");
  919:     }
  920: # ------------------------------------------------------------ Privileges Info
  921:     if (($advanced) && (($env{'user.error.msg'}) || ($error))) {
  922: 	$r->print('<hr /><h2>'.&mt('Current Privileges').'</h2>');
  923: 	$r->print(&privileges_info());
  924:     }
  925:     $r->print(&Apache::lonnet::getannounce());
  926:     if ($advanced) {
  927:         my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&');
  928:         $r->print('<p><small><i>'
  929:                  .&mt('This LON-CAPA server is version [_1]',$r->dir_config('lonVersion'))
  930:                  .'</i><br />'
  931:                  .'<a href="/adm/logout">'.&mt('Logout').'</a>&nbsp;&nbsp;'
  932:                  .'<a href="/adm/coursecatalog?showdom='.$esc_dom.'">'
  933:                  .&mt('Course/Community Catalog')
  934:                  .'</a></small></p>');
  935:     }
  936:     $r->print(&Apache::loncommon::end_page());
  937:     return OK;
  938: }
  939: 
  940: sub gather_roles {
  941:     my ($then,$refresh,$now,$reinit,$nochoose,$roletext,$sortrole,$roleclass,$futureroles,$timezones) = @_;
  942:     my ($countactive,$countfuture,$inrole,$possiblerole) = (0,0,0,'');
  943:     my $advanced = $env{'user.adv'};
  944:     my $tryagain = $env{'form.tryagain'};
  945:     foreach my $envkey (sort(keys(%env))) {
  946:         my $button = 1;
  947:         my $switchserver='';
  948:         my ($role_text,$role_text_end,$sortkey);
  949:         if ($envkey=~/^user\.role\./) {
  950:             my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
  951:             &Apache::lonnet::role_status($envkey,$then,$refresh,$now,\$role,\$where,
  952:                                          \$trolecode,\$tstatus,\$tstart,\$tend);
  953:             next if (!defined($role) || $role eq '' || $role =~ /^gr/);
  954:             my $timezone = &role_timezone($where,$timezones);
  955:             $tremark='';
  956:             $tpstart='&nbsp;';
  957:             $tpend='&nbsp;';
  958:             if ($tstart) {
  959:                 $tpstart=&Apache::lonlocal::locallocaltime($tstart,$timezone);
  960:             }
  961:             if ($tend) {
  962:                 $tpend=&Apache::lonlocal::locallocaltime($tend,$timezone);
  963:             }
  964:             if ($env{'request.role'} eq $trolecode) {
  965:                 $tstatus='selected';
  966:             }
  967:             my $tbg;
  968:             if (($tstatus eq 'is')
  969:                 || ($tstatus eq 'selected')
  970:                 || ($tstatus eq 'future')
  971:                 || ($env{'form.showall'})) {
  972:                 if ($tstatus eq 'is') {
  973:                     $tbg='LC_roles_is';
  974:                     $possiblerole=$trolecode;
  975:                     $countactive++;
  976:                 } elsif ($tstatus eq 'future') {
  977:                     $tbg='LC_roles_future';
  978:                     $button=0;
  979:                     $futureroles->{$trolecode} = $tstart.':'.$tend;
  980:                     $countfuture ++;
  981:                 } elsif ($tstatus eq 'expired') {
  982:                     $tbg='LC_roles_expired';
  983:                     $button=0;
  984:                 } elsif ($tstatus eq 'will_not') {
  985:                     $tbg='LC_roles_will_not';
  986:                     $tremark.=&mt('Expired after logout.').' ';
  987:                 } elsif ($tstatus eq 'selected') {
  988:                     $tbg='LC_roles_selected';
  989:                     $inrole=1;
  990:                     $countactive++;
  991:                     $tremark.=&mt('Currently selected.').' ';
  992:                 }
  993:                 my $trole;
  994:                 if ($role =~ /^cr\//) {
  995:                     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$role);
  996:                     if ($tremark) { $tremark.='<br />'; }
  997:                     $tremark.=&mt('Defined by [_1] at [_2].',$rauthor,$rdomain);
  998:                 }
  999:                 $trole=Apache::lonnet::plaintext($role);
 1000:                 my $ttype;
 1001:                 my $twhere;
 1002:                 my ($tdom,$trest,$tsection)=
 1003:                     split(/\//,Apache::lonnet::declutter($where));
 1004:                 # First, Co-Authorship roles
 1005:                 if (($role eq 'ca') || ($role eq 'aa')) {
 1006:                     my $home = &Apache::lonnet::homeserver($trest,$tdom);
 1007:                     my $allowed=0;
 1008:                     my @ids=&Apache::lonnet::current_machine_ids();
 1009:                     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 1010:                     if (!$allowed) {
 1011:                         $button=0;
 1012:                         $switchserver='otherserver='.$home.'&role='.$trolecode;
 1013:                     }
 1014:                     #next if ($home eq 'no_host');
 1015:                     $home = &Apache::lonnet::hostname($home);
 1016:                     $ttype='Construction Space';
 1017:                     $twhere=&mt('User').': '.$trest.'<br />'.&mt('Domain').
 1018:                         ': '.$tdom.'<br />'.
 1019:                         ' '.&mt('Server').':&nbsp;'.$home;
 1020:                     $env{'course.'.$tdom.'_'.$trest.'.description'}='ca';
 1021:                     $tremark.=&Apache::lonhtmlcommon::authorbombs('/res/'.$tdom.'/'.$trest.'/');
 1022:                     $sortkey=$role."$trest:$tdom";
 1023:                 } elsif ($role eq 'au') {
 1024:                     # Authors
 1025:                     my $home = &Apache::lonnet::homeserver
 1026:                         ($env{'user.name'},$env{'user.domain'});
 1027:                     my $allowed=0;
 1028:                     my @ids=&Apache::lonnet::current_machine_ids();
 1029:                     foreach my $id (@ids) { if ($id eq $home) { $allowed=1; } }
 1030:                     if (!$allowed) {
 1031:                         $button=0;
 1032:                         $switchserver='otherserver='.$home.'&role='.$trolecode;
 1033:                     }
 1034:                     #next if ($home eq 'no_host');
 1035:                     $home = &Apache::lonnet::hostname($home);
 1036:                     $ttype='Construction Space';
 1037:                     $twhere=&mt('Domain').': '.$tdom.'<br />'.&mt('Server').
 1038:                         ':&nbsp;'.$home;
 1039:                     $env{'course.'.$tdom.'_'.$trest.'.description'}='ca';
 1040:                     $tremark.=&Apache::lonhtmlcommon::authorbombs('/res/'.$tdom.'/'.$env{'user.name'}.'/');
 1041:                     $sortkey=$role;
 1042:                 } elsif ($trest) {
 1043:                     my $tcourseid=$tdom.'_'.$trest;
 1044:                     $ttype = &Apache::loncommon::course_type($tcourseid);
 1045:                     $trole = &Apache::lonnet::plaintext($role,$ttype);
 1046:                     if ($env{'course.'.$tcourseid.'.description'}) {
 1047:                         $twhere=$env{'course.'.$tcourseid.'.description'};
 1048:                         $sortkey=$role."\0".$tdom."\0".$twhere."\0".$envkey;
 1049:                         unless ($twhere eq &mt('Currently not available')) {
 1050:                             $twhere.=' <span class="LC_fontsize_small">'.
 1051:         &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$trest,$tdom).
 1052:                                     '</span>';
 1053:                         }
 1054:                     } else {
 1055:                         my %newhash=&Apache::lonnet::coursedescription($tcourseid);
 1056:                         if (%newhash) {
 1057:                             $sortkey=$role."\0".$tdom."\0".$newhash{'description'}.
 1058:                                 "\0".$envkey;
 1059:                             $twhere=$newhash{'description'}.
 1060:                               ' <span class="LC_fontsize_small">'.
 1061:         &Apache::loncommon::syllabuswrapper(&mt('Syllabus'),$trest,$tdom).
 1062:                               '</span>';
 1063:                             $ttype = $newhash{'type'};
 1064:                             $trole = &Apache::lonnet::plaintext($role,$ttype);
 1065:                         } else {
 1066:                             $twhere=&mt('Currently not available');
 1067:                             $env{'course.'.$tcourseid.'.description'}=$twhere;
 1068:                             $sortkey=$role."\0".$tdom."\0".$twhere."\0".$envkey;
 1069:                             $ttype = 'Unavailable';
 1070:                         }
 1071:                     }
 1072:                     if ($tsection) {
 1073:                         $twhere.='<br />'.&mt('Section').': '.$tsection;
 1074:                     }
 1075:                     if ($role ne 'st') { $twhere.="<br />".&mt('Domain').":".$tdom; }
 1076:                 } elsif ($tdom) {
 1077:                     $ttype='Domain';
 1078:                     $twhere=$tdom;
 1079:                     $sortkey=$role.$twhere;
 1080:                 } else {
 1081:                     $ttype='System';
 1082:                     $twhere=&mt('system wide');
 1083:                     $sortkey=$role.$twhere;
 1084:                 }
 1085:                 ($role_text,$role_text_end) =
 1086:                     &build_roletext($trolecode,$tdom,$trest,$tstatus,$tryagain,
 1087:                                     $advanced,$tremark,$tbg,$trole,$twhere,$tpstart,
 1088:                                     $tpend,$nochoose,$button,$switchserver,$reinit);
 1089:                 $roletext->{$envkey}=[$role_text,$role_text_end];
 1090:                 if (!$sortkey) {$sortkey=$twhere."\0".$envkey;}
 1091:                 $sortrole->{$sortkey}=$envkey;
 1092:                 $roleclass->{$envkey}=$ttype;
 1093:             }
 1094:         }
 1095:     }
 1096:     return ($countactive,$countfuture,$inrole,$possiblerole);
 1097: }
 1098: 
 1099: sub role_timezone {
 1100:     my ($where,$timezones) = @_;
 1101:     my $timezone;
 1102:     if (ref($timezones) eq 'HASH') { 
 1103:         if ($where =~ m{^/($match_domain)/($match_courseid)}) {
 1104:             my $cdom = $1;
 1105:             my $cnum = $2;
 1106:             if ($cdom && $cnum) {
 1107:                 if (!exists($timezones->{$cdom.'_'.$cnum})) {
 1108:                     my %timehash =
 1109:                         &Apache::lonnet::get('environment',['timezone'],$cdom,$cnum);
 1110:                     if ($timehash{'timezone'} eq '') {
 1111:                         if (!exists($timezones->{$cdom})) {
 1112:                             my %domdefaults = 
 1113:                                 &Apache::lonnet::get_domain_defaults($cdom);
 1114:                             if ($domdefaults{'timezone_def'} eq '') {
 1115:                                 $timezones->{$cdom} = 'local';
 1116:                             } else {
 1117:                                 $timezones->{$cdom} = $domdefaults{'timezone_def'};
 1118:                             }
 1119:                         }
 1120:                         $timezones->{$cdom.'_'.$cnum} = $timezones->{$cdom};
 1121:                     } else {
 1122:                         $timezones->{$cdom.'_'.$cnum} = 
 1123:                             &Apache::lonlocal::gettimezone($timehash{'timezone'});
 1124:                     }
 1125:                 }
 1126:                 $timezone = $timezones->{$cdom.'_'.$cnum};
 1127:             }
 1128:         } else {
 1129:             my ($tdom) = ($where =~ m{^/($match_domain)});
 1130:             if ($tdom) {
 1131:                 if (!exists($timezones->{$tdom})) {
 1132:                     my %domdefaults = &Apache::lonnet::get_domain_defaults($tdom);
 1133:                     if ($domdefaults{'timezone_def'} eq '') {
 1134:                         $timezones->{$tdom} = 'local';
 1135:                     } else {
 1136:                         $timezones->{$tdom} = $domdefaults{'timezone_def'};
 1137:                     }
 1138:                 }
 1139:                 $timezone = $timezones->{$tdom};
 1140:             }
 1141:         }
 1142:         if ($timezone eq 'local') {
 1143:             $timezone = undef;
 1144:         }
 1145:     }
 1146:     return $timezone;
 1147: }
 1148: 
 1149: sub roletable_headers {
 1150:     my ($r,$roleclass,$sortrole,$nochoose) = @_;
 1151:     my $doheaders;
 1152:     if ((ref($sortrole) eq 'HASH') && (ref($roleclass) eq 'HASH')) {
 1153:         $r->print('<br />'
 1154:                  .&Apache::loncommon::start_data_table()
 1155:                  .&Apache::loncommon::start_data_table_header_row()
 1156:         );
 1157:         if (!$nochoose) { $r->print('<th>&nbsp;</th>'); }
 1158:         $r->print('<th>'.&mt('User Role').'</th>'
 1159:                  .'<th>'.&mt('Extent').'</th>'
 1160:                  .'<th>'.&mt('Start').'</th>'
 1161:                  .'<th>'.&mt('End').'</th>'
 1162:                  .&Apache::loncommon::end_data_table_header_row()
 1163:         );
 1164:         $doheaders=-1;
 1165:         my @roletypes = &roletypes();
 1166:         foreach my $type (@roletypes) {
 1167:             my $haverole=0;
 1168:             foreach my $which (sort {uc($a) cmp uc($b)} (keys(%{$sortrole}))) {
 1169:                 if ($roleclass->{$sortrole->{$which}} =~ /^\Q$type\E/) {
 1170:                     $haverole=1;
 1171:                 }
 1172:             }
 1173:             if ($haverole) { $doheaders++; }
 1174:         }
 1175:     }
 1176:     return $doheaders;
 1177: }
 1178: 
 1179: sub roletypes {
 1180:     my @types = ('Domain','Construction Space','Course','Community','Unavailable','System');
 1181:     return @types; 
 1182: }
 1183: 
 1184: sub print_rolerows {
 1185:     my ($r,$doheaders,$roleclass,$sortrole,$dcroles,$roletext) = @_;
 1186:     if ((ref($roleclass) eq 'HASH') && (ref($sortrole) eq 'HASH')) {
 1187:         my @types = &roletypes();
 1188:         foreach my $type (@types) {
 1189:             my $output;
 1190:             foreach my $which (sort {uc($a) cmp uc($b)} (keys(%{$sortrole}))) {
 1191:                 if ($roleclass->{$sortrole->{$which}} =~ /^\Q$type\E/) {
 1192:                     if (ref($roletext) eq 'HASH') {
 1193:                         if (ref($roletext->{$sortrole->{$which}}) eq 'ARRAY') {
 1194:                             $output.= &Apache::loncommon::start_data_table_row().
 1195:                                       $roletext->{$sortrole->{$which}}->[0].
 1196:                                       &Apache::loncommon::end_data_table_row().
 1197:                                       &Apache::loncommon::continue_data_table_row().
 1198:                                       $roletext->{$sortrole->{$which}}->[1].
 1199:                                       &Apache::loncommon::end_data_table_row();
 1200:                         }
 1201:                         if ($sortrole->{$which} =~ m-dc\./($match_domain)/-) {
 1202:                             if (ref($dcroles) eq 'HASH') {
 1203:                                 if ($dcroles->{$1}) {
 1204:                                     $output .= &adhoc_roles_row($1,'');
 1205:                                 }
 1206:                             }
 1207:                         }
 1208:                     }
 1209:                 }
 1210:             }
 1211:             if ($output) {
 1212:                 if ($doheaders > 0) {
 1213:                     $r->print(&Apache::loncommon::start_data_table_empty_row()
 1214:                              .'<td align="center" colspan="5">'
 1215:                              .&mt($type)
 1216:                              .'</td>'
 1217:                              .&Apache::loncommon::end_data_table_empty_row()
 1218:                     );
 1219:                 }
 1220:                 $r->print($output);
 1221:             }
 1222:         }
 1223:     }
 1224: }
 1225: 
 1226: sub findcourse_advice {
 1227:     my ($r) = @_;
 1228:     my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
 1229:     my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&');
 1230:     if (&Apache::lonnet::auto_run(undef,$env{'user.domain'})) {
 1231:         $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).'
 1232: <ul>
 1233:  <li>'.&mt('The course has yet to be created.').'</li>
 1234:  <li>'.&mt('Automatic enrollment of registered students has not been enabled for the course.').'</li>
 1235:  <li>'.&mt('You are in a section of course for which automatic enrollment in the corresponding LON-CAPA course is not active.').'</li>
 1236:  <li>'.&mt('The start date for automated enrollment has yet to be reached.').'</li>
 1237:  <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>
 1238:  </ul>');
 1239:     } else {
 1240:         $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 />');
 1241:     }
 1242:     $r->print('<h3>'.&mt('Self-Enrollment').'</h3>'.
 1243:               '<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 />');
 1244:     $r->print(&mt('You can search for courses and communities which permit self-enrollment, if you would like to enroll in one.').'</p>');
 1245:     &queued_selfenrollment($r);
 1246:     return;
 1247: }
 1248: 
 1249: sub requestcourse_advice {
 1250:     my ($r) = @_;
 1251:     my $domdesc = &Apache::lonnet::domain($env{'user.domain'},'description');
 1252:     my $esc_dom = &HTML::Entities::encode($env{'user.domain'},'"<>&');
 1253:     my (%can_request,%request_doms);
 1254:     &Apache::lonnet::check_can_request($env{'user.domain'},\%can_request,\%request_doms);
 1255:     if (keys(%request_doms) > 0) {
 1256:         my ($types,$typename) = &Apache::loncommon::course_types();
 1257:         if ((ref($types) eq 'ARRAY') && (ref($typename) eq 'HASH')) { 
 1258:             $r->print('<h3>'.&mt('Request creation of a course or community').'</h3>'.
 1259:                       '<p>'.&mt('You have rights to request the creation of courses and/or communities in the following domain(s):').'<ul>');
 1260:             my (@reqdoms,@reqtypes);
 1261:             foreach my $type (sort(keys(%request_doms))) {
 1262:                 push(@reqtypes,$type); 
 1263:                 if (ref($request_doms{$type}) eq 'ARRAY') {
 1264:                     my $domstr = join(', ',map { &Apache::lonnet::domain($_) } sort(@{$request_doms{$type}}));
 1265:                     $r->print(
 1266:                         '<li>'
 1267:                        .&mt('[_1]'.$typename->{$type}.'[_2] in domain: [_3]',
 1268:                             '<i>',
 1269:                             '</i>',
 1270:                             '<b>'.$domstr.'</b>')
 1271:                        .'</li>'
 1272:                     );
 1273:                     foreach my $dom (@{$request_doms{$type}}) {
 1274:                         unless (grep(/^\Q$dom\E/,@reqdoms)) {
 1275:                             push(@reqdoms,$dom);
 1276:                         }
 1277:                     }
 1278:                 }
 1279:             }
 1280:             my @showtypes;
 1281:             foreach my $type (@{$types}) {
 1282:                 if (grep(/^\Q$type\E$/,@reqtypes)) {
 1283:                     push(@showtypes,$type);
 1284:                 }
 1285:             }
 1286:             my $requrl = '/adm/requestcourse';
 1287:             if (@reqdoms == 1) {
 1288:                 $requrl .= '?showdom='.$reqdoms[0];
 1289:             }
 1290:             if (@showtypes > 0) {
 1291:                 $requrl.=(($requrl=~/\?/)?'&':'?').'crstype='.$showtypes[0];
 1292:             }
 1293:             if (@reqdoms == 1 || @showtypes > 0) {
 1294:                 $requrl .= '&state=crstype&action=new';
 1295:             } 
 1296:             $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>');
 1297:         }
 1298:     }
 1299:     return;
 1300: }
 1301: 
 1302: sub queued_selfenrollment {
 1303:     my ($r) = @_;
 1304:     my %selfenrollrequests = &Apache::lonnet::dump('selfenrollrequests');
 1305:     my %reqs_by_date;
 1306:     foreach my $item (keys(%selfenrollrequests)) {
 1307:         if (ref($selfenrollrequests{$item}) eq 'HASH') {
 1308:             if ($selfenrollrequests{$item}{'status'} eq 'request') {
 1309:                 if ($selfenrollrequests{$item}{'timestamp'}) {
 1310:                     push(@{$reqs_by_date{$selfenrollrequests{$item}{'timestamp'}}},$item);
 1311:                 }
 1312:             } 
 1313:         }
 1314:     }
 1315:     if (keys(%reqs_by_date)) {
 1316:         my $rolename = &Apache::lonnet::plaintext('st');
 1317:         $r->print('<b>'.&mt('Enrollment requests pending Course Coordinator approval').'</b><br />'.
 1318:                   &Apache::loncommon::start_data_table().
 1319:                   &Apache::loncommon::start_data_table_header_row().
 1320:                   '<th>'.&mt('Date requested').'</th><th>'.&mt('Course title').'</th>'.
 1321:                   '<th>'.&mt('User role').'</th><th>'.&mt('Section').'</th>'.
 1322:                  &Apache::loncommon::end_data_table_header_row());
 1323:         my @sorted = sort { $a <=> $b } (keys(%reqs_by_date));
 1324:         foreach my $item (@sorted) {
 1325:             if (ref($reqs_by_date{$item}) eq 'ARRAY') {
 1326:                 foreach my $crs (@{$reqs_by_date{$item}}) {
 1327:                     my %courseinfo = &Apache::lonnet::coursedescription($crs);
 1328:                     my $usec = $selfenrollrequests{$crs}{'section'};
 1329:                     if ($usec eq '') {
 1330:                         $usec = &mt('No section'); 
 1331:                     }
 1332:                     $r->print(&Apache::loncommon::start_data_table_row().
 1333:                              '<td>'.&Apache::lonlocal::locallocaltime($item).'</td>'.
 1334:                              '<td>'.$courseinfo{'description'}.'</td>'.
 1335:                              '<td>'.$rolename.'</td><td>'.$usec.'</td>'.
 1336:                              &Apache::loncommon::end_data_table_row());
 1337:                 }
 1338:             }
 1339:         }
 1340:         $r->print(&Apache::loncommon::end_data_table());
 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);
 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>