File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.370: download - view: text, annotated - select for diffs
Thu May 8 21:50:54 2003 UTC (21 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- user login load balancing should work now BUG#958

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.370 2003/05/08 21:50:54 albertel 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: # 6/1/99,6/2,6/10,6/11,6/12,6/14,6/26,6/28,6/29,6/30,
   29: # 7/1,7/2,7/9,7/10,7/12,7/14,7/15,7/19,
   30: # 11/8,11/16,11/18,11/22,11/23,12/22,
   31: # 01/06,01/13,02/24,02/28,02/29,
   32: # 03/01,03/02,03/06,03/07,03/13,
   33: # 04/05,05/29,05/31,06/01,
   34: # 06/05,06/26 Gerd Kortemeyer
   35: # 06/26 Ben Tyszka
   36: # 06/30,07/15,07/17,07/18,07/20,07/21,07/22,07/25 Gerd Kortemeyer
   37: # 08/14 Ben Tyszka
   38: # 08/22,08/28,08/31,09/01,09/02,09/04,09/05,09/25,09/28,09/30 Gerd Kortemeyer
   39: # 10/04 Gerd Kortemeyer
   40: # 10/04 Guy Albertelli
   41: # 10/06,10/09,10/10,10/11,10/14,10/20,10/23,10/25,10/26,10/27,10/28,10/29, 
   42: # 10/30,10/31,
   43: # 11/2,11/14,11/15,11/16,11/20,11/21,11/22,11/25,11/27,
   44: # 12/02,12/12,12/13,12/14,12/28,12/29 Gerd Kortemeyer
   45: # 05/01/01 Guy Albertelli
   46: # 05/01,06/01,09/01 Gerd Kortemeyer
   47: # 09/01 Guy Albertelli
   48: # 09/01,10/01,11/01 Gerd Kortemeyer
   49: # YEAR=2001
   50: # 3/2 Gerd Kortemeyer
   51: # 3/19,3/20 Gerd Kortemeyer
   52: # 5/26,5/28 Gerd Kortemeyer
   53: # 5/30 H. K. Ng
   54: # 6/1 Gerd Kortemeyer
   55: # July Guy Albertelli
   56: # 8/4,8/7,8/8,8/9,8/11,8/16,8/17,8/18,8/20,8/23,9/20,9/21,9/26,
   57: # 10/2 Gerd Kortemeyer
   58: # 11/17,11/20,11/22,11/29 Gerd Kortemeyer
   59: # 12/5 Matthew Hall
   60: # 12/5 Guy Albertelli
   61: # 12/6,12/7,12/12 Gerd Kortemeyer
   62: # 12/21,12/22,12/27,12/28 Gerd Kortemeyer
   63: # YEAR=2002
   64: # 1/4,2/4,2/7 Gerd Kortemeyer
   65: #
   66: ###
   67: 
   68: package Apache::lonnet;
   69: 
   70: use strict;
   71: use Apache::File;
   72: use LWP::UserAgent();
   73: use HTTP::Headers;
   74: use vars 
   75: qw(%perlvar %hostname %homecache %badServerCache %hostip %iphost %spareid %hostdom 
   76:    %libserv %pr %prp %metacache %packagetab %titlecache 
   77:    %courselogs %accesshash %userrolehash $processmarker $dumpcount 
   78:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseresdatacache 
   79:    %domaindescription %domain_auth_def %domain_auth_arg_def $tmpdir);
   80: use IO::Socket;
   81: use GDBM_File;
   82: use Apache::Constants qw(:common :http);
   83: use HTML::LCParser;
   84: use Fcntl qw(:flock);
   85: use Apache::loncoursedata;
   86: 
   87: my $readit;
   88: 
   89: # --------------------------------------------------------------------- Logging
   90: 
   91: sub logtouch {
   92:     my $execdir=$perlvar{'lonDaemons'};
   93:     unless (-e "$execdir/logs/lonnet.log") {
   94: 	my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
   95: 	close $fh;
   96:     }
   97:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
   98:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
   99: }
  100: 
  101: sub logthis {
  102:     my $message=shift;
  103:     my $execdir=$perlvar{'lonDaemons'};
  104:     my $now=time;
  105:     my $local=localtime($now);
  106:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.log");
  107:     print $fh "$local ($$): $message\n";
  108:     return 1;
  109: }
  110: 
  111: sub logperm {
  112:     my $message=shift;
  113:     my $execdir=$perlvar{'lonDaemons'};
  114:     my $now=time;
  115:     my $local=localtime($now);
  116:     my $fh=Apache::File->new(">>$execdir/logs/lonnet.perm.log");
  117:     print $fh "$now:$message:$local\n";
  118:     return 1;
  119: }
  120: 
  121: # -------------------------------------------------- Non-critical communication
  122: sub subreply {
  123:     my ($cmd,$server)=@_;
  124:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  125:     my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  126:                                      Type    => SOCK_STREAM,
  127:                                      Timeout => 10)
  128:        or return "con_lost";
  129:     print $client "$cmd\n";
  130:     my $answer=<$client>;
  131:     if (!$answer) { $answer="con_lost"; }
  132:     chomp($answer);
  133:     return $answer;
  134: }
  135: 
  136: sub reply {
  137:     my ($cmd,$server)=@_;
  138:     unless (defined($hostname{$server})) { return 'no_such_host'; }
  139:     my $answer=subreply($cmd,$server);
  140:     if ($answer eq 'con_lost') {
  141:         #sleep 5; 
  142:         #$answer=subreply($cmd,$server);
  143:         #if ($answer eq 'con_lost') {
  144: 	#   &logthis("Second attempt con_lost on $server");
  145:         #   my $peerfile="$perlvar{'lonSockDir'}/$server";
  146:         #   my $client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  147:         #                                    Type    => SOCK_STREAM,
  148:         #                                    Timeout => 10)
  149:         #              or return "con_lost";
  150:         #   &logthis("Killing socket");
  151:         #   print $client "close_connection_exit\n";
  152:            #sleep 5;
  153:         #   $answer=subreply($cmd,$server);       
  154:        #}   
  155:     }
  156:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  157:        &logthis("<font color=blue>WARNING:".
  158:                 " $cmd to $server returned $answer</font>");
  159:     }
  160:     return $answer;
  161: }
  162: 
  163: # ----------------------------------------------------------- Send USR1 to lonc
  164: 
  165: sub reconlonc {
  166:     my $peerfile=shift;
  167:     &logthis("Trying to reconnect for $peerfile");
  168:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  169:     if (my $fh=Apache::File->new("$loncfile")) {
  170: 	my $loncpid=<$fh>;
  171:         chomp($loncpid);
  172:         if (kill 0 => $loncpid) {
  173: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  174:             kill USR1 => $loncpid;
  175:             sleep 1;
  176:             if (-e "$peerfile") { return; }
  177:             &logthis("$peerfile still not there, give it another try");
  178:             sleep 5;
  179:             if (-e "$peerfile") { return; }
  180:             &logthis(
  181:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
  182:         } else {
  183: 	    &logthis(
  184:                "<font color=blue>WARNING:".
  185:                " lonc at pid $loncpid not responding, giving up</font>");
  186:         }
  187:     } else {
  188:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
  189:     }
  190: }
  191: 
  192: # ------------------------------------------------------ Critical communication
  193: 
  194: sub critical {
  195:     my ($cmd,$server)=@_;
  196:     unless ($hostname{$server}) {
  197:         &logthis("<font color=blue>WARNING:".
  198:                " Critical message to unknown server ($server)</font>");
  199:         return 'no_such_host';
  200:     }
  201:     my $answer=reply($cmd,$server);
  202:     if ($answer eq 'con_lost') {
  203:         my $pingreply=reply('ping',$server);
  204: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  205:         my $pongreply=reply('pong',$server);
  206:         &logthis("Ping/Pong for $server: $pingreply/$pongreply");
  207:         $answer=reply($cmd,$server);
  208:         if ($answer eq 'con_lost') {
  209:             my $now=time;
  210:             my $middlename=$cmd;
  211:             $middlename=substr($middlename,0,16);
  212:             $middlename=~s/\W//g;
  213:             my $dfilename=
  214:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  215:             $dumpcount++;
  216:             {
  217:              my $dfh;
  218:              if ($dfh=Apache::File->new(">$dfilename")) {
  219:                 print $dfh "$cmd\n";
  220: 	     }
  221:             }
  222:             sleep 2;
  223:             my $wcmd='';
  224:             {
  225: 	     my $dfh;
  226:              if ($dfh=Apache::File->new("$dfilename")) {
  227:                 $wcmd=<$dfh>;
  228: 	     }
  229:             }
  230:             chomp($wcmd);
  231:             if ($wcmd eq $cmd) {
  232: 		&logthis("<font color=blue>WARNING: ".
  233:                          "Connection buffer $dfilename: $cmd</font>");
  234:                 &logperm("D:$server:$cmd");
  235: 	        return 'con_delayed';
  236:             } else {
  237:                 &logthis("<font color=red>CRITICAL:"
  238:                         ." Critical connection failed: $server $cmd</font>");
  239:                 &logperm("F:$server:$cmd");
  240:                 return 'con_failed';
  241:             }
  242:         }
  243:     }
  244:     return $answer;
  245: }
  246: 
  247: # ---------------------------------------------------------- Append Environment
  248: 
  249: sub appenv {
  250:     my %newenv=@_;
  251:     foreach (keys %newenv) {
  252: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
  253:             &logthis("<font color=blue>WARNING: ".
  254:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
  255:                 .'</font>');
  256: 	    delete($newenv{$_});
  257:         } else {
  258:             $ENV{$_}=$newenv{$_};
  259:         }
  260:     }
  261: 
  262:     my $lockfh;
  263:     unless ($lockfh=Apache::File->new("$ENV{'user.environment'}")) {
  264:        return 'error: '.$!;
  265:     }
  266:     unless (flock($lockfh,LOCK_EX)) {
  267:          &logthis("<font color=blue>WARNING: ".
  268:                   'Could not obtain exclusive lock in appenv: '.$!);
  269:          $lockfh->close();
  270:          return 'error: '.$!;
  271:     }
  272: 
  273:     my @oldenv;
  274:     {
  275:      my $fh;
  276:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  277: 	return 'error: '.$!;
  278:      }
  279:      @oldenv=<$fh>;
  280:      $fh->close();
  281:     }
  282:     for (my $i=0; $i<=$#oldenv; $i++) {
  283:         chomp($oldenv[$i]);
  284:         if ($oldenv[$i] ne '') {
  285:            my ($name,$value)=split(/=/,$oldenv[$i]);
  286:            unless (defined($newenv{$name})) {
  287: 	      $newenv{$name}=$value;
  288: 	   }
  289:         }
  290:     }
  291:     {
  292:      my $fh;
  293:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  294: 	return 'error';
  295:      }
  296:      my $newname;
  297:      foreach $newname (keys %newenv) {
  298: 	 print $fh "$newname=$newenv{$newname}\n";
  299:      }
  300:      $fh->close();
  301:     }
  302: 
  303:     $lockfh->close();
  304:     return 'ok';
  305: }
  306: # ----------------------------------------------------- Delete from Environment
  307: 
  308: sub delenv {
  309:     my $delthis=shift;
  310:     my %newenv=();
  311:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  312:         &logthis("<font color=blue>WARNING: ".
  313:                 "Attempt to delete from environment ".$delthis);
  314:         return 'error';
  315:     }
  316:     my @oldenv;
  317:     {
  318:      my $fh;
  319:      unless ($fh=Apache::File->new("$ENV{'user.environment'}")) {
  320: 	return 'error';
  321:      }
  322:      unless (flock($fh,LOCK_SH)) {
  323:          &logthis("<font color=blue>WARNING: ".
  324:                   'Could not obtain shared lock in delenv: '.$!);
  325:          $fh->close();
  326:          return 'error: '.$!;
  327:      }
  328:      @oldenv=<$fh>;
  329:      $fh->close();
  330:     }
  331:     {
  332:      my $fh;
  333:      unless ($fh=Apache::File->new(">$ENV{'user.environment'}")) {
  334: 	return 'error';
  335:      }
  336:      unless (flock($fh,LOCK_EX)) {
  337:          &logthis("<font color=blue>WARNING: ".
  338:                   'Could not obtain exclusive lock in delenv: '.$!);
  339:          $fh->close();
  340:          return 'error: '.$!;
  341:      }
  342:      foreach (@oldenv) {
  343: 	 unless ($_=~/^$delthis/) { print $fh $_; }
  344:      }
  345:      $fh->close();
  346:     }
  347:     return 'ok';
  348: }
  349: 
  350: # ------------------------------------------ Find out current server userload
  351: # there is a copy in lond
  352: sub userload {
  353:     my $numusers=0;
  354:     {
  355: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  356: 	my $filename;
  357: 	my $curtime=time;
  358: 	while ($filename=readdir(LONIDS)) {
  359: 	    if ($filename eq '.' || $filename eq '..') {next;}
  360: 	    my ($atime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[8];
  361: 	    if ($curtime-$atime < 3600) { $num_users++; }
  362: 	}
  363: 	closedir(LONIDS);
  364:     }
  365:     my $userloadpercent=0;
  366:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  367:     if ($maxuserload) {
  368: 	$userloadpercent=100*$num_users/$maxuserload;
  369:     }
  370:     return $userloadpercent;
  371: }
  372: 
  373: # ------------------------------------------ Fight off request when overloaded
  374: 
  375: sub overloaderror {
  376:     my ($r,$checkserver)=@_;
  377:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  378:     my $loadavg;
  379:     if ($checkserver eq $perlvar{'lonHostID'}) {
  380:        my $loadfile=Apache::File->new('/proc/loadavg');
  381:        $loadavg=<$loadfile>;
  382:        $loadavg =~ s/\s.*//g;
  383:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  384:     } else {
  385:        $loadavg=&reply('load',$checkserver);
  386:     }
  387:     my $overload=$loadavg-100;
  388:     if ($overload>0) {
  389: 	$r->err_headers_out->{'Retry-After'}=$overload;
  390:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  391:         return 413;
  392:     }    
  393:     return '';
  394: }
  395: 
  396: # ------------------------------ Find server with least workload from spare.tab
  397: 
  398: sub spareserver {
  399:     my ($loadpercent,$userloadpercent) = @_;
  400:     my $tryserver;
  401:     my $spareserver='';
  402:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  403:     my $lowestserver=$loadpercent > $userloadpercent?
  404: 	             $loadpercent :  $userloadpercent;
  405:     foreach $tryserver (keys %spareid) {
  406:        my $loadans=reply('load',$tryserver);
  407:        my $userloadans=reply('userload',$tryserver);
  408:        if ($userloadans !~ /\d/) { $userloadans=0; }
  409:        my $answer=$loadans > $userloadans?
  410:                   $loadans :  $userloadans;
  411:        if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  412: 	   $spareserver="http://$hostname{$tryserver}";
  413:            $lowestserver=$answer;
  414:        }
  415:     }
  416:     return $spareserver;
  417: }
  418: 
  419: # --------------------------------------------- Try to change a user's password
  420: 
  421: sub changepass {
  422:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  423:     $currentpass = &escape($currentpass);
  424:     $newpass     = &escape($newpass);
  425:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  426: 		       $server);
  427:     if (! $answer) {
  428: 	&logthis("No reply on password change request to $server ".
  429: 		 "by $uname in domain $udom.");
  430:     } elsif ($answer =~ "^ok") {
  431:         &logthis("$uname in $udom successfully changed their password ".
  432: 		 "on $server.");
  433:     } elsif ($answer =~ "^pwchange_failure") {
  434: 	&logthis("$uname in $udom was unable to change their password ".
  435: 		 "on $server.  The action was blocked by either lcpasswd ".
  436: 		 "or pwchange");
  437:     } elsif ($answer =~ "^non_authorized") {
  438:         &logthis("$uname in $udom did not get their password correct when ".
  439: 		 "attempting to change it on $server.");
  440:     } elsif ($answer =~ "^auth_mode_error") {
  441:         &logthis("$uname in $udom attempted to change their password despite ".
  442: 		 "not being locally or internally authenticated on $server.");
  443:     } elsif ($answer =~ "^unknown_user") {
  444:         &logthis("$uname in $udom attempted to change their password ".
  445: 		 "on $server but were unable to because $server is not ".
  446: 		 "their home server.");
  447:     } elsif ($answer =~ "^refused") {
  448: 	&logthis("$server refused to change $uname in $udom password because ".
  449: 		 "it was sent an unencrypted request to change the password.");
  450:     }
  451:     return $answer;
  452: }
  453: 
  454: # ----------------------- Try to determine user's current authentication scheme
  455: 
  456: sub queryauthenticate {
  457:     my ($uname,$udom)=@_;
  458:     if (($perlvar{'lonRole'} eq 'library') && 
  459:         ($udom eq $perlvar{'lonDefDomain'})) {
  460: 	my $answer=reply("encrypt:currentauth:$udom:$uname",
  461: 			 $perlvar{'lonHostID'});
  462: 	unless ($answer eq 'unknown_user' or $answer eq 'refused') {
  463: 	    if (length($answer)) {
  464: 		return $answer;
  465: 	    }
  466: 	    else {
  467: 	&logthis("User $uname at $udom lacks an authentication mechanism");
  468: 		return 'no_host';
  469: 	    }
  470: 	}
  471:     }
  472: 
  473:     my $tryserver;
  474:     foreach $tryserver (keys %libserv) {
  475: 	if ($hostdom{$tryserver} eq $udom) {
  476:            my $answer=reply("encrypt:currentauth:$udom:$uname",$tryserver);
  477: 	   unless ($answer eq 'unknown_user' or $answer eq 'refused') {
  478: 	       if (length($answer)) {
  479: 		   return $answer;
  480: 	       }
  481: 	       else {
  482: 	   &logthis("User $uname at $udom lacks an authentication mechanism");
  483: 		   return 'no_host';
  484: 	       }
  485: 	   }
  486:        }
  487:     }
  488:     &logthis("User $uname at $udom lacks an authentication mechanism");    
  489:     return 'no_host';
  490: }
  491: 
  492: # --------- Try to authenticate user from domain's lib servers (first this one)
  493: 
  494: sub authenticate {
  495:     my ($uname,$upass,$udom)=@_;
  496:     $upass=escape($upass);
  497:     $uname=~s/\W//g;
  498:     if (($perlvar{'lonRole'} eq 'library') && 
  499:         ($udom eq $perlvar{'lonDefDomain'})) {
  500:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$perlvar{'lonHostID'});
  501:         if ($answer =~ /authorized/) {
  502:               if ($answer eq 'authorized') {
  503:                  &logthis("User $uname at $udom authorized by local server"); 
  504:                  return $perlvar{'lonHostID'}; 
  505:               }
  506:               if ($answer eq 'non_authorized') {
  507:                  &logthis("User $uname at $udom rejected by local server"); 
  508:                  return 'no_host'; 
  509:               }
  510: 	}
  511:     }
  512: 
  513:     my $tryserver;
  514:     foreach $tryserver (keys %libserv) {
  515: 	if ($hostdom{$tryserver} eq $udom) {
  516:            my $answer=reply("encrypt:auth:$udom:$uname:$upass",$tryserver);
  517:            if ($answer =~ /authorized/) {
  518:               if ($answer eq 'authorized') {
  519:                  &logthis("User $uname at $udom authorized by $tryserver"); 
  520:                  return $tryserver; 
  521:               }
  522:               if ($answer eq 'non_authorized') {
  523:                  &logthis("User $uname at $udom rejected by $tryserver");
  524:                  return 'no_host';
  525:               } 
  526: 	   }
  527:        }
  528:     }
  529:     &logthis("User $uname at $udom could not be authenticated");    
  530:     return 'no_host';
  531: }
  532: 
  533: # ---------------------- Find the homebase for a user from domain's lib servers
  534: 
  535: sub homeserver {
  536:     my ($uname,$udom,$ignoreBadCache)=@_;
  537:     my $index="$uname:$udom";
  538:     if ($homecache{$index}) { 
  539:         return "$homecache{$index}"; 
  540:     }
  541:     my $tryserver;
  542:     foreach $tryserver (keys %libserv) {
  543:         next if ($ignoreBadCache ne 'true' && 
  544: 		 exists($badServerCache{$tryserver}));
  545: 	if ($hostdom{$tryserver} eq $udom) {
  546:            my $answer=reply("home:$udom:$uname",$tryserver);
  547:            if ($answer eq 'found') { 
  548:               $homecache{$index}=$tryserver;
  549:               return $tryserver; 
  550:            } elsif ($answer eq 'no_host') {
  551: 	       $badServerCache{$tryserver}=1;
  552:            }
  553:        }
  554:     }    
  555:     return 'no_host';
  556: }
  557: 
  558: # ------------------------------------- Find the usernames behind a list of IDs
  559: 
  560: sub idget {
  561:     my ($udom,@ids)=@_;
  562:     my %returnhash=();
  563:     
  564:     my $tryserver;
  565:     foreach $tryserver (keys %libserv) {
  566:        if ($hostdom{$tryserver} eq $udom) {
  567: 	  my $idlist=join('&',@ids);
  568:           $idlist=~tr/A-Z/a-z/; 
  569: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  570:           my @answer=();
  571:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  572: 	      @answer=split(/\&/,$reply);
  573:           }                    ;
  574:           my $i;
  575:           for ($i=0;$i<=$#ids;$i++) {
  576:               if ($answer[$i]) {
  577: 		  $returnhash{$ids[$i]}=$answer[$i];
  578:               } 
  579:           }
  580:        }
  581:     }    
  582:     return %returnhash;
  583: }
  584: 
  585: # ------------------------------------- Find the IDs behind a list of usernames
  586: 
  587: sub idrget {
  588:     my ($udom,@unames)=@_;
  589:     my %returnhash=();
  590:     foreach (@unames) {
  591:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  592:     }
  593:     return %returnhash;
  594: }
  595: 
  596: # ------------------------------- Store away a list of names and associated IDs
  597: 
  598: sub idput {
  599:     my ($udom,%ids)=@_;
  600:     my %servers=();
  601:     foreach (keys %ids) {
  602:         my $uhom=&homeserver($_,$udom);
  603:         if ($uhom ne 'no_host') {
  604:             my $id=&escape($ids{$_});
  605:             $id=~tr/A-Z/a-z/;
  606:             my $unam=&escape($_);
  607: 	    if ($servers{$uhom}) {
  608: 		$servers{$uhom}.='&'.$id.'='.$unam;
  609:             } else {
  610:                 $servers{$uhom}=$id.'='.$unam;
  611:             }
  612:             &critical('put:'.$udom.':'.$unam.':environment:id='.$id,$uhom);
  613:         }
  614:     }
  615:     foreach (keys %servers) {
  616:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  617:     }
  618: }
  619: 
  620: # --------------------------------------------------- Assign a key to a student
  621: 
  622: sub assign_access_key {
  623: #
  624: # a valid key looks like uname:udom#comments
  625: # comments are being appended
  626: #
  627:     my ($ckey,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  628:     $cdom=
  629:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  630:     $cnum=
  631:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  632:     $udom=$ENV{'user.name'} unless (defined($udom));
  633:     $uname=$ENV{'user.domain'} unless (defined($uname));
  634:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  635:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  636:         ($existing{$ckey}=~/^$uname\:$udom\#(.*)$/)) { 
  637:                                                   # assigned to this person
  638:                                                   # - this should not happen,
  639:                                                   # unless something went wrong
  640:                                                   # the first time around
  641: # ready to assign
  642:         $logentry=$1.'; '.$logentry;
  643:         if (&put('accesskey',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  644:                                                  $cdom,$cnum) eq 'ok') {
  645: # key now belongs to user
  646: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  647:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  648:                 &appenv('environment.'.$envkey => $ckey);
  649:                 return 'ok';
  650:             } else {
  651:                 return 
  652:   'error: Count not permanently assign key, will need to be re-entered later.';
  653: 	    }
  654:         } else {
  655:             return 'error: Could not assign key, try again later.';
  656:         }
  657:     } elsif (!$existing{$ckey}) {
  658: # the key does not exist
  659: 	return 'error: The key does not exist';
  660:     } else {
  661: # the key is somebody else's
  662: 	return 'error: The key is already in use';
  663:     }
  664: }
  665: 
  666: # ------------------------------------------ put an additional comment on a key
  667: 
  668: sub comment_access_key {
  669: #
  670: # a valid key looks like uname:udom#comments
  671: # comments are being appended
  672: #
  673:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  674:     $cdom=
  675:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  676:     $cnum=
  677:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  678:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  679:     if ($existing{$ckey}) {
  680:         $existing{$ckey}.='; '.$logentry;
  681: # ready to assign
  682:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  683:                                                  $cdom,$cnum) eq 'ok') {
  684: 	    return 'ok';
  685:         } else {
  686: 	    return 'error: Count not store comment.';
  687:         }
  688:     } else {
  689: # the key does not exist
  690: 	return 'error: The key does not exist';
  691:     }
  692: }
  693: 
  694: # ------------------------------------------------------ Generate a set of keys
  695: 
  696: sub generate_access_keys {
  697:     my ($number,$cdom,$cnum,$logentry)=@_;
  698:     $cdom=
  699:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  700:     $cnum=
  701:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  702:     unless (&allowed('mky',$cdom)) { return 0; }
  703:     unless (($cdom) && ($cnum)) { return 0; }
  704:     if ($number>10000) { return 0; }
  705:     sleep(2); # make sure don't get same seed twice
  706:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  707:     my $total=0;
  708:     for (my $i=1;$i<=$number;$i++) {
  709:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  710:                   sprintf("%lx",int(100000*rand)).'-'.
  711:                   sprintf("%lx",int(100000*rand));
  712:        $newkey=~s/1/g/g; # folks mix up 1 and l
  713:        $newkey=~s/0/h/g; # and also 0 and O
  714:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  715:        if ($existing{$newkey}) {
  716:            $i--;
  717:        } else {
  718: 	  if (&put('accesskeys',
  719:               { $newkey => '# generated '.localtime().
  720:                            ' by '.$ENV{'user.name'}.'@'.$ENV{'user.domain'}.
  721:                            '; '.$logentry },
  722: 		   $cdom,$cnum) eq 'ok') {
  723:               $total++;
  724: 	  }
  725:        }
  726:     }
  727:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
  728:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  729:     return $total;
  730: }
  731: 
  732: # ------------------------------------------------------- Validate an accesskey
  733: 
  734: sub validate_access_key {
  735:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  736:     $cdom=
  737:    $ENV{'course.'.$ENV{'request.course.id'}.'.domain'} unless (defined($cdom));
  738:     $cnum=
  739:    $ENV{'course.'.$ENV{'request.course.id'}.'.num'} unless (defined($cnum));
  740:     $udom=$ENV{'user.name'} unless (defined($udom));
  741:     $uname=$ENV{'user.domain'} unless (defined($uname));
  742:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  743:     return ($existing{$ckey}=~/^$uname\:$udom\#/);
  744: }
  745: 
  746: # ------------------------------------- Find the section of student in a course
  747: 
  748: sub getsection {
  749:     my ($udom,$unam,$courseid)=@_;
  750:     $courseid=~s/\_/\//g;
  751:     $courseid=~s/^(\w)/\/$1/;
  752:     my %Pending; 
  753:     my %Expired;
  754:     #
  755:     # Each role can either have not started yet (pending), be active, 
  756:     #    or have expired.
  757:     #
  758:     # If there is an active role, we are done.
  759:     #
  760:     # If there is more than one role which has not started yet, 
  761:     #     choose the one which will start sooner
  762:     # If there is one role which has not started yet, return it.
  763:     #
  764:     # If there is more than one expired role, choose the one which ended last.
  765:     # If there is a role which has expired, return it.
  766:     #
  767:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  768:                         &homeserver($unam,$udom)))) {
  769:         my ($key,$value)=split(/\=/,$_);
  770:         $key=&unescape($key);
  771:         next if ($key !~/^$courseid(?:\/)*(\w+)*\_st$/);
  772:         my $section=$1;
  773:         if ($key eq $courseid.'_st') { $section=''; }
  774:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  775:         my $now=time;
  776:         if (defined($end) && ($now > $end)) {
  777:             $Expired{$end}=$section;
  778:             next;
  779:         }
  780:         if (defined($start) && ($now < $start)) {
  781:             $Pending{$start}=$section;
  782:             next;
  783:         }
  784:         return $section;
  785:     }
  786:     #
  787:     # Presumedly there will be few matching roles from the above
  788:     # loop and the sorting time will be negligible.
  789:     if (scalar(keys(%Pending))) {
  790:         my ($time) = sort {$a <=> $b} keys(%Pending);
  791:         return $Pending{$time};
  792:     } 
  793:     if (scalar(keys(%Expired))) {
  794:         my @sorted = sort {$a <=> $b} keys(%Expired);
  795:         my $time = pop(@sorted);
  796:         return $Expired{$time};
  797:     }
  798:     return '-1';
  799: }
  800: 
  801: sub usection {
  802:     my ($udom,$unam,$courseid)=@_;
  803:     $courseid=~s/\_/\//g;
  804:     $courseid=~s/^(\w)/\/$1/;
  805:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  806:                         &homeserver($unam,$udom)))) {
  807:         my ($key,$value)=split(/\=/,$_);
  808:         $key=&unescape($key);
  809:         if ($key=~/^$courseid(?:\/)*(\w+)*\_st$/) {
  810:             my $section=$1;
  811:             if ($key eq $courseid.'_st') { $section=''; }
  812: 	    my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  813:             my $now=time;
  814:             my $notactive=0;
  815:             if ($start) {
  816: 		if ($now<$start) { $notactive=1; }
  817:             }
  818:             if ($end) {
  819:                 if ($now>$end) { $notactive=1; }
  820:             } 
  821:             unless ($notactive) { return $section; }
  822:         }
  823:     }
  824:     return '-1';
  825: }
  826: 
  827: # ------------------------------------- Read an entry from a user's environment
  828: 
  829: sub userenvironment {
  830:     my ($udom,$unam,@what)=@_;
  831:     my %returnhash=();
  832:     my @answer=split(/\&/,
  833:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  834:                       &homeserver($unam,$udom)));
  835:     my $i;
  836:     for ($i=0;$i<=$#what;$i++) {
  837: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  838:     }
  839:     return %returnhash;
  840: }
  841: 
  842: # -------------------------------------------------------------------- New chat
  843: 
  844: sub chatsend {
  845:     my ($newentry,$anon)=@_;
  846:     my $cnum=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
  847:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
  848:     my $chome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
  849:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
  850: 	   &escape($ENV{'user.domain'}.':'.$ENV{'user.name'}.':'.$anon.':'.
  851: 		   &escape($newentry)),$chome);
  852: }
  853: 
  854: # ------------------------------------------ Find current version of a resource
  855: 
  856: sub getversion {
  857:     my $fname=&clutter(shift);
  858:     unless ($fname=~/^\/res\//) { return -1; }
  859:     return &currentversion(&filelocation('',$fname));
  860: }
  861: 
  862: sub currentversion {
  863:     my $fname=shift;
  864:     my $author=$fname;
  865:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  866:     my ($udom,$uname)=split(/\//,$author);
  867:     my $home=homeserver($uname,$udom);
  868:     if ($home eq 'no_host') { 
  869:         return -1; 
  870:     }
  871:     my $answer=reply("currentversion:$fname",$home);
  872:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
  873: 	return -1;
  874:     }
  875:     return $answer;
  876: }
  877: 
  878: # ----------------------------- Subscribe to a resource, return URL if possible
  879: 
  880: sub subscribe {
  881:     my $fname=shift;
  882:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
  883:     my $author=$fname;
  884:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  885:     my ($udom,$uname)=split(/\//,$author);
  886:     my $home=homeserver($uname,$udom);
  887:     if ($home eq 'no_host') {
  888:         return 'not_found';
  889:     }
  890:     my $answer=reply("sub:$fname",$home);
  891:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
  892: 	$answer.=' by '.$home;
  893:     }
  894:     return $answer;
  895: }
  896:     
  897: # -------------------------------------------------------------- Replicate file
  898: 
  899: sub repcopy {
  900:     my $filename=shift;
  901:     $filename=~s/\/+/\//g;
  902:     if ($filename=~/^\/home\/httpd\/html\/adm\//) { return OK; }
  903:     my $transname="$filename.in.transfer";
  904:     if ((-e $filename) || (-e $transname)) { return OK; }
  905:     my $remoteurl=subscribe($filename);
  906:     if ($remoteurl =~ /^con_lost by/) {
  907: 	   &logthis("Subscribe returned $remoteurl: $filename");
  908:            return HTTP_SERVICE_UNAVAILABLE;
  909:     } elsif ($remoteurl eq 'not_found') {
  910: 	   &logthis("Subscribe returned not_found: $filename");
  911: 	   return HTTP_NOT_FOUND;
  912:     } elsif ($remoteurl =~ /^rejected by/) {
  913: 	   &logthis("Subscribe returned $remoteurl: $filename");
  914:            return FORBIDDEN;
  915:     } elsif ($remoteurl eq 'directory') {
  916:            return OK;
  917:     } else {
  918:         my $author=$filename;
  919:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  920:         my ($udom,$uname)=split(/\//,$author);
  921:         my $home=homeserver($uname,$udom);
  922:         unless ($home eq $perlvar{'lonHostID'}) {
  923:            my @parts=split(/\//,$filename);
  924:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
  925:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
  926:                &logthis("Malconfiguration for replication: $filename");
  927: 	       return HTTP_BAD_REQUEST;
  928:            }
  929:            my $count;
  930:            for ($count=5;$count<$#parts;$count++) {
  931:                $path.="/$parts[$count]";
  932:                if ((-e $path)!=1) {
  933: 		   mkdir($path,0777);
  934:                }
  935:            }
  936:            my $ua=new LWP::UserAgent;
  937:            my $request=new HTTP::Request('GET',"$remoteurl");
  938:            my $response=$ua->request($request,$transname);
  939:            if ($response->is_error()) {
  940: 	       unlink($transname);
  941:                my $message=$response->status_line;
  942:                &logthis("<font color=blue>WARNING:"
  943:                        ." LWP get: $message: $filename</font>");
  944:                return HTTP_SERVICE_UNAVAILABLE;
  945:            } else {
  946: 	       if ($remoteurl!~/\.meta$/) {
  947:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
  948:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
  949:                   if ($mresponse->is_error()) {
  950: 		      unlink($filename.'.meta');
  951:                       &logthis(
  952:                      "<font color=yellow>INFO: No metadata: $filename</font>");
  953:                   }
  954: 	       }
  955:                rename($transname,$filename);
  956:                return OK;
  957:            }
  958:        }
  959:     }
  960: }
  961: 
  962: # ------------------------------------------------ Get server side include body
  963: sub ssi_body {
  964:     my $filelink=shift;
  965:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
  966:                                      &ssi($filelink));
  967:     $output=~s/^.*\<body[^\>]*\>//si;
  968:     $output=~s/\<\/body\s*\>.*$//si;
  969:     $output=~
  970:             s/\/\/ BEGIN LON\-CAPA Internal.+\/\/ END LON\-CAPA Internal\s//gs;
  971:     return $output;
  972: }
  973: 
  974: # --------------------------------------------------------- Server Side Include
  975: 
  976: sub ssi {
  977: 
  978:     my ($fn,%form)=@_;
  979: 
  980:     my $ua=new LWP::UserAgent;
  981:     
  982:     my $request;
  983:     
  984:     if (%form) {
  985:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
  986:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
  987:     } else {
  988:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
  989:     }
  990: 
  991:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
  992:     my $response=$ua->request($request);
  993: 
  994:     return $response->content;
  995: }
  996: 
  997: sub externalssi {
  998:     my ($url)=@_;
  999:     my $ua=new LWP::UserAgent;
 1000:     my $request=new HTTP::Request('GET',$url);
 1001:     my $response=$ua->request($request);
 1002:     return $response->content;
 1003: }
 1004: 
 1005: # ------- Add a token to a remote URI's query string to vouch for access rights
 1006: 
 1007: sub tokenwrapper {
 1008:     my $uri=shift;
 1009:     $uri=~s/^http\:\/\/([^\/]+)//;
 1010:     $uri=~s/^\///;
 1011:     $ENV{'user.environment'}=~/\/([^\/]+)\.id/;
 1012:     my $token=$1;
 1013:     if ($uri=~/^uploaded\/([^\/]+)\/([^\/]+)\/([^\/]+)(\?\.*)*$/) {
 1014: 	&appenv('userfile.'.$1.'/'.$2.'/'.$3 => $ENV{'request.course.id'});
 1015:         return 'http://'.$hostname{ &homeserver($2,$1)}.'/'.$uri.
 1016:                (($uri=~/\?/)?'&':'?').'token='.$token.
 1017:                                '&tokenissued='.$perlvar{'lonHostID'};
 1018:     } else {
 1019: 	return '/adm/notfound.html';
 1020:     }
 1021: }
 1022:     
 1023: # --------------- Take an uploaded file and put it into the userfiles directory
 1024: # input: name of form element, coursedoc=1 means this is for the course
 1025: # output: url of file in userspace
 1026: 
 1027: sub userfileupload {
 1028:     my ($formname,$coursedoc)=@_;
 1029:     my $fname=$ENV{'form.'.$formname.'.filename'};
 1030: # Replace Windows backslashes by forward slashes
 1031:     $fname=~s/\\/\//g;
 1032: # Get rid of everything but the actual filename
 1033:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1034: # Replace spaces by underscores
 1035:     $fname=~s/\s+/\_/g;
 1036: # Replace all other weird characters by nothing
 1037:     $fname=~s/[^\w\.\-]//g;
 1038: # See if there is anything left
 1039:     unless ($fname) { return 'error: no uploaded file'; }
 1040:     chop($ENV{'form.'.$formname});
 1041: # Create the directory if not present
 1042:     my $docuname='';
 1043:     my $docudom='';
 1044:     my $docuhome='';
 1045:     if ($coursedoc) {
 1046: 	$docuname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 1047: 	$docudom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 1048: 	$docuhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1049:     } else {
 1050:         $docuname=$ENV{'user.name'};
 1051:         $docudom=$ENV{'user.domain'};
 1052:         $docuhome=$ENV{'user.home'};
 1053:     }
 1054:     return 
 1055:         &finishuserfileupload($docuname,$docudom,$docuhome,$formname,$fname);
 1056: }
 1057: 
 1058: sub finishuserfileupload {
 1059:     my ($docuname,$docudom,$docuhome,$formname,$fname)=@_;
 1060:     my $path=$docudom.'/'.$docuname.'/';
 1061:     my $filepath=$perlvar{'lonDocRoot'};
 1062:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1063:     my $count;
 1064:     for ($count=4;$count<=$#parts;$count++) {
 1065:         $filepath.="/$parts[$count]";
 1066:         if ((-e $filepath)!=1) {
 1067: 	    mkdir($filepath,0777);
 1068:         }
 1069:     }
 1070: # Save the file
 1071:     {
 1072:        my $fh=Apache::File->new('>'.$filepath.'/'.$fname);
 1073:        print $fh $ENV{'form.'.$formname};
 1074:     }
 1075: # Notify homeserver to grep it
 1076: #
 1077:     
 1078:     my $fetchresult= 
 1079:  &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$fname,$docuhome);
 1080:     if ($fetchresult eq 'ok') {
 1081: #
 1082: # Return the URL to it
 1083:         return '/uploaded/'.$path.$fname;
 1084:     } else {
 1085:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$fname.
 1086:          ' to host '.$docuhome.': '.$fetchresult);
 1087:         return '/adm/notfound.html';
 1088:     }    
 1089: }
 1090: 
 1091: # ------------------------------------------------------------------------- Log
 1092: 
 1093: sub log {
 1094:     my ($dom,$nam,$hom,$what)=@_;
 1095:     return critical("log:$dom:$nam:$what",$hom);
 1096: }
 1097: 
 1098: # ------------------------------------------------------------------ Course Log
 1099: #
 1100: # This routine flushes several buffers of non-mission-critical nature
 1101: #
 1102: 
 1103: sub flushcourselogs {
 1104:     &logthis('Flushing log buffers');
 1105: #
 1106: # course logs
 1107: # This is a log of all transactions in a course, which can be used
 1108: # for data mining purposes
 1109: #
 1110: # It also collects the courseid database, which lists last transaction
 1111: # times and course titles for all courseids
 1112: #
 1113:     my %courseidbuffer=();
 1114:     foreach (keys %courselogs) {
 1115:         my $crsid=$_;
 1116:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1117: 		          &escape($courselogs{$crsid}),
 1118: 		          $coursehombuf{$crsid}) eq 'ok') {
 1119: 	    delete $courselogs{$crsid};
 1120:         } else {
 1121:             &logthis('Failed to flush log buffer for '.$crsid);
 1122:             if (length($courselogs{$crsid})>40000) {
 1123:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
 1124:                         " exceeded maximum size, deleting.</font>");
 1125:                delete $courselogs{$crsid};
 1126:             }
 1127:         }
 1128:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1129:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1130: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
 1131:         } else {
 1132:            $courseidbuffer{$coursehombuf{$crsid}}=
 1133: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid});
 1134:         }    
 1135:     }
 1136: #
 1137: # Write course id database (reverse lookup) to homeserver of courses 
 1138: # Is used in pickcourse
 1139: #
 1140:     foreach (keys %courseidbuffer) {
 1141:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1142:     }
 1143: #
 1144: # File accesses
 1145: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1146: #
 1147:     foreach (keys %accesshash) {
 1148:         my $entry=$_;
 1149:         $entry=~/\_\_\_(\w+)\/(\w+)\/(.*)\_\_\_(\w+)$/;
 1150:         my %temphash=($entry => $accesshash{$entry});
 1151:         if (&Apache::lonnet::put('nohist_resevaldata',\%temphash,$1,$2) eq 'ok') {
 1152: 	    delete $accesshash{$entry};
 1153:         }
 1154:     }
 1155: #
 1156: # Roles
 1157: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1158: #
 1159:     foreach (keys %userrolehash) {
 1160:         my $entry=$_;
 1161:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1162: 	    split(/\:/,$entry);
 1163:         if (&Apache::lonnet::put('nohist_userroles',
 1164:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1165:                 $rudom,$runame) eq 'ok') {
 1166: 	    delete $userrolehash{$entry};
 1167:         }
 1168:     }
 1169:     $dumpcount++;
 1170: }
 1171: 
 1172: sub courselog {
 1173:     my $what=shift;
 1174:     $what=time.':'.$what;
 1175:     unless ($ENV{'request.course.id'}) { return ''; }
 1176:     $coursedombuf{$ENV{'request.course.id'}}=
 1177:        $ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 1178:     $coursenumbuf{$ENV{'request.course.id'}}=
 1179:        $ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 1180:     $coursehombuf{$ENV{'request.course.id'}}=
 1181:        $ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 1182:     $coursedescrbuf{$ENV{'request.course.id'}}=
 1183:        $ENV{'course.'.$ENV{'request.course.id'}.'.description'};
 1184:     if (defined $courselogs{$ENV{'request.course.id'}}) {
 1185: 	$courselogs{$ENV{'request.course.id'}}.='&'.$what;
 1186:     } else {
 1187: 	$courselogs{$ENV{'request.course.id'}}.=$what;
 1188:     }
 1189:     if (length($courselogs{$ENV{'request.course.id'}})>4048) {
 1190: 	&flushcourselogs();
 1191:     }
 1192: }
 1193: 
 1194: sub courseacclog {
 1195:     my $fnsymb=shift;
 1196:     unless ($ENV{'request.course.id'}) { return ''; }
 1197:     my $what=$fnsymb.':'.$ENV{'user.name'}.':'.$ENV{'user.domain'};
 1198:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form)$/) {
 1199:         $what.=':POST';
 1200: 	foreach (keys %ENV) {
 1201:             if ($_=~/^form\.(.*)/) {
 1202: 		$what.=':'.$1.'='.$ENV{$_};
 1203:             }
 1204:         }
 1205:     }
 1206:     &courselog($what);
 1207: }
 1208: 
 1209: sub countacc {
 1210:     my $url=&declutter(shift);
 1211:     unless ($ENV{'request.course.id'}) { return ''; }
 1212:     $accesshash{$ENV{'request.course.id'}.'___'.$url.'___course'}=1;
 1213:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1214:     if (defined($accesshash{$key})) {
 1215: 	$accesshash{$key}++;
 1216:     } else {
 1217:         $accesshash{$key}=1;
 1218:     }
 1219: }
 1220: 
 1221: sub linklog {
 1222:     my ($from,$to)=@_;
 1223:     $from=&declutter($from);
 1224:     $to=&declutter($to);
 1225:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1226:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1227: }
 1228:   
 1229: sub userrolelog {
 1230:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1231:     if (($trole=~/^ca/) || ($trole=~/^in/) || 
 1232:         ($trole=~/^cc/) || ($trole=~/^ep/) ||
 1233:         ($trole=~/^cr/)) {
 1234:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1235:        $userrolehash
 1236:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1237:                     =$tend.':'.$tstart;
 1238:    }
 1239: }
 1240: 
 1241: sub get_course_adv_roles {
 1242:     my $cid=shift;
 1243:     $cid=$ENV{'request.course.id'} unless (defined($cid));
 1244:     my %coursehash=&coursedescription($cid);
 1245:     my %returnhash=();
 1246:     my %dumphash=
 1247:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1248:     my $now=time;
 1249:     foreach (keys %dumphash) {
 1250: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1251:         if (($tstart) && ($tstart<0)) { next; }
 1252:         if (($tend) && ($tend<$now)) { next; }
 1253:         if (($tstart) && ($now<$tstart)) { next; }
 1254:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1255:         my $key=&plaintext($role);
 1256:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1257:         if ($returnhash{$key}) {
 1258: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1259:         } else {
 1260:             $returnhash{$key}=$username.':'.$domain;
 1261:         }
 1262:     }
 1263:     return sort %returnhash;
 1264: }
 1265: 
 1266: # ---------------------------------------------------------- Course ID routines
 1267: # Deal with domain's nohist_courseid.db files
 1268: #
 1269: 
 1270: sub courseidput {
 1271:     my ($domain,$what,$coursehome)=@_;
 1272:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1273: }
 1274: 
 1275: sub courseiddump {
 1276:     my ($domfilter,$descfilter,$sincefilter)=@_;
 1277:     my %returnhash=();
 1278:     unless ($domfilter) { $domfilter=''; }
 1279:     foreach my $tryserver (keys %libserv) {
 1280: 	if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1281: 	    foreach (
 1282:              split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1283: 			       $sincefilter.':'.&escape($descfilter),
 1284:                                $tryserver))) {
 1285: 		my ($key,$value)=split(/\=/,$_);
 1286:                 if (($key) && ($value)) {
 1287: 		    $returnhash{&unescape($key)}=&unescape($value);
 1288:                 }
 1289:             }
 1290: 
 1291:         }
 1292:     }
 1293:     return %returnhash;
 1294: }
 1295: 
 1296: #
 1297: # ----------------------------------------------------------- Check out an item
 1298: 
 1299: sub checkout {
 1300:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 1301:     my $now=time;
 1302:     my $lonhost=$perlvar{'lonHostID'};
 1303:     my $infostr=&escape(
 1304:                  'CHECKOUTTOKEN&'.
 1305:                  $tuname.'&'.
 1306:                  $tudom.'&'.
 1307:                  $tcrsid.'&'.
 1308:                  $symb.'&'.
 1309: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 1310:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 1311:     if ($token=~/^error\:/) { 
 1312:         &logthis("<font color=blue>WARNING: ".
 1313:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 1314:                  "</font>");
 1315:         return ''; 
 1316:     }
 1317: 
 1318:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 1319:     $token=~tr/a-z/A-Z/;
 1320: 
 1321:     my %infohash=('resource.0.outtoken' => $token,
 1322:                   'resource.0.checkouttime' => $now,
 1323:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 1324: 
 1325:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 1326:        return '';
 1327:     } else {
 1328:         &logthis("<font color=blue>WARNING: ".
 1329:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 1330:                  "</font>");
 1331:     }    
 1332: 
 1333:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 1334:                          &escape('Checkout '.$infostr.' - '.
 1335:                                                  $token)) ne 'ok') {
 1336: 	return '';
 1337:     } else {
 1338:         &logthis("<font color=blue>WARNING: ".
 1339:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 1340:                  "</font>");
 1341:     }
 1342:     return $token;
 1343: }
 1344: 
 1345: # ------------------------------------------------------------ Check in an item
 1346: 
 1347: sub checkin {
 1348:     my $token=shift;
 1349:     my $now=time;
 1350:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 1351:     $lonhost=~tr/A-Z/a-z/;
 1352:     my $dtoken=$ta.'_'.$hostip{$lonhost}.'_'.$tb;
 1353:     $dtoken=~s/\W/\_/g;
 1354:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 1355:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 1356: 
 1357:     unless (($tuname) && ($tudom)) {
 1358:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 1359:         return '';
 1360:     }
 1361:     
 1362:     unless (&allowed('mgr',$tcrsid)) {
 1363:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 1364:                  $ENV{'user.name'}.' - '.$ENV{'user.domain'});
 1365:         return '';
 1366:     }
 1367: 
 1368:     my %infohash=('resource.0.intoken' => $token,
 1369:                   'resource.0.checkintime' => $now,
 1370:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 1371: 
 1372:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 1373:        return '';
 1374:     }    
 1375: 
 1376:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 1377:                          &escape('Checkin - '.$token)) ne 'ok') {
 1378: 	return '';
 1379:     }
 1380: 
 1381:     return ($symb,$tuname,$tudom,$tcrsid);    
 1382: }
 1383: 
 1384: # --------------------------------------------- Set Expire Date for Spreadsheet
 1385: 
 1386: sub expirespread {
 1387:     my ($uname,$udom,$stype,$usymb)=@_;
 1388:     my $cid=$ENV{'request.course.id'}; 
 1389:     if ($cid) {
 1390:        my $now=time;
 1391:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 1392:        return &reply('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 1393:                             $ENV{'course.'.$cid.'.num'}.
 1394: 	        	    ':nohist_expirationdates:'.
 1395:                             &escape($key).'='.$now,
 1396:                             $ENV{'course.'.$cid.'.home'})
 1397:     }
 1398:     return 'ok';
 1399: }
 1400: 
 1401: # ----------------------------------------------------- Devalidate Spreadsheets
 1402: 
 1403: sub devalidate {
 1404:     my ($symb,$uname,$udom)=@_;
 1405:     my $cid=$ENV{'request.course.id'}; 
 1406:     if ($cid) {
 1407: # delete the stored spreadsheets for
 1408: # - the student level sheet of this user in course's homespace
 1409: # - the assessment level sheet for this resource 
 1410: #   for this user in user's homespace
 1411: 	my $key=$uname.':'.$udom.':';
 1412:         my $status=
 1413: 	    &del('nohist_calculatedsheets',
 1414: 		 [$key.'studentcalc'],
 1415: 		 $ENV{'course.'.$cid.'.domain'},
 1416: 		 $ENV{'course.'.$cid.'.num'})
 1417: 		.' '.
 1418: 	    &del('nohist_calculatedsheets_'.$cid,
 1419: 		 [$key.'assesscalc:'.$symb]);
 1420:         unless ($status eq 'ok ok') {
 1421:            &logthis('Could not devalidate spreadsheet '.
 1422:                     $uname.' at '.$udom.' for '.
 1423: 		    $symb.': '.$status);
 1424:         }
 1425:     }
 1426: }
 1427: 
 1428: sub get_scalar {
 1429:     my ($string,$end) = @_;
 1430:     my $value;
 1431:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 1432: 	$value = $1;
 1433:     } elsif ($$string =~ s/^([^&]*?)&//) {
 1434: 	$value = $1;
 1435:     }
 1436:     return &unescape($value);
 1437: }
 1438: 
 1439: sub array2str {
 1440:   my (@array) = @_;
 1441:   my $result=&arrayref2str(\@array);
 1442:   $result=~s/^__ARRAY_REF__//;
 1443:   $result=~s/__END_ARRAY_REF__$//;
 1444:   return $result;
 1445: }
 1446: 
 1447: sub arrayref2str {
 1448:   my ($arrayref) = @_;
 1449:   my $result='__ARRAY_REF__';
 1450:   foreach my $elem (@$arrayref) {
 1451:     if(ref($elem) eq 'ARRAY') {
 1452:       $result.=&arrayref2str($elem).'&';
 1453:     } elsif(ref($elem) eq 'HASH') {
 1454:       $result.=&hashref2str($elem).'&';
 1455:     } elsif(ref($elem)) {
 1456:       #print("Got a ref of ".(ref($elem))." skipping.");
 1457:     } else {
 1458:       $result.=&escape($elem).'&';
 1459:     }
 1460:   }
 1461:   $result=~s/\&$//;
 1462:   $result .= '__END_ARRAY_REF__';
 1463:   return $result;
 1464: }
 1465: 
 1466: sub hash2str {
 1467:   my (%hash) = @_;
 1468:   my $result=&hashref2str(\%hash);
 1469:   $result=~s/^__HASH_REF__//;
 1470:   $result=~s/__END_HASH_REF__$//;
 1471:   return $result;
 1472: }
 1473: 
 1474: sub hashref2str {
 1475:   my ($hashref)=@_;
 1476:   my $result='__HASH_REF__';
 1477:   foreach (keys(%$hashref)) {
 1478:     if (ref($_) eq 'ARRAY') {
 1479:       $result.=&arrayref2str($_).'=';
 1480:     } elsif (ref($_) eq 'HASH') {
 1481:       $result.=&hashref2str($_).'=';
 1482:     } elsif (ref($_)) {
 1483:       $result.='=';
 1484:       #print("Got a ref of ".(ref($_))." skipping.");
 1485:     } else {
 1486: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 1487:     }
 1488: 
 1489:     if(ref($hashref->{$_}) eq 'ARRAY') {
 1490:       $result.=&arrayref2str($hashref->{$_}).'&';
 1491:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 1492:       $result.=&hashref2str($hashref->{$_}).'&';
 1493:     } elsif(ref($hashref->{$_})) {
 1494:        $result.='&';
 1495:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 1496:     } else {
 1497:       $result.=&escape($hashref->{$_}).'&';
 1498:     }
 1499:   }
 1500:   $result=~s/\&$//;
 1501:   $result .= '__END_HASH_REF__';
 1502:   return $result;
 1503: }
 1504: 
 1505: sub str2hash {
 1506:     my ($string)=@_;
 1507:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 1508:     return %$hash;
 1509: }
 1510: 
 1511: sub str2hashref {
 1512:   my ($string) = @_;
 1513: 
 1514:   my %hash;
 1515: 
 1516:   if($string !~ /^__HASH_REF__/) {
 1517:       if (! ($string eq '' || !defined($string))) {
 1518: 	  $hash{'error'}='Not hash reference';
 1519:       }
 1520:       return (\%hash, $string);
 1521:   }
 1522: 
 1523:   $string =~ s/^__HASH_REF__//;
 1524: 
 1525:   while($string !~ /^__END_HASH_REF__/) {
 1526:       #key
 1527:       my $key='';
 1528:       if($string =~ /^__HASH_REF__/) {
 1529:           ($key, $string)=&str2hashref($string);
 1530:           if(defined($key->{'error'})) {
 1531:               $hash{'error'}='Bad data';
 1532:               return (\%hash, $string);
 1533:           }
 1534:       } elsif($string =~ /^__ARRAY_REF__/) {
 1535:           ($key, $string)=&str2arrayref($string);
 1536:           if($key->[0] eq 'Array reference error') {
 1537:               $hash{'error'}='Bad data';
 1538:               return (\%hash, $string);
 1539:           }
 1540:       } else {
 1541:           $string =~ s/^(.*?)=//;
 1542: 	  $key=&unescape($1);
 1543:       }
 1544:       $string =~ s/^=//;
 1545: 
 1546:       #value
 1547:       my $value='';
 1548:       if($string =~ /^__HASH_REF__/) {
 1549:           ($value, $string)=&str2hashref($string);
 1550:           if(defined($value->{'error'})) {
 1551:               $hash{'error'}='Bad data';
 1552:               return (\%hash, $string);
 1553:           }
 1554:       } elsif($string =~ /^__ARRAY_REF__/) {
 1555:           ($value, $string)=&str2arrayref($string);
 1556:           if($value->[0] eq 'Array reference error') {
 1557:               $hash{'error'}='Bad data';
 1558:               return (\%hash, $string);
 1559:           }
 1560:       } else {
 1561: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 1562:       }
 1563:       $string =~ s/^&//;
 1564: 
 1565:       $hash{$key}=$value;
 1566:   }
 1567: 
 1568:   $string =~ s/^__END_HASH_REF__//;
 1569: 
 1570:   return (\%hash, $string);
 1571: }
 1572: 
 1573: sub str2array {
 1574:     my ($string)=@_;
 1575:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 1576:     return @$array;
 1577: }
 1578: 
 1579: sub str2arrayref {
 1580:   my ($string) = @_;
 1581:   my @array;
 1582: 
 1583:   if($string !~ /^__ARRAY_REF__/) {
 1584:       if (! ($string eq '' || !defined($string))) {
 1585: 	  $array[0]='Array reference error';
 1586:       }
 1587:       return (\@array, $string);
 1588:   }
 1589: 
 1590:   $string =~ s/^__ARRAY_REF__//;
 1591: 
 1592:   while($string !~ /^__END_ARRAY_REF__/) {
 1593:       my $value='';
 1594:       if($string =~ /^__HASH_REF__/) {
 1595:           ($value, $string)=&str2hashref($string);
 1596:           if(defined($value->{'error'})) {
 1597:               $array[0] ='Array reference error';
 1598:               return (\@array, $string);
 1599:           }
 1600:       } elsif($string =~ /^__ARRAY_REF__/) {
 1601:           ($value, $string)=&str2arrayref($string);
 1602:           if($value->[0] eq 'Array reference error') {
 1603:               $array[0] ='Array reference error';
 1604:               return (\@array, $string);
 1605:           }
 1606:       } else {
 1607: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 1608:       }
 1609:       $string =~ s/^&//;
 1610: 
 1611:       push(@array, $value);
 1612:   }
 1613: 
 1614:   $string =~ s/^__END_ARRAY_REF__//;
 1615: 
 1616:   return (\@array, $string);
 1617: }
 1618: 
 1619: # -------------------------------------------------------------------Temp Store
 1620: 
 1621: sub tmpreset {
 1622:   my ($symb,$namespace,$domain,$stuname) = @_;
 1623:   if (!$symb) {
 1624:     $symb=&symbread();
 1625:     if (!$symb) { $symb= $ENV{'REQUEST_URI'}; }
 1626:   }
 1627:   $symb=escape($symb);
 1628: 
 1629:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 1630:   $namespace=~s/\//\_/g;
 1631:   $namespace=~s/\W//g;
 1632: 
 1633:   #FIXME needs to do something for /pub resources
 1634:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1635:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1636:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1637:   my %hash;
 1638:   if (tie(%hash,'GDBM_File',
 1639: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1640: 	  &GDBM_WRCREAT(),0640)) {
 1641:     foreach my $key (keys %hash) {
 1642:       if ($key=~ /:$symb/) {
 1643: 	delete($hash{$key});
 1644:       }
 1645:     }
 1646:   }
 1647: }
 1648: 
 1649: sub tmpstore {
 1650:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1651: 
 1652:   if (!$symb) {
 1653:     $symb=&symbread();
 1654:     if (!$symb) { $symb= $ENV{'request.url'}; }
 1655:   }
 1656:   $symb=escape($symb);
 1657: 
 1658:   if (!$namespace) {
 1659:     # I don't think we would ever want to store this for a course.
 1660:     # it seems this will only be used if we don't have a course.
 1661:     #$namespace=$ENV{'request.course.id'};
 1662:     #if (!$namespace) {
 1663:       $namespace=$ENV{'request.state'};
 1664:     #}
 1665:   }
 1666:   $namespace=~s/\//\_/g;
 1667:   $namespace=~s/\W//g;
 1668: #FIXME needs to do something for /pub resources
 1669:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1670:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1671:   my $now=time;
 1672:   my %hash;
 1673:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1674:   if (tie(%hash,'GDBM_File',
 1675: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1676: 	  &GDBM_WRCREAT(),0640)) {
 1677:     $hash{"version:$symb"}++;
 1678:     my $version=$hash{"version:$symb"};
 1679:     my $allkeys=''; 
 1680:     foreach my $key (keys(%$storehash)) {
 1681:       $allkeys.=$key.':';
 1682:       $hash{"$version:$symb:$key"}=$$storehash{$key};
 1683:     }
 1684:     $hash{"$version:$symb:timestamp"}=$now;
 1685:     $allkeys.='timestamp';
 1686:     $hash{"$version:keys:$symb"}=$allkeys;
 1687:     if (untie(%hash)) {
 1688:       return 'ok';
 1689:     } else {
 1690:       return "error:$!";
 1691:     }
 1692:   } else {
 1693:     return "error:$!";
 1694:   }
 1695: }
 1696: 
 1697: # -----------------------------------------------------------------Temp Restore
 1698: 
 1699: sub tmprestore {
 1700:   my ($symb,$namespace,$domain,$stuname) = @_;
 1701: 
 1702:   if (!$symb) {
 1703:     $symb=&symbread();
 1704:     if (!$symb) { $symb= $ENV{'request.url'}; }
 1705:   }
 1706:   $symb=escape($symb);
 1707: 
 1708:   if (!$namespace) { $namespace=$ENV{'request.state'}; }
 1709:   #FIXME needs to do something for /pub resources
 1710:   if (!$domain) { $domain=$ENV{'user.domain'}; }
 1711:   if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1712: 
 1713:   my %returnhash;
 1714:   $namespace=~s/\//\_/g;
 1715:   $namespace=~s/\W//g;
 1716:   my %hash;
 1717:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 1718:   if (tie(%hash,'GDBM_File',
 1719: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 1720: 	  &GDBM_READER(),0640)) {
 1721:     my $version=$hash{"version:$symb"};
 1722:     $returnhash{'version'}=$version;
 1723:     my $scope;
 1724:     for ($scope=1;$scope<=$version;$scope++) {
 1725:       my $vkeys=$hash{"$scope:keys:$symb"};
 1726:       my @keys=split(/:/,$vkeys);
 1727:       my $key;
 1728:       $returnhash{"$scope:keys"}=$vkeys;
 1729:       foreach $key (@keys) {
 1730: 	$returnhash{"$scope:$key"}=$hash{"$scope:$symb:$key"};
 1731: 	$returnhash{"$key"}=$hash{"$scope:$symb:$key"};
 1732:       }
 1733:     }
 1734:     if (!(untie(%hash))) {
 1735:       return "error:$!";
 1736:     }
 1737:   } else {
 1738:     return "error:$!";
 1739:   }
 1740:   return %returnhash;
 1741: }
 1742: 
 1743: # ----------------------------------------------------------------------- Store
 1744: 
 1745: sub store {
 1746:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1747:     my $home='';
 1748: 
 1749:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1750: 
 1751:     $symb=&symbclean($symb);
 1752:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1753: 
 1754:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1755:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1756: 
 1757:     &devalidate($symb,$stuname,$domain);
 1758: 
 1759:     $symb=escape($symb);
 1760:     if (!$namespace) { 
 1761:        unless ($namespace=$ENV{'request.course.id'}) { 
 1762:           return ''; 
 1763:        } 
 1764:     }
 1765:     if (!$home) { $home=$ENV{'user.home'}; }
 1766:     my $namevalue='';
 1767:     foreach (keys %$storehash) {
 1768:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1769:     }
 1770:     $namevalue=~s/\&$//;
 1771:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 1772:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1773: }
 1774: 
 1775: # -------------------------------------------------------------- Critical Store
 1776: 
 1777: sub cstore {
 1778:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 1779:     my $home='';
 1780: 
 1781:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1782: 
 1783:     $symb=&symbclean($symb);
 1784:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 1785: 
 1786:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1787:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1788: 
 1789:     &devalidate($symb,$stuname,$domain);
 1790: 
 1791:     $symb=escape($symb);
 1792:     if (!$namespace) { 
 1793:        unless ($namespace=$ENV{'request.course.id'}) { 
 1794:           return ''; 
 1795:        } 
 1796:     }
 1797:     if (!$home) { $home=$ENV{'user.home'}; }
 1798: 
 1799:     my $namevalue='';
 1800:     foreach (keys %$storehash) {
 1801:         $namevalue.=escape($_).'='.escape($$storehash{$_}).'&';
 1802:     }
 1803:     $namevalue=~s/\&$//;
 1804:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 1805:     return critical
 1806:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 1807: }
 1808: 
 1809: # --------------------------------------------------------------------- Restore
 1810: 
 1811: sub restore {
 1812:     my ($symb,$namespace,$domain,$stuname) = @_;
 1813:     my $home='';
 1814: 
 1815:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 1816: 
 1817:     if (!$symb) {
 1818:       unless ($symb=escape(&symbread())) { return ''; }
 1819:     } else {
 1820:       $symb=&escape(&symbclean($symb));
 1821:     }
 1822:     if (!$namespace) { 
 1823:        unless ($namespace=$ENV{'request.course.id'}) { 
 1824:           return ''; 
 1825:        } 
 1826:     }
 1827:     if (!$domain) { $domain=$ENV{'user.domain'}; }
 1828:     if (!$stuname) { $stuname=$ENV{'user.name'}; }
 1829:     if (!$home) { $home=$ENV{'user.home'}; }
 1830:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 1831: 
 1832:     my %returnhash=();
 1833:     foreach (split(/\&/,$answer)) {
 1834: 	my ($name,$value)=split(/\=/,$_);
 1835:         $returnhash{&unescape($name)}=&unescape($value);
 1836:     }
 1837:     my $version;
 1838:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 1839:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 1840:           $returnhash{$_}=$returnhash{$version.':'.$_};
 1841:        }
 1842:     }
 1843:     return %returnhash;
 1844: }
 1845: 
 1846: # ---------------------------------------------------------- Course Description
 1847: 
 1848: sub coursedescription {
 1849:     my $courseid=shift;
 1850:     $courseid=~s/^\///;
 1851:     $courseid=~s/\_/\//g;
 1852:     my ($cdomain,$cnum)=split(/\//,$courseid);
 1853:     my $chome=&homeserver($cnum,$cdomain);
 1854:     my $normalid=$cdomain.'_'.$cnum;
 1855:     # need to always cache even if we get errors otherwise we keep 
 1856:     # trying and trying and trying to get the course description.
 1857:     my %envhash=();
 1858:     my %returnhash=();
 1859:     $envhash{'course.'.$normalid.'.last_cache'}=time;
 1860:     if ($chome ne 'no_host') {
 1861:        %returnhash=&dump('environment',$cdomain,$cnum);
 1862:        if (!exists($returnhash{'con_lost'})) {
 1863:            $returnhash{'home'}= $chome;
 1864: 	   $returnhash{'domain'} = $cdomain;
 1865: 	   $returnhash{'num'} = $cnum;
 1866:            while (my ($name,$value) = each %returnhash) {
 1867:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 1868:            }
 1869:            $returnhash{'url'}=&clutter($returnhash{'url'});
 1870:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 1871: 	       $ENV{'user.name'}.'_'.$cdomain.'_'.$cnum;
 1872:            $envhash{'course.'.$normalid.'.home'}=$chome;
 1873:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 1874:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 1875:        }
 1876:     }
 1877:     &appenv(%envhash);
 1878:     return %returnhash;
 1879: }
 1880: 
 1881: # -------------------------------------------------------- Get user privileges
 1882: 
 1883: sub rolesinit {
 1884:     my ($domain,$username,$authhost)=@_;
 1885:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 1886:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 1887:     my %allroles=();
 1888:     my %thesepriv=();
 1889:     my $now=time;
 1890:     my $userroles="user.login.time=$now\n";
 1891:     my $thesestr;
 1892: 
 1893:     if ($rolesdump ne '') {
 1894:         foreach (split(/&/,$rolesdump)) {
 1895: 	  if ($_!~/^rolesdef\&/) {
 1896:             my ($area,$role)=split(/=/,$_);
 1897:             $area=~s/\_\w\w$//;
 1898:             my ($trole,$tend,$tstart)=split(/_/,$role);
 1899:             $userroles.='user.role.'.$trole.'.'.$area.'='.
 1900:                         $tstart.'.'.$tend."\n";
 1901: # log the associated role with the area
 1902:             &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 1903:             if ($tend!=0) {
 1904: 	        if ($tend<$now) {
 1905: 	            $trole='';
 1906:                 } 
 1907:             }
 1908:             if ($tstart!=0) {
 1909:                 if ($tstart>$now) {
 1910:                    $trole='';        
 1911:                 }
 1912:             }
 1913:             if (($area ne '') && ($trole ne '')) {
 1914: 		my $spec=$trole.'.'.$area;
 1915: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 1916: 		if ($trole =~ /^cr\//) {
 1917: 		    my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 1918: 		    my $homsvr=homeserver($rauthor,$rdomain);
 1919: 		    if ($hostname{$homsvr} ne '') {
 1920: 			my $roledef=
 1921: 			    reply("get:$rdomain:$rauthor:roles:rolesdef_$rrole",
 1922: 				  $homsvr);
 1923: 			if (($roledef ne 'con_lost') && ($roledef ne '')) {
 1924: 			    my ($syspriv,$dompriv,$coursepriv)=
 1925: 				split(/\_/,unescape($roledef));
 1926: 			    if (defined($syspriv)) {
 1927: 				$allroles{'cm./'}.=':'.$syspriv;
 1928: 				$allroles{$spec.'./'}.=':'.$syspriv;
 1929: 			    }
 1930: 			    if ($tdomain ne '') {
 1931: 				if (defined($dompriv)) {
 1932: 				    $allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 1933: 				    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 1934: 				}
 1935: 				if ($trest ne '') {
 1936: 				    if (defined($coursepriv)) {
 1937: 					$allroles{'cm.'.$area}.=':'.$coursepriv;
 1938: 					$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 1939: 				    }
 1940: 				}
 1941: 			    }
 1942: 			}
 1943: 		    }
 1944: 		} else {
 1945: 		    if (defined($pr{$trole.':s'})) {
 1946: 			$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 1947: 			$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 1948: 		    }
 1949: 		    if ($tdomain ne '') {
 1950: 			if (defined($pr{$trole.':d'})) {
 1951: 			    $allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1952: 			    $allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 1953: 			}
 1954: 			if ($trest ne '') {
 1955: 			    if (defined($pr{$trole.':c'})) {
 1956: 				$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 1957: 				$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 1958: 			    }
 1959: 			}
 1960: 		    }
 1961: 		}
 1962:             }
 1963:           } 
 1964:         }
 1965:         my $adv=0;
 1966:         my $author=0;
 1967:         foreach (keys %allroles) {
 1968:             %thesepriv=();
 1969:             if (($_!~/^st/) && ($_!~/^ta/) && ($_!~/^cm/)) { $adv=1; }
 1970:             if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 1971:             foreach (split(/:/,$allroles{$_})) {
 1972:                 if ($_ ne '') {
 1973: 		    my ($privilege,$restrictions)=split(/&/,$_);
 1974:                     if ($restrictions eq '') {
 1975: 			$thesepriv{$privilege}='F';
 1976:                     } else {
 1977:                         if ($thesepriv{$privilege} ne 'F') {
 1978: 			    $thesepriv{$privilege}.=$restrictions;
 1979:                         }
 1980:                     }
 1981:                 }
 1982:             }
 1983:             $thesestr='';
 1984:             foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 1985:             $userroles.='user.priv.'.$_.'='.$thesestr."\n";
 1986:         }
 1987:         $userroles.='user.adv='.$adv."\n".
 1988: 	            'user.author='.$author."\n";
 1989:         $ENV{'user.adv'}=$adv;
 1990:     }
 1991:     return $userroles;  
 1992: }
 1993: 
 1994: # --------------------------------------------------------------- get interface
 1995: 
 1996: sub get {
 1997:    my ($namespace,$storearr,$udomain,$uname)=@_;
 1998:    my $items='';
 1999:    foreach (@$storearr) {
 2000:        $items.=escape($_).'&';
 2001:    }
 2002:    $items=~s/\&$//;
 2003:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2004:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2005:    my $uhome=&homeserver($uname,$udomain);
 2006: 
 2007:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2008:    my @pairs=split(/\&/,$rep);
 2009:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2010:      return @pairs;
 2011:    }
 2012:    my %returnhash=();
 2013:    my $i=0;
 2014:    foreach (@$storearr) {
 2015:       $returnhash{$_}=unescape($pairs[$i]);
 2016:       $i++;
 2017:    }
 2018:    return %returnhash;
 2019: }
 2020: 
 2021: # --------------------------------------------------------------- del interface
 2022: 
 2023: sub del {
 2024:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2025:    my $items='';
 2026:    foreach (@$storearr) {
 2027:        $items.=escape($_).'&';
 2028:    }
 2029:    $items=~s/\&$//;
 2030:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2031:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2032:    my $uhome=&homeserver($uname,$udomain);
 2033: 
 2034:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2035: }
 2036: 
 2037: # -------------------------------------------------------------- dump interface
 2038: 
 2039: sub dump {
 2040:    my ($namespace,$udomain,$uname,$regexp)=@_;
 2041:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2042:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2043:    my $uhome=&homeserver($uname,$udomain);
 2044:    if ($regexp) {
 2045:        $regexp=&escape($regexp);
 2046:    } else {
 2047:        $regexp='.';
 2048:    }
 2049:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
 2050:    my @pairs=split(/\&/,$rep);
 2051:    my %returnhash=();
 2052:    foreach (@pairs) {
 2053:       my ($key,$value)=split(/=/,$_);
 2054:       $returnhash{unescape($key)}=unescape($value);
 2055:    }
 2056:    return %returnhash;
 2057: }
 2058: 
 2059: # --------------------------------------------------------------- currentdump
 2060: sub currentdump {
 2061:    my ($courseid,$sdom,$sname)=@_;
 2062:    $courseid = $ENV{'request.course.id'} if (! defined($courseid));
 2063:    $sdom     = $ENV{'user.domain'}       if (! defined($sdom));
 2064:    $sname    = $ENV{'user.name'}         if (! defined($sname));
 2065:    my $uhome = &homeserver($sname,$sdom);
 2066:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2067:    return if ($rep =~ /^(error:|no_such_host)/);
 2068:    #
 2069:    my %returnhash=();
 2070:    #
 2071:    if ($rep eq "unknown_cmd") { 
 2072:        # an old lond will not know currentdump
 2073:        # Do a dump and make it look like a currentdump
 2074:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 2075:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 2076:        my %hash = @tmp;
 2077:        @tmp=();
 2078:        # Code ripped from lond, essentially.  The only difference
 2079:        # here is the unescaping done by lonnet::dump().  Conceivably
 2080:        # we might run in to problems with parameter names =~ /^v\./
 2081:        while (my ($key,$value) = each(%hash)) {
 2082:            my ($v,$symb,$param) = split(/:/,$key);
 2083:            next if ($v eq 'version' || $symb eq 'keys');
 2084:            next if (exists($returnhash{$symb}) &&
 2085:                     exists($returnhash{$symb}->{$param}) &&
 2086:                     $returnhash{$symb}->{'v.'.$param} > $v);
 2087:            $returnhash{$symb}->{$param}=$value;
 2088:            $returnhash{$symb}->{'v.'.$param}=$v;
 2089:        }
 2090:        #
 2091:        # Remove all of the keys in the hashes which keep track of
 2092:        # the version of the parameter.
 2093:        while (my ($symb,$param_hash) = each(%returnhash)) {
 2094:            # use a foreach because we are going to delete from the hash.
 2095:            foreach my $key (keys(%$param_hash)) {
 2096:                delete($param_hash->{$key}) if ($key =~ /^v\./);
 2097:            }
 2098:        }
 2099:    } else {
 2100:        my @pairs=split(/\&/,$rep);
 2101:        foreach (@pairs) {
 2102:            my ($key,$value)=split(/=/,$_);
 2103:            my ($symb,$param) = split(/:/,$key);
 2104:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 2105:                                                           &unescape($value);
 2106:        }
 2107:    }
 2108:    return %returnhash;
 2109: }
 2110: 
 2111: # --------------------------------------------------------------- put interface
 2112: 
 2113: sub put {
 2114:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2115:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2116:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2117:    my $uhome=&homeserver($uname,$udomain);
 2118:    my $items='';
 2119:    foreach (keys %$storehash) {
 2120:        $items.=&escape($_).'='.&escape($$storehash{$_}).'&';
 2121:    }
 2122:    $items=~s/\&$//;
 2123:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 2124: }
 2125: 
 2126: # ------------------------------------------------------ critical put interface
 2127: 
 2128: sub cput {
 2129:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2130:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2131:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2132:    my $uhome=&homeserver($uname,$udomain);
 2133:    my $items='';
 2134:    foreach (keys %$storehash) {
 2135:        $items.=escape($_).'='.escape($$storehash{$_}).'&';
 2136:    }
 2137:    $items=~s/\&$//;
 2138:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 2139: }
 2140: 
 2141: # -------------------------------------------------------------- eget interface
 2142: 
 2143: sub eget {
 2144:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2145:    my $items='';
 2146:    foreach (@$storearr) {
 2147:        $items.=escape($_).'&';
 2148:    }
 2149:    $items=~s/\&$//;
 2150:    if (!$udomain) { $udomain=$ENV{'user.domain'}; }
 2151:    if (!$uname) { $uname=$ENV{'user.name'}; }
 2152:    my $uhome=&homeserver($uname,$udomain);
 2153:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 2154:    my @pairs=split(/\&/,$rep);
 2155:    my %returnhash=();
 2156:    my $i=0;
 2157:    foreach (@$storearr) {
 2158:       $returnhash{$_}=unescape($pairs[$i]);
 2159:       $i++;
 2160:    }
 2161:    return %returnhash;
 2162: }
 2163: 
 2164: # ---------------------------------------------- Custom access rule evaluation
 2165: 
 2166: sub customaccess {
 2167:     my ($priv,$uri)=@_;
 2168:     my ($urole,$urealm)=split(/\./,$ENV{'request.role'});
 2169:     $urealm=~s/^\W//;
 2170:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 2171:     my $access=0;
 2172:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 2173: 	my ($effect,$realm,$role)=split(/\:/,$_);
 2174:         if ($role) {
 2175: 	   if ($role ne $urole) { next; }
 2176:         }
 2177:         foreach (split(/\s*\,\s*/,$realm)) {
 2178:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 2179:             if ($tdom) {
 2180: 		if ($tdom ne $udom) { next; }
 2181:             }
 2182:             if ($tcrs) {
 2183: 		if ($tcrs ne $ucrs) { next; }
 2184:             }
 2185:             if ($tsec) {
 2186: 		if ($tsec ne $usec) { next; }
 2187:             }
 2188:             $access=($effect eq 'allow');
 2189:             last;
 2190:         }
 2191:     }
 2192:     return $access;
 2193: }
 2194: 
 2195: # ------------------------------------------------- Check for a user privilege
 2196: 
 2197: sub allowed {
 2198:     my ($priv,$uri)=@_;
 2199: 
 2200:     my $orguri=$uri;
 2201:     $uri=&declutter($uri);
 2202: 
 2203: # Free bre access to adm and meta resources
 2204: 
 2205:     if ((($uri=~/^adm\//) || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 2206: 	return 'F';
 2207:     }
 2208: 
 2209: # Free bre to public access
 2210: 
 2211:     if ($priv eq 'bre') {
 2212:         my $copyright=&metadata($uri,'copyright');
 2213: 	if (($copyright eq 'public') && (!$ENV{'request.course.id'})) { 
 2214:            return 'F'; 
 2215:         }
 2216:         if ($copyright eq 'priv') {
 2217:             $uri=~/([^\/]+)\/([^\/]+)\//;
 2218: 	    unless (($ENV{'user.name'} eq $2) && ($ENV{'user.domain'} eq $1)) {
 2219: 		return '';
 2220:             }
 2221:         }
 2222:         if ($copyright eq 'domain') {
 2223:             $uri=~/([^\/]+)\/([^\/]+)\//;
 2224: 	    unless (($ENV{'user.domain'} eq $1) ||
 2225:                  ($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $1)) {
 2226: 		return '';
 2227:             }
 2228:         }
 2229:         if ($ENV{'request.role'}=~ /li\.\//) {
 2230:             # Library role, so allow browsing of resources in this domain.
 2231:             return 'F';
 2232:         }
 2233:         if ($copyright eq 'custom') {
 2234: 	    unless (&customaccess($priv,$uri)) { return ''; }
 2235:         }
 2236:     }
 2237:     # Domain coordinator is trying to create a course
 2238:     if (($priv eq 'ccc') && ($ENV{'request.role'} =~ /^dc\./)) {
 2239:         # uri is the requested domain in this case.
 2240:         # comparison to 'request.role.domain' shows if the user has selected
 2241:         # a role of dc for the domain in question. 
 2242:         return 'F' if ($uri eq $ENV{'request.role.domain'});
 2243:     }
 2244: 
 2245:     my $thisallowed='';
 2246:     my $statecond=0;
 2247:     my $courseprivid='';
 2248: 
 2249: # Course
 2250: 
 2251:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'}=~/$priv\&([^\:]*)/) {
 2252:        $thisallowed.=$1;
 2253:     }
 2254: 
 2255: # Domain
 2256: 
 2257:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 2258:        =~/$priv\&([^\:]*)/) {
 2259:        $thisallowed.=$1;
 2260:     }
 2261: 
 2262: # Course: uri itself is a course
 2263:     my $courseuri=$uri;
 2264:     $courseuri=~s/\_(\d)/\/$1/;
 2265:     $courseuri=~s/^([^\/])/\/$1/;
 2266: 
 2267:     if ($ENV{'user.priv.'.$ENV{'request.role'}.'.'.$courseuri}
 2268:        =~/$priv\&([^\:]*)/) {
 2269:        $thisallowed.=$1;
 2270:     }
 2271: 
 2272: # URI is an uploaded document for this course
 2273: 
 2274:     if (($priv eq 'bre') && 
 2275:         ($uri=~/^uploaded\/$ENV{'course.'.$ENV{'request.course.id'}.'.domain'}\/$ENV{'course.'.$ENV{'request.course.id'}.'.num'}/)) {
 2276:         return 'F';
 2277:     }
 2278: # Full access at system, domain or course-wide level? Exit.
 2279: 
 2280:     if ($thisallowed=~/F/) {
 2281: 	return 'F';
 2282:     }
 2283: 
 2284: # If this is generating or modifying users, exit with special codes
 2285: 
 2286:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:'=~/\:$priv\:/) {
 2287: 	return $thisallowed;
 2288:     }
 2289: #
 2290: # Gathered so far: system, domain and course wide privileges
 2291: #
 2292: # Course: See if uri or referer is an individual resource that is part of 
 2293: # the course
 2294: 
 2295:     if ($ENV{'request.course.id'}) {
 2296: 
 2297:        $courseprivid=$ENV{'request.course.id'};
 2298:        if ($ENV{'request.course.sec'}) {
 2299:           $courseprivid.='/'.$ENV{'request.course.sec'};
 2300:        }
 2301:        $courseprivid=~s/\_/\//;
 2302:        my $checkreferer=1;
 2303:        my ($match,$cond)=&is_on_map($uri);
 2304:        if ($match) {
 2305:            $statecond=$cond;
 2306:            if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 2307:                =~/$priv\&([^\:]*)/) {
 2308:                $thisallowed.=$1;
 2309:                $checkreferer=0;
 2310:            }
 2311:        }
 2312:        
 2313:        if ($checkreferer) {
 2314: 	  my $refuri=$ENV{'httpref.'.$orguri};
 2315:             unless ($refuri) {
 2316:                 foreach (keys %ENV) {
 2317: 		    if ($_=~/^httpref\..*\*/) {
 2318: 			my $pattern=$_;
 2319:                         $pattern=~s/^httpref\.\/res\///;
 2320:                         $pattern=~s/\*/\[\^\/\]\+/g;
 2321:                         $pattern=~s/\//\\\//g;
 2322:                         if ($orguri=~/$pattern/) {
 2323: 			    $refuri=$ENV{$_};
 2324:                         }
 2325:                     }
 2326:                 }
 2327:             }
 2328: 
 2329:          if ($refuri) { 
 2330: 	  $refuri=&declutter($refuri);
 2331:           my ($match,$cond)=&is_on_map($refuri);
 2332:             if ($match) {
 2333:               my $refstatecond=$cond;
 2334:               if ($ENV{'user.priv.'.$ENV{'request.role'}.'./'.$courseprivid}
 2335:                   =~/$priv\&([^\:]*)/) {
 2336:                   $thisallowed.=$1;
 2337:                   $uri=$refuri;
 2338:                   $statecond=$refstatecond;
 2339:               }
 2340:           }
 2341:         }
 2342:        }
 2343:    }
 2344: 
 2345: #
 2346: # Gathered now: all privileges that could apply, and condition number
 2347: # 
 2348: #
 2349: # Full or no access?
 2350: #
 2351: 
 2352:     if ($thisallowed=~/F/) {
 2353: 	return 'F';
 2354:     }
 2355: 
 2356:     unless ($thisallowed) {
 2357:         return '';
 2358:     }
 2359: 
 2360: # Restrictions exist, deal with them
 2361: #
 2362: #   C:according to course preferences
 2363: #   R:according to resource settings
 2364: #   L:unless locked
 2365: #   X:according to user session state
 2366: #
 2367: 
 2368: # Possibly locked functionality, check all courses
 2369: # Locks might take effect only after 10 minutes cache expiration for other
 2370: # courses, and 2 minutes for current course
 2371: 
 2372:     my $envkey;
 2373:     if ($thisallowed=~/L/) {
 2374:         foreach $envkey (keys %ENV) {
 2375:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 2376:                my $courseid=$2;
 2377:                my $roleid=$1.'.'.$2;
 2378:                $courseid=~s/^\///;
 2379:                my $expiretime=600;
 2380:                if ($ENV{'request.role'} eq $roleid) {
 2381: 		  $expiretime=120;
 2382:                }
 2383: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 2384:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 2385:                if ((time-$ENV{$prefix.'last_cache'})>$expiretime) {
 2386: 		   &coursedescription($courseid);
 2387:                }
 2388:                if (($ENV{$prefix.'res.'.$uri.'.lock.sections'}=~/\,$csec\,/)
 2389:                 || ($ENV{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 2390: 		   if ($ENV{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 2391:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 2392:                             $ENV{'user.home'},
 2393:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 2394:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 2395:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 2396: 		       return '';
 2397:                    }
 2398:                }
 2399:                if (($ENV{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,$csec\,/)
 2400:                 || ($ENV{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 2401: 		   if ($ENV{'priv.'.$priv.'.lock.expire'}>time) {
 2402:                        &log($ENV{'user.domain'},$ENV{'user.name'},
 2403:                             $ENV{'user.home'},
 2404:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 2405:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 2406:                             $ENV{$prefix.'priv.'.$priv.'.lock.expire'});
 2407: 		       return '';
 2408:                    }
 2409:                }
 2410: 	   }
 2411:        }
 2412:     }
 2413:    
 2414: #
 2415: # Rest of the restrictions depend on selected course
 2416: #
 2417: 
 2418:     unless ($ENV{'request.course.id'}) {
 2419:        return '1';
 2420:     }
 2421: 
 2422: #
 2423: # Now user is definitely in a course
 2424: #
 2425: 
 2426: 
 2427: # Course preferences
 2428: 
 2429:    if ($thisallowed=~/C/) {
 2430:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 2431:        my $unamedom=$ENV{'user.name'}.':'.$ENV{'user.domain'};
 2432:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.roles.denied'}
 2433: 	   =~/$rolecode/) {
 2434:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 2435:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 2436:                 $ENV{'request.course.id'});
 2437:            return '';
 2438:        }
 2439: 
 2440:        if ($ENV{'course.'.$ENV{'request.course.id'}.'.'.$priv.'.users.denied'}
 2441: 	   =~/$unamedom/) {
 2442:            &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 2443:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 2444:                 $ENV{'request.course.id'});
 2445:            return '';
 2446:        }
 2447:    }
 2448: 
 2449: # Resource preferences
 2450: 
 2451:    if ($thisallowed=~/R/) {
 2452:        my $rolecode=(split(/\./,$ENV{'request.role'}))[0];
 2453:        if (&metadata($uri,'roledeny')=~/$rolecode/) {
 2454: 	  &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.host'},
 2455:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 2456:           return '';
 2457:        }
 2458:    }
 2459: 
 2460: # Restricted by state or randomout?
 2461: 
 2462:    if ($thisallowed=~/X/) {
 2463:       if ($ENV{'acc.randomout'}) {
 2464:          my $symb=&symbread($uri,1);
 2465:          if (($symb) && ($ENV{'acc.randomout'}=~/\&$symb\&/)) { 
 2466:             return ''; 
 2467:          }
 2468:       }
 2469:       if (&condval($statecond)) {
 2470: 	 return '2';
 2471:       } else {
 2472:          return '';
 2473:       }
 2474:    }
 2475: 
 2476:    return 'F';
 2477: }
 2478: 
 2479: # --------------------------------------------------- Is a resource on the map?
 2480: 
 2481: sub is_on_map {
 2482:     my $uri=&declutter(shift);
 2483:     my @uriparts=split(/\//,$uri);
 2484:     my $filename=$uriparts[$#uriparts];
 2485:     my $pathname=$uri;
 2486:     $pathname=~s|/\Q$filename\E$||;
 2487:     $pathname=~s/^adm\/wrapper\///;    
 2488:     #Trying to find the conditional for the file
 2489:     my $match=($ENV{'acc.res.'.$ENV{'request.course.id'}.'.'.$pathname}=~
 2490: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 2491:     if ($match) {
 2492: 	return (1,$1);
 2493:     } else {
 2494: 	return (0,0);
 2495:     }
 2496: }
 2497: 
 2498: # ----------------------------------------------------------------- Define Role
 2499: 
 2500: sub definerole {
 2501:   if (allowed('mcr','/')) {
 2502:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 2503:     foreach (split('/',$sysrole)) {
 2504: 	my ($crole,$cqual)=split(/\&/,$_);
 2505:         if ($pr{'cr:s'}!~/$crole/) { return "refused:s:$crole"; }
 2506:         if ($pr{'cr:s'}=~/$crole\&/) {
 2507: 	    if ($pr{'cr:s'}!~/$crole\&\w*$cqual/) { 
 2508:                return "refused:s:$crole&$cqual"; 
 2509:             }
 2510:         }
 2511:     }
 2512:     foreach (split('/',$domrole)) {
 2513: 	my ($crole,$cqual)=split(/\&/,$_);
 2514:         if ($pr{'cr:d'}!~/$crole/) { return "refused:d:$crole"; }
 2515:         if ($pr{'cr:d'}=~/$crole\&/) {
 2516: 	    if ($pr{'cr:d'}!~/$crole\&\w*$cqual/) { 
 2517:                return "refused:d:$crole&$cqual"; 
 2518:             }
 2519:         }
 2520:     }
 2521:     foreach (split('/',$courole)) {
 2522: 	my ($crole,$cqual)=split(/\&/,$_);
 2523:         if ($pr{'cr:c'}!~/$crole/) { return "refused:c:$crole"; }
 2524:         if ($pr{'cr:c'}=~/$crole\&/) {
 2525: 	    if ($pr{'cr:c'}!~/$crole\&\w*$cqual/) { 
 2526:                return "refused:c:$crole&$cqual"; 
 2527:             }
 2528:         }
 2529:     }
 2530:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 2531:                 "$ENV{'user.domain'}:$ENV{'user.name'}:".
 2532: 	        "rolesdef_$rolename=".
 2533:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 2534:     return reply($command,$ENV{'user.home'});
 2535:   } else {
 2536:     return 'refused';
 2537:   }
 2538: }
 2539: 
 2540: # ---------------- Make a metadata query against the network of library servers
 2541: 
 2542: sub metadata_query {
 2543:     my ($query,$custom,$customshow,$server_array)=@_;
 2544:     my %rhash;
 2545:     my @server_list = (defined($server_array) ? @$server_array
 2546:                                               : keys(%libserv) );
 2547:     for my $server (@server_list) {
 2548: 	unless ($custom or $customshow) {
 2549: 	    my $reply=&reply("querysend:".&escape($query),$server);
 2550: 	    $rhash{$server}=$reply;
 2551: 	}
 2552: 	else {
 2553: 	    my $reply=&reply("querysend:".&escape($query).':'.
 2554: 			     &escape($custom).':'.&escape($customshow),
 2555: 			     $server);
 2556: 	    $rhash{$server}=$reply;
 2557: 	}
 2558:     }
 2559:     return \%rhash;
 2560: }
 2561: 
 2562: # ----------------------------------------- Send log queries and wait for reply
 2563: 
 2564: sub log_query {
 2565:     my ($uname,$udom,$query,%filters)=@_;
 2566:     my $uhome=&homeserver($uname,$udom);
 2567:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 2568:     my $uhost=$hostname{$uhome};
 2569:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 2570:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 2571:                        $uhome);
 2572:     unless ($queryid=~/^$uhost\_/) { return 'error: '.$queryid; }
 2573:     return get_query_reply($queryid);
 2574: }
 2575: 
 2576: sub get_query_reply {
 2577:     my $queryid=shift;
 2578:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 2579:     my $reply='';
 2580:     for (1..100) {
 2581: 	sleep 2;
 2582:         if (-e $replyfile.'.end') {
 2583: 	    if (my $fh=Apache::File->new($replyfile)) {
 2584:                $reply.=<$fh>;
 2585:                $fh->close;
 2586: 	   } else { return 'error: reply_file_error'; }
 2587:            return &unescape($reply);
 2588: 	}
 2589:     }
 2590:     return 'timeout:'.$queryid;
 2591: }
 2592: 
 2593: sub courselog_query {
 2594: #
 2595: # possible filters:
 2596: # url: url or symb
 2597: # username
 2598: # domain
 2599: # action: view, submit, grade
 2600: # start: timestamp
 2601: # end: timestamp
 2602: #
 2603:     my (%filters)=@_;
 2604:     unless ($ENV{'request.course.id'}) { return 'no_course'; }
 2605:     if ($filters{'url'}) {
 2606: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 2607:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 2608:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 2609:     }
 2610:     my $cname=$ENV{'course.'.$ENV{'request.course.id'}.'.num'};
 2611:     my $cdom=$ENV{'course.'.$ENV{'request.course.id'}.'.domain'};
 2612:     return &log_query($cname,$cdom,'courselog',%filters);
 2613: }
 2614: 
 2615: sub userlog_query {
 2616:     my ($uname,$udom,%filters)=@_;
 2617:     return &log_query($uname,$udom,'userlog',%filters);
 2618: }
 2619: 
 2620: # ------------------------------------------------------------------ Plain Text
 2621: 
 2622: sub plaintext {
 2623:     my $short=shift;
 2624:     return $prp{$short};
 2625: }
 2626: 
 2627: # ----------------------------------------------------------------- Assign Role
 2628: 
 2629: sub assignrole {
 2630:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 2631:     my $mrole;
 2632:     if ($role =~ /^cr\//) {
 2633: 	unless (&allowed('ccr',$url)) {
 2634:            &logthis('Refused custom assignrole: '.
 2635:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 2636: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2637:            return 'refused'; 
 2638:         }
 2639:         $mrole='cr';
 2640:     } else {
 2641:         my $cwosec=$url;
 2642:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 2643:         unless (&allowed('c'.$role,$cwosec)) { 
 2644:            &logthis('Refused assignrole: '.
 2645:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 2646: 		    $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2647:            return 'refused'; 
 2648:         }
 2649:         $mrole=$role;
 2650:     }
 2651:     my $command="encrypt:rolesput:$ENV{'user.domain'}:$ENV{'user.name'}:".
 2652:                 "$udom:$uname:$url".'_'."$mrole=$role";
 2653:     if ($end) { $command.='_'.$end; }
 2654:     if ($start) {
 2655: 	if ($end) { 
 2656:            $command.='_'.$start; 
 2657:         } else {
 2658:            $command.='_0_'.$start;
 2659:         }
 2660:     }
 2661: # actually delete
 2662:     if ($deleteflag) {
 2663: 	if (&allowed('dro',$udom)) {
 2664: # modify command to delete the role
 2665:            $command="encrypt:rolesdel:$ENV{'user.domain'}:$ENV{'user.name'}:".
 2666:                 "$udom:$uname:$url".'_'."$mrole";
 2667: # set start and finish to negative values for userrolelog
 2668:            $start=-1;
 2669:            $end=-1;
 2670:         }
 2671:     }
 2672: # send command
 2673:     my $answer=&reply($command,&homeserver($uname,$udom));
 2674: # log new user role if status is ok
 2675:     if ($answer eq 'ok') {
 2676: 	&userrolelog($mrole,$uname,$udom,$url,$start,$end);
 2677:     }
 2678:     return $answer;
 2679: }
 2680: 
 2681: # -------------------------------------------------- Modify user authentication
 2682: # Overrides without validation
 2683: 
 2684: sub modifyuserauth {
 2685:     my ($udom,$uname,$umode,$upass)=@_;
 2686:     my $uhome=&homeserver($uname,$udom);
 2687:     unless (&allowed('mau',$udom)) { return 'refused'; }
 2688:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 2689:              $umode.' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 2690:              ' in domain '.$ENV{'request.role.domain'});  
 2691:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 2692: 		     &escape($upass),$uhome);
 2693:     &log($ENV{'user.domain'},$ENV{'user.name'},$ENV{'user.home'},
 2694:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 2695:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 2696:     &log($udom,,$uname,$uhome,
 2697:         'Authentication changed by '.$ENV{'user.domain'}.', '.
 2698:                                      $ENV{'user.name'}.', '.$umode.
 2699:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 2700:     unless ($reply eq 'ok') {
 2701:         &logthis('Authentication mode error: '.$reply);
 2702: 	return 'error: '.$reply;
 2703:     }   
 2704:     return 'ok';
 2705: }
 2706: 
 2707: # --------------------------------------------------------------- Modify a user
 2708: 
 2709: sub modifyuser {
 2710:     my ($udom,    $uname, $uid,
 2711:         $umode,   $upass, $first,
 2712:         $middle,  $last,  $gene,
 2713:         $forceid, $desiredhome)=@_;
 2714:     $udom=~s/\W//g;
 2715:     $uname=~s/\W//g;
 2716:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 2717:              $umode.', '.$first.', '.$middle.', '.
 2718: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 2719:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 2720:                                      ' desiredhome not specified'). 
 2721:              ' by '.$ENV{'user.name'}.' at '.$ENV{'user.domain'}.
 2722:              ' in domain '.$ENV{'request.role.domain'});
 2723:     my $uhome=&homeserver($uname,$udom,'true');
 2724: # ----------------------------------------------------------------- Create User
 2725:     if (($uhome eq 'no_host') && ($umode) && ($upass)) {
 2726:         my $unhome='';
 2727:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 2728:             $unhome = $desiredhome;
 2729: 	} elsif($ENV{'course.'.$ENV{'request.course.id'}.'.domain'} eq $udom) {
 2730: 	    $unhome=$ENV{'course.'.$ENV{'request.course.id'}.'.home'};
 2731:         } else { # load balancing routine for determining $unhome
 2732:             my $tryserver;
 2733:             my $loadm=10000000;
 2734:             foreach $tryserver (keys %libserv) {
 2735: 	       if ($hostdom{$tryserver} eq $udom) {
 2736:                   my $answer=reply('load',$tryserver);
 2737:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 2738: 		      $loadm=$answer;
 2739:                       $unhome=$tryserver;
 2740:                   }
 2741: 	       }
 2742: 	    }
 2743:         }
 2744:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 2745: 	    return 'error: unable to find a home server for '.$uname.
 2746:                    ' in domain '.$udom;
 2747:         }
 2748:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 2749:                          &escape($upass),$unhome);
 2750: 	unless ($reply eq 'ok') {
 2751:             return 'error: '.$reply;
 2752:         }   
 2753:         $uhome=&homeserver($uname,$udom,'true');
 2754:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 2755: 	    return 'error: verify home';
 2756:         }
 2757:     }   # End of creation of new user
 2758: # ---------------------------------------------------------------------- Add ID
 2759:     if ($uid) {
 2760:        $uid=~tr/A-Z/a-z/;
 2761:        my %uidhash=&idrget($udom,$uname);
 2762:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 2763:          && (!$forceid)) {
 2764: 	  unless ($uid eq $uidhash{$uname}) {
 2765: 	      return 'error: mismatch '.$uidhash{$uname}.' versus '.$uid;
 2766:           }
 2767:        } else {
 2768: 	  &idput($udom,($uname => $uid));
 2769:        }
 2770:     }
 2771: # -------------------------------------------------------------- Add names, etc
 2772:     my @tmp=&get('environment',
 2773: 		   ['firstname','middlename','lastname','generation'],
 2774: 		   $udom,$uname);
 2775:     my %names;
 2776:     if ($tmp[0] =~ m/^error:.*/) { 
 2777:         %names=(); 
 2778:     } else {
 2779:         %names = @tmp;
 2780:     }
 2781:     if ($first)  { $names{'firstname'}  = $first; }
 2782:     if ($middle) { $names{'middlename'} = $middle; }
 2783:     if ($last)   { $names{'lastname'}   = $last; }
 2784:     if ($gene)   { $names{'generation'} = $gene; }
 2785:     my $reply = &put('environment', \%names, $udom,$uname);
 2786:     if ($reply ne 'ok') { return 'error: '.$reply; }
 2787:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 2788:              $umode.', '.$first.', '.$middle.', '.
 2789: 	     $last.', '.$gene.' by '.
 2790:              $ENV{'user.name'}.' at '.$ENV{'user.domain'});
 2791:     return 'ok';
 2792: }
 2793: 
 2794: # -------------------------------------------------------------- Modify student
 2795: 
 2796: sub modifystudent {
 2797:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 2798:         $end,$start,$forceid,$desiredhome)=@_;
 2799:     my $cid='';
 2800:     unless ($cid=$ENV{'request.course.id'}) {
 2801: 	return 'not_in_class';
 2802:     }
 2803: # --------------------------------------------------------------- Make the user
 2804:     my $reply=&modifyuser
 2805: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 2806:          $desiredhome);
 2807:     unless ($reply eq 'ok') { return $reply; }
 2808:     # This will cause &modify_student_enrollment to get the uid from the
 2809:     # students environment
 2810:     $uid = undef if (!$forceid);
 2811:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,
 2812:                                         $last,$gene,$usec,$end,$start);
 2813:     return $reply;
 2814: }
 2815: 
 2816: sub modify_student_enrollment {
 2817:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start) = @_;
 2818:     # Get the course id from the environment
 2819:     my $cid='';
 2820:     unless ($cid=$ENV{'request.course.id'}) {
 2821: 	return 'not_in_class';
 2822:     }
 2823:     # Make sure the user exists
 2824:     my $uhome=&homeserver($uname,$udom);
 2825:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 2826: 	return 'error: no such user';
 2827:     }
 2828:     #
 2829:     # Get student data if we were not given enough information
 2830:     if (!defined($first)  || $first  eq '' || 
 2831:         !defined($last)   || $last   eq '' || 
 2832:         !defined($uid)    || $uid    eq '' || 
 2833:         !defined($middle) || $middle eq '' || 
 2834:         !defined($gene)   || $gene   eq '') {
 2835:         # They did not supply us with enough data to enroll the student, so
 2836:         # we need to pick up more information.
 2837:         my %tmp = &get('environment',
 2838:                        ['firstname','middlename','lastname', 'generation','id']
 2839:                        ,$udom,$uname);
 2840: 
 2841:         foreach (keys(%tmp)) {
 2842:             &logthis("key $_ = ".$tmp{$_});
 2843:         }
 2844:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 2845:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 2846:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 2847:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 2848:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 2849:     }
 2850:     my $fullname = &Apache::loncoursedata::ProcessFullName($last,$gene,
 2851:                                                            $first,$middle);
 2852:     my $reply=critical('put:'.$ENV{'course.'.$cid.'.domain'}.':'.
 2853: 	              $ENV{'course.'.$cid.'.num'}.':classlist:'.
 2854:                       &escape($uname.':'.$udom).'='.
 2855:                       &escape(join(':',$end,$start,$uid,$usec,$fullname)),
 2856: 	              $ENV{'course.'.$cid.'.home'});
 2857:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 2858: 	return 'error: '.$reply;
 2859:     }
 2860:     # Add student role to user
 2861:     my $uurl='/'.$cid;
 2862:     $uurl=~s/\_/\//g;
 2863:     if ($usec) {
 2864: 	$uurl.='/'.$usec;
 2865:     }
 2866:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 2867: }
 2868: 
 2869: # ------------------------------------------------- Write to course preferences
 2870: 
 2871: sub writecoursepref {
 2872:     my ($courseid,%prefs)=@_;
 2873:     $courseid=~s/^\///;
 2874:     $courseid=~s/\_/\//g;
 2875:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2876:     my $chome=homeserver($cnum,$cdomain);
 2877:     if (($chome eq '') || ($chome eq 'no_host')) { 
 2878: 	return 'error: no such course';
 2879:     }
 2880:     my $cstring='';
 2881:     foreach (keys %prefs) {
 2882: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 2883:     }
 2884:     $cstring=~s/\&$//;
 2885:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 2886: }
 2887: 
 2888: # ---------------------------------------------------------- Make/modify course
 2889: 
 2890: sub createcourse {
 2891:     my ($udom,$description,$url,$course_server,$nonstandard)=@_;
 2892:     $url=&declutter($url);
 2893:     my $cid='';
 2894:     unless (&allowed('ccc',$udom)) {
 2895:         return 'refused';
 2896:     }
 2897: # ------------------------------------------------------------------- Create ID
 2898:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 2899:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 2900: # ----------------------------------------------- Make sure that does not exist
 2901:    my $uhome=&homeserver($uname,$udom,'true');
 2902:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 2903:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 2904:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 2905:        $uhome=&homeserver($uname,$udom,'true');       
 2906:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 2907:            return 'error: unable to generate unique course-ID';
 2908:        } 
 2909:    }
 2910: # ------------------------------------------------ Check supplied server name
 2911:     $course_server = $ENV{'user.homeserver'} if (! defined($course_server));
 2912:     if (! exists($libserv{$course_server})) {
 2913:         return 'error:bad server name '.$course_server;
 2914:     }
 2915: # ------------------------------------------------------------- Make the course
 2916:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 2917:                       $course_server);
 2918:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 2919:     $uhome=&homeserver($uname,$udom,'true');
 2920:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 2921: 	return 'error: no such course';
 2922:     }
 2923: # ----------------------------------------------------------------- Course made
 2924: # log existance
 2925:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description),
 2926:                  $uhome);
 2927:     &flushcourselogs();
 2928: # set toplevel url
 2929:     my $topurl=$url;
 2930:     unless ($nonstandard) {
 2931: # ------------------------------------------ For standard courses, make top url
 2932:         my $mapurl=&clutter($url);
 2933:         if ($mapurl eq '/res/') { $mapurl=''; }
 2934:         $ENV{'form.initmap'}=(<<ENDINITMAP);
 2935: <map>
 2936: <resource id="1" type="start"></resource>
 2937: <resource id="2" src="$mapurl"></resource>
 2938: <resource id="3" type="finish"></resource>
 2939: <link index="1" from="1" to="2"></link>
 2940: <link index="2" from="2" to="3"></link>
 2941: </map>
 2942: ENDINITMAP
 2943:         $topurl=&declutter(
 2944:         &finishuserfileupload($uname,$udom,$uhome,'initmap','default.sequence')
 2945:                           );
 2946:     }
 2947: # ----------------------------------------------------------- Write preferences
 2948:     &writecoursepref($udom.'_'.$uname,
 2949:                      ('description' => $description,
 2950:                       'url'         => $topurl));
 2951:     return '/'.$udom.'/'.$uname;
 2952: }
 2953: 
 2954: # ---------------------------------------------------------- Assign Custom Role
 2955: 
 2956: sub assigncustomrole {
 2957:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 2958:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 2959:                        $end,$start,$deleteflag);
 2960: }
 2961: 
 2962: # ----------------------------------------------------------------- Revoke Role
 2963: 
 2964: sub revokerole {
 2965:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 2966:     my $now=time;
 2967:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 2968: }
 2969: 
 2970: # ---------------------------------------------------------- Revoke Custom Role
 2971: 
 2972: sub revokecustomrole {
 2973:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 2974:     my $now=time;
 2975:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 2976:            $deleteflag);
 2977: }
 2978: 
 2979: # ------------------------------------------------------------ Directory lister
 2980: 
 2981: sub dirlist {
 2982:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 2983: 
 2984:     $uri=~s/^\///;
 2985:     $uri=~s/\/$//;
 2986:     my ($udom, $uname);
 2987:     (undef,$udom,$uname)=split(/\//,$uri);
 2988:     if(defined($userdomain)) {
 2989:         $udom = $userdomain;
 2990:     }
 2991:     if(defined($username)) {
 2992:         $uname = $username;
 2993:     }
 2994: 
 2995:     my $dirRoot = $perlvar{'lonDocRoot'};
 2996:     if(defined($alternateDirectoryRoot)) {
 2997:         $dirRoot = $alternateDirectoryRoot;
 2998:         $dirRoot =~ s/\/$//;
 2999:     }
 3000: 
 3001:     if($udom) {
 3002:         if($uname) {
 3003:             my $listing=reply('ls:'.$dirRoot.'/'.$uri,
 3004:                               homeserver($uname,$udom));
 3005:             return split(/:/,$listing);
 3006:         } elsif(!defined($alternateDirectoryRoot)) {
 3007:             my $tryserver;
 3008:             my %allusers=();
 3009:             foreach $tryserver (keys %libserv) {
 3010:                 if($hostdom{$tryserver} eq $udom) {
 3011:                     my $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 3012:                                       $udom, $tryserver);
 3013:                     if (($listing ne 'no_such_dir') && ($listing ne 'empty')
 3014:                         && ($listing ne 'con_lost')) {
 3015:                         foreach (split(/:/,$listing)) {
 3016:                             my ($entry,@stat)=split(/&/,$_);
 3017:                             $allusers{$entry}=1;
 3018:                         }
 3019:                     }
 3020:                 }
 3021:             }
 3022:             my $alluserstr='';
 3023:             foreach (sort keys %allusers) {
 3024:                 $alluserstr.=$_.'&user:';
 3025:             }
 3026:             $alluserstr=~s/:$//;
 3027:             return split(/:/,$alluserstr);
 3028:         } else {
 3029:             my @emptyResults = ();
 3030:             push(@emptyResults, 'missing user name');
 3031:             return split(':',@emptyResults);
 3032:         }
 3033:     } elsif(!defined($alternateDirectoryRoot)) {
 3034:         my $tryserver;
 3035:         my %alldom=();
 3036:         foreach $tryserver (keys %libserv) {
 3037:             $alldom{$hostdom{$tryserver}}=1;
 3038:         }
 3039:         my $alldomstr='';
 3040:         foreach (sort keys %alldom) {
 3041:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'&domain:';
 3042:         }
 3043:         $alldomstr=~s/:$//;
 3044:         return split(/:/,$alldomstr);       
 3045:     } else {
 3046:         my @emptyResults = ();
 3047:         push(@emptyResults, 'missing domain');
 3048:         return split(':',@emptyResults);
 3049:     }
 3050: }
 3051: 
 3052: # --------------------------------------------- GetFileTimestamp
 3053: # This function utilizes dirlist and returns the date stamp for
 3054: # when it was last modified.  It will also return an error of -1
 3055: # if an error occurs
 3056: 
 3057: sub GetFileTimestamp {
 3058:     my ($studentDomain,$studentName,$filename,$root)=@_;
 3059:     $studentDomain=~s/\W//g;
 3060:     $studentName=~s/\W//g;
 3061:     my $subdir=$studentName.'__';
 3062:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 3063:     my $proname="$studentDomain/$subdir/$studentName";
 3064:     $proname .= '/'.$filename;
 3065:     my @dir = &Apache::lonnet::dirlist($proname, $studentDomain, $studentName,
 3066:                                        $root);
 3067:     my $fileStat = $dir[0];
 3068:     my @stats = split('&', $fileStat);
 3069:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 3070:         return $stats[9];
 3071:     } else {
 3072:         return -1;
 3073:     }
 3074: }
 3075: 
 3076: # -------------------------------------------------------- Value of a Condition
 3077: 
 3078: sub directcondval {
 3079:     my $number=shift;
 3080:     if ($ENV{'user.state.'.$ENV{'request.course.id'}}) {
 3081:        return substr($ENV{'user.state.'.$ENV{'request.course.id'}},$number,1);
 3082:     } else {
 3083:        return 2;
 3084:     }
 3085: }
 3086: 
 3087: sub condval {
 3088:     my $condidx=shift;
 3089:     my $result=0;
 3090:     my $allpathcond='';
 3091:     foreach (split(/\|/,$condidx)) {
 3092:        if (defined($ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_})) {
 3093: 	   $allpathcond.=
 3094:                '('.$ENV{'acc.cond.'.$ENV{'request.course.id'}.'.'.$_}.')|';
 3095:        }
 3096:     }
 3097:     $allpathcond=~s/\|$//;
 3098:     if ($ENV{'request.course.id'}) {
 3099:        if ($allpathcond) {
 3100:           my $operand='|';
 3101: 	  my @stack;
 3102:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
 3103:               if ($_ eq '(') {
 3104:                  push @stack,($operand,$result)
 3105:               } elsif ($_ eq ')') {
 3106:                   my $before=pop @stack;
 3107: 		  if (pop @stack eq '&') {
 3108: 		      $result=$result>$before?$before:$result;
 3109:                   } else {
 3110:                       $result=$result>$before?$result:$before;
 3111:                   }
 3112:               } elsif (($_ eq '&') || ($_ eq '|')) {
 3113:                   $operand=$_;
 3114:               } else {
 3115:                   my $new=directcondval($_);
 3116:                   if ($operand eq '&') {
 3117:                      $result=$result>$new?$new:$result;
 3118:                   } else {
 3119:                      $result=$result>$new?$result:$new;
 3120:                   }
 3121:               }
 3122:           }
 3123:        }
 3124:     }
 3125:     return $result;
 3126: }
 3127: 
 3128: # ---------------------------------------------------- Devalidate courseresdata
 3129: 
 3130: sub devalidatecourseresdata {
 3131:     my ($coursenum,$coursedomain)=@_;
 3132:     my $hashid=$coursenum.':'.$coursedomain;
 3133:     delete $courseresdatacache{$hashid.'.time'};
 3134: }
 3135: 
 3136: # --------------------------------------------------- Course Resourcedata Query
 3137: 
 3138: sub courseresdata {
 3139:     my ($coursenum,$coursedomain,@which)=@_;
 3140:     my $coursehom=&homeserver($coursenum,$coursedomain);
 3141:     my $hashid=$coursenum.':'.$coursedomain;
 3142:     my $dodump=0;
 3143:     if (!defined($courseresdatacache{$hashid.'.time'})) {
 3144: 	$dodump=1;
 3145:     } else {
 3146: 	if (time-$courseresdatacache{$hashid.'.time'}>300) { $dodump=1; }
 3147:     }
 3148:     if ($dodump) {
 3149: 	my %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 3150: 	my ($tmp) = keys(%dumpreply);
 3151: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 3152: 	    $courseresdatacache{$hashid.'.time'}=time;
 3153: 	    $courseresdatacache{$hashid}=\%dumpreply;
 3154: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 3155: 	    return $tmp;
 3156: 	}
 3157:     }
 3158:     foreach my $item (@which) {
 3159: 	if (defined($courseresdatacache{$hashid}->{$item})) {
 3160: 	    return $courseresdatacache{$hashid}->{$item};
 3161: 	}
 3162:     }
 3163:     return undef;
 3164: }
 3165: 
 3166: # --------------------------------------------------------- Value of a Variable
 3167: 
 3168: sub EXT {
 3169:     my ($varname,$symbparm,$udom,$uname,)=@_;
 3170: 
 3171:     unless ($varname) { return ''; }
 3172:     #get real user name/domain, courseid and symb
 3173:     my $courseid;
 3174:     my $publicuser;
 3175:     if (!($uname && $udom)) {
 3176:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 3177: 	  &Apache::lonxml::whichuser();
 3178:       if (!$symbparm) {	$symbparm=$cursymb; }
 3179:     } else {
 3180: 	$courseid=$ENV{'request.course.id'};
 3181:     }
 3182:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 3183:     my $rest;
 3184:     if (defined($therest[0])) {
 3185:        $rest=join('.',@therest);
 3186:     } else {
 3187:        $rest='';
 3188:     }
 3189: 
 3190:     my $qualifierrest=$qualifier;
 3191:     if ($rest) { $qualifierrest.='.'.$rest; }
 3192:     my $spacequalifierrest=$space;
 3193:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 3194:     if ($realm eq 'user') {
 3195: # --------------------------------------------------------------- user.resource
 3196: 	if ($space eq 'resource') {
 3197: 	    if (defined($Apache::lonhomework::parsing_a_problem)) {
 3198: 		return $Apache::lonhomework::history{$qualifierrest};
 3199: 	    } else {
 3200: 		my %restored;
 3201: 		if ($publicuser || $ENV{'request.state'} eq 'construct') {
 3202: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 3203: 		} else {
 3204: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 3205: 		}
 3206: 		return $restored{$qualifierrest};
 3207: 	    }
 3208: # ----------------------------------------------------------------- user.access
 3209:         } elsif ($space eq 'access') {
 3210: 	    # FIXME - not supporting calls for a specific user
 3211:             return &allowed($qualifier,$rest);
 3212: # ------------------------------------------ user.preferences, user.environment
 3213:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 3214: 	    if (($uname eq $ENV{'user.name'}) &&
 3215: 		($udom eq $ENV{'user.domain'})) {
 3216: 		return $ENV{join('.',('environment',$qualifierrest))};
 3217: 	    } else {
 3218: 		my %returnhash;
 3219: 		if (!$publicuser) {
 3220: 		    %returnhash=&userenvironment($udom,$uname,
 3221: 						 $qualifierrest);
 3222: 		}
 3223: 		return $returnhash{$qualifierrest};
 3224: 	    }
 3225: # ----------------------------------------------------------------- user.course
 3226:         } elsif ($space eq 'course') {
 3227: 	    # FIXME - not supporting calls for a specific user
 3228:             return $ENV{join('.',('request.course',$qualifier))};
 3229: # ------------------------------------------------------------------- user.role
 3230:         } elsif ($space eq 'role') {
 3231: 	    # FIXME - not supporting calls for a specific user
 3232:             my ($role,$where)=split(/\./,$ENV{'request.role'});
 3233:             if ($qualifier eq 'value') {
 3234: 		return $role;
 3235:             } elsif ($qualifier eq 'extent') {
 3236:                 return $where;
 3237:             }
 3238: # ----------------------------------------------------------------- user.domain
 3239:         } elsif ($space eq 'domain') {
 3240:             return $udom;
 3241: # ------------------------------------------------------------------- user.name
 3242:         } elsif ($space eq 'name') {
 3243:             return $uname;
 3244: # ---------------------------------------------------- Any other user namespace
 3245:         } else {
 3246: 	    my %reply;
 3247: 	    if (!$publicuser) {
 3248: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 3249: 	    }
 3250: 	    return $reply{$qualifierrest};
 3251:         }
 3252:     } elsif ($realm eq 'query') {
 3253: # ---------------------------------------------- pull stuff out of query string
 3254:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},[$space]);
 3255: 	return $ENV{'form.'.$space}; 
 3256:    } elsif ($realm eq 'request') {
 3257: # ------------------------------------------------------------- request.browser
 3258:         if ($space eq 'browser') {
 3259: 	    return $ENV{'browser.'.$qualifier};
 3260: # ------------------------------------------------------------ request.filename
 3261:         } else {
 3262:             return $ENV{'request.'.$spacequalifierrest};
 3263:         }
 3264:     } elsif ($realm eq 'course') {
 3265: # ---------------------------------------------------------- course.description
 3266:         return $ENV{'course.'.$courseid.'.'.$spacequalifierrest};
 3267:     } elsif ($realm eq 'resource') {
 3268: 
 3269: 	if (defined($courseid) && $courseid eq $ENV{'request.course.id'}) {
 3270: 
 3271: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 3272: 
 3273: # ----------------------------------------------------- Cascading lookup scheme
 3274: 	    if (!$symbparm) { $symbparm=&symbread(); }
 3275: 	    my $symbp=$symbparm;
 3276: 	    my $mapp=(split(/\_\_\_/,$symbp))[0];
 3277: 
 3278: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 3279: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 3280: 
 3281: 	    my $section;
 3282: 	    if (($ENV{'user.name'} eq $uname) &&
 3283: 		($ENV{'user.domain'} eq $udom)) {
 3284: 		$section=$ENV{'request.course.sec'};
 3285: 	    } else {
 3286: 		$section=&usection($udom,$uname,$courseid);
 3287: 	    }
 3288: 
 3289: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 3290: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 3291: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 3292: 
 3293: 	    my $courselevel=$courseid.'.'.$spacequalifierrest;
 3294: 	    my $courselevelr=$courseid.'.'.$symbparm;
 3295: 	    my $courselevelm=$courseid.'.'.$mapparm;
 3296: 
 3297: # ----------------------------------------------------------- first, check user
 3298: 	    #most student don't have any data set, check if there is some data
 3299:             #every thirty minutes
 3300: 	    if (!
 3301: 		(exists($ENV{'cache.studentresdata'})
 3302: 		    && (($ENV{'cache.studentresdata'}+1800) > time))) {
 3303: 		my %resourcedata=&get('resourcedata',
 3304: 				      [$courselevelr,$courselevelm,$courselevel],
 3305: 				      $udom,$uname);
 3306: 		my ($tmp)=keys(%resourcedata);
 3307: 		if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 3308: 		    if ($resourcedata{$courselevelr}) {
 3309: 			return $resourcedata{$courselevelr}; }
 3310: 		    if ($resourcedata{$courselevelm}) {
 3311: 			return $resourcedata{$courselevelm}; }
 3312: 		    if ($resourcedata{$courselevel}) {
 3313: 			return $resourcedata{$courselevel}; }
 3314: 		} else {
 3315: 		    if ($tmp!~/No such file/) {
 3316: 			&logthis("<font color=blue>WARNING:".
 3317: 				 " Trying to get resource data for ".
 3318: 				 $uname." at ".$udom.": ".
 3319: 				 $tmp."</font>");
 3320: 		    } elsif ($tmp=~/error:No such file/) {
 3321: 			$ENV{'cache.studentresdata'}=time;
 3322: 			&appenv(('cache.studentresdata'=>
 3323: 				 $ENV{'cache.studentresdata'}));
 3324: 		    } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 3325: 			return $tmp;
 3326: 		    }
 3327: 		}
 3328: 	    }
 3329: 
 3330: # -------------------------------------------------------- second, check course
 3331: 
 3332: 	    my $coursereply=&courseresdata($ENV{'course.'.$courseid.'.num'},
 3333: 					  $ENV{'course.'.$courseid.'.domain'},
 3334: 					  ($seclevelr,$seclevelm,$seclevel,
 3335: 					   $courselevelr,$courselevelm,
 3336: 					   $courselevel));
 3337: 	    if (defined($coursereply)) { return $coursereply; }
 3338: 
 3339: # ------------------------------------------------------ third, check map parms
 3340: 	    my %parmhash=();
 3341: 	    my $thisparm='';
 3342: 	    if (tie(%parmhash,'GDBM_File',
 3343: 		    $ENV{'request.course.fn'}.'_parms.db',
 3344: 		    &GDBM_READER(),0640)) {
 3345: 		$thisparm=$parmhash{$symbparm};
 3346: 		untie(%parmhash);
 3347: 	    }
 3348: 	    if ($thisparm) { return $thisparm; }
 3349: 	}
 3350: # --------------------------------------------- last, look in resource metadata
 3351: 
 3352: 	$spacequalifierrest=~s/\./\_/;
 3353: 	my $filename;
 3354: 	if (!$symbparm) { $symbparm=&symbread(); }
 3355: 	if ($symbparm) {
 3356: 	    $filename=(split(/\_\_\_/,$symbparm))[2];
 3357: 	} else {
 3358: 	    $filename=$ENV{'request.filename'};
 3359: 	}
 3360: 	my $metadata=&metadata($filename,$spacequalifierrest);
 3361: 	if (defined($metadata)) { return $metadata; }
 3362: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 3363: 	if (defined($metadata)) { return $metadata; }
 3364: 
 3365: # ------------------------------------------------------------------ Cascade up
 3366: 	unless ($space eq '0') {
 3367: 	    my @parts=split(/_/,$space);
 3368: 	    my $id=pop(@parts);
 3369: 	    my $part=join('_',@parts);
 3370: 	    if ($part eq '') { $part='0'; }
 3371: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 3372: 				 $symbparm,$udom,$uname);
 3373: 	    if (defined($partgeneral)) { return $partgeneral; }
 3374: 	}
 3375: 
 3376: # ---------------------------------------------------- Any other user namespace
 3377:     } elsif ($realm eq 'environment') {
 3378: # ----------------------------------------------------------------- environment
 3379: 	if (($uname eq $ENV{'user.name'})&&($udom eq $ENV{'user.domain'})) {
 3380: 	    return $ENV{'environment.'.$spacequalifierrest};
 3381: 	} else {
 3382: 	    my %returnhash=&userenvironment($udom,$uname,
 3383: 					    $spacequalifierrest);
 3384: 	    return $returnhash{$spacequalifierrest};
 3385: 	}
 3386:     } elsif ($realm eq 'system') {
 3387: # ----------------------------------------------------------------- system.time
 3388: 	if ($space eq 'time') {
 3389: 	    return time;
 3390:         }
 3391:     }
 3392:     return '';
 3393: }
 3394: 
 3395: sub add_prefix_and_part {
 3396:     my ($prefix,$part)=@_;
 3397:     my $keyroot;
 3398:     if (defined($prefix) && $prefix !~ /^__/) {
 3399: 	# prefix that has a part already
 3400: 	$keyroot=$prefix;
 3401:     } elsif (defined($prefix)) {
 3402: 	# prefix that is missing a part
 3403: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 3404:     } else {
 3405: 	# no prefix at all
 3406: 	if (defined($part)) { $keyroot='_'.$part; }
 3407:     }
 3408:     return $keyroot;
 3409: }
 3410: 
 3411: # ---------------------------------------------------------------- Get metadata
 3412: 
 3413: sub metadata {
 3414:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 3415: 
 3416:     $uri=&declutter($uri);
 3417:     # if it is a non metadata possible uri return quickly
 3418:     if (($uri eq '') || (($uri =~ m|^/*adm/|) && ($uri !~ m|^adm/includes|)) ||
 3419:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|)) {
 3420: 	return '';
 3421:     }
 3422:     my $filename=$uri;
 3423:     $uri=~s/\.meta$//;
 3424: #
 3425: # Is the metadata already cached?
 3426: # Look at timestamp of caching
 3427: # Everything is cached by the main uri, libraries are never directly cached
 3428: #
 3429:     unless (abs($metacache{$uri.':cachedtimestamp'}-time)<600 && !defined($liburi)) {
 3430: #
 3431: # Is this a recursive call for a library?
 3432: #
 3433:         if ($liburi) {
 3434: 	    $liburi=&declutter($liburi);
 3435:             $filename=$liburi;
 3436:         }
 3437:         my %metathesekeys=();
 3438:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 3439: 	my $metastring=&getfile(&filelocation('',&clutter($filename)));
 3440:         my $parser=HTML::LCParser->new(\$metastring);
 3441:         my $token;
 3442:         undef %metathesekeys;
 3443: 	delete($metacache{$uri.':packages'});
 3444:         while ($token=$parser->get_token) {
 3445: 	    if ($token->[0] eq 'S') {
 3446: 		if (defined($token->[2]->{'package'})) {
 3447: #
 3448: # This is a package - get package info
 3449: #
 3450: 		    my $package=$token->[2]->{'package'};
 3451: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 3452: 		    if (defined($token->[2]->{'id'})) { 
 3453: 			$keyroot.='_'.$token->[2]->{'id'}; 
 3454: 		    }
 3455: 		    if ($metacache{$uri.':packages'}) {
 3456: 			$metacache{$uri.':packages'}.=','.$package.$keyroot;
 3457: 		    } else {
 3458: 			$metacache{$uri.':packages'}=$package.$keyroot;
 3459: 		    }
 3460: 		    foreach (keys %packagetab) {
 3461: 			if ($_=~/^$package\&/) {
 3462: 			    my ($pack,$name,$subp)=split(/\&/,$_);
 3463: 			    my $value=$packagetab{$_};
 3464: 			    my $part=$keyroot;
 3465: 			    $part=~s/^\_//;
 3466: 			    if ($subp eq 'display') {
 3467: 				$value.=' [Part: '.$part.']';
 3468: 			    }
 3469: 			    my $unikey='parameter'.$keyroot.'_'.$name;
 3470: 			    if ($subp eq 'default') {
 3471: 				$unikey='parameter_0_'.$name;
 3472: 				$metacache{$uri.':'.$unikey.'.part'}='0';
 3473: 			    } else {
 3474: 				$metacache{$uri.':'.$unikey.'.part'}=$part;
 3475: 				$metathesekeys{$unikey}=1;
 3476: 			    }
 3477: 			    unless (defined($metacache{$uri.':'.$unikey.'.'.$subp})) {
 3478: 				$metacache{$uri.':'.$unikey.'.'.$subp}=$value;
 3479: 			    }
 3480: 			    if (defined($metacache{$uri.':'.$unikey.'.default'})) {
 3481: 				$metacache{$uri.':'.$unikey}=
 3482: 				    $metacache{$uri.':'.$unikey.'.default'};
 3483: 			    }
 3484: 			}
 3485: 		    }
 3486: 		} else {
 3487: #
 3488: # This is not a package - some other kind of start tag
 3489: #
 3490: 		    my $entry=$token->[1];
 3491: 		    my $unikey;
 3492: 		    if ($entry eq 'import') {
 3493: 			$unikey='';
 3494: 		    } else {
 3495: 			$unikey=$entry;
 3496: 		    }
 3497: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 3498: 
 3499: 		    if (defined($token->[2]->{'id'})) { 
 3500: 			$unikey.='_'.$token->[2]->{'id'}; 
 3501: 		    }
 3502: 
 3503: 		    if ($entry eq 'import') {
 3504: #
 3505: # Importing a library here
 3506: #
 3507: 			if ($depthcount<20) {
 3508: 			    my $location=$parser->get_text('/import');
 3509: 			    my $dir=$filename;
 3510: 			    $dir=~s|[^/]*$||;
 3511: 			    $location=&filelocation($dir,$location);
 3512: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
 3513: 							       $location,$unikey,
 3514: 							       $depthcount+1)))) {
 3515: 				$metathesekeys{$_}=1;
 3516: 			    }
 3517: 			}
 3518: 		    } else { 
 3519: 			
 3520: 			if (defined($token->[2]->{'name'})) { 
 3521: 			    $unikey.='_'.$token->[2]->{'name'}; 
 3522: 			}
 3523: 			$metathesekeys{$unikey}=1;
 3524: 			foreach (@{$token->[3]}) {
 3525: 			    $metacache{$uri.':'.$unikey.'.'.$_}=$token->[2]->{$_};
 3526: 			}
 3527: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 3528: 			my $default=$metacache{$uri.':'.$unikey.'.default'};
 3529: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 3530: 		 # only ws inside the tag, and not in default, so use default
 3531: 		 # as value
 3532: 			    $metacache{$uri.':'.$unikey}=$default;
 3533: 			} else {
 3534: 		  # either something interesting inside the tag or default
 3535:                   # uninteresting
 3536: 			    $metacache{$uri.':'.$unikey}=$internaltext;
 3537: 			}
 3538: # end of not-a-package not-a-library import
 3539: 		    }
 3540: # end of not-a-package start tag
 3541: 		}
 3542: # the next is the end of "start tag"
 3543: 	    }
 3544: 	}
 3545: # are there custom rights to evaluate
 3546: 	if ($metacache{$uri.':copyright'} eq 'custom') {
 3547: 
 3548:     #
 3549:     # Importing a rights file here
 3550:     #
 3551: 	    unless ($depthcount) {
 3552: 		my $location=$metacache{$uri.':customdistributionfile'};
 3553: 		my $dir=$filename;
 3554: 		$dir=~s|[^/]*$||;
 3555: 		$location=&filelocation($dir,$location);
 3556: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
 3557: 						   $location,'_rights',
 3558: 						   $depthcount+1)))) {
 3559: 		    $metathesekeys{$_}=1;
 3560: 		}
 3561: 	    }
 3562: 	}
 3563: 	$metacache{$uri.':keys'}=join(',',keys %metathesekeys);
 3564: 	&metadata_generate_part0(\%metathesekeys,\%metacache,$uri);
 3565: 	$metacache{$uri.':allpossiblekeys'}=join(',',keys %metathesekeys);
 3566: 	$metacache{$uri.':cachedtimestamp'}=time;
 3567: # this is the end of "was not already recently cached
 3568:     }
 3569:     return $metacache{$uri.':'.$what};
 3570: }
 3571: 
 3572: sub metadata_generate_part0 {
 3573:     my ($metadata,$metacache,$uri) = @_;
 3574:     my %allnames;
 3575:     foreach my $metakey (sort keys %$metadata) {
 3576: 	if ($metakey=~/^parameter\_(.*)/) {
 3577: 	  my $part=$$metacache{$uri.':'.$metakey.'.part'};
 3578: 	  my $name=$$metacache{$uri.':'.$metakey.'.name'};
 3579: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 3580: 	    $allnames{$name}=$part;
 3581: 	  }
 3582: 	}
 3583:     }
 3584:     foreach my $name (keys(%allnames)) {
 3585:       $$metadata{"parameter_0_$name"}=1;
 3586:       my $key="$uri:parameter_0_$name";
 3587:       $$metacache{"$key.part"}='0';
 3588:       $$metacache{"$key.name"}=$name;
 3589:       $$metacache{"$key.type"}=$$metacache{$uri.':parameter_'.
 3590: 					   $allnames{$name}.'_'.$name.
 3591: 					   '.type'};
 3592:       my $olddis=$$metacache{$uri.':parameter_'.$allnames{$name}.'_'.$name.
 3593: 			     '.display'};
 3594:       my $expr='\\[Part: '.$allnames{$name}.'\\]';
 3595:       $olddis=~s/$expr/\[Part: 0\]/;
 3596:       $$metacache{"$key.display"}=$olddis;
 3597:     }
 3598: }
 3599: 
 3600: # ------------------------------------------------- Get the title of a resource
 3601: 
 3602: sub gettitle {
 3603:     my $urlsymb=shift;
 3604:     my $symb=&symbread($urlsymb);
 3605:     unless ($symb) {
 3606: 	unless ($urlsymb) { $urlsymb=$ENV{'request.filename'}; }
 3607:         return &metadata($urlsymb,'title'); 
 3608:     }
 3609:     if ($titlecache{$symb}) { return $titlecache{$symb}; }
 3610:     my ($map,$resid,$url)=split(/\_\_\_/,$symb);
 3611:     my $title='';
 3612:     my %bighash;
 3613:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3614:                             &GDBM_READER(),0640)) {
 3615:         my $mapid=$bighash{'map_pc_'.&clutter($map)};
 3616:         $title=$bighash{'title_'.$mapid.'.'.$resid};
 3617:         untie %bighash;
 3618:     }
 3619:     $title=~s/\&colon\;/\:/gs;
 3620:     if ($title) {
 3621:         $titlecache{$symb}=$title;
 3622:         return $title;
 3623:     } else {
 3624: 	return &metadata($urlsymb,'title');
 3625:     }
 3626: }
 3627:     
 3628: # ------------------------------------------------- Update symbolic store links
 3629: 
 3630: sub symblist {
 3631:     my ($mapname,%newhash)=@_;
 3632:     $mapname=declutter($mapname);
 3633:     my %hash;
 3634:     if (($ENV{'request.course.fn'}) && (%newhash)) {
 3635:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 3636:                       &GDBM_WRCREAT(),0640)) {
 3637: 	    foreach (keys %newhash) {
 3638:                 $hash{declutter($_)}=$mapname.'___'.$newhash{$_};
 3639:             }
 3640:             if (untie(%hash)) {
 3641: 		return 'ok';
 3642:             }
 3643:         }
 3644:     }
 3645:     return 'error';
 3646: }
 3647: 
 3648: # --------------------------------------------------------------- Verify a symb
 3649: 
 3650: sub symbverify {
 3651:     my ($symb,$thisfn)=@_;
 3652:     $thisfn=&declutter($thisfn);
 3653: # direct jump to resource in page or to a sequence - will construct own symbs
 3654:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 3655: # check URL part
 3656:     my ($map,$resid,$url)=split(/\_\_\_/,$symb);
 3657:     unless (&symbclean($url) eq &symbclean($thisfn)) { return 0; }
 3658: 
 3659:     $symb=&symbclean($symb);
 3660: 
 3661:     my %bighash;
 3662:     my $okay=0;
 3663:     if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3664:                             &GDBM_READER(),0640)) {
 3665:         my $ids=$bighash{'ids_'.&clutter($thisfn)};
 3666:         unless ($ids) { 
 3667:            $ids=$bighash{'ids_/'.$thisfn};
 3668:         }
 3669:         if ($ids) {
 3670: # ------------------------------------------------------------------- Has ID(s)
 3671: 	    foreach (split(/\,/,$ids)) {
 3672:                my ($mapid,$resid)=split(/\./,$_);
 3673:                if (
 3674:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 3675:    eq $symb) { 
 3676:                   $okay=1; 
 3677:                }
 3678: 	   }
 3679:         }
 3680: 	untie(%bighash);
 3681:     }
 3682:     return $okay;
 3683: }
 3684: 
 3685: # --------------------------------------------------------------- Clean-up symb
 3686: 
 3687: sub symbclean {
 3688:     my $symb=shift;
 3689: 
 3690: # remove version from map
 3691:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 3692: 
 3693: # remove version from URL
 3694:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 3695: 
 3696:     return $symb;
 3697: }
 3698: 
 3699: # ------------------------------------------------------ Return symb list entry
 3700: 
 3701: sub symbread {
 3702:     my ($thisfn,$donotrecurse)=@_;
 3703: # no filename provided? try from environment
 3704:     unless ($thisfn) {
 3705:         if ($ENV{'request.symb'}) { return &symbclean($ENV{'request.symb'}); }
 3706: 	$thisfn=$ENV{'request.filename'};
 3707:     }
 3708: # is that filename actually a symb? Verify, clean, and return
 3709:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 3710: 	if (&symbverify($thisfn,$1)) { return &symbclean($thisfn); }
 3711:     }
 3712:     $thisfn=declutter($thisfn);
 3713:     my %hash;
 3714:     my %bighash;
 3715:     my $syval='';
 3716:     if (($ENV{'request.course.fn'}) && ($thisfn)) {
 3717:         if (tie(%hash,'GDBM_File',$ENV{'request.course.fn'}.'_symb.db',
 3718:                       &GDBM_READER(),0640)) {
 3719: 	    $syval=$hash{$thisfn};
 3720:             untie(%hash);
 3721:         }
 3722: # ---------------------------------------------------------- There was an entry
 3723:         if ($syval) {
 3724:            unless ($syval=~/\_\d+$/) {
 3725: 	       unless ($ENV{'form.request.prefix'}=~/\.(\d+)\_$/) {
 3726:                   &appenv('request.ambiguous' => $thisfn);
 3727:                   return '';
 3728:                }    
 3729:                $syval.=$1;
 3730: 	   }
 3731:         } else {
 3732: # ------------------------------------------------------- Was not in symb table
 3733:            if (tie(%bighash,'GDBM_File',$ENV{'request.course.fn'}.'.db',
 3734:                             &GDBM_READER(),0640)) {
 3735: # ---------------------------------------------- Get ID(s) for current resource
 3736:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 3737:               unless ($ids) { 
 3738:                  $ids=$bighash{'ids_/'.$thisfn};
 3739:               }
 3740:               unless ($ids) {
 3741: # alias?
 3742: 		  $ids=$bighash{'mapalias_'.$thisfn};
 3743:               }
 3744:               if ($ids) {
 3745: # ------------------------------------------------------------------- Has ID(s)
 3746:                  my @possibilities=split(/\,/,$ids);
 3747:                  if ($#possibilities==0) {
 3748: # ----------------------------------------------- There is only one possibility
 3749: 		     my ($mapid,$resid)=split(/\./,$ids);
 3750:                      $syval=declutter($bighash{'map_id_'.$mapid}).'___'.$resid;
 3751:                  } elsif (!$donotrecurse) {
 3752: # ------------------------------------------ There is more than one possibility
 3753:                      my $realpossible=0;
 3754:                      foreach (@possibilities) {
 3755: 			 my $file=$bighash{'src_'.$_};
 3756:                          if (&allowed('bre',$file)) {
 3757:          		    my ($mapid,$resid)=split(/\./,$_);
 3758:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 3759: 				$realpossible++;
 3760:                                 $syval=declutter($bighash{'map_id_'.$mapid}).
 3761:                                        '___'.$resid;
 3762:                             }
 3763: 			 }
 3764:                      }
 3765: 		     if ($realpossible!=1) { $syval=''; }
 3766:                  } else {
 3767:                      $syval='';
 3768:                  }
 3769: 	      }
 3770:               untie(%bighash)
 3771:            } 
 3772:         }
 3773:         if ($syval) {
 3774:            return &symbclean($syval.'___'.$thisfn); 
 3775:         }
 3776:     }
 3777:     &appenv('request.ambiguous' => $thisfn);
 3778:     return '';
 3779: }
 3780: 
 3781: # ---------------------------------------------------------- Return random seed
 3782: 
 3783: sub numval {
 3784:     my $txt=shift;
 3785:     $txt=~tr/A-J/0-9/;
 3786:     $txt=~tr/a-j/0-9/;
 3787:     $txt=~tr/K-T/0-9/;
 3788:     $txt=~tr/k-t/0-9/;
 3789:     $txt=~tr/U-Z/0-5/;
 3790:     $txt=~tr/u-z/0-5/;
 3791:     $txt=~s/\D//g;
 3792:     return int($txt);
 3793: }
 3794: 
 3795: sub latest_rnd_algorithm_id {
 3796:     return '64bit';
 3797: }
 3798: 
 3799: sub rndseed {
 3800:     my ($symb,$courseid,$domain,$username)=@_;
 3801: 
 3802:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 3803:     if (!$symb) {
 3804: 	unless ($symb=$wsymb) { return time; }
 3805:     }
 3806:     if (!$courseid) { $courseid=$wcourseid; }
 3807:     if (!$domain) { $domain=$wdomain; }
 3808:     if (!$username) { $username=$wusername }
 3809:     my $which=$ENV{"course.$courseid.rndseed"};
 3810:     my $CODE=$ENV{'scantron.CODE'};
 3811:     if (defined($CODE)) {
 3812: 	&rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 3813:     } elsif ($which eq '64bit') {
 3814: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 3815:     }
 3816:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 3817: }
 3818: 
 3819: sub rndseed_32bit {
 3820:     my ($symb,$courseid,$domain,$username)=@_;
 3821:     {
 3822: 	use integer;
 3823: 	my $symbchck=unpack("%32C*",$symb) << 27;
 3824: 	my $symbseed=numval($symb) << 22;
 3825: 	my $namechck=unpack("%32C*",$username) << 17;
 3826: 	my $nameseed=numval($username) << 12;
 3827: 	my $domainseed=unpack("%32C*",$domain) << 7;
 3828: 	my $courseseed=unpack("%32C*",$courseid);
 3829: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 3830: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 3831: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 3832: 	return $num;
 3833:     }
 3834: }
 3835: 
 3836: sub rndseed_64bit {
 3837:     my ($symb,$courseid,$domain,$username)=@_;
 3838:     {
 3839: 	use integer;
 3840: 	my $symbchck=unpack("%32S*",$symb) << 21;
 3841: 	my $symbseed=numval($symb) << 10;
 3842: 	my $namechck=unpack("%32S*",$username);
 3843: 	
 3844: 	my $nameseed=numval($username) << 21;
 3845: 	my $domainseed=unpack("%32S*",$domain) << 10;
 3846: 	my $courseseed=unpack("%32S*",$courseid);
 3847: 	
 3848: 	my $num1=$symbchck+$symbseed+$namechck;
 3849: 	my $num2=$nameseed+$domainseed+$courseseed;
 3850: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 3851: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 3852: 	return "$num1,$num2";
 3853:     }
 3854: }
 3855: 
 3856: sub rndseed_CODE_64bit {
 3857:     my ($symb,$courseid,$domain,$username)=@_;
 3858:     {
 3859: 	use integer;
 3860: 	my $symbchck=unpack("%32S*",$symb) << 16;
 3861: 	my $symbseed=numval($symb);
 3862: 	my $CODEseed=numval($ENV{'scantron.CODE'}) << 16;
 3863: 	my $courseseed=unpack("%32S*",$courseid);
 3864: 	my $num1=$symbseed+$CODEseed;
 3865: 	my $num2=$courseseed+$symbchck;
 3866: 	#&Apache::lonxml::debug("$symbseed:$CODEseed|$courseseed:$symbchck");
 3867: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 3868: 	return "$num1,$num2";
 3869:     }
 3870: }
 3871: 
 3872: sub setup_random_from_rndseed {
 3873:     my ($rndseed)=@_;
 3874:     if ($rndseed =~/,/) {
 3875: 	my ($num1,$num2)=split(/,/,$rndseed);
 3876: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 3877:     } else {
 3878: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 3879:     }
 3880: }
 3881: 
 3882: sub ireceipt {
 3883:     my ($funame,$fudom,$fucourseid,$fusymb)=@_;
 3884:     my $cuname=unpack("%32C*",$funame);
 3885:     my $cudom=unpack("%32C*",$fudom);
 3886:     my $cucourseid=unpack("%32C*",$fucourseid);
 3887:     my $cusymb=unpack("%32C*",$fusymb);
 3888:     my $cunique=unpack("%32C*",$perlvar{'lonReceipt'});
 3889:     return unpack("%32C*",$perlvar{'lonHostID'}).'-'.
 3890:            ($cunique%$cuname+
 3891:             $cunique%$cudom+
 3892:             $cusymb%$cuname+
 3893:             $cusymb%$cudom+
 3894:             $cucourseid%$cuname+
 3895:             $cucourseid%$cudom);
 3896: }
 3897: 
 3898: sub receipt {
 3899:   my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 3900:   return &ireceipt($name,$domain,$courseid,$symb);
 3901: }
 3902: 
 3903: # ------------------------------------------------------------ Serves up a file
 3904: # returns either the contents of the file or a -1
 3905: sub getfile {
 3906:  my $file=shift;
 3907:  if ($file=~/^\/*uploaded\//) { # user file
 3908:     my $ua=new LWP::UserAgent;
 3909:     my $request=new HTTP::Request('GET',&tokenwrapper($file));
 3910:     my $response=$ua->request($request);
 3911:     if ($response->is_success()) {
 3912:        return $response->content;
 3913:     } else { 
 3914:        return -1; 
 3915:     }
 3916:  } else { # normal file from res space
 3917:   &repcopy($file);
 3918:   if (! -e $file ) { return -1; };
 3919:   my $fh=Apache::File->new($file);
 3920:   my $a='';
 3921:   while (<$fh>) { $a .=$_; }
 3922:   return $a;
 3923:  }
 3924: }
 3925: 
 3926: sub filelocation {
 3927:   my ($dir,$file) = @_;
 3928:   my $location;
 3929:   $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 3930:   if ($file=~m:^/~:) { # is a contruction space reference
 3931:     $location = $file;
 3932:     $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 3933:   } elsif ($file=~/^\/*uploaded/) { # is an uploaded file
 3934:     $location=$file;
 3935:   } else {
 3936:     $file=~s/^$perlvar{'lonDocRoot'}//;
 3937:     $file=~s:^/*res::;
 3938:     if ( !( $file =~ m:^/:) ) {
 3939:       $location = $dir. '/'.$file;
 3940:     } else {
 3941:       $location = '/home/httpd/html/res'.$file;
 3942:     }
 3943:   }
 3944:   $location=~s://+:/:g; # remove duplicate /
 3945:   while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 3946:   return $location;
 3947: }
 3948: 
 3949: sub hreflocation {
 3950:     my ($dir,$file)=@_;
 3951:     unless (($file=~/^http:\/\//i) || ($file=~/^\//)) {
 3952:        my $finalpath=filelocation($dir,$file);
 3953:        $finalpath=~s/^\/home\/httpd\/html//;
 3954:        $finalpath=~s-/home/(\w+)/public_html/-/~$1/-;
 3955:        return $finalpath;
 3956:     } else {
 3957:        return $file;
 3958:     }
 3959: }
 3960: 
 3961: # ------------------------------------------------------------- Declutters URLs
 3962: 
 3963: sub declutter {
 3964:     my $thisfn=shift;
 3965:     $thisfn=~s/^$perlvar{'lonDocRoot'}//;
 3966:     $thisfn=~s/^\///;
 3967:     $thisfn=~s/^res\///;
 3968:     $thisfn=~s/\?.+$//;
 3969:     return $thisfn;
 3970: }
 3971: 
 3972: # ------------------------------------------------------------- Clutter up URLs
 3973: 
 3974: sub clutter {
 3975:     my $thisfn='/'.&declutter(shift);
 3976:     unless ($thisfn=~/^\/(uploaded|adm|userfiles|ext|raw|priv)\//) { 
 3977:        $thisfn='/res'.$thisfn; 
 3978:     }
 3979:     return $thisfn;
 3980: }
 3981: 
 3982: # -------------------------------------------------------- Escape Special Chars
 3983: 
 3984: sub escape {
 3985:     my $str=shift;
 3986:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 3987:     return $str;
 3988: }
 3989: 
 3990: # ----------------------------------------------------- Un-Escape Special Chars
 3991: 
 3992: sub unescape {
 3993:     my $str=shift;
 3994:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 3995:     return $str;
 3996: }
 3997: 
 3998: # ================================================================ Main Program
 3999: 
 4000: sub goodbye {
 4001:    &logthis("Starting Shut down");
 4002:    &flushcourselogs();
 4003:    &logthis("Shutting down");
 4004:    return DONE;
 4005: }
 4006: 
 4007: BEGIN {
 4008: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 4009:     unless ($readit) {
 4010: {
 4011:     my $config=Apache::File->new("/etc/httpd/conf/loncapa.conf");
 4012: 
 4013:     while (my $configline=<$config>) {
 4014:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 4015: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 4016:            chomp($varvalue);
 4017:            $perlvar{$varname}=$varvalue;
 4018:         }
 4019:     }
 4020: }
 4021: {
 4022:     my $config=Apache::File->new("/etc/httpd/conf/loncapa_apache.conf");
 4023: 
 4024:     while (my $configline=<$config>) {
 4025:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 4026: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 4027:            chomp($varvalue);
 4028:            $perlvar{$varname}=$varvalue;
 4029:         }
 4030:     }
 4031: }
 4032: 
 4033: # ------------------------------------------------------------ Read domain file
 4034: {
 4035:     my $fh=Apache::File->new($Apache::lonnet::perlvar{'lonTabDir'}.
 4036:                             '/domain.tab');
 4037:     %domaindescription = ();
 4038:     %domain_auth_def = ();
 4039:     %domain_auth_arg_def = ();
 4040:     if ($fh) {
 4041:        while (<$fh>) {
 4042:            next if /^\#/;
 4043:            chomp;
 4044:            my ($domain, $domain_description, $def_auth, $def_auth_arg)
 4045:                = split(/:/,$_,4);
 4046:            $domain_auth_def{$domain}=$def_auth;
 4047:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 4048:            $domaindescription{$domain}=$domain_description;
 4049: #          &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 4050: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 4051:        }
 4052:     }
 4053: }
 4054: 
 4055: 
 4056: # ------------------------------------------------------------- Read hosts file
 4057: {
 4058:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/hosts.tab");
 4059: 
 4060:     while (my $configline=<$config>) {
 4061:        next if ($configline =~ /^(\#|\s*$)/);
 4062:        chomp($configline);
 4063:        my ($id,$domain,$role,$name,$ip,$domdescr)=split(/:/,$configline);
 4064:        if ($id && $domain && $role && $name && $ip) {
 4065: 	 $hostname{$id}=$name;
 4066: 	 $hostdom{$id}=$domain;
 4067: 	 $hostip{$id}=$ip;
 4068: 	 $iphost{$ip}=$id;
 4069: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 4070:        } else {
 4071: 	 if ($configline) {
 4072: 	   &logthis("Skipping hosts.tab line -$configline-");
 4073: 	 }
 4074:        }
 4075:     }
 4076: }
 4077: 
 4078: # ------------------------------------------------------ Read spare server file
 4079: {
 4080:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/spare.tab");
 4081: 
 4082:     while (my $configline=<$config>) {
 4083:        chomp($configline);
 4084:        if ($configline) {
 4085:           $spareid{$configline}=1;
 4086:        }
 4087:     }
 4088: }
 4089: # ------------------------------------------------------------ Read permissions
 4090: {
 4091:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/roles.tab");
 4092: 
 4093:     while (my $configline=<$config>) {
 4094:        chomp($configline);
 4095:       if ($configline) {
 4096:        my ($role,$perm)=split(/ /,$configline);
 4097:        if ($perm ne '') { $pr{$role}=$perm; }
 4098:       }
 4099:     }
 4100: }
 4101: 
 4102: # -------------------------------------------- Read plain texts for permissions
 4103: {
 4104:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/rolesplain.tab");
 4105: 
 4106:     while (my $configline=<$config>) {
 4107:        chomp($configline);
 4108:       if ($configline) {
 4109:        my ($short,$plain)=split(/:/,$configline);
 4110:        if ($plain ne '') { $prp{$short}=$plain; }
 4111:       }
 4112:     }
 4113: }
 4114: 
 4115: # ---------------------------------------------------------- Read package table
 4116: {
 4117:     my $config=Apache::File->new("$perlvar{'lonTabDir'}/packages.tab");
 4118: 
 4119:     while (my $configline=<$config>) {
 4120:        chomp($configline);
 4121:        my ($short,$plain)=split(/:/,$configline);
 4122:        my ($pack,$name)=split(/\&/,$short);
 4123:        if ($plain ne '') {
 4124:           $packagetab{$pack.'&'.$name.'&name'}=$name; 
 4125:           $packagetab{$short}=$plain; 
 4126:        }
 4127:     }
 4128: }
 4129: 
 4130: # ------------- set up temporary directory
 4131: {
 4132:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 4133: 
 4134: }
 4135: 
 4136: %metacache=();
 4137: 
 4138: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 4139: $dumpcount=0;
 4140: 
 4141: &logtouch();
 4142: &logthis('<font color=yellow>INFO: Read configuration</font>');
 4143: $readit=1;
 4144: }
 4145: }
 4146: 
 4147: 1;
 4148: __END__
 4149: 
 4150: =pod
 4151: 
 4152: =head1 NAME
 4153: 
 4154: Apache::lonnet - Subroutines to ask questions about things in the network.
 4155: 
 4156: =head1 SYNOPSIS
 4157: 
 4158: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 4159: 
 4160:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 4161: 
 4162: Common parameters:
 4163: 
 4164: =over 4
 4165: 
 4166: =item *
 4167: 
 4168: $uname : an internal username (if $cname expecting a course Id specifically)
 4169: 
 4170: =item *
 4171: 
 4172: $udom : a domain (if $cdom expecting a course's domain specifically)
 4173: 
 4174: =item *
 4175: 
 4176: $symb : a resource instance identifier
 4177: 
 4178: =item *
 4179: 
 4180: $namespace : the name of a .db file that contains the data needed or
 4181: being set.
 4182: 
 4183: =back
 4184: 
 4185: =head1 INTRODUCTION
 4186: 
 4187: This module provides subroutines which interact with the
 4188: lonc/lond (TCP) network layer of LON-CAPA. And Can be used to ask about 
 4189: - classes
 4190: - users 
 4191: - resources
 4192: 
 4193: For many of these objects you can also use this to store data about
 4194: them or modify them in various ways.
 4195: 
 4196: This is part of the LearningOnline Network with CAPA project
 4197: described at http://www.lon-capa.org.
 4198: 
 4199: =head1 RETURN MESSAGES
 4200: 
 4201: =over 4
 4202: 
 4203: =item *
 4204: 
 4205: con_lost : unable to contact remote host
 4206: 
 4207: =item *
 4208: 
 4209: con_delayed : unable to contact remote host, message will be delivered
 4210: when the connection is brought back up
 4211: 
 4212: =item *
 4213: 
 4214: con_failed : unable to contact remote host and unable to save message
 4215: for later delivery
 4216: 
 4217: =item *
 4218: 
 4219: error: : an error a occured, a description of the error follows the :
 4220: 
 4221: =item *
 4222: 
 4223: no_such_host : unable to fund a host associated with the user/domain
 4224: that was requested
 4225: 
 4226: =back
 4227: 
 4228: =head1 PUBLIC SUBROUTINES
 4229: 
 4230: =head2 Session Environment Functions
 4231: 
 4232: =over 4
 4233: 
 4234: =item *
 4235: 
 4236: appenv(%hash) : the value of %hash is written to the user envirnoment
 4237: file, and will be restored for each access this user makes during this
 4238: session, also modifies the %ENV for the current process
 4239: 
 4240: =item *
 4241: 
 4242: delenv($regexp) : removes all items from the session environment file that matches the regular expression in $regexp. The values are also delted from the current processes %ENV.
 4243: 
 4244: =back
 4245: 
 4246: =head2 User Information
 4247: 
 4248: =over 4
 4249: 
 4250: =item *
 4251: 
 4252: queryauthenticate($uname,$udom) : try to determine user's current
 4253: authentication scheme
 4254: 
 4255: =item *
 4256: 
 4257: authenticate($uname,$upass,$udom) : try to authenticate user from domain's lib
 4258: servers (first use the current one), $upass should be the users password
 4259: 
 4260: =item *
 4261: 
 4262: homeserver($uname,$udom) : find the server which has the user's
 4263: directory and files (there must be only one), this caches the answer,
 4264: and also caches if there is a borken connection.
 4265: 
 4266: =item *
 4267: 
 4268: idget($udom,@ids) : find the usernames behind a list of IDs (IDs are a
 4269: unique resource in a domain, there must be only 1 ID per username, and
 4270: only 1 username per ID in a specific domain) (returns hash:
 4271: id=>name,id=>name)
 4272: 
 4273: =item *
 4274: 
 4275: idrget($udom,@unames) : find the IDs behind a list of usernames (returns hash:
 4276: name=>id,name=>id)
 4277: 
 4278: =item *
 4279: 
 4280: idput($udom,%ids) : store away a list of names and associated IDs
 4281: 
 4282: =item *
 4283: 
 4284: rolesinit($udom,$username,$authhost) : get user privileges
 4285: 
 4286: =item *
 4287: 
 4288: usection($udom,$uname,$cname) : finds the section of student in the
 4289: course $cname, return section name/number or '' for "not in course"
 4290: and '-1' for "no section"
 4291: 
 4292: =item *
 4293: 
 4294: userenvironment($udom,$uname,@what) : gets the values of the keys
 4295: passed in @what from the requested user's environment, returns a hash
 4296: 
 4297: =back
 4298: 
 4299: =head2 User Roles
 4300: 
 4301: =over 4
 4302: 
 4303: =item *
 4304: 
 4305: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 4306: actions
 4307:  F: full access
 4308:  U,I,K: authentication modes (cxx only)
 4309:  '': forbidden
 4310:  1: user needs to choose course
 4311:  2: browse allowed
 4312: 
 4313: =item *
 4314: 
 4315: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 4316: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 4317: and course level
 4318: 
 4319: =item *
 4320: 
 4321: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 4322: explanation of a user role term
 4323: 
 4324: =back
 4325: 
 4326: =head2 User Modification
 4327: 
 4328: =over 4
 4329: 
 4330: =item *
 4331: 
 4332: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 4333: user for the level given by URL.  Optional start and end dates (leave empty
 4334: string or zero for "no date")
 4335: 
 4336: =item *
 4337: 
 4338: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 4339: change a users, password, possible return values are: ok,
 4340: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 4341: refused
 4342: 
 4343: =item *
 4344: 
 4345: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 4346: 
 4347: =item *
 4348: 
 4349: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 4350: modify user
 4351: 
 4352: =item *
 4353: 
 4354: modifystudent
 4355: 
 4356: modify a students enrollment and identification information.
 4357: The course id is resolved based on the current users environment.  
 4358: This means the envoking user must be a course coordinator or otherwise
 4359: associated with a course.
 4360: 
 4361: This call is essentially a wrapper for lonnet::modifyuser and
 4362: lonnet::modify_student_enrollment
 4363: 
 4364: Inputs: 
 4365: 
 4366: =over 4
 4367: 
 4368: =item B<$udom> Students loncapa domain
 4369: 
 4370: =item B<$uname> Students loncapa login name
 4371: 
 4372: =item B<$uid> Students id/student number
 4373: 
 4374: =item B<$umode> Students authentication mode
 4375: 
 4376: =item B<$upass> Students password
 4377: 
 4378: =item B<$first> Students first name
 4379: 
 4380: =item B<$middle> Students middle name
 4381: 
 4382: =item B<$last> Students last name
 4383: 
 4384: =item B<$gene> Students generation
 4385: 
 4386: =item B<$usec> Students section in course
 4387: 
 4388: =item B<$end> Unix time of the roles expiration
 4389: 
 4390: =item B<$start> Unix time of the roles start date
 4391: 
 4392: =item B<$forceid> If defined, allow $uid to be changed
 4393: 
 4394: =item B<$desiredhome> server to use as home server for student
 4395: 
 4396: =back
 4397: 
 4398: =item *
 4399: 
 4400: modify_student_enrollment
 4401: 
 4402: Change a students enrollment status in a class.  The environment variable
 4403: 'role.request.course' must be defined for this function to proceed.
 4404: 
 4405: Inputs:
 4406: 
 4407: =over 4
 4408: 
 4409: =item $udom, students domain
 4410: 
 4411: =item $uname, students name
 4412: 
 4413: =item $uid, students user id
 4414: 
 4415: =item $first, students first name
 4416: 
 4417: =item $middle
 4418: 
 4419: =item $last
 4420: 
 4421: =item $gene
 4422: 
 4423: =item $usec
 4424: 
 4425: =item $end
 4426: 
 4427: =item $start
 4428: 
 4429: =back
 4430: 
 4431: 
 4432: =item *
 4433: 
 4434: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 4435: custom role; give a custom role to a user for the level given by URL.  Specify
 4436: name and domain of role author, and role name
 4437: 
 4438: =item *
 4439: 
 4440: revokerole($udom,$uname,$url,$role) : revoke a role for url
 4441: 
 4442: =item *
 4443: 
 4444: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 4445: 
 4446: =back
 4447: 
 4448: =head2 Course Infomation
 4449: 
 4450: =over 4
 4451: 
 4452: =item *
 4453: 
 4454: coursedescription($courseid) : course description
 4455: 
 4456: =item *
 4457: 
 4458: courseresdata($coursenum,$coursedomain,@which) : request for current
 4459: parameter setting for a specific course, @what should be a list of
 4460: parameters to ask about. This routine caches answers for 5 minutes.
 4461: 
 4462: =back
 4463: 
 4464: =head2 Course Modification
 4465: 
 4466: =over 4
 4467: 
 4468: =item *
 4469: 
 4470: writecoursepref($courseid,%prefs) : write preferences (environment
 4471: database) for a course
 4472: 
 4473: =item *
 4474: 
 4475: createcourse($udom,$description,$url) : make/modify course
 4476: 
 4477: =back
 4478: 
 4479: =head2 Resource Subroutines
 4480: 
 4481: =over 4
 4482: 
 4483: =item *
 4484: 
 4485: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 4486: 
 4487: =item *
 4488: 
 4489: repcopy($filename) : subscribes to the requested file, and attempts to
 4490: replicate from the owning library server, Might return
 4491: HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND, FORBIDDEN, OK, or
 4492: HTTP_BAD_REQUEST, also attempts to grab the metadata for the
 4493: resource. Expects the local filesystem pathname
 4494: (/home/httpd/html/res/....)
 4495: 
 4496: =back
 4497: 
 4498: =head2 Resource Information
 4499: 
 4500: =over 4
 4501: 
 4502: =item *
 4503: 
 4504: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 4505: a vairety of different possible values, $varname should be a request
 4506: string, and the other parameters can be used to specify who and what
 4507: one is asking about.
 4508: 
 4509: Possible values for $varname are environment.lastname (or other item
 4510: from the envirnment hash), user.name (or someother aspect about the
 4511: user), resource.0.maxtries (or some other part and parameter of a
 4512: resource)
 4513: 
 4514: =item *
 4515: 
 4516: directcondval($number) : get current value of a condition; reads from a state
 4517: string
 4518: 
 4519: =item *
 4520: 
 4521: condval($condidx) : value of condition index based on state
 4522: 
 4523: =item *
 4524: 
 4525: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 4526: resource's metadata, $what should be either a specific key, or either
 4527: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 4528: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 4529: 
 4530: this function automatically caches all requests
 4531: 
 4532: =item *
 4533: 
 4534: metadata_query($query,$custom,$customshow) : make a metadata query against the
 4535: network of library servers; returns file handle of where SQL and regex results
 4536: will be stored for query
 4537: 
 4538: =item *
 4539: 
 4540: symbread($filename) : return symbolic list entry (filename argument optional);
 4541: returns the data handle
 4542: 
 4543: =item *
 4544: 
 4545: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 4546: a possible symb for the URL in $thisfn, returns a 1 on success, 0 on
 4547: failure, user must be in a course, as it assumes the existance of the
 4548: course initi hash, and uses $ENV('request.course.id'}
 4549: 
 4550: 
 4551: =item *
 4552: 
 4553: symbclean($symb) : removes versions numbers from a symb, returns the
 4554: cleaned symb
 4555: 
 4556: =item *
 4557: 
 4558: is_on_map($uri) : checks if the $uri is somewhere on the current
 4559: course map, user must be in a course for it to work.
 4560: 
 4561: =item *
 4562: 
 4563: numval($salt) : return random seed value (addend for rndseed)
 4564: 
 4565: =item *
 4566: 
 4567: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 4568: a random seed, all arguments are optional, if they aren't sent it uses the
 4569: environment to derive them. Note: if symb isn't sent and it can't get one
 4570: from &symbread it will use the current time as its return value
 4571: 
 4572: =item *
 4573: 
 4574: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 4575: unfakeable, receipt
 4576: 
 4577: =item *
 4578: 
 4579: receipt() : API to ireceipt working off of ENV values; given out to users
 4580: 
 4581: =item *
 4582: 
 4583: countacc($url) : count the number of accesses to a given URL
 4584: 
 4585: =item *
 4586: 
 4587: checkout($symb,$tuname,$tudom,$tcrsid) :  creates a record of a user having looked at an item, most likely printed out or otherwise using a resource
 4588: 
 4589: =item *
 4590: 
 4591: checkin($token) : updates that a resource has beeen returned (a hard copy version for instance) and returns the data that $token was Checkout with ($symb, $tuname, $tudom, and $tcrsid)
 4592: 
 4593: =item *
 4594: 
 4595: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 4596: 
 4597: =item *
 4598: 
 4599: devalidate($symb) : devalidate temporary spreadsheet calculations,
 4600: forcing spreadsheet to reevaluate the resource scores next time.
 4601: 
 4602: =back
 4603: 
 4604: =head2 Storing/Retreiving Data
 4605: 
 4606: =over 4
 4607: 
 4608: =item *
 4609: 
 4610: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 4611: for this url; hashref needs to be given and should be a \%hashname; the
 4612: remaining args aren't required and if they aren't passed or are '' they will
 4613: be derived from the ENV
 4614: 
 4615: =item *
 4616: 
 4617: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 4618: uses critical subroutine
 4619: 
 4620: =item *
 4621: 
 4622: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 4623: all args are optional
 4624: 
 4625: =item *
 4626: 
 4627: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 4628: works very similar to store/cstore, but all data is stored in a
 4629: temporary location and can be reset using tmpreset, $storehash should
 4630: be a hash reference, returns nothing on success
 4631: 
 4632: =item *
 4633: 
 4634: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 4635: similar to restore, but all data is stored in a temporary location and
 4636: can be reset using tmpreset. Returns a hash of values on success,
 4637: error string otherwise.
 4638: 
 4639: =item *
 4640: 
 4641: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 4642: deltes all keys for $symb form the temporary storage hash.
 4643: 
 4644: =item *
 4645: 
 4646: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 4647: reference filled in from namesp ($udom and $uname are optional)
 4648: 
 4649: =item *
 4650: 
 4651: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 4652: namesp ($udom and $uname are optional)
 4653: 
 4654: =item *
 4655: 
 4656: dump($namespace,$udom,$uname,$regexp) : 
 4657: dumps the complete (or key matching regexp) namespace into a hash
 4658: ($udom, $uname and $regexp are optional)
 4659: 
 4660: =item *
 4661: 
 4662: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 4663: ($udom and $uname are optional)
 4664: 
 4665: =item *
 4666: 
 4667: cput($namespace,$storehash,$udom,$uname) : critical put
 4668: ($udom and $uname are optional)
 4669: 
 4670: =item *
 4671: 
 4672: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 4673: reference filled in from namesp (encrypts the return communication)
 4674: ($udom and $uname are optional)
 4675: 
 4676: =item *
 4677: 
 4678: log($udom,$name,$home,$message) : write to permanent log for user; use
 4679: critical subroutine
 4680: 
 4681: =back
 4682: 
 4683: =head2 Network Status Functions
 4684: 
 4685: =over 4
 4686: 
 4687: =item *
 4688: 
 4689: dirlist($uri) : return directory list based on URI
 4690: 
 4691: =item *
 4692: 
 4693: spareserver() : find server with least workload from spare.tab
 4694: 
 4695: =back
 4696: 
 4697: =head2 Apache Request
 4698: 
 4699: =over 4
 4700: 
 4701: =item *
 4702: 
 4703: ssi($url,%hash) : server side include, does a complete request cycle on url to
 4704: localhost, posts hash
 4705: 
 4706: =back
 4707: 
 4708: =head2 Data to String to Data
 4709: 
 4710: =over 4
 4711: 
 4712: =item *
 4713: 
 4714: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 4715: and '&' separators, supports elements that are arrayrefs and hashrefs
 4716: 
 4717: =item *
 4718: 
 4719: hashref2str($hashref) : convert a hashref into a string complete with
 4720: escaping and '=' and '&' separators, supports elements that are
 4721: arrayrefs and hashrefs
 4722: 
 4723: =item *
 4724: 
 4725: arrayref2str($arrayref) : convert an arrayref into a string complete
 4726: with escaping and '&' separators, supports elements that are arrayrefs
 4727: and hashrefs
 4728: 
 4729: =item *
 4730: 
 4731: str2hash($string) : convert string to hash using unescaping and
 4732: splitting on '=' and '&', supports elements that are arrayrefs and
 4733: hashrefs
 4734: 
 4735: =item *
 4736: 
 4737: str2array($string) : convert string to hash using unescaping and
 4738: splitting on '&', supports elements that are arrayrefs and hashrefs
 4739: 
 4740: =back
 4741: 
 4742: =head2 Logging Routines
 4743: 
 4744: =over 4
 4745: 
 4746: These routines allow one to make log messages in the lonnet.log and
 4747: lonnet.perm logfiles.
 4748: 
 4749: =item *
 4750: 
 4751: logtouch() : make sure the logfile, lonnet.log, exists
 4752: 
 4753: =item *
 4754: 
 4755: logthis() : append message to the normal lonnet.log file, it gets
 4756: preiodically rolled over and deleted.
 4757: 
 4758: =item *
 4759: 
 4760: logperm() : append a permanent message to lonnet.perm.log, this log
 4761: file never gets deleted by any automated portion of the system, only
 4762: messages of critical importance should go in here.
 4763: 
 4764: =back
 4765: 
 4766: =head2 General File Helper Routines
 4767: 
 4768: =over 4
 4769: 
 4770: =item *
 4771: 
 4772: getfile($file) : returns the entire contents of a file or -1; it
 4773: properly subscribes to and replicates the file if neccessary.
 4774: 
 4775: =item *
 4776: 
 4777: filelocation($dir,$file) : returns file system location of a file
 4778: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 4779: directory that relative $file lookups are to looked in ($dir of /a/dir
 4780: and a file of ../bob will become /a/bob)
 4781: 
 4782: =item *
 4783: 
 4784: hreflocation($dir,$file) : returns file system location or a URL; same as
 4785: filelocation except for hrefs
 4786: 
 4787: =item *
 4788: 
 4789: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 4790: 
 4791: =back
 4792: 
 4793: =head2 HTTP Helper Routines
 4794: 
 4795: =over 4
 4796: 
 4797: =item *
 4798: 
 4799: escape() : unpack non-word characters into CGI-compatible hex codes
 4800: 
 4801: =item *
 4802: 
 4803: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 4804: 
 4805: =back
 4806: 
 4807: =head1 PRIVATE SUBROUTINES
 4808: 
 4809: =head2 Underlying communication routines (Shouldn't call)
 4810: 
 4811: =over 4
 4812: 
 4813: =item *
 4814: 
 4815: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 4816: 
 4817: =item *
 4818: 
 4819: reply() : uses subreply to send a message to remote machine, logs all failures
 4820: 
 4821: =item *
 4822: 
 4823: critical() : passes a critical message to another server; if cannot
 4824: get through then place message in connection buffer directory and
 4825: returns con_delayed, if incapable of saving message, returns
 4826: con_failed
 4827: 
 4828: =item *
 4829: 
 4830: reconlonc() : tries to reconnect lonc client processes.
 4831: 
 4832: =back
 4833: 
 4834: =head2 Resource Access Logging
 4835: 
 4836: =over 4
 4837: 
 4838: =item *
 4839: 
 4840: flushcourselogs() : flush (save) buffer logs and access logs
 4841: 
 4842: =item *
 4843: 
 4844: courselog($what) : save message for course in hash
 4845: 
 4846: =item *
 4847: 
 4848: courseacclog($what) : save message for course using &courselog().  Perform
 4849: special processing for specific resource types (problems, exams, quizzes, etc).
 4850: 
 4851: =item *
 4852: 
 4853: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 4854: as a PerlChildExitHandler
 4855: 
 4856: =back
 4857: 
 4858: =head2 Other
 4859: 
 4860: =over 4
 4861: 
 4862: =item *
 4863: 
 4864: symblist($mapname,%newhash) : update symbolic storage links
 4865: 
 4866: =back
 4867: 
 4868: =cut

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