File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.433: download - view: text, annotated - select for diffs
Mon Oct 27 21:59:34 2003 UTC (20 years, 8 months ago) by matthew
Branches: MAIN
CVS tags: HEAD
First swipe at removing keys from the users profile automatically.

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

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