File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.203: download - view: text, annotated - select for diffs
Wed Jul 30 15:34:34 2008 UTC (15 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- For bug 3987.  lonroles.pm will accept a destsymb form item, encode it and append it to the destinationurl.
- Intended to support linking to a specific resource in a course from outside LON-CAPA.
- Login page and SSO need to preserve an appropriate query string for the call to /adm/roles after authentication and session initialization.

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

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