File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.401: download - view: text, annotated - select for diffs
Thu Aug 14 22:23:53 2003 UTC (20 years, 11 months ago) by bowersj2
Branches: MAIN
CVS tags: HEAD
Fix problem when metadata called itself recursively.

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

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