File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.406: download - view: text, annotated - select for diffs
Tue Aug 26 04:56:30 2003 UTC (20 years, 10 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- BUG #2097, localauth should not require a password when doing CSV uploads

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

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