File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.428: download - view: text, annotated - select for diffs
Tue Oct 7 07:20:05 2003 UTC (20 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- converted to use GDBM on lonnet caches
- converted metacache to use common caching infrastructure

- this looks like it works well and quickly, I wann do some further testing
  but nothing is blowing up on me

(Probably still need to try this out on s1 just to get an idea at if it scales well I think it will)

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

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