File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.240.2.2: download - view: text, annotated - select for diffs
Mon Dec 7 04:38:22 2009 UTC (14 years, 6 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3.
  - If no role, redirect to orgurl (if specified as a form element).

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

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