File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.313: download - view: text, annotated - select for diffs
Mon Dec 9 22:09:58 2002 UTC (21 years, 7 months ago) by matthew
Branches: MAIN
CVS tags: version_0_6, HEAD
Change to &modifyuser.  When creating a user the call to &get('environment'..
does not return an error the way the code seemed to expect it to.  We were
ending up with keys in 'evironment.db' of "error:No such file or directory".

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

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