File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.444: download - view: text, annotated - select for diffs
Mon Nov 10 21:50:21 2003 UTC (20 years, 7 months ago) by www
Branches: MAIN
CVS tags: HEAD
When fixing up versions, do not explicitly glue in current version number.

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

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