File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.415: download - view: text, annotated - select for diffs
Wed Sep 17 17:50:49 2003 UTC (20 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- an even better solution

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

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