File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.417: download - view: text, annotated - select for diffs
Fri Sep 19 16:53:35 2003 UTC (20 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- can now successfully devaildate cache entry
- courseresdata successfully converted to use caching structure
- can now cache 'undef' as a value

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

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