File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.372: download - view: text, annotated - select for diffs
Thu May 8 22:23:19 2003 UTC (21 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- put user load on front page
- make userload pretty

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

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