File:  [LON-CAPA] / loncom / auth / lonroles.pm
Revision 1.240.2.5: download - view: text, annotated - select for diffs
Thu Dec 24 18:28:54 2009 UTC (14 years, 7 months ago) by raeburn
Branches: GCI_3
- Customization for GCI_3
  - Welcome page after successful log-in.

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

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