File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.666: download - view: text, annotated - select for diffs
Tue Oct 18 21:29:35 2005 UTC (18 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- hreflocation was brain dead about /uploaded urls
- fixed to use $perlvar for dir paths

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.666 2005/10/18 21:29:35 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Headers;
   35: use HTTP::Date;
   36: # use Date::Parse;
   37: use vars 
   38: qw(%perlvar %hostname %badServerCache %iphost %spareid %hostdom 
   39:    %libserv %pr %prp $memcache %packagetab 
   40:    %courselogs %accesshash %userrolehash %domainrolehash $processmarker $dumpcount 
   41:    %coursedombuf %coursenumbuf %coursehombuf %coursedescrbuf %courseinstcodebuf %courseownerbuf
   42:    %domaindescription %domain_auth_def %domain_auth_arg_def 
   43:    %domain_lang_def %domain_city %domain_longi %domain_lati $tmpdir $_64bit
   44:    %env);
   45: 
   46: use IO::Socket;
   47: use GDBM_File;
   48: use Apache::Constants qw(:common :http);
   49: use HTML::LCParser;
   50: use HTML::Parser;
   51: use Fcntl qw(:flock);
   52: use Apache::lonlocal;
   53: use Storable qw(lock_store lock_nstore lock_retrieve freeze thaw nfreeze);
   54: use Time::HiRes qw( gettimeofday tv_interval );
   55: use Cache::Memcached;
   56: my $readit;
   57: my $max_connection_retries = 10;     # Or some such value.
   58: 
   59: require Exporter;
   60: 
   61: our @ISA = qw (Exporter);
   62: our @EXPORT = qw(%env);
   63: 
   64: =pod
   65: 
   66: =head1 Package Variables
   67: 
   68: These are largely undocumented, so if you decipher one please note it here.
   69: 
   70: =over 4
   71: 
   72: =item $processmarker
   73: 
   74: Contains the time this process was started and this servers host id.
   75: 
   76: =item $dumpcount
   77: 
   78: Counts the number of times a message log flush has been attempted (regardless
   79: of success) by this process.  Used as part of the filename when messages are
   80: delayed.
   81: 
   82: =back
   83: 
   84: =cut
   85: 
   86: 
   87: # --------------------------------------------------------------------- Logging
   88: 
   89: sub logtouch {
   90:     my $execdir=$perlvar{'lonDaemons'};
   91:     unless (-e "$execdir/logs/lonnet.log") {	
   92: 	open(my $fh,">>$execdir/logs/lonnet.log");
   93: 	close $fh;
   94:     }
   95:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
   96:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
   97: }
   98: 
   99: sub logthis {
  100:     my $message=shift;
  101:     my $execdir=$perlvar{'lonDaemons'};
  102:     my $now=time;
  103:     my $local=localtime($now);
  104:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  105: 	print $fh "$local ($$): $message\n";
  106: 	close($fh);
  107:     }
  108:     return 1;
  109: }
  110: 
  111: sub logperm {
  112:     my $message=shift;
  113:     my $execdir=$perlvar{'lonDaemons'};
  114:     my $now=time;
  115:     my $local=localtime($now);
  116:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  117: 	print $fh "$now:$message:$local\n";
  118: 	close($fh);
  119:     }
  120:     return 1;
  121: }
  122: 
  123: # -------------------------------------------------- Non-critical communication
  124: sub subreply {
  125:     my ($cmd,$server)=@_;
  126:     my $peerfile="$perlvar{'lonSockDir'}/$server";
  127:     #
  128:     #  With loncnew process trimming, there's a timing hole between lonc server
  129:     #  process exit and the master server picking up the listen on the AF_UNIX
  130:     #  socket.  In that time interval, a lock file will exist:
  131: 
  132:     my $lockfile=$peerfile.".lock";
  133:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  134: 	sleep(1);
  135:     }
  136:     # At this point, either a loncnew parent is listening or an old lonc
  137:     # or loncnew child is listening so we can connect or everything's dead.
  138:     #
  139:     #   We'll give the connection a few tries before abandoning it.  If
  140:     #   connection is not possible, we'll con_lost back to the client.
  141:     #   
  142:     my $client;
  143:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  144: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  145: 				      Type    => SOCK_STREAM,
  146: 				      Timeout => 10);
  147: 	if($client) {
  148: 	    last;		# Connected!
  149: 	}
  150: 	sleep(1);		# Try again later if failed connection.
  151:     }
  152:     my $answer;
  153:     if ($client) {
  154: 	print $client "$cmd\n";
  155: 	$answer=<$client>;
  156: 	if (!$answer) { $answer="con_lost"; }
  157: 	chomp($answer);
  158:     } else {
  159: 	$answer = 'con_lost';	# Failed connection.
  160:     }
  161:     return $answer;
  162: }
  163: 
  164: sub reply {
  165:     my ($cmd,$server)=@_;
  166:     unless (defined($hostname{$server})) { return 'no_such_host'; }
  167:     my $answer=subreply($cmd,$server);
  168:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  169:        &logthis("<font color=blue>WARNING:".
  170:                 " $cmd to $server returned $answer</font>");
  171:     }
  172:     return $answer;
  173: }
  174: 
  175: # ----------------------------------------------------------- Send USR1 to lonc
  176: 
  177: sub reconlonc {
  178:     my $peerfile=shift;
  179:     &logthis("Trying to reconnect for $peerfile");
  180:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  181:     if (open(my $fh,"<$loncfile")) {
  182: 	my $loncpid=<$fh>;
  183:         chomp($loncpid);
  184:         if (kill 0 => $loncpid) {
  185: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  186:             kill USR1 => $loncpid;
  187:             sleep 1;
  188:             if (-e "$peerfile") { return; }
  189:             &logthis("$peerfile still not there, give it another try");
  190:             sleep 5;
  191:             if (-e "$peerfile") { return; }
  192:             &logthis(
  193:   "<font color=blue>WARNING: $peerfile still not there, giving up</font>");
  194:         } else {
  195: 	    &logthis(
  196:                "<font color=blue>WARNING:".
  197:                " lonc at pid $loncpid not responding, giving up</font>");
  198:         }
  199:     } else {
  200:      &logthis('<font color=blue>WARNING: lonc not running, giving up</font>');
  201:     }
  202: }
  203: 
  204: # ------------------------------------------------------ Critical communication
  205: 
  206: sub critical {
  207:     my ($cmd,$server)=@_;
  208:     unless ($hostname{$server}) {
  209:         &logthis("<font color=blue>WARNING:".
  210:                " Critical message to unknown server ($server)</font>");
  211:         return 'no_such_host';
  212:     }
  213:     my $answer=reply($cmd,$server);
  214:     if ($answer eq 'con_lost') {
  215: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  216: 	my $answer=reply($cmd,$server);
  217:         if ($answer eq 'con_lost') {
  218:             my $now=time;
  219:             my $middlename=$cmd;
  220:             $middlename=substr($middlename,0,16);
  221:             $middlename=~s/\W//g;
  222:             my $dfilename=
  223:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  224:             $dumpcount++;
  225:             {
  226: 		my $dfh;
  227: 		if (open($dfh,">$dfilename")) {
  228: 		    print $dfh "$cmd\n"; 
  229: 		    close($dfh);
  230: 		}
  231:             }
  232:             sleep 2;
  233:             my $wcmd='';
  234:             {
  235: 		my $dfh;
  236: 		if (open($dfh,"<$dfilename")) {
  237: 		    $wcmd=<$dfh>; 
  238: 		    close($dfh);
  239: 		}
  240:             }
  241:             chomp($wcmd);
  242:             if ($wcmd eq $cmd) {
  243: 		&logthis("<font color=blue>WARNING: ".
  244:                          "Connection buffer $dfilename: $cmd</font>");
  245:                 &logperm("D:$server:$cmd");
  246: 	        return 'con_delayed';
  247:             } else {
  248:                 &logthis("<font color=red>CRITICAL:"
  249:                         ." Critical connection failed: $server $cmd</font>");
  250:                 &logperm("F:$server:$cmd");
  251:                 return 'con_failed';
  252:             }
  253:         }
  254:     }
  255:     return $answer;
  256: }
  257: 
  258: # ------------------------------------------- Transfer profile into environment
  259: 
  260: sub transfer_profile_to_env {
  261:     my ($lonidsdir,$handle)=@_;
  262:     my @profile;
  263:     {
  264: 	open(my $idf,"$lonidsdir/$handle.id");
  265: 	flock($idf,LOCK_SH);
  266: 	@profile=<$idf>;
  267: 	close($idf);
  268:     }
  269:     my $envi;
  270:     my %Remove;
  271:     for ($envi=0;$envi<=$#profile;$envi++) {
  272: 	chomp($profile[$envi]);
  273: 	my ($envname,$envvalue)=split(/=/,$profile[$envi]);
  274: 	$env{$envname} = $envvalue;
  275:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  276:             if ($time < time-300) {
  277:                 $Remove{$key}++;
  278:             }
  279:         }
  280:     }
  281:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  282:     foreach my $expired_key (keys(%Remove)) {
  283:         &delenv($expired_key);
  284:     }
  285: }
  286: 
  287: # ---------------------------------------------------------- Append Environment
  288: 
  289: sub appenv {
  290:     my %newenv=@_;
  291:     foreach (keys %newenv) {
  292: 	if (($newenv{$_}=~/^user\.role/) || ($newenv{$_}=~/^user\.priv/)) {
  293:             &logthis("<font color=blue>WARNING: ".
  294:                 "Attempt to modify environment ".$_." to ".$newenv{$_}
  295:                 .'</font>');
  296: 	    delete($newenv{$_});
  297:         } else {
  298:             $env{$_}=$newenv{$_};
  299:         }
  300:     }
  301: 
  302:     my $lockfh;
  303:     unless (open($lockfh,"$env{'user.environment'}")) {
  304: 	return 'error: '.$!;
  305:     }
  306:     unless (flock($lockfh,LOCK_EX)) {
  307:          &logthis("<font color=blue>WARNING: ".
  308:                   'Could not obtain exclusive lock in appenv: '.$!);
  309:          close($lockfh);
  310:          return 'error: '.$!;
  311:     }
  312: 
  313:     my @oldenv;
  314:     {
  315: 	my $fh;
  316: 	unless (open($fh,"$env{'user.environment'}")) {
  317: 	    return 'error: '.$!;
  318: 	}
  319: 	@oldenv=<$fh>;
  320: 	close($fh);
  321:     }
  322:     for (my $i=0; $i<=$#oldenv; $i++) {
  323:         chomp($oldenv[$i]);
  324:         if ($oldenv[$i] ne '') {
  325: 	    my ($name,$value)=split(/=/,$oldenv[$i]);
  326: 	    unless (defined($newenv{$name})) {
  327: 		$newenv{$name}=$value;
  328: 	    }
  329:         }
  330:     }
  331:     {
  332: 	my $fh;
  333: 	unless (open($fh,">$env{'user.environment'}")) {
  334: 	    return 'error';
  335: 	}
  336: 	my $newname;
  337: 	foreach $newname (keys %newenv) {
  338: 	    print $fh "$newname=$newenv{$newname}\n";
  339: 	}
  340: 	close($fh);
  341:     }
  342: 	
  343:     close($lockfh);
  344:     return 'ok';
  345: }
  346: # ----------------------------------------------------- Delete from Environment
  347: 
  348: sub delenv {
  349:     my $delthis=shift;
  350:     my %newenv=();
  351:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  352:         &logthis("<font color=blue>WARNING: ".
  353:                 "Attempt to delete from environment ".$delthis);
  354:         return 'error';
  355:     }
  356:     my @oldenv;
  357:     {
  358: 	my $fh;
  359: 	unless (open($fh,"$env{'user.environment'}")) {
  360: 	    return 'error';
  361: 	}
  362: 	unless (flock($fh,LOCK_SH)) {
  363: 	    &logthis("<font color=blue>WARNING: ".
  364: 		     'Could not obtain shared lock in delenv: '.$!);
  365: 	    close($fh);
  366: 	    return 'error: '.$!;
  367: 	}
  368: 	@oldenv=<$fh>;
  369: 	close($fh);
  370:     }
  371:     {
  372: 	my $fh;
  373: 	unless (open($fh,">$env{'user.environment'}")) {
  374: 	    return 'error';
  375: 	}
  376: 	unless (flock($fh,LOCK_EX)) {
  377: 	    &logthis("<font color=blue>WARNING: ".
  378: 		     'Could not obtain exclusive lock in delenv: '.$!);
  379: 	    close($fh);
  380: 	    return 'error: '.$!;
  381: 	}
  382: 	foreach (@oldenv) {
  383: 	    if ($_=~/^$delthis/) { 
  384:                 my ($key,undef) = split('=',$_);
  385:                 delete($env{$key});
  386:             } else {
  387:                 print $fh $_; 
  388:             }
  389: 	}
  390: 	close($fh);
  391:     }
  392:     return 'ok';
  393: }
  394: 
  395: # ------------------------------------------ Find out current server userload
  396: # there is a copy in lond
  397: sub userload {
  398:     my $numusers=0;
  399:     {
  400: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  401: 	my $filename;
  402: 	my $curtime=time;
  403: 	while ($filename=readdir(LONIDS)) {
  404: 	    if ($filename eq '.' || $filename eq '..') {next;}
  405: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  406: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  407: 	}
  408: 	closedir(LONIDS);
  409:     }
  410:     my $userloadpercent=0;
  411:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  412:     if ($maxuserload) {
  413: 	$userloadpercent=100*$numusers/$maxuserload;
  414:     }
  415:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  416:     return $userloadpercent;
  417: }
  418: 
  419: # ------------------------------------------ Fight off request when overloaded
  420: 
  421: sub overloaderror {
  422:     my ($r,$checkserver)=@_;
  423:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  424:     my $loadavg;
  425:     if ($checkserver eq $perlvar{'lonHostID'}) {
  426:        open(my $loadfile,'/proc/loadavg');
  427:        $loadavg=<$loadfile>;
  428:        $loadavg =~ s/\s.*//g;
  429:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  430:        close($loadfile);
  431:     } else {
  432:        $loadavg=&reply('load',$checkserver);
  433:     }
  434:     my $overload=$loadavg-100;
  435:     if ($overload>0) {
  436: 	$r->err_headers_out->{'Retry-After'}=$overload;
  437:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  438:         return 413;
  439:     }    
  440:     return '';
  441: }
  442: 
  443: # ------------------------------ Find server with least workload from spare.tab
  444: 
  445: sub spareserver {
  446:     my ($loadpercent,$userloadpercent) = @_;
  447:     my $tryserver;
  448:     my $spareserver='';
  449:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  450:     my $lowestserver=$loadpercent > $userloadpercent?
  451: 	             $loadpercent :  $userloadpercent;
  452:     foreach $tryserver (keys %spareid) {
  453: 	my $loadans=reply('load',$tryserver);
  454: 	my $userloadans=reply('userload',$tryserver);
  455: 	if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  456: 	    next; #didn't get a number from the server
  457: 	}
  458: 	my $answer;
  459: 	if ($loadans =~ /\d/) {
  460: 	    if ($userloadans =~ /\d/) {
  461: 		#both are numbers, pick the bigger one
  462: 		$answer=$loadans > $userloadans?
  463: 		    $loadans :  $userloadans;
  464: 	    } else {
  465: 		$answer = $loadans;
  466: 	    }
  467: 	} else {
  468: 	    $answer = $userloadans;
  469: 	}
  470: 	if (($answer =~ /\d/) && ($answer<$lowestserver)) {
  471: 	    $spareserver="http://$hostname{$tryserver}";
  472: 	    $lowestserver=$answer;
  473: 	}
  474:     }
  475:     return $spareserver;
  476: }
  477: 
  478: # --------------------------------------------- Try to change a user's password
  479: 
  480: sub changepass {
  481:     my ($uname,$udom,$currentpass,$newpass,$server)=@_;
  482:     $currentpass = &escape($currentpass);
  483:     $newpass     = &escape($newpass);
  484:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass",
  485: 		       $server);
  486:     if (! $answer) {
  487: 	&logthis("No reply on password change request to $server ".
  488: 		 "by $uname in domain $udom.");
  489:     } elsif ($answer =~ "^ok") {
  490:         &logthis("$uname in $udom successfully changed their password ".
  491: 		 "on $server.");
  492:     } elsif ($answer =~ "^pwchange_failure") {
  493: 	&logthis("$uname in $udom was unable to change their password ".
  494: 		 "on $server.  The action was blocked by either lcpasswd ".
  495: 		 "or pwchange");
  496:     } elsif ($answer =~ "^non_authorized") {
  497:         &logthis("$uname in $udom did not get their password correct when ".
  498: 		 "attempting to change it on $server.");
  499:     } elsif ($answer =~ "^auth_mode_error") {
  500:         &logthis("$uname in $udom attempted to change their password despite ".
  501: 		 "not being locally or internally authenticated on $server.");
  502:     } elsif ($answer =~ "^unknown_user") {
  503:         &logthis("$uname in $udom attempted to change their password ".
  504: 		 "on $server but were unable to because $server is not ".
  505: 		 "their home server.");
  506:     } elsif ($answer =~ "^refused") {
  507: 	&logthis("$server refused to change $uname in $udom password because ".
  508: 		 "it was sent an unencrypted request to change the password.");
  509:     }
  510:     return $answer;
  511: }
  512: 
  513: # ----------------------- Try to determine user's current authentication scheme
  514: 
  515: sub queryauthenticate {
  516:     my ($uname,$udom)=@_;
  517:     my $uhome=&homeserver($uname,$udom);
  518:     if (!$uhome) {
  519: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  520: 	return 'no_host';
  521:     }
  522:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  523:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  524: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  525:     }
  526:     return $answer;
  527: }
  528: 
  529: # --------- Try to authenticate user from domain's lib servers (first this one)
  530: 
  531: sub authenticate {
  532:     my ($uname,$upass,$udom)=@_;
  533:     $upass=escape($upass);
  534:     $uname=~s/\W//g;
  535:     my $uhome=&homeserver($uname,$udom);
  536:     if (!$uhome) {
  537: 	&logthis("User $uname at $udom is unknown in authenticate");
  538: 	return 'no_host';
  539:     }
  540:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  541:     if ($answer eq 'authorized') {
  542: 	&logthis("User $uname at $udom authorized by $uhome"); 
  543: 	return $uhome; 
  544:     }
  545:     if ($answer eq 'non_authorized') {
  546: 	&logthis("User $uname at $udom rejected by $uhome");
  547: 	return 'no_host'; 
  548:     }
  549:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  550:     return 'no_host';
  551: }
  552: 
  553: # ---------------------- Find the homebase for a user from domain's lib servers
  554: 
  555: my %homecache;
  556: sub homeserver {
  557:     my ($uname,$udom,$ignoreBadCache)=@_;
  558:     my $index="$uname:$udom";
  559: 
  560:     if (exists($homecache{$index})) { return $homecache{$index}; }
  561:     my $tryserver;
  562:     foreach $tryserver (keys %libserv) {
  563:         next if ($ignoreBadCache ne 'true' && 
  564: 		 exists($badServerCache{$tryserver}));
  565: 	if ($hostdom{$tryserver} eq $udom) {
  566:            my $answer=reply("home:$udom:$uname",$tryserver);
  567:            if ($answer eq 'found') { 
  568: 	       return $homecache{$index}=$tryserver;
  569:            } elsif ($answer eq 'no_host') {
  570: 	       $badServerCache{$tryserver}=1;
  571:            }
  572:        }
  573:     }    
  574:     return 'no_host';
  575: }
  576: 
  577: # ------------------------------------- Find the usernames behind a list of IDs
  578: 
  579: sub idget {
  580:     my ($udom,@ids)=@_;
  581:     my %returnhash=();
  582:     
  583:     my $tryserver;
  584:     foreach $tryserver (keys %libserv) {
  585:        if ($hostdom{$tryserver} eq $udom) {
  586: 	  my $idlist=join('&',@ids);
  587:           $idlist=~tr/A-Z/a-z/; 
  588: 	  my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  589:           my @answer=();
  590:           if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  591: 	      @answer=split(/\&/,$reply);
  592:           }                    ;
  593:           my $i;
  594:           for ($i=0;$i<=$#ids;$i++) {
  595:               if ($answer[$i]) {
  596: 		  $returnhash{$ids[$i]}=$answer[$i];
  597:               } 
  598:           }
  599:        }
  600:     }    
  601:     return %returnhash;
  602: }
  603: 
  604: # ------------------------------------- Find the IDs behind a list of usernames
  605: 
  606: sub idrget {
  607:     my ($udom,@unames)=@_;
  608:     my %returnhash=();
  609:     foreach (@unames) {
  610:         $returnhash{$_}=(&userenvironment($udom,$_,'id'))[1];
  611:     }
  612:     return %returnhash;
  613: }
  614: 
  615: # ------------------------------- Store away a list of names and associated IDs
  616: 
  617: sub idput {
  618:     my ($udom,%ids)=@_;
  619:     my %servers=();
  620:     foreach (keys %ids) {
  621: 	&cput('environment',{'id'=>$ids{$_}},$udom,$_);
  622:         my $uhom=&homeserver($_,$udom);
  623:         if ($uhom ne 'no_host') {
  624:             my $id=&escape($ids{$_});
  625:             $id=~tr/A-Z/a-z/;
  626:             my $unam=&escape($_);
  627: 	    if ($servers{$uhom}) {
  628: 		$servers{$uhom}.='&'.$id.'='.$unam;
  629:             } else {
  630:                 $servers{$uhom}=$id.'='.$unam;
  631:             }
  632:         }
  633:     }
  634:     foreach (keys %servers) {
  635:         &critical('idput:'.$udom.':'.$servers{$_},$_);
  636:     }
  637: }
  638: 
  639: # --------------------------------------------------- Assign a key to a student
  640: 
  641: sub assign_access_key {
  642: #
  643: # a valid key looks like uname:udom#comments
  644: # comments are being appended
  645: #
  646:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  647:     $kdom=
  648:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  649:     $knum=
  650:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  651:     $cdom=
  652:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  653:     $cnum=
  654:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  655:     $udom=$env{'user.name'} unless (defined($udom));
  656:     $uname=$env{'user.domain'} unless (defined($uname));
  657:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  658:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  659:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  660:                                                   # assigned to this person
  661:                                                   # - this should not happen,
  662:                                                   # unless something went wrong
  663:                                                   # the first time around
  664: # ready to assign
  665:         $logentry=$1.'; '.$logentry;
  666:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  667:                                                  $kdom,$knum) eq 'ok') {
  668: # key now belongs to user
  669: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  670:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  671:                 &appenv('environment.'.$envkey => $ckey);
  672:                 return 'ok';
  673:             } else {
  674:                 return 
  675:   'error: Count not permanently assign key, will need to be re-entered later.';
  676: 	    }
  677:         } else {
  678:             return 'error: Could not assign key, try again later.';
  679:         }
  680:     } elsif (!$existing{$ckey}) {
  681: # the key does not exist
  682: 	return 'error: The key does not exist';
  683:     } else {
  684: # the key is somebody else's
  685: 	return 'error: The key is already in use';
  686:     }
  687: }
  688: 
  689: # ------------------------------------------ put an additional comment on a key
  690: 
  691: sub comment_access_key {
  692: #
  693: # a valid key looks like uname:udom#comments
  694: # comments are being appended
  695: #
  696:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  697:     $cdom=
  698:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  699:     $cnum=
  700:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  701:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  702:     if ($existing{$ckey}) {
  703:         $existing{$ckey}.='; '.$logentry;
  704: # ready to assign
  705:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  706:                                                  $cdom,$cnum) eq 'ok') {
  707: 	    return 'ok';
  708:         } else {
  709: 	    return 'error: Count not store comment.';
  710:         }
  711:     } else {
  712: # the key does not exist
  713: 	return 'error: The key does not exist';
  714:     }
  715: }
  716: 
  717: # ------------------------------------------------------ Generate a set of keys
  718: 
  719: sub generate_access_keys {
  720:     my ($number,$cdom,$cnum,$logentry)=@_;
  721:     $cdom=
  722:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  723:     $cnum=
  724:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  725:     unless (&allowed('mky',$cdom)) { return 0; }
  726:     unless (($cdom) && ($cnum)) { return 0; }
  727:     if ($number>10000) { return 0; }
  728:     sleep(2); # make sure don't get same seed twice
  729:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  730:     my $total=0;
  731:     for (my $i=1;$i<=$number;$i++) {
  732:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  733:                   sprintf("%lx",int(100000*rand)).'-'.
  734:                   sprintf("%lx",int(100000*rand));
  735:        $newkey=~s/1/g/g; # folks mix up 1 and l
  736:        $newkey=~s/0/h/g; # and also 0 and O
  737:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  738:        if ($existing{$newkey}) {
  739:            $i--;
  740:        } else {
  741: 	  if (&put('accesskeys',
  742:               { $newkey => '# generated '.localtime().
  743:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  744:                            '; '.$logentry },
  745: 		   $cdom,$cnum) eq 'ok') {
  746:               $total++;
  747: 	  }
  748:        }
  749:     }
  750:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  751:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  752:     return $total;
  753: }
  754: 
  755: # ------------------------------------------------------- Validate an accesskey
  756: 
  757: sub validate_access_key {
  758:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  759:     $cdom=
  760:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  761:     $cnum=
  762:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  763:     $udom=$env{'user.domain'} unless (defined($udom));
  764:     $uname=$env{'user.name'} unless (defined($uname));
  765:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  766:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  767: }
  768: 
  769: # ------------------------------------- Find the section of student in a course
  770: sub devalidate_getsection_cache {
  771:     my ($udom,$unam,$courseid)=@_;
  772:     $courseid=~s/\_/\//g;
  773:     $courseid=~s/^(\w)/\/$1/;
  774:     my $hashid="$udom:$unam:$courseid";
  775:     &devalidate_cache_new('getsection',$hashid);
  776: }
  777: 
  778: sub getsection {
  779:     my ($udom,$unam,$courseid)=@_;
  780:     my $cachetime=1800;
  781:     $courseid=~s/\_/\//g;
  782:     $courseid=~s/^(\w)/\/$1/;
  783: 
  784:     my $hashid="$udom:$unam:$courseid";
  785:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
  786:     if (defined($cached)) { return $result; }
  787: 
  788:     my %Pending; 
  789:     my %Expired;
  790:     #
  791:     # Each role can either have not started yet (pending), be active, 
  792:     #    or have expired.
  793:     #
  794:     # If there is an active role, we are done.
  795:     #
  796:     # If there is more than one role which has not started yet, 
  797:     #     choose the one which will start sooner
  798:     # If there is one role which has not started yet, return it.
  799:     #
  800:     # If there is more than one expired role, choose the one which ended last.
  801:     # If there is a role which has expired, return it.
  802:     #
  803:     foreach (split(/\&/,&reply('dump:'.$udom.':'.$unam.':roles',
  804:                         &homeserver($unam,$udom)))) {
  805:         my ($key,$value)=split(/\=/,$_);
  806:         $key=&unescape($key);
  807:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
  808:         my $section=$1;
  809:         if ($key eq $courseid.'_st') { $section=''; }
  810:         my ($dummy,$end,$start)=split(/\_/,&unescape($value));
  811:         my $now=time;
  812:         if (defined($end) && $end && ($now > $end)) {
  813:             $Expired{$end}=$section;
  814:             next;
  815:         }
  816:         if (defined($start) && $start && ($now < $start)) {
  817:             $Pending{$start}=$section;
  818:             next;
  819:         }
  820:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
  821:     }
  822:     #
  823:     # Presumedly there will be few matching roles from the above
  824:     # loop and the sorting time will be negligible.
  825:     if (scalar(keys(%Pending))) {
  826:         my ($time) = sort {$a <=> $b} keys(%Pending);
  827:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
  828:     } 
  829:     if (scalar(keys(%Expired))) {
  830:         my @sorted = sort {$a <=> $b} keys(%Expired);
  831:         my $time = pop(@sorted);
  832:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
  833:     }
  834:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
  835: }
  836: 
  837: sub save_cache {
  838:     my ($r)=@_;
  839:     if (! $r->is_initial_req()) { return DECLINED; }
  840:     &purge_remembered();
  841:     undef(%env);
  842:     return OK;
  843: }
  844: 
  845: my $to_remember=-1;
  846: my %remembered;
  847: my %accessed;
  848: my $kicks=0;
  849: my $hits=0;
  850: sub devalidate_cache_new {
  851:     my ($name,$id,$debug) = @_;
  852:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
  853:     $id=&escape($name.':'.$id);
  854:     $memcache->delete($id);
  855:     delete($remembered{$id});
  856:     delete($accessed{$id});
  857: }
  858: 
  859: sub is_cached_new {
  860:     my ($name,$id,$debug) = @_;
  861:     $id=&escape($name.':'.$id);
  862:     if (exists($remembered{$id})) {
  863: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
  864: 	$accessed{$id}=[&gettimeofday()];
  865: 	$hits++;
  866: 	return ($remembered{$id},1);
  867:     }
  868:     my $value = $memcache->get($id);
  869:     if (!(defined($value))) {
  870: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
  871: 	return (undef,undef);
  872:     }
  873:     if ($value eq '__undef__') {
  874: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
  875: 	$value=undef;
  876:     }
  877:     &make_room($id,$value,$debug);
  878:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
  879:     return ($value,1);
  880: }
  881: 
  882: sub do_cache_new {
  883:     my ($name,$id,$value,$time,$debug) = @_;
  884:     $id=&escape($name.':'.$id);
  885:     my $setvalue=$value;
  886:     if (!defined($setvalue)) {
  887: 	$setvalue='__undef__';
  888:     }
  889:     if (!defined($time) ) {
  890: 	$time=600;
  891:     }
  892:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
  893:     $memcache->set($id,$setvalue,$time);
  894:     # need to make a copy of $value
  895:     #&make_room($id,$value,$debug);
  896:     return $value;
  897: }
  898: 
  899: sub make_room {
  900:     my ($id,$value,$debug)=@_;
  901:     $remembered{$id}=$value;
  902:     if ($to_remember<0) { return; }
  903:     $accessed{$id}=[&gettimeofday()];
  904:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
  905:     my $to_kick;
  906:     my $max_time=0;
  907:     foreach my $other (keys(%accessed)) {
  908: 	if (&tv_interval($accessed{$other}) > $max_time) {
  909: 	    $to_kick=$other;
  910: 	    $max_time=&tv_interval($accessed{$other});
  911: 	}
  912:     }
  913:     delete($remembered{$to_kick});
  914:     delete($accessed{$to_kick});
  915:     $kicks++;
  916:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
  917:     return;
  918: }
  919: 
  920: sub purge_remembered {
  921:     #&logthis("Tossing ".scalar(keys(%remembered)));
  922:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
  923:     undef(%remembered);
  924:     undef(%accessed);
  925: }
  926: # ------------------------------------- Read an entry from a user's environment
  927: 
  928: sub userenvironment {
  929:     my ($udom,$unam,@what)=@_;
  930:     my %returnhash=();
  931:     my @answer=split(/\&/,
  932:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
  933:                       &homeserver($unam,$udom)));
  934:     my $i;
  935:     for ($i=0;$i<=$#what;$i++) {
  936: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
  937:     }
  938:     return %returnhash;
  939: }
  940: 
  941: # ---------------------------------------------------------- Get a studentphoto
  942: sub studentphoto {
  943:     my ($udom,$unam,$ext) = @_;
  944:     my $home=&Apache::lonnet::homeserver($unam,$udom);
  945:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext",$home);
  946:     my $url="/uploaded/$udom/$unam/internal/studentphoto.".$ext;
  947:     if ($ret ne 'ok') {
  948: 	return '/adm/lonKaputt/lonlogo_broken.gif';
  949:     }
  950:     my $tokenurl=&Apache::lonnet::tokenwrapper($url);
  951:     return $tokenurl;
  952: }
  953: 
  954: # -------------------------------------------------------------------- New chat
  955: 
  956: sub chatsend {
  957:     my ($newentry,$anon)=@_;
  958:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
  959:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
  960:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
  961:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
  962: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
  963: 		   &escape($newentry)),$chome);
  964: }
  965: 
  966: # ------------------------------------------ Find current version of a resource
  967: 
  968: sub getversion {
  969:     my $fname=&clutter(shift);
  970:     unless ($fname=~/^\/res\//) { return -1; }
  971:     return &currentversion(&filelocation('',$fname));
  972: }
  973: 
  974: sub currentversion {
  975:     my $fname=shift;
  976:     my ($result,$cached)=&is_cached_new('resversion',$fname);
  977:     if (defined($cached)) { return $result; }
  978:     my $author=$fname;
  979:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
  980:     my ($udom,$uname)=split(/\//,$author);
  981:     my $home=homeserver($uname,$udom);
  982:     if ($home eq 'no_host') { 
  983:         return -1; 
  984:     }
  985:     my $answer=reply("currentversion:$fname",$home);
  986:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
  987: 	return -1;
  988:     }
  989:     return &do_cache_new('resversion',$fname,$answer,600);
  990: }
  991: 
  992: # ----------------------------- Subscribe to a resource, return URL if possible
  993: 
  994: sub subscribe {
  995:     my $fname=shift;
  996:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
  997:     $fname=~s/[\n\r]//g;
  998:     my $author=$fname;
  999:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1000:     my ($udom,$uname)=split(/\//,$author);
 1001:     my $home=homeserver($uname,$udom);
 1002:     if ($home eq 'no_host') {
 1003:         return 'not_found';
 1004:     }
 1005:     my $answer=reply("sub:$fname",$home);
 1006:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1007: 	$answer.=' by '.$home;
 1008:     }
 1009:     return $answer;
 1010: }
 1011:     
 1012: # -------------------------------------------------------------- Replicate file
 1013: 
 1014: sub repcopy {
 1015:     my $filename=shift;
 1016:     $filename=~s/\/+/\//g;
 1017:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1018:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1019:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1020: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1021: 	return &repcopy_userfile($filename);
 1022:     }
 1023:     $filename=~s/[\n\r]//g;
 1024:     my $transname="$filename.in.transfer";
 1025:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1026:     my $remoteurl=subscribe($filename);
 1027:     if ($remoteurl =~ /^con_lost by/) {
 1028: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1029:            return 'unavailable';
 1030:     } elsif ($remoteurl eq 'not_found') {
 1031: 	   #&logthis("Subscribe returned not_found: $filename");
 1032: 	   return 'not_found';
 1033:     } elsif ($remoteurl =~ /^rejected by/) {
 1034: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1035:            return 'forbidden';
 1036:     } elsif ($remoteurl eq 'directory') {
 1037:            return 'ok';
 1038:     } else {
 1039:         my $author=$filename;
 1040:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1041:         my ($udom,$uname)=split(/\//,$author);
 1042:         my $home=homeserver($uname,$udom);
 1043:         unless ($home eq $perlvar{'lonHostID'}) {
 1044:            my @parts=split(/\//,$filename);
 1045:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1046:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1047:                &logthis("Malconfiguration for replication: $filename");
 1048: 	       return 'bad_request';
 1049:            }
 1050:            my $count;
 1051:            for ($count=5;$count<$#parts;$count++) {
 1052:                $path.="/$parts[$count]";
 1053:                if ((-e $path)!=1) {
 1054: 		   mkdir($path,0777);
 1055:                }
 1056:            }
 1057:            my $ua=new LWP::UserAgent;
 1058:            my $request=new HTTP::Request('GET',"$remoteurl");
 1059:            my $response=$ua->request($request,$transname);
 1060:            if ($response->is_error()) {
 1061: 	       unlink($transname);
 1062:                my $message=$response->status_line;
 1063:                &logthis("<font color=blue>WARNING:"
 1064:                        ." LWP get: $message: $filename</font>");
 1065:                return 'unavailable';
 1066:            } else {
 1067: 	       if ($remoteurl!~/\.meta$/) {
 1068:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1069:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1070:                   if ($mresponse->is_error()) {
 1071: 		      unlink($filename.'.meta');
 1072:                       &logthis(
 1073:                      "<font color=yellow>INFO: No metadata: $filename</font>");
 1074:                   }
 1075: 	       }
 1076:                rename($transname,$filename);
 1077:                return 'ok';
 1078:            }
 1079:        }
 1080:     }
 1081: }
 1082: 
 1083: # ------------------------------------------------ Get server side include body
 1084: sub ssi_body {
 1085:     my ($filelink,%form)=@_;
 1086:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1087:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1088:     }
 1089:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1090:                                      &ssi($filelink,%form));
 1091:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+// END LON-CAPA Internal\s*(-->)?\s||gs;
 1092:     $output=~s/^.*?\<body[^\>]*\>//si;
 1093:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1094:     return $output;
 1095: }
 1096: 
 1097: # --------------------------------------------------------- Server Side Include
 1098: 
 1099: sub ssi {
 1100: 
 1101:     my ($fn,%form)=@_;
 1102: 
 1103:     my $ua=new LWP::UserAgent;
 1104:     
 1105:     my $request;
 1106:     
 1107:     if (%form) {
 1108:       $request=new HTTP::Request('POST',"http://".$ENV{'HTTP_HOST'}.$fn);
 1109:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1110:     } else {
 1111:       $request=new HTTP::Request('GET',"http://".$ENV{'HTTP_HOST'}.$fn);
 1112:     }
 1113: 
 1114:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1115:     my $response=$ua->request($request);
 1116: 
 1117:     return $response->content;
 1118: }
 1119: 
 1120: sub externalssi {
 1121:     my ($url)=@_;
 1122:     my $ua=new LWP::UserAgent;
 1123:     my $request=new HTTP::Request('GET',$url);
 1124:     my $response=$ua->request($request);
 1125:     return $response->content;
 1126: }
 1127: 
 1128: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1129: 
 1130: sub allowuploaded {
 1131:     my ($srcurl,$url)=@_;
 1132:     $url=&clutter(&declutter($url));
 1133:     my $dir=$url;
 1134:     $dir=~s/\/[^\/]+$//;
 1135:     my %httpref=();
 1136:     my $httpurl=&hreflocation('',$url);
 1137:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1138:     &Apache::lonnet::appenv(%httpref);
 1139: }
 1140: 
 1141: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1142: # input: action, courseID, current domain, intended
 1143: #        path to file, source of file, instruction to parse file for objects,
 1144: #        ref to hash for embedded objects,
 1145: #        ref to hash for codebase of java objects.
 1146: #
 1147: # output: url to file (if action was uploaddoc), 
 1148: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1149: #
 1150: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1151: # course.
 1152: #
 1153: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1154: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1155: #          course's home server.
 1156: #
 1157: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1158: #          be copied from $source (current location) to 
 1159: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1160: #         and will then be copied to
 1161: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1162: #         course's home server.
 1163: #
 1164: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1165: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1166: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1167: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1168: #         in course's home server.
 1169: #
 1170: 
 1171: sub process_coursefile {
 1172:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1173:     my $fetchresult;
 1174:     my $home=&homeserver($docuname,$docudom);
 1175:     if ($action eq 'propagate') {
 1176:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1177: 			     $home);
 1178:     } else {
 1179:         my $fetchresult = '';
 1180:         my $fpath = '';
 1181:         my $fname = $file;
 1182:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1183:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1184:         my $filepath = &build_filepath($fpath);
 1185:         if ($action eq 'copy') {
 1186:             if ($source eq '') {
 1187:                 $fetchresult = 'no source file';
 1188:                 return $fetchresult;
 1189:             } else {
 1190:                 my $destination = $filepath.'/'.$fname;
 1191:                 rename($source,$destination);
 1192:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1193:                                  $home);
 1194:             }
 1195:         } elsif ($action eq 'uploaddoc') {
 1196:             open(my $fh,'>'.$filepath.'/'.$fname);
 1197:             print $fh $env{'form.'.$source};
 1198:             close($fh);
 1199:             if ($parser eq 'parse') {
 1200:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1201:                 unless ($parse_result eq 'ok') {
 1202:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1203:                 }
 1204:             }
 1205:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1206:                                  $home);
 1207:             if ($fetchresult eq 'ok') {
 1208:                 return '/uploaded/'.$fpath.'/'.$fname;
 1209:             } else {
 1210:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1211:                         ' to host '.$home.': '.$fetchresult);
 1212:                 return '/adm/notfound.html';
 1213:             }
 1214:         }
 1215:     }
 1216:     unless ( $fetchresult eq 'ok') {
 1217:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1218:              ' to host '.$home.': '.$fetchresult);
 1219:     }
 1220:     return $fetchresult;
 1221: }
 1222: 
 1223: sub build_filepath {
 1224:     my ($fpath) = @_;
 1225:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1226:     unless ($fpath eq '') {
 1227:         my @parts=split('/',$fpath);
 1228:         foreach my $part (@parts) {
 1229:             $filepath.= '/'.$part;
 1230:             if ((-e $filepath)!=1) {
 1231:                 mkdir($filepath,0777);
 1232:             }
 1233:         }
 1234:     }
 1235:     return $filepath;
 1236: }
 1237: 
 1238: sub store_edited_file {
 1239:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1240:     my $file = $primary_url;
 1241:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1242:     my $fpath = '';
 1243:     my $fname = $file;
 1244:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1245:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1246:     my $filepath = &build_filepath($fpath);
 1247:     open(my $fh,'>'.$filepath.'/'.$fname);
 1248:     print $fh $content;
 1249:     close($fh);
 1250:     my $home=&homeserver($docuname,$docudom);
 1251:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1252: 			  $home);
 1253:     if ($$fetchresult eq 'ok') {
 1254:         return '/uploaded/'.$fpath.'/'.$fname;
 1255:     } else {
 1256:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1257: 		 ' to host '.$home.': '.$$fetchresult);
 1258:         return '/adm/notfound.html';
 1259:     }
 1260: }
 1261: 
 1262: sub clean_filename {
 1263:     my ($fname)=@_;
 1264: # Replace Windows backslashes by forward slashes
 1265:     $fname=~s/\\/\//g;
 1266: # Get rid of everything but the actual filename
 1267:     $fname=~s/^.*\/([^\/]+)$/$1/;
 1268: # Replace spaces by underscores
 1269:     $fname=~s/\s+/\_/g;
 1270: # Replace all other weird characters by nothing
 1271:     $fname=~s/[^\w\.\-]//g;
 1272: # Replace all .\d. sequences with _\d. so they no longer look like version
 1273: # numbers
 1274:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1275:     return $fname;
 1276: }
 1277: 
 1278: # --------------- Take an uploaded file and put it into the userfiles directory
 1279: # input: name of form element, coursedoc=1 means this is for the course
 1280: # output: url of file in userspace
 1281: 
 1282: 
 1283: sub userfileupload {
 1284:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase)=@_;
 1285:     if (!defined($subdir)) { $subdir='unknown'; }
 1286:     my $fname=$env{'form.'.$formname.'.filename'};
 1287:     $fname=&clean_filename($fname);
 1288: # See if there is anything left
 1289:     unless ($fname) { return 'error: no uploaded file'; }
 1290:     chop($env{'form.'.$formname});
 1291:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1292:         my $now = time;
 1293:         my $filepath = 'tmp/helprequests/'.$now;
 1294:         my @parts=split(/\//,$filepath);
 1295:         my $fullpath = $perlvar{'lonDaemons'};
 1296:         for (my $i=0;$i<@parts;$i++) {
 1297:             $fullpath .= '/'.$parts[$i];
 1298:             if ((-e $fullpath)!=1) {
 1299:                 mkdir($fullpath,0777);
 1300:             }
 1301:         }
 1302:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1303:         print $fh $env{'form.'.$formname};
 1304:         close($fh);
 1305:         return $fullpath.'/'.$fname; 
 1306:     }
 1307: # Create the directory if not present
 1308:     $fname="$subdir/$fname";
 1309:     if ($coursedoc) {
 1310: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1311: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1312:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1313:             return &finishuserfileupload($docuname,$docudom,
 1314: 					 $formname,$fname,$parser,$allfiles,
 1315: 					 $codebase);
 1316:         } else {
 1317:             $fname=$env{'form.folder'}.'/'.$fname;
 1318:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1319: 				       $fname,$formname,$parser,
 1320: 				       $allfiles,$codebase);
 1321:         }
 1322:     } else {
 1323:         my $docuname=$env{'user.name'};
 1324:         my $docudom=$env{'user.domain'};
 1325: 	return &finishuserfileupload($docuname,$docudom,$formname,
 1326: 				     $fname,$parser,$allfiles,$codebase);
 1327:     }
 1328: }
 1329: 
 1330: sub finishuserfileupload {
 1331:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase) = @_;
 1332:     my $path=$docudom.'/'.$docuname.'/';
 1333:     my $filepath=$perlvar{'lonDocRoot'};
 1334:     my ($fnamepath,$file);
 1335:     $file=$fname;
 1336:     if ($fname=~m|/|) {
 1337:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1338: 	$path.=$fnamepath.'/';
 1339:     }
 1340:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1341:     my $count;
 1342:     for ($count=4;$count<=$#parts;$count++) {
 1343:         $filepath.="/$parts[$count]";
 1344:         if ((-e $filepath)!=1) {
 1345: 	    mkdir($filepath,0777);
 1346:         }
 1347:     }
 1348: # Save the file
 1349:     {
 1350: 	open(FH,'>'.$filepath.'/'.$file);
 1351: 	print FH $env{'form.'.$formname};
 1352: 	close(FH);
 1353:     }
 1354:     if ($parser eq 'parse') {
 1355:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1356: 						   $codebase);
 1357:         unless ($parse_result eq 'ok') {
 1358:             &logthis('Failed to parse '.$filepath.$file.
 1359: 		     ' for embedded media: '.$parse_result); 
 1360:         }
 1361:     }
 1362: # Notify homeserver to grep it
 1363: #
 1364:     my $docuhome=&homeserver($docuname,$docudom);
 1365:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1366:     if ($fetchresult eq 'ok') {
 1367: #
 1368: # Return the URL to it
 1369:         return '/uploaded/'.$path.$file;
 1370:     } else {
 1371:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1372: 		 ': '.$fetchresult);
 1373:         return '/adm/notfound.html';
 1374:     }    
 1375: }
 1376: 
 1377: sub extract_embedded_items {
 1378:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1379:     my @state = ();
 1380:     my %javafiles = (
 1381:                       codebase => '',
 1382:                       code => '',
 1383:                       archive => ''
 1384:                     );
 1385:     my %mediafiles = (
 1386:                       src => '',
 1387:                       movie => '',
 1388:                      );
 1389:     my $p;
 1390:     if ($content) {
 1391:         $p = HTML::LCParser->new($content);
 1392:     } else {
 1393:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1394:     }
 1395:     while (my $t=$p->get_token()) {
 1396: 	if ($t->[0] eq 'S') {
 1397: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1398: 	    push (@state, $tagname);
 1399:             if (lc($tagname) eq 'allow') {
 1400:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1401:             }
 1402: 	    if (lc($tagname) eq 'img') {
 1403: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1404: 	    }
 1405:             if (lc($tagname) eq 'script') {
 1406:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1407:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1408:                 } else {
 1409:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1410:                 }
 1411:             }
 1412:             if (lc($tagname) eq 'link') {
 1413:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1414:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1415:                 }
 1416:             }
 1417: 	    if (lc($tagname) eq 'object' ||
 1418: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1419: 		foreach my $item (keys(%javafiles)) {
 1420: 		    $javafiles{$item} = '';
 1421: 		}
 1422: 	    }
 1423: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1424: 		my $name = lc($attr->{'name'});
 1425: 		foreach my $item (keys(%javafiles)) {
 1426: 		    if ($name eq $item) {
 1427: 			$javafiles{$item} = $attr->{'value'};
 1428: 			last;
 1429: 		    }
 1430: 		}
 1431: 		foreach my $item (keys(%mediafiles)) {
 1432: 		    if ($name eq $item) {
 1433: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1434: 			last;
 1435: 		    }
 1436: 		}
 1437: 	    }
 1438: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1439: 		foreach my $item (keys(%javafiles)) {
 1440: 		    if ($attr->{$item}) {
 1441: 			$javafiles{$item} = $attr->{$item};
 1442: 			last;
 1443: 		    }
 1444: 		}
 1445: 		foreach my $item (keys(%mediafiles)) {
 1446: 		    if ($attr->{$item}) {
 1447: 			&add_filetype($allfiles,$attr->{$item},$item);
 1448: 			last;
 1449: 		    }
 1450: 		}
 1451: 	    }
 1452: 	} elsif ($t->[0] eq 'E') {
 1453: 	    my ($tagname) = ($t->[1]);
 1454: 	    if ($javafiles{'codebase'} ne '') {
 1455: 		$javafiles{'codebase'} .= '/';
 1456: 	    }  
 1457: 	    if (lc($tagname) eq 'applet' ||
 1458: 		lc($tagname) eq 'object' ||
 1459: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1460: 		) {
 1461: 		foreach my $item (keys(%javafiles)) {
 1462: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1463: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1464: 			&add_filetype($allfiles,$file,$item);
 1465: 		    }
 1466: 		}
 1467: 	    } 
 1468: 	    pop @state;
 1469: 	}
 1470:     }
 1471:     return 'ok';
 1472: }
 1473: 
 1474: sub add_filetype {
 1475:     my ($allfiles,$file,$type)=@_;
 1476:     if (exists($allfiles->{$file})) {
 1477: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1478: 	    push(@{$allfiles->{$file}}, &escape($type));
 1479: 	}
 1480:     } else {
 1481: 	@{$allfiles->{$file}} = (&escape($type));
 1482:     }
 1483: }
 1484: 
 1485: sub removeuploadedurl {
 1486:     my ($url)=@_;
 1487:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1488:     return &removeuserfile($uname,$udom,$fname);
 1489: }
 1490: 
 1491: sub removeuserfile {
 1492:     my ($docuname,$docudom,$fname)=@_;
 1493:     my $home=&homeserver($docuname,$docudom);
 1494:     return &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1495: }
 1496: 
 1497: sub mkdiruserfile {
 1498:     my ($docuname,$docudom,$dir)=@_;
 1499:     my $home=&homeserver($docuname,$docudom);
 1500:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1501: }
 1502: 
 1503: sub renameuserfile {
 1504:     my ($docuname,$docudom,$old,$new)=@_;
 1505:     my $home=&homeserver($docuname,$docudom);
 1506:     return &reply("renameuserfile:$docudom:$docuname:".&escape("$old").':'.
 1507: 		  &escape("$new"),$home);
 1508: }
 1509: 
 1510: # ------------------------------------------------------------------------- Log
 1511: 
 1512: sub log {
 1513:     my ($dom,$nam,$hom,$what)=@_;
 1514:     return critical("log:$dom:$nam:$what",$hom);
 1515: }
 1516: 
 1517: # ------------------------------------------------------------------ Course Log
 1518: #
 1519: # This routine flushes several buffers of non-mission-critical nature
 1520: #
 1521: 
 1522: sub flushcourselogs {
 1523:     &logthis('Flushing log buffers');
 1524: #
 1525: # course logs
 1526: # This is a log of all transactions in a course, which can be used
 1527: # for data mining purposes
 1528: #
 1529: # It also collects the courseid database, which lists last transaction
 1530: # times and course titles for all courseids
 1531: #
 1532:     my %courseidbuffer=();
 1533:     foreach (keys %courselogs) {
 1534:         my $crsid=$_;
 1535:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1536: 		          &escape($courselogs{$crsid}),
 1537: 		          $coursehombuf{$crsid}) eq 'ok') {
 1538: 	    delete $courselogs{$crsid};
 1539:         } else {
 1540:             &logthis('Failed to flush log buffer for '.$crsid);
 1541:             if (length($courselogs{$crsid})>40000) {
 1542:                &logthis("<font color=blue>WARNING: Buffer for ".$crsid.
 1543:                         " exceeded maximum size, deleting.</font>");
 1544:                delete $courselogs{$crsid};
 1545:             }
 1546:         }
 1547:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1548:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1549: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1550:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
 1551:         } else {
 1552:            $courseidbuffer{$coursehombuf{$crsid}}=
 1553: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1554:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid});
 1555:         }
 1556:     }
 1557: #
 1558: # Write course id database (reverse lookup) to homeserver of courses 
 1559: # Is used in pickcourse
 1560: #
 1561:     foreach (keys %courseidbuffer) {
 1562:         &courseidput($hostdom{$_},$courseidbuffer{$_},$_);
 1563:     }
 1564: #
 1565: # File accesses
 1566: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1567: #
 1568:     foreach my $entry (keys(%accesshash)) {
 1569:         if ($entry =~ /___count$/) {
 1570:             my ($dom,$name);
 1571:             ($dom,$name,undef)=($entry=~m:___(\w+)/(\w+)/(.*)___count$:);
 1572:             if (! defined($dom) || $dom eq '' || 
 1573:                 ! defined($name) || $name eq '') {
 1574:                 my $cid = $env{'request.course.id'};
 1575:                 $dom  = $env{'request.'.$cid.'.domain'};
 1576:                 $name = $env{'request.'.$cid.'.num'};
 1577:             }
 1578:             my $value = $accesshash{$entry};
 1579:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1580:             my %temphash=($url => $value);
 1581:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1582:             if ($result eq 'ok') {
 1583:                 delete $accesshash{$entry};
 1584:             } elsif ($result eq 'unknown_cmd') {
 1585:                 # Target server has old code running on it.
 1586:                 my %temphash=($entry => $value);
 1587:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1588:                     delete $accesshash{$entry};
 1589:                 }
 1590:             }
 1591:         } else {
 1592:             my ($dom,$name) = ($entry=~m:___(\w+)/(\w+)/(.*)___(\w+)$:);
 1593:             my %temphash=($entry => $accesshash{$entry});
 1594:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1595:                 delete $accesshash{$entry};
 1596:             }
 1597:         }
 1598:     }
 1599: #
 1600: # Roles
 1601: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1602: #
 1603:     foreach (keys %userrolehash) {
 1604:         my $entry=$_;
 1605:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1606: 	    split(/\:/,$entry);
 1607:         if (&Apache::lonnet::put('nohist_userroles',
 1608:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 1609:                 $rudom,$runame) eq 'ok') {
 1610: 	    delete $userrolehash{$entry};
 1611:         }
 1612:     }
 1613: #
 1614: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 1615: #
 1616:     my %domrolebuffer = ();
 1617:     foreach my $entry (keys %domainrolehash) {
 1618:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 1619:         if ($domrolebuffer{$rudom}) {
 1620:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 1621:                       '='.&escape($domainrolehash{$entry});
 1622:         } else {
 1623:             $domrolebuffer{$rudom}.=&escape($entry).
 1624:                       '='.&escape($domainrolehash{$entry});
 1625:         }
 1626:         delete $domainrolehash{$entry};
 1627:     }
 1628:     foreach my $dom (keys(%domrolebuffer)) {
 1629:         foreach my $tryserver (keys %libserv) {
 1630:             if ($hostdom{$tryserver} eq $dom) {
 1631:                 unless (&reply('domroleput:'.$dom.':'.
 1632:                   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 1633:                     &logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 1634:                 }
 1635:             }
 1636:         }
 1637:     }
 1638:     $dumpcount++;
 1639: }
 1640: 
 1641: sub courselog {
 1642:     my $what=shift;
 1643:     $what=time.':'.$what;
 1644:     unless ($env{'request.course.id'}) { return ''; }
 1645:     $coursedombuf{$env{'request.course.id'}}=
 1646:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 1647:     $coursenumbuf{$env{'request.course.id'}}=
 1648:        $env{'course.'.$env{'request.course.id'}.'.num'};
 1649:     $coursehombuf{$env{'request.course.id'}}=
 1650:        $env{'course.'.$env{'request.course.id'}.'.home'};
 1651:     $coursedescrbuf{$env{'request.course.id'}}=
 1652:        $env{'course.'.$env{'request.course.id'}.'.description'};
 1653:     $courseinstcodebuf{$env{'request.course.id'}}=
 1654:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 1655:     $courseownerbuf{$env{'request.course.id'}}=
 1656:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 1657:     if (defined $courselogs{$env{'request.course.id'}}) {
 1658: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 1659:     } else {
 1660: 	$courselogs{$env{'request.course.id'}}.=$what;
 1661:     }
 1662:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 1663: 	&flushcourselogs();
 1664:     }
 1665: }
 1666: 
 1667: sub courseacclog {
 1668:     my $fnsymb=shift;
 1669:     unless ($env{'request.course.id'}) { return ''; }
 1670:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 1671:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 1672:         $what.=':POST';
 1673:         # FIXME: Probably ought to escape things....
 1674: 	foreach (keys %env) {
 1675:             if ($_=~/^form\.(.*)/) {
 1676: 		$what.=':'.$1.'='.$env{$_};
 1677:             }
 1678:         }
 1679:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 1680:         # FIXME: We should not be depending on a form parameter that someone
 1681:         # editing lonsearchcat.pm might change in the future.
 1682:         if ($env{'form.phase'} eq 'course_search') {
 1683:             $what.= ':POST';
 1684:             # FIXME: Probably ought to escape things....
 1685:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 1686:                                  'crsdiscuss') {
 1687:                 $what.=':'.$element.'='.$env{'form.'.$element};
 1688:             }
 1689:         }
 1690:     }
 1691:     &courselog($what);
 1692: }
 1693: 
 1694: sub countacc {
 1695:     my $url=&declutter(shift);
 1696:     return if (! defined($url) || $url eq '');
 1697:     unless ($env{'request.course.id'}) { return ''; }
 1698:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 1699:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 1700:     $accesshash{$key}++;
 1701: }
 1702: 
 1703: sub linklog {
 1704:     my ($from,$to)=@_;
 1705:     $from=&declutter($from);
 1706:     $to=&declutter($to);
 1707:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 1708:     $accesshash{$to.'___'.$from.'___goto'}=1;
 1709: }
 1710:   
 1711: sub userrolelog {
 1712:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 1713:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 1714:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 1715:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 1716:         ($trole=~/^ta/)) {
 1717:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1718:        $userrolehash
 1719:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1720:                     =$tend.':'.$tstart;
 1721:     }
 1722:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 1723:         ($trole=~/^li/) || ($trole=~/^li/) ||
 1724:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 1725:         ($trole=~/^sc/)) {
 1726:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 1727:        $domainrolehash
 1728:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 1729:                     = $tend.':'.$tstart;
 1730:     }
 1731: }
 1732: 
 1733: sub get_course_adv_roles {
 1734:     my $cid=shift;
 1735:     $cid=$env{'request.course.id'} unless (defined($cid));
 1736:     my %coursehash=&coursedescription($cid);
 1737:     my %nothide=();
 1738:     foreach (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 1739: 	$nothide{join(':',split(/[\@\:]/,$_))}=1;
 1740:     }
 1741:     my %returnhash=();
 1742:     my %dumphash=
 1743:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 1744:     my $now=time;
 1745:     foreach (keys %dumphash) {
 1746: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1747:         if (($tstart) && ($tstart<0)) { next; }
 1748:         if (($tend) && ($tend<$now)) { next; }
 1749:         if (($tstart) && ($now<$tstart)) { next; }
 1750:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1751: 	if ($username eq '' || $domain eq '') { next; }
 1752: 	if ((&privileged($username,$domain)) && 
 1753: 	    (!$nothide{$username.':'.$domain})) { next; }
 1754: 	if ($role eq 'cr') { next; }
 1755:         my $key=&plaintext($role);
 1756: 	if ($role =~ /^cr/) {
 1757: 	    $key=(split('/',$role))[3];
 1758: 	}
 1759:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 1760:         if ($returnhash{$key}) {
 1761: 	    $returnhash{$key}.=','.$username.':'.$domain;
 1762:         } else {
 1763:             $returnhash{$key}=$username.':'.$domain;
 1764:         }
 1765:      }
 1766:     return %returnhash;
 1767: }
 1768: 
 1769: sub get_my_roles {
 1770:     my ($uname,$udom)=@_;
 1771:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 1772:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 1773:     my %dumphash=
 1774:             &dump('nohist_userroles',$udom,$uname);
 1775:     my %returnhash=();
 1776:     my $now=time;
 1777:     foreach (keys %dumphash) {
 1778: 	my ($tend,$tstart)=split(/\:/,$dumphash{$_});
 1779:         if (($tstart) && ($tstart<0)) { next; }
 1780:         if (($tend) && ($tend<$now)) { next; }
 1781:         if (($tstart) && ($now<$tstart)) { next; }
 1782:         my ($role,$username,$domain,$section)=split(/\:/,$_);
 1783: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 1784:      }
 1785:     return %returnhash;
 1786: }
 1787: 
 1788: # ----------------------------------------------------- Frontpage Announcements
 1789: #
 1790: #
 1791: 
 1792: sub postannounce {
 1793:     my ($server,$text)=@_;
 1794:     unless (&allowed('psa',$hostdom{$server})) { return 'refused'; }
 1795:     unless ($text=~/\w/) { $text=''; }
 1796:     return &reply('setannounce:'.&escape($text),$server);
 1797: }
 1798: 
 1799: sub getannounce {
 1800: 
 1801:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 1802: 	my $announcement='';
 1803: 	while (<$fh>) { $announcement .=$_; }
 1804: 	close($fh);
 1805: 	if ($announcement=~/\w/) { 
 1806: 	    return 
 1807:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 1808:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 1809: 	} else {
 1810: 	    return '';
 1811: 	}
 1812:     } else {
 1813: 	return '';
 1814:     }
 1815: }
 1816: 
 1817: # ---------------------------------------------------------- Course ID routines
 1818: # Deal with domain's nohist_courseid.db files
 1819: #
 1820: 
 1821: sub courseidput {
 1822:     my ($domain,$what,$coursehome)=@_;
 1823:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 1824: }
 1825: 
 1826: sub courseiddump {
 1827:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref)=@_;
 1828:     my %returnhash=();
 1829:     unless ($domfilter) { $domfilter=''; }
 1830:     foreach my $tryserver (keys %libserv) {
 1831:         if ( ($hostidflag == 1 && grep/^$tryserver$/,@{$hostidref}) || (!defined($hostidflag)) ) {
 1832: 	    if ((!$domfilter) || ($hostdom{$tryserver} eq $domfilter)) {
 1833: 	        foreach (
 1834:                  split(/\&/,&reply('courseiddump:'.$hostdom{$tryserver}.':'.
 1835: 			       $sincefilter.':'.&escape($descfilter).':'.
 1836:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter),
 1837:                                $tryserver))) {
 1838: 		    my ($key,$value)=split(/\=/,$_);
 1839:                     if (($key) && ($value)) {
 1840: 		        $returnhash{&unescape($key)}=$value;
 1841:                     }
 1842:                 }
 1843:             }
 1844:         }
 1845:     }
 1846:     return %returnhash;
 1847: }
 1848: 
 1849: # ---------------------------------------------------------- DC e-mail
 1850: 
 1851: sub dcmailput {
 1852:     my ($domain,$msgid,$contents,$server)=@_;
 1853:     my $status = &Apache::lonnet::critical(
 1854:        'dcmailput:'.$domain.':'.&Apache::lonnet::escape($msgid).'='.
 1855:        &Apache::lonnet::escape($$contents{$server}),$server);
 1856:     return $status;
 1857: }
 1858: 
 1859: sub dcmaildump {
 1860:     my ($dom,$startdate,$enddate,$senders) = @_;
 1861:     my %returnhash=(); 
 1862:     foreach my $tryserver (keys(%libserv)) {
 1863:         if ($hostdom{$tryserver} eq $dom) {
 1864:             %{$returnhash{$tryserver}}=();
 1865: 	    my $cmd='dcmaildump:'.$dom.':'.
 1866: 		&escape($startdate).':'.&escape($enddate).':';
 1867: 	    my @esc_senders=map { &escape($_)} @$senders;
 1868: 	    $cmd.=&escape(join('&',@esc_senders));
 1869: 	    foreach (split(/\&/,&reply($cmd,$tryserver))) {
 1870:                 my ($key,$value) = split(/\=/,$_);
 1871:                 if (($key) && ($value)) {
 1872:                     $returnhash{$tryserver}{&unescape($key)} = &unescape($value);
 1873:                 }
 1874:             }
 1875:         }
 1876:     }
 1877:     return %returnhash;
 1878: }
 1879: # ---------------------------------------------------------- Domain roles
 1880: 
 1881: sub get_domain_roles {
 1882:     my ($dom,$roles,$startdate,$enddate)=@_;
 1883:     if (undef($startdate) || $startdate eq '') {
 1884:         $startdate = '.';
 1885:     }
 1886:     if (undef($enddate) || $enddate eq '') {
 1887:         $enddate = '.';
 1888:     }
 1889:     my $rolelist = join(':',@{$roles});
 1890:     my %personnel = ();
 1891:     foreach my $tryserver (keys(%libserv)) {
 1892:         if ($hostdom{$tryserver} eq $dom) {
 1893:             %{$personnel{$tryserver}}=();
 1894:             foreach (
 1895:                 split(/\&/,&reply('domrolesdump:'.$dom.':'.
 1896:                    &escape($startdate).':'.&escape($enddate).':'.
 1897:                    &escape($rolelist), $tryserver))) {
 1898:                 my($key,$value) = split(/\=/,$_);
 1899:                 if (($key) && ($value)) {
 1900:                     $personnel{$tryserver}{&unescape($key)} = &unescape($value);
 1901:                 }
 1902:             }
 1903:         }
 1904:     }
 1905:     return %personnel;
 1906: }
 1907: 
 1908: # ----------------------------------------------------------- Check out an item
 1909: 
 1910: sub get_first_access {
 1911:     my ($type,$argsymb)=@_;
 1912:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 1913:     if ($argsymb) { $symb=$argsymb; }
 1914:     my ($map,$id,$res)=&decode_symb($symb);
 1915:     if ($type eq 'map') {
 1916: 	$res=&symbread($map);
 1917:     } else {
 1918: 	$res=$symb;
 1919:     }
 1920:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 1921:     return $times{"$courseid\0$res"};
 1922: }
 1923: 
 1924: sub set_first_access {
 1925:     my ($type)=@_;
 1926:     my ($symb,$courseid,$udom,$uname)=&Apache::lonxml::whichuser();
 1927:     my ($map,$id,$res)=&decode_symb($symb);
 1928:     if ($type eq 'map') {
 1929: 	$res=&symbread($map);
 1930:     } else {
 1931: 	$res=$symb;
 1932:     }
 1933:     my $firstaccess=&get_first_access($type,$symb);
 1934:     if (!$firstaccess) {
 1935: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 1936:     }
 1937:     return 'already_set';
 1938: }
 1939: 
 1940: sub checkout {
 1941:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 1942:     my $now=time;
 1943:     my $lonhost=$perlvar{'lonHostID'};
 1944:     my $infostr=&escape(
 1945:                  'CHECKOUTTOKEN&'.
 1946:                  $tuname.'&'.
 1947:                  $tudom.'&'.
 1948:                  $tcrsid.'&'.
 1949:                  $symb.'&'.
 1950: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 1951:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 1952:     if ($token=~/^error\:/) { 
 1953:         &logthis("<font color=blue>WARNING: ".
 1954:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 1955:                  "</font>");
 1956:         return ''; 
 1957:     }
 1958: 
 1959:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 1960:     $token=~tr/a-z/A-Z/;
 1961: 
 1962:     my %infohash=('resource.0.outtoken' => $token,
 1963:                   'resource.0.checkouttime' => $now,
 1964:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 1965: 
 1966:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 1967:        return '';
 1968:     } else {
 1969:         &logthis("<font color=blue>WARNING: ".
 1970:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 1971:                  "</font>");
 1972:     }    
 1973: 
 1974:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 1975:                          &escape('Checkout '.$infostr.' - '.
 1976:                                                  $token)) ne 'ok') {
 1977: 	return '';
 1978:     } else {
 1979:         &logthis("<font color=blue>WARNING: ".
 1980:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 1981:                  "</font>");
 1982:     }
 1983:     return $token;
 1984: }
 1985: 
 1986: # ------------------------------------------------------------ Check in an item
 1987: 
 1988: sub checkin {
 1989:     my $token=shift;
 1990:     my $now=time;
 1991:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 1992:     $lonhost=~tr/A-Z/a-z/;
 1993:     my $dtoken=$ta.'_'.$hostname{$lonhost}.'_'.$tb;
 1994:     $dtoken=~s/\W/\_/g;
 1995:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 1996:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 1997: 
 1998:     unless (($tuname) && ($tudom)) {
 1999:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2000:         return '';
 2001:     }
 2002:     
 2003:     unless (&allowed('mgr',$tcrsid)) {
 2004:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2005:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2006:         return '';
 2007:     }
 2008: 
 2009:     my %infohash=('resource.0.intoken' => $token,
 2010:                   'resource.0.checkintime' => $now,
 2011:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2012: 
 2013:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2014:        return '';
 2015:     }    
 2016: 
 2017:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2018:                          &escape('Checkin - '.$token)) ne 'ok') {
 2019: 	return '';
 2020:     }
 2021: 
 2022:     return ($symb,$tuname,$tudom,$tcrsid);    
 2023: }
 2024: 
 2025: # --------------------------------------------- Set Expire Date for Spreadsheet
 2026: 
 2027: sub expirespread {
 2028:     my ($uname,$udom,$stype,$usymb)=@_;
 2029:     my $cid=$env{'request.course.id'}; 
 2030:     if ($cid) {
 2031:        my $now=time;
 2032:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2033:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2034:                             $env{'course.'.$cid.'.num'}.
 2035: 	        	    ':nohist_expirationdates:'.
 2036:                             &escape($key).'='.$now,
 2037:                             $env{'course.'.$cid.'.home'})
 2038:     }
 2039:     return 'ok';
 2040: }
 2041: 
 2042: # ----------------------------------------------------- Devalidate Spreadsheets
 2043: 
 2044: sub devalidate {
 2045:     my ($symb,$uname,$udom)=@_;
 2046:     my $cid=$env{'request.course.id'}; 
 2047:     if ($cid) {
 2048:         # delete the stored spreadsheets for
 2049:         # - the student level sheet of this user in course's homespace
 2050:         # - the assessment level sheet for this resource 
 2051:         #   for this user in user's homespace
 2052: 	# - current conditional state info
 2053: 	my $key=$uname.':'.$udom.':';
 2054:         my $status=
 2055: 	    &del('nohist_calculatedsheets',
 2056: 		 [$key.'studentcalc:'],
 2057: 		 $env{'course.'.$cid.'.domain'},
 2058: 		 $env{'course.'.$cid.'.num'})
 2059: 		.' '.
 2060: 	    &del('nohist_calculatedsheets_'.$cid,
 2061: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2062:         unless ($status eq 'ok ok') {
 2063:            &logthis('Could not devalidate spreadsheet '.
 2064:                     $uname.' at '.$udom.' for '.
 2065: 		    $symb.': '.$status);
 2066:         }
 2067: 	&delenv('user.state.'.$cid);
 2068:     }
 2069: }
 2070: 
 2071: sub get_scalar {
 2072:     my ($string,$end) = @_;
 2073:     my $value;
 2074:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2075: 	$value = $1;
 2076:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2077: 	$value = $1;
 2078:     }
 2079:     return &unescape($value);
 2080: }
 2081: 
 2082: sub array2str {
 2083:   my (@array) = @_;
 2084:   my $result=&arrayref2str(\@array);
 2085:   $result=~s/^__ARRAY_REF__//;
 2086:   $result=~s/__END_ARRAY_REF__$//;
 2087:   return $result;
 2088: }
 2089: 
 2090: sub arrayref2str {
 2091:   my ($arrayref) = @_;
 2092:   my $result='__ARRAY_REF__';
 2093:   foreach my $elem (@$arrayref) {
 2094:     if(ref($elem) eq 'ARRAY') {
 2095:       $result.=&arrayref2str($elem).'&';
 2096:     } elsif(ref($elem) eq 'HASH') {
 2097:       $result.=&hashref2str($elem).'&';
 2098:     } elsif(ref($elem)) {
 2099:       #print("Got a ref of ".(ref($elem))." skipping.");
 2100:     } else {
 2101:       $result.=&escape($elem).'&';
 2102:     }
 2103:   }
 2104:   $result=~s/\&$//;
 2105:   $result .= '__END_ARRAY_REF__';
 2106:   return $result;
 2107: }
 2108: 
 2109: sub hash2str {
 2110:   my (%hash) = @_;
 2111:   my $result=&hashref2str(\%hash);
 2112:   $result=~s/^__HASH_REF__//;
 2113:   $result=~s/__END_HASH_REF__$//;
 2114:   return $result;
 2115: }
 2116: 
 2117: sub hashref2str {
 2118:   my ($hashref)=@_;
 2119:   my $result='__HASH_REF__';
 2120:   foreach (sort(keys(%$hashref))) {
 2121:     if (ref($_) eq 'ARRAY') {
 2122:       $result.=&arrayref2str($_).'=';
 2123:     } elsif (ref($_) eq 'HASH') {
 2124:       $result.=&hashref2str($_).'=';
 2125:     } elsif (ref($_)) {
 2126:       $result.='=';
 2127:       #print("Got a ref of ".(ref($_))." skipping.");
 2128:     } else {
 2129: 	if ($_) {$result.=&escape($_).'=';} else { last; }
 2130:     }
 2131: 
 2132:     if(ref($hashref->{$_}) eq 'ARRAY') {
 2133:       $result.=&arrayref2str($hashref->{$_}).'&';
 2134:     } elsif(ref($hashref->{$_}) eq 'HASH') {
 2135:       $result.=&hashref2str($hashref->{$_}).'&';
 2136:     } elsif(ref($hashref->{$_})) {
 2137:        $result.='&';
 2138:       #print("Got a ref of ".(ref($hashref->{$_}))." skipping.");
 2139:     } else {
 2140:       $result.=&escape($hashref->{$_}).'&';
 2141:     }
 2142:   }
 2143:   $result=~s/\&$//;
 2144:   $result .= '__END_HASH_REF__';
 2145:   return $result;
 2146: }
 2147: 
 2148: sub str2hash {
 2149:     my ($string)=@_;
 2150:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2151:     return %$hash;
 2152: }
 2153: 
 2154: sub str2hashref {
 2155:   my ($string) = @_;
 2156: 
 2157:   my %hash;
 2158: 
 2159:   if($string !~ /^__HASH_REF__/) {
 2160:       if (! ($string eq '' || !defined($string))) {
 2161: 	  $hash{'error'}='Not hash reference';
 2162:       }
 2163:       return (\%hash, $string);
 2164:   }
 2165: 
 2166:   $string =~ s/^__HASH_REF__//;
 2167: 
 2168:   while($string !~ /^__END_HASH_REF__/) {
 2169:       #key
 2170:       my $key='';
 2171:       if($string =~ /^__HASH_REF__/) {
 2172:           ($key, $string)=&str2hashref($string);
 2173:           if(defined($key->{'error'})) {
 2174:               $hash{'error'}='Bad data';
 2175:               return (\%hash, $string);
 2176:           }
 2177:       } elsif($string =~ /^__ARRAY_REF__/) {
 2178:           ($key, $string)=&str2arrayref($string);
 2179:           if($key->[0] eq 'Array reference error') {
 2180:               $hash{'error'}='Bad data';
 2181:               return (\%hash, $string);
 2182:           }
 2183:       } else {
 2184:           $string =~ s/^(.*?)=//;
 2185: 	  $key=&unescape($1);
 2186:       }
 2187:       $string =~ s/^=//;
 2188: 
 2189:       #value
 2190:       my $value='';
 2191:       if($string =~ /^__HASH_REF__/) {
 2192:           ($value, $string)=&str2hashref($string);
 2193:           if(defined($value->{'error'})) {
 2194:               $hash{'error'}='Bad data';
 2195:               return (\%hash, $string);
 2196:           }
 2197:       } elsif($string =~ /^__ARRAY_REF__/) {
 2198:           ($value, $string)=&str2arrayref($string);
 2199:           if($value->[0] eq 'Array reference error') {
 2200:               $hash{'error'}='Bad data';
 2201:               return (\%hash, $string);
 2202:           }
 2203:       } else {
 2204: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2205:       }
 2206:       $string =~ s/^&//;
 2207: 
 2208:       $hash{$key}=$value;
 2209:   }
 2210: 
 2211:   $string =~ s/^__END_HASH_REF__//;
 2212: 
 2213:   return (\%hash, $string);
 2214: }
 2215: 
 2216: sub str2array {
 2217:     my ($string)=@_;
 2218:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2219:     return @$array;
 2220: }
 2221: 
 2222: sub str2arrayref {
 2223:   my ($string) = @_;
 2224:   my @array;
 2225: 
 2226:   if($string !~ /^__ARRAY_REF__/) {
 2227:       if (! ($string eq '' || !defined($string))) {
 2228: 	  $array[0]='Array reference error';
 2229:       }
 2230:       return (\@array, $string);
 2231:   }
 2232: 
 2233:   $string =~ s/^__ARRAY_REF__//;
 2234: 
 2235:   while($string !~ /^__END_ARRAY_REF__/) {
 2236:       my $value='';
 2237:       if($string =~ /^__HASH_REF__/) {
 2238:           ($value, $string)=&str2hashref($string);
 2239:           if(defined($value->{'error'})) {
 2240:               $array[0] ='Array reference error';
 2241:               return (\@array, $string);
 2242:           }
 2243:       } elsif($string =~ /^__ARRAY_REF__/) {
 2244:           ($value, $string)=&str2arrayref($string);
 2245:           if($value->[0] eq 'Array reference error') {
 2246:               $array[0] ='Array reference error';
 2247:               return (\@array, $string);
 2248:           }
 2249:       } else {
 2250: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2251:       }
 2252:       $string =~ s/^&//;
 2253: 
 2254:       push(@array, $value);
 2255:   }
 2256: 
 2257:   $string =~ s/^__END_ARRAY_REF__//;
 2258: 
 2259:   return (\@array, $string);
 2260: }
 2261: 
 2262: # -------------------------------------------------------------------Temp Store
 2263: 
 2264: sub tmpreset {
 2265:   my ($symb,$namespace,$domain,$stuname) = @_;
 2266:   if (!$symb) {
 2267:     $symb=&symbread();
 2268:     if (!$symb) { $symb= $env{'request.url'}; }
 2269:   }
 2270:   $symb=escape($symb);
 2271: 
 2272:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2273:   $namespace=~s/\//\_/g;
 2274:   $namespace=~s/\W//g;
 2275: 
 2276:   if (!$domain) { $domain=$env{'user.domain'}; }
 2277:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2278:   if ($domain eq 'public' && $stuname eq 'public') {
 2279:       $stuname=$ENV{'REMOTE_ADDR'};
 2280:   }
 2281:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2282:   my %hash;
 2283:   if (tie(%hash,'GDBM_File',
 2284: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2285: 	  &GDBM_WRCREAT(),0640)) {
 2286:     foreach my $key (keys %hash) {
 2287:       if ($key=~ /:$symb/) {
 2288: 	delete($hash{$key});
 2289:       }
 2290:     }
 2291:   }
 2292: }
 2293: 
 2294: sub tmpstore {
 2295:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2296: 
 2297:   if (!$symb) {
 2298:     $symb=&symbread();
 2299:     if (!$symb) { $symb= $env{'request.url'}; }
 2300:   }
 2301:   $symb=escape($symb);
 2302: 
 2303:   if (!$namespace) {
 2304:     # I don't think we would ever want to store this for a course.
 2305:     # it seems this will only be used if we don't have a course.
 2306:     #$namespace=$env{'request.course.id'};
 2307:     #if (!$namespace) {
 2308:       $namespace=$env{'request.state'};
 2309:     #}
 2310:   }
 2311:   $namespace=~s/\//\_/g;
 2312:   $namespace=~s/\W//g;
 2313:   if (!$domain) { $domain=$env{'user.domain'}; }
 2314:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2315:   if ($domain eq 'public' && $stuname eq 'public') {
 2316:       $stuname=$ENV{'REMOTE_ADDR'};
 2317:   }
 2318:   my $now=time;
 2319:   my %hash;
 2320:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2321:   if (tie(%hash,'GDBM_File',
 2322: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2323: 	  &GDBM_WRCREAT(),0640)) {
 2324:     $hash{"version:$symb"}++;
 2325:     my $version=$hash{"version:$symb"};
 2326:     my $allkeys=''; 
 2327:     foreach my $key (keys(%$storehash)) {
 2328:       $allkeys.=$key.':';
 2329:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2330:     }
 2331:     $hash{"$version:$symb:timestamp"}=$now;
 2332:     $allkeys.='timestamp';
 2333:     $hash{"$version:keys:$symb"}=$allkeys;
 2334:     if (untie(%hash)) {
 2335:       return 'ok';
 2336:     } else {
 2337:       return "error:$!";
 2338:     }
 2339:   } else {
 2340:     return "error:$!";
 2341:   }
 2342: }
 2343: 
 2344: # -----------------------------------------------------------------Temp Restore
 2345: 
 2346: sub tmprestore {
 2347:   my ($symb,$namespace,$domain,$stuname) = @_;
 2348: 
 2349:   if (!$symb) {
 2350:     $symb=&symbread();
 2351:     if (!$symb) { $symb= $env{'request.url'}; }
 2352:   }
 2353:   $symb=escape($symb);
 2354: 
 2355:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2356: 
 2357:   if (!$domain) { $domain=$env{'user.domain'}; }
 2358:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2359:   if ($domain eq 'public' && $stuname eq 'public') {
 2360:       $stuname=$ENV{'REMOTE_ADDR'};
 2361:   }
 2362:   my %returnhash;
 2363:   $namespace=~s/\//\_/g;
 2364:   $namespace=~s/\W//g;
 2365:   my %hash;
 2366:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2367:   if (tie(%hash,'GDBM_File',
 2368: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2369: 	  &GDBM_READER(),0640)) {
 2370:     my $version=$hash{"version:$symb"};
 2371:     $returnhash{'version'}=$version;
 2372:     my $scope;
 2373:     for ($scope=1;$scope<=$version;$scope++) {
 2374:       my $vkeys=$hash{"$scope:keys:$symb"};
 2375:       my @keys=split(/:/,$vkeys);
 2376:       my $key;
 2377:       $returnhash{"$scope:keys"}=$vkeys;
 2378:       foreach $key (@keys) {
 2379: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2380: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2381:       }
 2382:     }
 2383:     if (!(untie(%hash))) {
 2384:       return "error:$!";
 2385:     }
 2386:   } else {
 2387:     return "error:$!";
 2388:   }
 2389:   return %returnhash;
 2390: }
 2391: 
 2392: # ----------------------------------------------------------------------- Store
 2393: 
 2394: sub store {
 2395:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2396:     my $home='';
 2397: 
 2398:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2399: 
 2400:     $symb=&symbclean($symb);
 2401:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2402: 
 2403:     if (!$domain) { $domain=$env{'user.domain'}; }
 2404:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2405: 
 2406:     &devalidate($symb,$stuname,$domain);
 2407: 
 2408:     $symb=escape($symb);
 2409:     if (!$namespace) { 
 2410:        unless ($namespace=$env{'request.course.id'}) { 
 2411:           return ''; 
 2412:        } 
 2413:     }
 2414:     if (!$home) { $home=$env{'user.home'}; }
 2415: 
 2416:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2417:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2418: 
 2419:     my $namevalue='';
 2420:     foreach (keys %$storehash) {
 2421:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2422:     }
 2423:     $namevalue=~s/\&$//;
 2424:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2425:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2426: }
 2427: 
 2428: # -------------------------------------------------------------- Critical Store
 2429: 
 2430: sub cstore {
 2431:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2432:     my $home='';
 2433: 
 2434:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2435: 
 2436:     $symb=&symbclean($symb);
 2437:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2438: 
 2439:     if (!$domain) { $domain=$env{'user.domain'}; }
 2440:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2441: 
 2442:     &devalidate($symb,$stuname,$domain);
 2443: 
 2444:     $symb=escape($symb);
 2445:     if (!$namespace) { 
 2446:        unless ($namespace=$env{'request.course.id'}) { 
 2447:           return ''; 
 2448:        } 
 2449:     }
 2450:     if (!$home) { $home=$env{'user.home'}; }
 2451: 
 2452:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2453:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2454: 
 2455:     my $namevalue='';
 2456:     foreach (keys %$storehash) {
 2457:         $namevalue.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2458:     }
 2459:     $namevalue=~s/\&$//;
 2460:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2461:     return critical
 2462:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2463: }
 2464: 
 2465: # --------------------------------------------------------------------- Restore
 2466: 
 2467: sub restore {
 2468:     my ($symb,$namespace,$domain,$stuname) = @_;
 2469:     my $home='';
 2470: 
 2471:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2472: 
 2473:     if (!$symb) {
 2474:       unless ($symb=escape(&symbread())) { return ''; }
 2475:     } else {
 2476:       $symb=&escape(&symbclean($symb));
 2477:     }
 2478:     if (!$namespace) { 
 2479:        unless ($namespace=$env{'request.course.id'}) { 
 2480:           return ''; 
 2481:        } 
 2482:     }
 2483:     if (!$domain) { $domain=$env{'user.domain'}; }
 2484:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2485:     if (!$home) { $home=$env{'user.home'}; }
 2486:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2487: 
 2488:     my %returnhash=();
 2489:     foreach (split(/\&/,$answer)) {
 2490: 	my ($name,$value)=split(/\=/,$_);
 2491:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2492:     }
 2493:     my $version;
 2494:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2495:        foreach (split(/\:/,$returnhash{$version.':keys'})) {
 2496:           $returnhash{$_}=$returnhash{$version.':'.$_};
 2497:        }
 2498:     }
 2499:     return %returnhash;
 2500: }
 2501: 
 2502: # ---------------------------------------------------------- Course Description
 2503: 
 2504: sub coursedescription {
 2505:     my $courseid=shift;
 2506:     $courseid=~s/^\///;
 2507:     $courseid=~s/\_/\//g;
 2508:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2509:     my $chome=&homeserver($cnum,$cdomain);
 2510:     my $normalid=$cdomain.'_'.$cnum;
 2511:     # need to always cache even if we get errors otherwise we keep 
 2512:     # trying and trying and trying to get the course description.
 2513:     my %envhash=();
 2514:     my %returnhash=();
 2515:     $envhash{'course.'.$normalid.'.last_cache'}=time;
 2516:     if ($chome ne 'no_host') {
 2517:        %returnhash=&dump('environment',$cdomain,$cnum);
 2518:        if (!exists($returnhash{'con_lost'})) {
 2519:            $returnhash{'home'}= $chome;
 2520: 	   $returnhash{'domain'} = $cdomain;
 2521: 	   $returnhash{'num'} = $cnum;
 2522:            while (my ($name,$value) = each %returnhash) {
 2523:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2524:            }
 2525:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2526:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2527: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2528:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2529:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2530:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2531:        }
 2532:     }
 2533:     &appenv(%envhash);
 2534:     return %returnhash;
 2535: }
 2536: 
 2537: # -------------------------------------------------See if a user is privileged
 2538: 
 2539: sub privileged {
 2540:     my ($username,$domain)=@_;
 2541:     my $rolesdump=&reply("dump:$domain:$username:roles",
 2542: 			&homeserver($username,$domain));
 2543:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 2544:     my $now=time;
 2545:     if ($rolesdump ne '') {
 2546:         foreach (split(/&/,$rolesdump)) {
 2547: 	    if ($_!~/^rolesdef_/) {
 2548: 		my ($area,$role)=split(/=/,$_);
 2549: 		$area=~s/\_\w\w$//;
 2550: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 2551: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 2552: 		    my $active=1;
 2553: 		    if ($tend) {
 2554: 			if ($tend<$now) { $active=0; }
 2555: 		    }
 2556: 		    if ($tstart) {
 2557: 			if ($tstart>$now) { $active=0; }
 2558: 		    }
 2559: 		    if ($active) { return 1; }
 2560: 		}
 2561: 	    }
 2562: 	}
 2563:     }
 2564:     return 0;
 2565: }
 2566: 
 2567: # -------------------------------------------------------- Get user privileges
 2568: 
 2569: sub rolesinit {
 2570:     my ($domain,$username,$authhost)=@_;
 2571:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 2572:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 2573:     my %allroles=();
 2574:     my $now=time;
 2575:     my $userroles="user.login.time=$now\n";
 2576: 
 2577:     if ($rolesdump ne '') {
 2578:         foreach (split(/&/,$rolesdump)) {
 2579: 	  if ($_!~/^rolesdef_/) {
 2580:             my ($area,$role)=split(/=/,$_);
 2581: 	    $area=~s/\_\w\w$//;
 2582:             my ($trole,$tend,$tstart);
 2583: 	    if ($role=~/^cr/) { 
 2584: 		if ($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|) {
 2585: 		    ($trole,my $trest)=($role=~m|^(cr/\w+/\w+/[a-zA-Z0-9]+)_(.*)$|);
 2586: 		    ($tend,$tstart)=split('_',$trest);
 2587: 		} else {
 2588: 		    $trole=$role;
 2589: 		}
 2590: 	    } else {
 2591: 		($trole,$tend,$tstart)=split(/_/,$role);
 2592: 	    }
 2593:             $userroles.=&set_arearole($trole,$area,$tstart,$tend,$domain,$username);
 2594:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 2595:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 2596:             if (($area ne '') && ($trole ne '')) {
 2597: 		my $spec=$trole.'.'.$area;
 2598: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 2599: 		if ($trole =~ /^cr\//) {
 2600:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 2601: 		} else {
 2602:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 2603: 		}
 2604:             }
 2605:           }
 2606:         }
 2607:         my ($author,$adv) = &set_userprivs(\$userroles,\%allroles);
 2608:         $userroles.='user.adv='.$adv."\n".
 2609: 	            'user.author='.$author."\n";
 2610:         $env{'user.adv'}=$adv;
 2611:     }
 2612:     return $userroles;  
 2613: }
 2614: 
 2615: sub set_arearole {
 2616:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 2617: # log the associated role with the area
 2618:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 2619:     return 'user.role.'.$trole.'.'.$area.'='.$tstart.'.'.$tend."\n";
 2620: }
 2621: 
 2622: sub custom_roleprivs {
 2623:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 2624:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 2625:     my $homsvr=homeserver($rauthor,$rdomain);
 2626:     if ($hostname{$homsvr} ne '') {
 2627:         my ($rdummy,$roledef)=
 2628:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 2629:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 2630:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 2631:             if (defined($syspriv)) {
 2632:                 $$allroles{'cm./'}.=':'.$syspriv;
 2633:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 2634:             }
 2635:             if ($tdomain ne '') {
 2636:                 if (defined($dompriv)) {
 2637:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 2638:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 2639:                 }
 2640:                 if (($trest ne '') && (defined($coursepriv))) {
 2641:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 2642:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 2643:                 }
 2644:             }
 2645:         }
 2646:     }
 2647: }
 2648: 
 2649: 
 2650: sub standard_roleprivs {
 2651:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 2652:     if (defined($pr{$trole.':s'})) {
 2653:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 2654:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 2655:     }
 2656:     if ($tdomain ne '') {
 2657:         if (defined($pr{$trole.':d'})) {
 2658:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2659:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 2660:         }
 2661:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 2662:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 2663:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 2664:         }
 2665:     }
 2666: }
 2667: 
 2668: sub set_userprivs {
 2669:     my ($userroles,$allroles) = @_; 
 2670:     my $author=0;
 2671:     my $adv=0;
 2672:     foreach (keys %{$allroles}) {
 2673:         my %thesepriv=();
 2674:         if (($_=~/^au/) || ($_=~/^ca/)) { $author=1; }
 2675:         foreach (split(/:/,$$allroles{$_})) {
 2676:             if ($_ ne '') {
 2677:                 my ($privilege,$restrictions)=split(/&/,$_);
 2678:                 if ($restrictions eq '') {
 2679:                     $thesepriv{$privilege}='F';
 2680:                 } elsif ($thesepriv{$privilege} ne 'F') {
 2681:                     $thesepriv{$privilege}.=$restrictions;
 2682:                 }
 2683:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 2684:             }
 2685:         }
 2686:         my $thesestr='';
 2687:         foreach (keys %thesepriv) { $thesestr.=':'.$_.'&'.$thesepriv{$_}; }
 2688:         $$userroles.='user.priv.'.$_.'='.$thesestr."\n";
 2689:     }
 2690:     return ($author,$adv);
 2691: }
 2692: 
 2693: # --------------------------------------------------------------- get interface
 2694: 
 2695: sub get {
 2696:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2697:    my $items='';
 2698:    foreach (@$storearr) {
 2699:        $items.=escape($_).'&';
 2700:    }
 2701:    $items=~s/\&$//;
 2702:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2703:    if (!$uname) { $uname=$env{'user.name'}; }
 2704:    my $uhome=&homeserver($uname,$udomain);
 2705: 
 2706:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 2707:    my @pairs=split(/\&/,$rep);
 2708:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 2709:      return @pairs;
 2710:    }
 2711:    my %returnhash=();
 2712:    my $i=0;
 2713:    foreach (@$storearr) {
 2714:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2715:       $i++;
 2716:    }
 2717:    return %returnhash;
 2718: }
 2719: 
 2720: # --------------------------------------------------------------- del interface
 2721: 
 2722: sub del {
 2723:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2724:    my $items='';
 2725:    foreach (@$storearr) {
 2726:        $items.=escape($_).'&';
 2727:    }
 2728:    $items=~s/\&$//;
 2729:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2730:    if (!$uname) { $uname=$env{'user.name'}; }
 2731:    my $uhome=&homeserver($uname,$udomain);
 2732: 
 2733:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 2734: }
 2735: 
 2736: # -------------------------------------------------------------- dump interface
 2737: 
 2738: sub dump {
 2739:    my ($namespace,$udomain,$uname,$regexp)=@_;
 2740:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2741:    if (!$uname) { $uname=$env{'user.name'}; }
 2742:    my $uhome=&homeserver($uname,$udomain);
 2743:    if ($regexp) {
 2744:        $regexp=&escape($regexp);
 2745:    } else {
 2746:        $regexp='.';
 2747:    }
 2748:    my $rep=reply("dump:$udomain:$uname:$namespace:$regexp",$uhome);
 2749:    my @pairs=split(/\&/,$rep);
 2750:    my %returnhash=();
 2751:    foreach (@pairs) {
 2752:       my ($key,$value)=split(/=/,$_);
 2753:       $returnhash{unescape($key)}=&thaw_unescape($value);
 2754:    }
 2755:    return %returnhash;
 2756: }
 2757: 
 2758: # -------------------------------------------------------------- keys interface
 2759: 
 2760: sub getkeys {
 2761:    my ($namespace,$udomain,$uname)=@_;
 2762:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2763:    if (!$uname) { $uname=$env{'user.name'}; }
 2764:    my $uhome=&homeserver($uname,$udomain);
 2765:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 2766:    my @keyarray=();
 2767:    foreach (split(/\&/,$rep)) {
 2768:       push (@keyarray,&unescape($_));
 2769:    }
 2770:    return @keyarray;
 2771: }
 2772: 
 2773: # --------------------------------------------------------------- currentdump
 2774: sub currentdump {
 2775:    my ($courseid,$sdom,$sname)=@_;
 2776:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 2777:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 2778:    $sname    = $env{'user.name'}         if (! defined($sname));
 2779:    my $uhome = &homeserver($sname,$sdom);
 2780:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 2781:    return if ($rep =~ /^(error:|no_such_host)/);
 2782:    #
 2783:    my %returnhash=();
 2784:    #
 2785:    if ($rep eq "unknown_cmd") { 
 2786:        # an old lond will not know currentdump
 2787:        # Do a dump and make it look like a currentdump
 2788:        my @tmp = &dump($courseid,$sdom,$sname,'.');
 2789:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 2790:        my %hash = @tmp;
 2791:        @tmp=();
 2792:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 2793:    } else {
 2794:        my @pairs=split(/\&/,$rep);
 2795:        foreach (@pairs) {
 2796:            my ($key,$value)=split(/=/,$_);
 2797:            my ($symb,$param) = split(/:/,$key);
 2798:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 2799:                                                         &thaw_unescape($value);
 2800:        }
 2801:    }
 2802:    return %returnhash;
 2803: }
 2804: 
 2805: sub convert_dump_to_currentdump{
 2806:     my %hash = %{shift()};
 2807:     my %returnhash;
 2808:     # Code ripped from lond, essentially.  The only difference
 2809:     # here is the unescaping done by lonnet::dump().  Conceivably
 2810:     # we might run in to problems with parameter names =~ /^v\./
 2811:     while (my ($key,$value) = each(%hash)) {
 2812:         my ($v,$symb,$param) = split(/:/,$key);
 2813:         next if ($v eq 'version' || $symb eq 'keys');
 2814:         next if (exists($returnhash{$symb}) &&
 2815:                  exists($returnhash{$symb}->{$param}) &&
 2816:                  $returnhash{$symb}->{'v.'.$param} > $v);
 2817:         $returnhash{$symb}->{$param}=$value;
 2818:         $returnhash{$symb}->{'v.'.$param}=$v;
 2819:     }
 2820:     #
 2821:     # Remove all of the keys in the hashes which keep track of
 2822:     # the version of the parameter.
 2823:     while (my ($symb,$param_hash) = each(%returnhash)) {
 2824:         # use a foreach because we are going to delete from the hash.
 2825:         foreach my $key (keys(%$param_hash)) {
 2826:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 2827:         }
 2828:     }
 2829:     return \%returnhash;
 2830: }
 2831: 
 2832: # ------------------------------------------------------ critical inc interface
 2833: 
 2834: sub cinc {
 2835:     return &inc(@_,'critical');
 2836: }
 2837: 
 2838: # --------------------------------------------------------------- inc interface
 2839: 
 2840: sub inc {
 2841:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 2842:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 2843:     if (!$uname) { $uname=$env{'user.name'}; }
 2844:     my $uhome=&homeserver($uname,$udomain);
 2845:     my $items='';
 2846:     if (! ref($store)) {
 2847:         # got a single value, so use that instead
 2848:         $items = &escape($store).'=&';
 2849:     } elsif (ref($store) eq 'SCALAR') {
 2850:         $items = &escape($$store).'=&';        
 2851:     } elsif (ref($store) eq 'ARRAY') {
 2852:         $items = join('=&',map {&escape($_);} @{$store});
 2853:     } elsif (ref($store) eq 'HASH') {
 2854:         while (my($key,$value) = each(%{$store})) {
 2855:             $items.= &escape($key).'='.&escape($value).'&';
 2856:         }
 2857:     }
 2858:     $items=~s/\&$//;
 2859:     if ($critical) {
 2860: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 2861:     } else {
 2862: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 2863:     }
 2864: }
 2865: 
 2866: # --------------------------------------------------------------- put interface
 2867: 
 2868: sub put {
 2869:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2870:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2871:    if (!$uname) { $uname=$env{'user.name'}; }
 2872:    my $uhome=&homeserver($uname,$udomain);
 2873:    my $items='';
 2874:    foreach (keys %$storehash) {
 2875:        $items.=&escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2876:    }
 2877:    $items=~s/\&$//;
 2878:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 2879: }
 2880: 
 2881: # ------------------------------------------------------------ newput interface
 2882: 
 2883: sub newput {
 2884:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2885:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2886:    if (!$uname) { $uname=$env{'user.name'}; }
 2887:    my $uhome=&homeserver($uname,$udomain);
 2888:    my $items='';
 2889:    foreach my $key (keys(%$storehash)) {
 2890:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2891:    }
 2892:    $items=~s/\&$//;
 2893:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 2894: }
 2895: 
 2896: # ---------------------------------------------------------  putstore interface
 2897: 
 2898: sub putstore {
 2899:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2900:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2901:    if (!$uname) { $uname=$env{'user.name'}; }
 2902:    my $uhome=&homeserver($uname,$udomain);
 2903:    my $items='';
 2904:    my %allitems = ();
 2905:    foreach (keys %$storehash) {
 2906:        if ($_ =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 2907:            my $key = $1.':keys:'.$2;
 2908:            $allitems{$key} .= $3.':';
 2909:        }
 2910:        $items.=$_.'='.&freeze_escape($$storehash{$_}).'&';
 2911:    }
 2912:    foreach (keys %allitems) {
 2913:        $allitems{$_} =~ s/\:$//;
 2914:        $items.= $_.'='.$allitems{$_}.'&';
 2915:    }
 2916:    $items=~s/\&$//;
 2917:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 2918: }
 2919: 
 2920: # ------------------------------------------------------ critical put interface
 2921: 
 2922: sub cput {
 2923:    my ($namespace,$storehash,$udomain,$uname)=@_;
 2924:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2925:    if (!$uname) { $uname=$env{'user.name'}; }
 2926:    my $uhome=&homeserver($uname,$udomain);
 2927:    my $items='';
 2928:    foreach (keys %$storehash) {
 2929:        $items.=escape($_).'='.&freeze_escape($$storehash{$_}).'&';
 2930:    }
 2931:    $items=~s/\&$//;
 2932:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 2933: }
 2934: 
 2935: # -------------------------------------------------------------- eget interface
 2936: 
 2937: sub eget {
 2938:    my ($namespace,$storearr,$udomain,$uname)=@_;
 2939:    my $items='';
 2940:    foreach (@$storearr) {
 2941:        $items.=escape($_).'&';
 2942:    }
 2943:    $items=~s/\&$//;
 2944:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 2945:    if (!$uname) { $uname=$env{'user.name'}; }
 2946:    my $uhome=&homeserver($uname,$udomain);
 2947:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 2948:    my @pairs=split(/\&/,$rep);
 2949:    my %returnhash=();
 2950:    my $i=0;
 2951:    foreach (@$storearr) {
 2952:       $returnhash{$_}=&thaw_unescape($pairs[$i]);
 2953:       $i++;
 2954:    }
 2955:    return %returnhash;
 2956: }
 2957: 
 2958: # ---------------------------------------------- Custom access rule evaluation
 2959: 
 2960: sub customaccess {
 2961:     my ($priv,$uri)=@_;
 2962:     my ($urole,$urealm)=split(/\./,$env{'request.role'});
 2963:     $urealm=~s/^\W//;
 2964:     my ($udom,$ucrs,$usec)=split(/\//,$urealm);
 2965:     my $access=0;
 2966:     foreach (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 2967: 	my ($effect,$realm,$role)=split(/\:/,$_);
 2968:         if ($role) {
 2969: 	   if ($role ne $urole) { next; }
 2970:         }
 2971:         foreach (split(/\s*\,\s*/,$realm)) {
 2972:             my ($tdom,$tcrs,$tsec)=split(/\_/,$_);
 2973:             if ($tdom) {
 2974: 		if ($tdom ne $udom) { next; }
 2975:             }
 2976:             if ($tcrs) {
 2977: 		if ($tcrs ne $ucrs) { next; }
 2978:             }
 2979:             if ($tsec) {
 2980: 		if ($tsec ne $usec) { next; }
 2981:             }
 2982:             $access=($effect eq 'allow');
 2983:             last;
 2984:         }
 2985: 	if ($realm eq '' && $role eq '') {
 2986:             $access=($effect eq 'allow');
 2987: 	}
 2988:     }
 2989:     return $access;
 2990: }
 2991: 
 2992: # ------------------------------------------------- Check for a user privilege
 2993: 
 2994: sub allowed {
 2995:     my ($priv,$uri,$symb)=@_;
 2996:     $uri=&deversion($uri);
 2997:     my $orguri=$uri;
 2998:     $uri=&declutter($uri);
 2999:     
 3000:     
 3001:     
 3002:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3003: # Free bre access to adm and meta resources
 3004:     if (((($uri=~/^adm\//) && ($uri !~ m|/bulletinboard$|)) 
 3005: 	 || ($uri=~/\.meta$/)) && ($priv eq 'bre')) {
 3006: 	return 'F';
 3007:     }
 3008: 
 3009: # Free bre access to user's own portfolio contents
 3010:     my ($space,$domain,$name,$dir)=split('/',$uri);
 3011:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3012: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir)) {
 3013:         return 'F';
 3014:     }
 3015: 
 3016: # Free bre to public access
 3017: 
 3018:     if ($priv eq 'bre') {
 3019:         my $copyright=&metadata($uri,'copyright');
 3020: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3021:            return 'F'; 
 3022:         }
 3023:         if ($copyright eq 'priv') {
 3024:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3025: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3026: 		return '';
 3027:             }
 3028:         }
 3029:         if ($copyright eq 'domain') {
 3030:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3031: 	    unless (($env{'user.domain'} eq $1) ||
 3032:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3033: 		return '';
 3034:             }
 3035:         }
 3036:         if ($env{'request.role'}=~ /li\.\//) {
 3037:             # Library role, so allow browsing of resources in this domain.
 3038:             return 'F';
 3039:         }
 3040:         if ($copyright eq 'custom') {
 3041: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3042:         }
 3043:     }
 3044:     # Domain coordinator is trying to create a course
 3045:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3046:         # uri is the requested domain in this case.
 3047:         # comparison to 'request.role.domain' shows if the user has selected
 3048:         # a role of dc for the domain in question. 
 3049:         return 'F' if ($uri eq $env{'request.role.domain'});
 3050:     }
 3051: 
 3052:     my $thisallowed='';
 3053:     my $statecond=0;
 3054:     my $courseprivid='';
 3055: 
 3056: # Course
 3057: 
 3058:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3059:        $thisallowed.=$1;
 3060:     }
 3061: 
 3062: # Domain
 3063: 
 3064:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3065:        =~/\Q$priv\E\&([^\:]*)/) {
 3066:        $thisallowed.=$1;
 3067:     }
 3068: 
 3069: # Course: uri itself is a course
 3070:     my $courseuri=$uri;
 3071:     $courseuri=~s/\_(\d)/\/$1/;
 3072:     $courseuri=~s/^([^\/])/\/$1/;
 3073: 
 3074:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3075:        =~/\Q$priv\E\&([^\:]*)/) {
 3076:        $thisallowed.=$1;
 3077:     }
 3078: 
 3079: # URI is an uploaded document for this course, default permissions don't matter
 3080: # not allowing 'edit' access (editupload) to uploaded course docs
 3081:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3082: 	$thisallowed='';
 3083: 	my $refuri=$env{'httpref.'.$orguri};
 3084: 	if ($refuri) {
 3085: 	    if ($refuri =~ m|^/adm/|) {
 3086: 		$thisallowed='F';
 3087: 	    }
 3088: 	}
 3089:     }
 3090: 
 3091: # Full access at system, domain or course-wide level? Exit.
 3092: 
 3093:     if ($thisallowed=~/F/) {
 3094: 	return 'F';
 3095:     }
 3096: 
 3097: # If this is generating or modifying users, exit with special codes
 3098: 
 3099:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 3100: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 3101: 	    my ($audom,$auname)=split('/',$uri);
 3102: # no author name given, so this just checks on the general right to make a co-author in this domain
 3103: 	    unless ($auname) { return $thisallowed; }
 3104: # an author name is given, so we are about to actually make a co-author for a certain account
 3105: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 3106: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 3107: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 3108: 	}
 3109: 	return $thisallowed;
 3110:     }
 3111: #
 3112: # Gathered so far: system, domain and course wide privileges
 3113: #
 3114: # Course: See if uri or referer is an individual resource that is part of 
 3115: # the course
 3116: 
 3117:     if ($env{'request.course.id'}) {
 3118: 
 3119:        $courseprivid=$env{'request.course.id'};
 3120:        if ($env{'request.course.sec'}) {
 3121:           $courseprivid.='/'.$env{'request.course.sec'};
 3122:        }
 3123:        $courseprivid=~s/\_/\//;
 3124:        my $checkreferer=1;
 3125:        my ($match,$cond)=&is_on_map($uri);
 3126:        if ($match) {
 3127:            $statecond=$cond;
 3128:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3129:                =~/\Q$priv\E\&([^\:]*)/) {
 3130:                $thisallowed.=$1;
 3131:                $checkreferer=0;
 3132:            }
 3133:        }
 3134:        
 3135:        if ($checkreferer) {
 3136: 	  my $refuri=$env{'httpref.'.$orguri};
 3137:             unless ($refuri) {
 3138:                 foreach (keys %env) {
 3139: 		    if ($_=~/^httpref\..*\*/) {
 3140: 			my $pattern=$_;
 3141:                         $pattern=~s/^httpref\.\/res\///;
 3142:                         $pattern=~s/\*/\[\^\/\]\+/g;
 3143:                         $pattern=~s/\//\\\//g;
 3144:                         if ($orguri=~/$pattern/) {
 3145: 			    $refuri=$env{$_};
 3146:                         }
 3147:                     }
 3148:                 }
 3149:             }
 3150: 
 3151:          if ($refuri) { 
 3152: 	  $refuri=&declutter($refuri);
 3153:           my ($match,$cond)=&is_on_map($refuri);
 3154:             if ($match) {
 3155:               my $refstatecond=$cond;
 3156:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 3157:                   =~/\Q$priv\E\&([^\:]*)/) {
 3158:                   $thisallowed.=$1;
 3159:                   $uri=$refuri;
 3160:                   $statecond=$refstatecond;
 3161:               }
 3162:           }
 3163:         }
 3164:        }
 3165:    }
 3166: 
 3167: #
 3168: # Gathered now: all privileges that could apply, and condition number
 3169: # 
 3170: #
 3171: # Full or no access?
 3172: #
 3173: 
 3174:     if ($thisallowed=~/F/) {
 3175: 	return 'F';
 3176:     }
 3177: 
 3178:     unless ($thisallowed) {
 3179:         return '';
 3180:     }
 3181: 
 3182: # Restrictions exist, deal with them
 3183: #
 3184: #   C:according to course preferences
 3185: #   R:according to resource settings
 3186: #   L:unless locked
 3187: #   X:according to user session state
 3188: #
 3189: 
 3190: # Possibly locked functionality, check all courses
 3191: # Locks might take effect only after 10 minutes cache expiration for other
 3192: # courses, and 2 minutes for current course
 3193: 
 3194:     my $envkey;
 3195:     if ($thisallowed=~/L/) {
 3196:         foreach $envkey (keys %env) {
 3197:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 3198:                my $courseid=$2;
 3199:                my $roleid=$1.'.'.$2;
 3200:                $courseid=~s/^\///;
 3201:                my $expiretime=600;
 3202:                if ($env{'request.role'} eq $roleid) {
 3203: 		  $expiretime=120;
 3204:                }
 3205: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 3206:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 3207:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 3208: 		   &coursedescription($courseid);
 3209:                }
 3210:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3211:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 3212: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 3213:                        &log($env{'user.domain'},$env{'user.name'},
 3214:                             $env{'user.home'},
 3215:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 3216:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3217:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3218: 		       return '';
 3219:                    }
 3220:                }
 3221:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 3222:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 3223: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 3224:                        &log($env{'user.domain'},$env{'user.name'},
 3225:                             $env{'user.home'},
 3226:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 3227:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 3228:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 3229: 		       return '';
 3230:                    }
 3231:                }
 3232: 	   }
 3233:        }
 3234:     }
 3235:    
 3236: #
 3237: # Rest of the restrictions depend on selected course
 3238: #
 3239: 
 3240:     unless ($env{'request.course.id'}) {
 3241:        return '1';
 3242:     }
 3243: 
 3244: #
 3245: # Now user is definitely in a course
 3246: #
 3247: 
 3248: 
 3249: # Course preferences
 3250: 
 3251:    if ($thisallowed=~/C/) {
 3252:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3253:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 3254:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 3255: 	   =~/\Q$rolecode\E/) {
 3256:            &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
 3257:                 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 3258:                 $env{'request.course.id'});
 3259:            return '';
 3260:        }
 3261: 
 3262:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 3263: 	   =~/\Q$unamedom\E/) {
 3264:            &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
 3265:                 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 3266:                 $env{'request.course.id'});
 3267:            return '';
 3268:        }
 3269:    }
 3270: 
 3271: # Resource preferences
 3272: 
 3273:    if ($thisallowed=~/R/) {
 3274:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 3275:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 3276: 	  &log($env{'user.domain'},$env{'user.name'},$env{'user.host'},
 3277:                     'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 3278:           return '';
 3279:        }
 3280:    }
 3281: 
 3282: # Restricted by state or randomout?
 3283: 
 3284:    if ($thisallowed=~/X/) {
 3285:       if ($env{'acc.randomout'}) {
 3286: 	 if (!$symb) { $symb=&symbread($uri,1); }
 3287:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 3288:             return ''; 
 3289:          }
 3290:       }
 3291:       if (&condval($statecond)) {
 3292: 	 return '2';
 3293:       } else {
 3294:          return '';
 3295:       }
 3296:    }
 3297: 
 3298:    return 'F';
 3299: }
 3300: 
 3301: # --------------------------------------------------- Is a resource on the map?
 3302: 
 3303: sub is_on_map {
 3304:     my $uri=&deversion(&declutter(shift));
 3305:     my @uriparts=split(/\//,$uri);
 3306:     my $filename=$uriparts[$#uriparts];
 3307:     my $pathname=$uri;
 3308:     $pathname=~s|/\Q$filename\E$||;
 3309:     $pathname=~s/^adm\/wrapper\///;    
 3310:     #Trying to find the conditional for the file
 3311:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 3312: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 3313:     if ($match) {
 3314: 	return (1,$1);
 3315:     } else {
 3316: 	return (0,0);
 3317:     }
 3318: }
 3319: 
 3320: # --------------------------------------------------------- Get symb from alias
 3321: 
 3322: sub get_symb_from_alias {
 3323:     my $symb=shift;
 3324:     my ($map,$resid,$url)=&decode_symb($symb);
 3325: # Already is a symb
 3326:     if ($url) { return $symb; }
 3327: # Must be an alias
 3328:     my $aliassymb='';
 3329:     my %bighash;
 3330:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 3331:                             &GDBM_READER(),0640)) {
 3332:         my $rid=$bighash{'mapalias_'.$symb};
 3333: 	if ($rid) {
 3334: 	    my ($mapid,$resid)=split(/\./,$rid);
 3335: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 3336: 				    $resid,$bighash{'src_'.$rid});
 3337: 	}
 3338:         untie %bighash;
 3339:     }
 3340:     return $aliassymb;
 3341: }
 3342: 
 3343: # ----------------------------------------------------------------- Define Role
 3344: 
 3345: sub definerole {
 3346:   if (allowed('mcr','/')) {
 3347:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 3348:     foreach (split(':',$sysrole)) {
 3349: 	my ($crole,$cqual)=split(/\&/,$_);
 3350:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 3351:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 3352: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3353:                return "refused:s:$crole&$cqual"; 
 3354:             }
 3355:         }
 3356:     }
 3357:     foreach (split(':',$domrole)) {
 3358: 	my ($crole,$cqual)=split(/\&/,$_);
 3359:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 3360:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 3361: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 3362:                return "refused:d:$crole&$cqual"; 
 3363:             }
 3364:         }
 3365:     }
 3366:     foreach (split(':',$courole)) {
 3367: 	my ($crole,$cqual)=split(/\&/,$_);
 3368:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 3369:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 3370: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 3371:                return "refused:c:$crole&$cqual"; 
 3372:             }
 3373:         }
 3374:     }
 3375:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 3376:                 "$env{'user.domain'}:$env{'user.name'}:".
 3377: 	        "rolesdef_$rolename=".
 3378:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 3379:     return reply($command,$env{'user.home'});
 3380:   } else {
 3381:     return 'refused';
 3382:   }
 3383: }
 3384: 
 3385: # ---------------- Make a metadata query against the network of library servers
 3386: 
 3387: sub metadata_query {
 3388:     my ($query,$custom,$customshow,$server_array)=@_;
 3389:     my %rhash;
 3390:     my @server_list = (defined($server_array) ? @$server_array
 3391:                                               : keys(%libserv) );
 3392:     for my $server (@server_list) {
 3393: 	unless ($custom or $customshow) {
 3394: 	    my $reply=&reply("querysend:".&escape($query),$server);
 3395: 	    $rhash{$server}=$reply;
 3396: 	}
 3397: 	else {
 3398: 	    my $reply=&reply("querysend:".&escape($query).':'.
 3399: 			     &escape($custom).':'.&escape($customshow),
 3400: 			     $server);
 3401: 	    $rhash{$server}=$reply;
 3402: 	}
 3403:     }
 3404:     return \%rhash;
 3405: }
 3406: 
 3407: # ----------------------------------------- Send log queries and wait for reply
 3408: 
 3409: sub log_query {
 3410:     my ($uname,$udom,$query,%filters)=@_;
 3411:     my $uhome=&homeserver($uname,$udom);
 3412:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 3413:     my $uhost=$hostname{$uhome};
 3414:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys %filters));
 3415:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 3416:                        $uhome);
 3417:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 3418:     return get_query_reply($queryid);
 3419: }
 3420: 
 3421: # ------- Request retrieval of institutional classlists for course(s)
 3422: 
 3423: sub fetch_enrollment_query {
 3424:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 3425:     my $homeserver;
 3426:     my $maxtries = 1;
 3427:     if ($context eq 'automated') {
 3428:         $homeserver = $perlvar{'lonHostID'};
 3429:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 3430:     } else {
 3431:         $homeserver = &homeserver($cnum,$dom);
 3432:     }
 3433:     my $host=$hostname{$homeserver};
 3434:     my $cmd = '';
 3435:     foreach (keys %{$affiliatesref}) {
 3436:         $cmd .= $_.'='.join(",",@{$$affiliatesref{$_}}).'%%';
 3437:     }
 3438:     $cmd =~ s/%%$//;
 3439:     $cmd = &escape($cmd);
 3440:     my $query = 'fetchenrollment';
 3441:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 3442:     unless ($queryid=~/^\Q$host\E\_/) { 
 3443:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 3444:         return 'error: '.$queryid;
 3445:     }
 3446:     my $reply = &get_query_reply($queryid);
 3447:     my $tries = 1;
 3448:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 3449:         $reply = &get_query_reply($queryid);
 3450:         $tries ++;
 3451:     }
 3452:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 3453:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 3454:     } else {
 3455:         my @responses = split/:/,$reply;
 3456:         if ($homeserver eq $perlvar{'lonHostID'}) {
 3457:             foreach (@responses) {
 3458:                 my ($key,$value) = split/=/,$_;
 3459:                 $$replyref{$key} = $value;
 3460:             }
 3461:         } else {
 3462:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 3463:             foreach (@responses) {
 3464:                 my ($key,$value) = split/=/,$_;
 3465:                 $$replyref{$key} = $value;
 3466:                 if ($value > 0) {
 3467:                     foreach (@{$$affiliatesref{$key}}) {
 3468:                         my $filename = $dom.'_'.$key.'_'.$_.'_classlist.xml';
 3469:                         my $destname = $pathname.'/'.$filename;
 3470:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 3471:                         if ($xml_classlist =~ /^error/) {
 3472:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 3473:                         } else {
 3474:                             if ( open(FILE,">$destname") ) {
 3475:                                 print FILE &unescape($xml_classlist);
 3476:                                 close(FILE);
 3477:                             } else {
 3478:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 3479:                             }
 3480:                         }
 3481:                     }
 3482:                 }
 3483:             }
 3484:         }
 3485:         return 'ok';
 3486:     }
 3487:     return 'error';
 3488: }
 3489: 
 3490: sub get_query_reply {
 3491:     my $queryid=shift;
 3492:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 3493:     my $reply='';
 3494:     for (1..100) {
 3495: 	sleep 2;
 3496:         if (-e $replyfile.'.end') {
 3497: 	    if (open(my $fh,$replyfile)) {
 3498:                $reply.=<$fh>;
 3499:                close($fh);
 3500: 	   } else { return 'error: reply_file_error'; }
 3501:            return &unescape($reply);
 3502: 	}
 3503:     }
 3504:     return 'timeout:'.$queryid;
 3505: }
 3506: 
 3507: sub courselog_query {
 3508: #
 3509: # possible filters:
 3510: # url: url or symb
 3511: # username
 3512: # domain
 3513: # action: view, submit, grade
 3514: # start: timestamp
 3515: # end: timestamp
 3516: #
 3517:     my (%filters)=@_;
 3518:     unless ($env{'request.course.id'}) { return 'no_course'; }
 3519:     if ($filters{'url'}) {
 3520: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 3521:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 3522:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 3523:     }
 3524:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3525:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3526:     return &log_query($cname,$cdom,'courselog',%filters);
 3527: }
 3528: 
 3529: sub userlog_query {
 3530:     my ($uname,$udom,%filters)=@_;
 3531:     return &log_query($uname,$udom,'userlog',%filters);
 3532: }
 3533: 
 3534: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 3535: 
 3536: sub auto_run {
 3537:     my ($cnum,$cdom) = @_;
 3538:     my $homeserver = &homeserver($cnum,$cdom);
 3539:     my $response = &reply('autorun:'.$cdom,$homeserver);
 3540:     return $response;
 3541: }
 3542:                                                                                    
 3543: sub auto_get_sections {
 3544:     my ($cnum,$cdom,$inst_coursecode) = @_;
 3545:     my $homeserver = &homeserver($cnum,$cdom);
 3546:     my @secs = ();
 3547:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 3548:     unless ($response eq 'refused') {
 3549:         @secs = split/:/,$response;
 3550:     }
 3551:     return @secs;
 3552: }
 3553:                                                                                    
 3554: sub auto_new_course {
 3555:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 3556:     my $homeserver = &homeserver($cnum,$cdom);
 3557:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 3558:     return $response;
 3559: }
 3560:                                                                                    
 3561: sub auto_validate_courseID {
 3562:     my ($cnum,$cdom,$inst_course_id) = @_;
 3563:     my $homeserver = &homeserver($cnum,$cdom);
 3564:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 3565:     return $response;
 3566: }
 3567:                                                                                    
 3568: sub auto_create_password {
 3569:     my ($cnum,$cdom,$authparam) = @_;
 3570:     my $homeserver = &homeserver($cnum,$cdom); 
 3571:     my $create_passwd = 0;
 3572:     my $authchk = '';
 3573:     my $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 3574:     if ($response eq 'refused') {
 3575:         $authchk = 'refused';
 3576:     } else {
 3577:         ($authparam,$create_passwd,$authchk) = split/:/,$response;
 3578:     }
 3579:     return ($authparam,$create_passwd,$authchk);
 3580: }
 3581: 
 3582: sub auto_instcode_format {
 3583:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,$cat_order) = @_;
 3584:     my $courses = '';
 3585:     my $homeserver;
 3586:     if ($caller eq 'global') {
 3587:         foreach my $tryserver (keys %libserv) {
 3588:             if ($hostdom{$tryserver} eq $codedom) {
 3589:                 $homeserver = $tryserver;
 3590:                 last;
 3591:             }
 3592:         }
 3593:         if (($env{'user.name'}) && ($env{'user.domain'} eq $codedom)) {
 3594:             $homeserver = &homeserver($env{'user.name'},$codedom);
 3595:         }
 3596:     } else {
 3597:         $homeserver = &homeserver($caller,$codedom);
 3598:     }
 3599:     foreach (keys %{$instcodes}) {
 3600:         $courses .= &escape($_).'='.&escape($$instcodes{$_}).'&';
 3601:     }
 3602:     chop($courses);
 3603:     my $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$homeserver);
 3604:     unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 3605:         my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = split/:/,$response;
 3606:         %{$codes} = &str2hash($codes_str);
 3607:         @{$codetitles} = &str2array($codetitles_str);
 3608:         %{$cat_titles} = &str2hash($cat_titles_str);
 3609:         %{$cat_order} = &str2hash($cat_order_str);
 3610:         return 'ok';
 3611:     }
 3612:     return $response;
 3613: }
 3614: 
 3615: # ------------------------------------------------------------------ Plain Text
 3616: 
 3617: sub plaintext {
 3618:     my $short=shift;
 3619:     return &mt($prp{$short});
 3620: }
 3621: 
 3622: # ----------------------------------------------------------------- Assign Role
 3623: 
 3624: sub assignrole {
 3625:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 3626:     my $mrole;
 3627:     if ($role =~ /^cr\//) {
 3628:         my $cwosec=$url;
 3629:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 3630: 	unless (&allowed('ccr',$cwosec)) {
 3631:            &logthis('Refused custom assignrole: '.
 3632:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 3633: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 3634:            return 'refused'; 
 3635:         }
 3636:         $mrole='cr';
 3637:     } else {
 3638:         my $cwosec=$url;
 3639:         $cwosec=~s/^\/(\w+)\/(\w+)\/.*/$1\/$2/;
 3640:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 3641:            &logthis('Refused assignrole: '.
 3642:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 3643: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 3644:            return 'refused'; 
 3645:         }
 3646:         $mrole=$role;
 3647:     }
 3648:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 3649:                 "$udom:$uname:$url".'_'."$mrole=$role";
 3650:     if ($end) { $command.='_'.$end; }
 3651:     if ($start) {
 3652: 	if ($end) { 
 3653:            $command.='_'.$start; 
 3654:         } else {
 3655:            $command.='_0_'.$start;
 3656:         }
 3657:     }
 3658: # actually delete
 3659:     if ($deleteflag) {
 3660: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 3661: # modify command to delete the role
 3662:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 3663:                 "$udom:$uname:$url".'_'."$mrole";
 3664: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 3665: # set start and finish to negative values for userrolelog
 3666:            $start=-1;
 3667:            $end=-1;
 3668:         }
 3669:     }
 3670: # send command
 3671:     my $answer=&reply($command,&homeserver($uname,$udom));
 3672: # log new user role if status is ok
 3673:     if ($answer eq 'ok') {
 3674: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 3675:     }
 3676:     return $answer;
 3677: }
 3678: 
 3679: # -------------------------------------------------- Modify user authentication
 3680: # Overrides without validation
 3681: 
 3682: sub modifyuserauth {
 3683:     my ($udom,$uname,$umode,$upass)=@_;
 3684:     my $uhome=&homeserver($uname,$udom);
 3685:     unless (&allowed('mau',$udom)) { return 'refused'; }
 3686:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 3687:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 3688:              ' in domain '.$env{'request.role.domain'});  
 3689:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 3690: 		     &escape($upass),$uhome);
 3691:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 3692:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 3693:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 3694:     &log($udom,,$uname,$uhome,
 3695:         'Authentication changed by '.$env{'user.domain'}.', '.
 3696:                                      $env{'user.name'}.', '.$umode.
 3697:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 3698:     unless ($reply eq 'ok') {
 3699:         &logthis('Authentication mode error: '.$reply);
 3700: 	return 'error: '.$reply;
 3701:     }   
 3702:     return 'ok';
 3703: }
 3704: 
 3705: # --------------------------------------------------------------- Modify a user
 3706: 
 3707: sub modifyuser {
 3708:     my ($udom,    $uname, $uid,
 3709:         $umode,   $upass, $first,
 3710:         $middle,  $last,  $gene,
 3711:         $forceid, $desiredhome, $email)=@_;
 3712:     $udom=~s/\W//g;
 3713:     $uname=~s/\W//g;
 3714:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 3715:              $umode.', '.$first.', '.$middle.', '.
 3716: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 3717:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 3718:                                      ' desiredhome not specified'). 
 3719:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 3720:              ' in domain '.$env{'request.role.domain'});
 3721:     my $uhome=&homeserver($uname,$udom,'true');
 3722: # ----------------------------------------------------------------- Create User
 3723:     if (($uhome eq 'no_host') && 
 3724: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 3725:         my $unhome='';
 3726:         if (defined($desiredhome) && $hostdom{$desiredhome} eq $udom) { 
 3727:             $unhome = $desiredhome;
 3728: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 3729: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 3730:         } else { # load balancing routine for determining $unhome
 3731:             my $tryserver;
 3732:             my $loadm=10000000;
 3733:             foreach $tryserver (keys %libserv) {
 3734: 	       if ($hostdom{$tryserver} eq $udom) {
 3735:                   my $answer=reply('load',$tryserver);
 3736:                   if (($answer=~/\d+/) && ($answer<$loadm)) {
 3737: 		      $loadm=$answer;
 3738:                       $unhome=$tryserver;
 3739:                   }
 3740: 	       }
 3741: 	    }
 3742:         }
 3743:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 3744: 	    return 'error: unable to find a home server for '.$uname.
 3745:                    ' in domain '.$udom;
 3746:         }
 3747:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 3748:                          &escape($upass),$unhome);
 3749: 	unless ($reply eq 'ok') {
 3750:             return 'error: '.$reply;
 3751:         }   
 3752:         $uhome=&homeserver($uname,$udom,'true');
 3753:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 3754: 	    return 'error: unable verify users home machine.';
 3755:         }
 3756:     }   # End of creation of new user
 3757: # ---------------------------------------------------------------------- Add ID
 3758:     if ($uid) {
 3759:        $uid=~tr/A-Z/a-z/;
 3760:        my %uidhash=&idrget($udom,$uname);
 3761:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 3762:          && (!$forceid)) {
 3763: 	  unless ($uid eq $uidhash{$uname}) {
 3764: 	      return 'error: user id "'.$uid.'" does not match '.
 3765:                   'current user id "'.$uidhash{$uname}.'".';
 3766:           }
 3767:        } else {
 3768: 	  &idput($udom,($uname => $uid));
 3769:        }
 3770:     }
 3771: # -------------------------------------------------------------- Add names, etc
 3772:     my @tmp=&get('environment',
 3773: 		   ['firstname','middlename','lastname','generation'],
 3774: 		   $udom,$uname);
 3775:     my %names;
 3776:     if ($tmp[0] =~ m/^error:.*/) { 
 3777:         %names=(); 
 3778:     } else {
 3779:         %names = @tmp;
 3780:     }
 3781: #
 3782: # Make sure to not trash student environment if instructor does not bother
 3783: # to supply name and email information
 3784: #
 3785:     if ($first)  { $names{'firstname'}  = $first; }
 3786:     if (defined($middle)) { $names{'middlename'} = $middle; }
 3787:     if ($last)   { $names{'lastname'}   = $last; }
 3788:     if (defined($gene))   { $names{'generation'} = $gene; }
 3789:     if ($email) {
 3790:        $email=~s/[^\w\@\.\-\,]//gs;
 3791:        if ($email=~/\@/) { $names{'notification'} = $email;
 3792: 			   $names{'critnotification'} = $email;
 3793: 			   $names{'permanentemail'} = $email; }
 3794:     }
 3795:     my $reply = &put('environment', \%names, $udom,$uname);
 3796:     if ($reply ne 'ok') { return 'error: '.$reply; }
 3797:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 3798:              $umode.', '.$first.', '.$middle.', '.
 3799: 	     $last.', '.$gene.' by '.
 3800:              $env{'user.name'}.' at '.$env{'user.domain'});
 3801:     return 'ok';
 3802: }
 3803: 
 3804: # -------------------------------------------------------------- Modify student
 3805: 
 3806: sub modifystudent {
 3807:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 3808:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 3809:     if (!$cid) {
 3810: 	unless ($cid=$env{'request.course.id'}) {
 3811: 	    return 'not_in_class';
 3812: 	}
 3813:     }
 3814: # --------------------------------------------------------------- Make the user
 3815:     my $reply=&modifyuser
 3816: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 3817:          $desiredhome,$email);
 3818:     unless ($reply eq 'ok') { return $reply; }
 3819:     # This will cause &modify_student_enrollment to get the uid from the
 3820:     # students environment
 3821:     $uid = undef if (!$forceid);
 3822:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 3823: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 3824:     return $reply;
 3825: }
 3826: 
 3827: sub modify_student_enrollment {
 3828:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 3829:     my ($cdom,$cnum,$chome);
 3830:     if (!$cid) {
 3831: 	unless ($cid=$env{'request.course.id'}) {
 3832: 	    return 'not_in_class';
 3833: 	}
 3834: 	$cdom=$env{'course.'.$cid.'.domain'};
 3835: 	$cnum=$env{'course.'.$cid.'.num'};
 3836:     } else {
 3837: 	($cdom,$cnum)=split(/_/,$cid);
 3838:     }
 3839:     $chome=$env{'course.'.$cid.'.home'};
 3840:     if (!$chome) {
 3841: 	$chome=&homeserver($cnum,$cdom);
 3842:     }
 3843:     if (!$chome) { return 'unknown_course'; }
 3844:     # Make sure the user exists
 3845:     my $uhome=&homeserver($uname,$udom);
 3846:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 3847: 	return 'error: no such user';
 3848:     }
 3849:     # Get student data if we were not given enough information
 3850:     if (!defined($first)  || $first  eq '' || 
 3851:         !defined($last)   || $last   eq '' || 
 3852:         !defined($uid)    || $uid    eq '' || 
 3853:         !defined($middle) || $middle eq '' || 
 3854:         !defined($gene)   || $gene   eq '') {
 3855:         # They did not supply us with enough data to enroll the student, so
 3856:         # we need to pick up more information.
 3857:         my %tmp = &get('environment',
 3858:                        ['firstname','middlename','lastname', 'generation','id']
 3859:                        ,$udom,$uname);
 3860: 
 3861:         #foreach (keys(%tmp)) {
 3862:         #    &logthis("key $_ = ".$tmp{$_});
 3863:         #}
 3864:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 3865:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 3866:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 3867:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 3868:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 3869:     }
 3870:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 3871:     my $reply=cput('classlist',
 3872: 		   {"$uname:$udom" => 
 3873: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 3874: 		   $cdom,$cnum);
 3875:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 3876: 	return 'error: '.$reply;
 3877:     } else {
 3878: 	&devalidate_getsection_cache($udom,$uname,$cid);
 3879:     }
 3880:     # Add student role to user
 3881:     my $uurl='/'.$cid;
 3882:     $uurl=~s/\_/\//g;
 3883:     if ($usec) {
 3884: 	$uurl.='/'.$usec;
 3885:     }
 3886:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 3887: }
 3888: 
 3889: sub format_name {
 3890:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 3891:     my $name;
 3892:     if ($first ne 'lastname') {
 3893: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 3894:     } else {
 3895: 	if ($lastname=~/\S/) {
 3896: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 3897: 	    $name=~s/\s+,/,/;
 3898: 	} else {
 3899: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 3900: 	}
 3901:     }
 3902:     $name=~s/^\s+//;
 3903:     $name=~s/\s+$//;
 3904:     $name=~s/\s+/ /g;
 3905:     return $name;
 3906: }
 3907: 
 3908: # ------------------------------------------------- Write to course preferences
 3909: 
 3910: sub writecoursepref {
 3911:     my ($courseid,%prefs)=@_;
 3912:     $courseid=~s/^\///;
 3913:     $courseid=~s/\_/\//g;
 3914:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3915:     my $chome=homeserver($cnum,$cdomain);
 3916:     if (($chome eq '') || ($chome eq 'no_host')) { 
 3917: 	return 'error: no such course';
 3918:     }
 3919:     my $cstring='';
 3920:     foreach (keys %prefs) {
 3921: 	$cstring.=escape($_).'='.escape($prefs{$_}).'&';
 3922:     }
 3923:     $cstring=~s/\&$//;
 3924:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 3925: }
 3926: 
 3927: # ---------------------------------------------------------- Make/modify course
 3928: 
 3929: sub createcourse {
 3930:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner)=@_;
 3931:     $url=&declutter($url);
 3932:     my $cid='';
 3933:     unless (&allowed('ccc',$udom)) {
 3934:         return 'refused';
 3935:     }
 3936: # ------------------------------------------------------------------- Create ID
 3937:    my $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 3938:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 3939: # ----------------------------------------------- Make sure that does not exist
 3940:    my $uhome=&homeserver($uname,$udom,'true');
 3941:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 3942:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 3943:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 3944:        $uhome=&homeserver($uname,$udom,'true');       
 3945:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 3946:            return 'error: unable to generate unique course-ID';
 3947:        } 
 3948:    }
 3949: # ------------------------------------------------ Check supplied server name
 3950:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 3951:     if (! exists($libserv{$course_server})) {
 3952:         return 'error:bad server name '.$course_server;
 3953:     }
 3954: # ------------------------------------------------------------- Make the course
 3955:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 3956:                       $course_server);
 3957:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 3958:     $uhome=&homeserver($uname,$udom,'true');
 3959:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 3960: 	return 'error: no such course';
 3961:     }
 3962: # ----------------------------------------------------------------- Course made
 3963: # log existence
 3964:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 3965:                  ':'.&escape($inst_code).':'.&escape($course_owner),$uhome);
 3966:     &flushcourselogs();
 3967: # set toplevel url
 3968:     my $topurl=$url;
 3969:     unless ($nonstandard) {
 3970: # ------------------------------------------ For standard courses, make top url
 3971:         my $mapurl=&clutter($url);
 3972:         if ($mapurl eq '/res/') { $mapurl=''; }
 3973:         $env{'form.initmap'}=(<<ENDINITMAP);
 3974: <map>
 3975: <resource id="1" type="start"></resource>
 3976: <resource id="2" src="$mapurl"></resource>
 3977: <resource id="3" type="finish"></resource>
 3978: <link index="1" from="1" to="2"></link>
 3979: <link index="2" from="2" to="3"></link>
 3980: </map>
 3981: ENDINITMAP
 3982:         $topurl=&declutter(
 3983:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 3984:                           );
 3985:     }
 3986: # ----------------------------------------------------------- Write preferences
 3987:     &writecoursepref($udom.'_'.$uname,
 3988:                      ('description' => $description,
 3989:                       'url'         => $topurl));
 3990:     return '/'.$udom.'/'.$uname;
 3991: }
 3992: 
 3993: # ---------------------------------------------------------- Assign Custom Role
 3994: 
 3995: sub assigncustomrole {
 3996:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 3997:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 3998:                        $end,$start,$deleteflag);
 3999: }
 4000: 
 4001: # ----------------------------------------------------------------- Revoke Role
 4002: 
 4003: sub revokerole {
 4004:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 4005:     my $now=time;
 4006:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 4007: }
 4008: 
 4009: # ---------------------------------------------------------- Revoke Custom Role
 4010: 
 4011: sub revokecustomrole {
 4012:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 4013:     my $now=time;
 4014:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 4015:            $deleteflag);
 4016: }
 4017: 
 4018: # ------------------------------------------------------------ Disk usage
 4019: sub diskusage {
 4020:     my ($udom,$uname,$directoryRoot)=@_;
 4021:     $directoryRoot =~ s/\/$//;
 4022:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 4023:     return $listing;
 4024: }
 4025: 
 4026: sub is_locked {
 4027:     my ($file_name, $domain, $user) = @_;
 4028:     my @check;
 4029:     my $is_locked;
 4030:     push @check, $file_name;
 4031:     my %locked = &get('file_permissions',\@check,
 4032: 		      $env{'user.domain'},$env{'user.name'});
 4033:     my ($tmp)=keys(%locked);
 4034:     if ($tmp=~/^error:/) { undef(%locked); }
 4035: 
 4036:     if (ref($locked{$file_name}) eq 'ARRAY') {
 4037:         $is_locked = 'true';
 4038:     } else {
 4039:         $is_locked = 'false';
 4040:     }
 4041: }
 4042: 
 4043: # ------------------------------------------------------------- Mark as Read Only
 4044: 
 4045: sub mark_as_readonly {
 4046:     my ($domain,$user,$files,$what) = @_;
 4047:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4048:     my ($tmp)=keys(%current_permissions);
 4049:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4050:     foreach my $file (@{$files}) {
 4051:         push(@{$current_permissions{$file}},$what);
 4052:     }
 4053:     &put('file_permissions',\%current_permissions,$domain,$user);
 4054:     return;
 4055: }
 4056: 
 4057: # ------------------------------------------------------------Save Selected Files
 4058: 
 4059: sub save_selected_files {
 4060:     my ($user, $path, @files) = @_;
 4061:     my $filename = $user."savedfiles";
 4062:     my @other_files = &files_not_in_path($user, $path);
 4063:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4064:     foreach my $file (@files) {
 4065:         print (OUT $env{'form.currentpath'}.$file."\n");
 4066:     }
 4067:     foreach my $file (@other_files) {
 4068:         print (OUT $file."\n");
 4069:     }
 4070:     close (OUT);
 4071:     return 'ok';
 4072: }
 4073: 
 4074: sub clear_selected_files {
 4075:     my ($user) = @_;
 4076:     my $filename = $user."savedfiles";
 4077:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4078:     print (OUT undef);
 4079:     close (OUT);
 4080:     return ("ok");    
 4081: }
 4082: 
 4083: sub files_in_path {
 4084:     my ($user, $path) = @_;
 4085:     my $filename = $user."savedfiles";
 4086:     my %return_files;
 4087:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4088:     while (my $line_in = <IN>) {
 4089:         chomp ($line_in);
 4090:         my @paths_and_file = split (m!/!, $line_in);
 4091:         my $file_part = pop (@paths_and_file);
 4092:         my $path_part = join ('/', @paths_and_file);
 4093:         $path_part.='/';
 4094:         my $path_and_file = $path_part.$file_part;
 4095:         if ($path_part eq $path) {
 4096:             $return_files{$file_part}= 'selected';
 4097:         }
 4098:     }
 4099:     close (IN);
 4100:     return (\%return_files);
 4101: }
 4102: 
 4103: # called in portfolio select mode, to show files selected NOT in current directory
 4104: sub files_not_in_path {
 4105:     my ($user, $path) = @_;
 4106:     my $filename = $user."savedfiles";
 4107:     my @return_files;
 4108:     my $path_part;
 4109:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 4110:     while (<IN>) {
 4111:         #ok, I know it's clunky, but I want it to work
 4112:         my @paths_and_file = split m!/!, $_;
 4113:         my $file_part = pop (@paths_and_file);
 4114:         chomp ($file_part);
 4115:         my $path_part = join ('/', @paths_and_file);
 4116:         $path_part .= '/';
 4117:         my $path_and_file = $path_part.$file_part;
 4118:         if ($path_part ne $path) {
 4119:             push (@return_files, ($path_and_file));
 4120:         }
 4121:     }
 4122:     close (OUT);
 4123:     return (@return_files);
 4124: }
 4125: 
 4126: #--------------------------------------------------------------Get Marked as Read Only
 4127: 
 4128: 
 4129: sub get_marked_as_readonly {
 4130:     my ($domain,$user,$what) = @_;
 4131:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4132:     my ($tmp)=keys(%current_permissions);
 4133:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4134:     my @readonly_files;
 4135:     my $cmp1=$what;
 4136:     if (ref($what)) { $cmp1=join('',@{$what}) };
 4137:     while (my ($file_name,$value) = each(%current_permissions)) {
 4138:         if (ref($value) eq "ARRAY"){
 4139:             foreach my $stored_what (@{$value}) {
 4140:                 my $cmp2=$stored_what;
 4141:                 if (ref($stored_what)) { $cmp2=join('',@{$stored_what}) };
 4142:                 if ($cmp1 eq $cmp2) {
 4143:                     push(@readonly_files, $file_name);
 4144:                 } elsif (!defined($what)) {
 4145:                     push(@readonly_files, $file_name);
 4146:                 }
 4147:             }
 4148:         } 
 4149:     }
 4150:     return @readonly_files;
 4151: }
 4152: #-----------------------------------------------------------Get Marked as Read Only Hash
 4153: 
 4154: sub get_marked_as_readonly_hash {
 4155:     my ($domain,$user,$what) = @_;
 4156:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4157:     my ($tmp)=keys(%current_permissions);
 4158:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4159: 
 4160:     my %readonly_files;
 4161:     while (my ($file_name,$value) = each(%current_permissions)) {
 4162:         if (ref($value) eq "ARRAY"){
 4163:             foreach my $stored_what (@{$value}) {
 4164:                 if ($stored_what eq $what) {
 4165:                     $readonly_files{$file_name} = 'locked';
 4166:                 } elsif (!defined($what)) {
 4167:                     $readonly_files{$file_name} = 'locked';
 4168:                 }
 4169:             }
 4170:         } 
 4171:     }
 4172:     return %readonly_files;
 4173: }
 4174: # ------------------------------------------------------------ Unmark as Read Only
 4175: 
 4176: sub unmark_as_readonly {
 4177:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 4178:     # for portfolio submissions, $what contains [$symb,$crsid] 
 4179:     my ($domain,$user,$what,$file_name) = @_;
 4180:     my $symb_crs = $what;
 4181:     if (ref($what)) { $symb_crs=join('',@$what); }
 4182:     my %current_permissions = &dump('file_permissions',$domain,$user);
 4183:     my ($tmp)=keys(%current_permissions);
 4184:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 4185:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what);
 4186:     foreach my $file (@readonly_files) {
 4187: 	if (defined($file_name) && ($file_name ne $file)) { next; }
 4188: 	my $current_locks = $current_permissions{$file};
 4189:         my @new_locks;
 4190:         my @del_keys;
 4191:         if (ref($current_locks) eq "ARRAY"){
 4192:             foreach my $locker (@{$current_locks}) {
 4193:                 my $compare=$locker;
 4194:                 if (ref($locker)) { $compare=join('',@{$locker}) };
 4195:                 if ($compare ne $symb_crs) {
 4196:                     push(@new_locks, $locker);
 4197:                 }
 4198:             }
 4199:             if (scalar(@new_locks) > 0) {
 4200:                 $current_permissions{$file} = \@new_locks;
 4201:             } else {
 4202:                 push(@del_keys, $file);
 4203:                 &del('file_permissions',\@del_keys, $domain, $user);
 4204:                 delete($current_permissions{$file});
 4205:             }
 4206:         }
 4207:     }
 4208:     &put('file_permissions',\%current_permissions,$domain,$user);
 4209:     return;
 4210: }
 4211: 
 4212: # ------------------------------------------------------------ Directory lister
 4213: 
 4214: sub dirlist {
 4215:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 4216: 
 4217:     $uri=~s/^\///;
 4218:     $uri=~s/\/$//;
 4219:     my ($udom, $uname);
 4220:     (undef,$udom,$uname)=split(/\//,$uri);
 4221:     if(defined($userdomain)) {
 4222:         $udom = $userdomain;
 4223:     }
 4224:     if(defined($username)) {
 4225:         $uname = $username;
 4226:     }
 4227: 
 4228:     my $dirRoot = $perlvar{'lonDocRoot'};
 4229:     if(defined($alternateDirectoryRoot)) {
 4230:         $dirRoot = $alternateDirectoryRoot;
 4231:         $dirRoot =~ s/\/$//;
 4232:     }
 4233: 
 4234:     if($udom) {
 4235:         if($uname) {
 4236:             my $listing=reply('ls2:'.$dirRoot.'/'.$uri,
 4237:                               homeserver($uname,$udom));
 4238:             my @listing_results;
 4239:             if ($listing eq 'unknown_cmd') {
 4240:                 $listing=reply('ls:'.$dirRoot.'/'.$uri,
 4241:                                homeserver($uname,$udom));
 4242:                 @listing_results = split(/:/,$listing);
 4243:             } else {
 4244:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 4245:             }
 4246:             return @listing_results;
 4247:         } elsif(!defined($alternateDirectoryRoot)) {
 4248:             my $tryserver;
 4249:             my %allusers=();
 4250:             foreach $tryserver (keys %libserv) {
 4251:                 if($hostdom{$tryserver} eq $udom) {
 4252:                     my $listing=reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 4253:                                       $udom, $tryserver);
 4254:                     my @listing_results;
 4255:                     if ($listing eq 'unknown_cmd') {
 4256:                         $listing=reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 4257:                                        $udom, $tryserver);
 4258:                         @listing_results = split(/:/,$listing);
 4259:                     } else {
 4260:                         @listing_results =
 4261:                             map { &unescape($_); } split(/:/,$listing);
 4262:                     }
 4263:                     if ($listing_results[0] ne 'no_such_dir' && 
 4264:                         $listing_results[0] ne 'empty'       &&
 4265:                         $listing_results[0] ne 'con_lost') {
 4266:                         foreach (@listing_results) {
 4267:                             my ($entry,@stat)=split(/&/,$_);
 4268:                             $allusers{$entry}=1;
 4269:                         }
 4270:                     }
 4271:                 }
 4272:             }
 4273:             my $alluserstr='';
 4274:             foreach (sort keys %allusers) {
 4275:                 $alluserstr.=$_.'&user:';
 4276:             }
 4277:             $alluserstr=~s/:$//;
 4278:             return split(/:/,$alluserstr);
 4279:         } else {
 4280:             my @emptyResults = ();
 4281:             push(@emptyResults, 'missing user name');
 4282:             return split(':',@emptyResults);
 4283:         }
 4284:     } elsif(!defined($alternateDirectoryRoot)) {
 4285:         my $tryserver;
 4286:         my %alldom=();
 4287:         foreach $tryserver (keys %libserv) {
 4288:             $alldom{$hostdom{$tryserver}}=1;
 4289:         }
 4290:         my $alldomstr='';
 4291:         foreach (sort keys %alldom) {
 4292:             $alldomstr.=$perlvar{'lonDocRoot'}.'/res/'.$_.'/&domain:';
 4293:         }
 4294:         $alldomstr=~s/:$//;
 4295:         return split(/:/,$alldomstr);       
 4296:     } else {
 4297:         my @emptyResults = ();
 4298:         push(@emptyResults, 'missing domain');
 4299:         return split(':',@emptyResults);
 4300:     }
 4301: }
 4302: 
 4303: # --------------------------------------------- GetFileTimestamp
 4304: # This function utilizes dirlist and returns the date stamp for
 4305: # when it was last modified.  It will also return an error of -1
 4306: # if an error occurs
 4307: 
 4308: ##
 4309: ## FIXME: This subroutine assumes its caller knows something about the
 4310: ## directory structure of the home server for the student ($root).
 4311: ## Not a good assumption to make.  Since this is for looking up files
 4312: ## in user directories, the full path should be constructed by lond, not
 4313: ## whatever machine we request data from.
 4314: ##
 4315: sub GetFileTimestamp {
 4316:     my ($studentDomain,$studentName,$filename,$root)=@_;
 4317:     $studentDomain=~s/\W//g;
 4318:     $studentName=~s/\W//g;
 4319:     my $subdir=$studentName.'__';
 4320:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 4321:     my $proname="$studentDomain/$subdir/$studentName";
 4322:     $proname .= '/'.$filename;
 4323:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 4324:                                               $studentName, $root);
 4325:     my @stats = split('&', $fileStat);
 4326:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 4327:         # @stats contains first the filename, then the stat output
 4328:         return $stats[10]; # so this is 10 instead of 9.
 4329:     } else {
 4330:         return -1;
 4331:     }
 4332: }
 4333: 
 4334: # -------------------------------------------------------- Value of a Condition
 4335: 
 4336: sub directcondval {
 4337:     my $number=shift;
 4338:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 4339: 	&Apache::lonuserstate::evalstate();
 4340:     }
 4341:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 4342:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 4343:     } else {
 4344:        return 2;
 4345:     }
 4346: }
 4347: 
 4348: sub condval {
 4349:     my $condidx=shift;
 4350:     my $result=0;
 4351:     my $allpathcond='';
 4352:     foreach (split(/\|/,$condidx)) {
 4353:        if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$_})) {
 4354: 	   $allpathcond.=
 4355:                '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$_}.')|';
 4356:        }
 4357:     }
 4358:     $allpathcond=~s/\|$//;
 4359:     if ($env{'request.course.id'}) {
 4360:        if ($allpathcond) {
 4361:           my $operand='|';
 4362: 	  my @stack;
 4363:            foreach ($allpathcond=~/(\d+|\(|\)|\&|\|)/g) {
 4364:               if ($_ eq '(') {
 4365:                  push @stack,($operand,$result)
 4366:               } elsif ($_ eq ')') {
 4367:                   my $before=pop @stack;
 4368: 		  if (pop @stack eq '&') {
 4369: 		      $result=$result>$before?$before:$result;
 4370:                   } else {
 4371:                       $result=$result>$before?$result:$before;
 4372:                   }
 4373:               } elsif (($_ eq '&') || ($_ eq '|')) {
 4374:                   $operand=$_;
 4375:               } else {
 4376:                   my $new=directcondval($_);
 4377:                   if ($operand eq '&') {
 4378:                      $result=$result>$new?$new:$result;
 4379:                   } else {
 4380:                      $result=$result>$new?$result:$new;
 4381:                   }
 4382:               }
 4383:           }
 4384:        }
 4385:     }
 4386:     return $result;
 4387: }
 4388: 
 4389: # ---------------------------------------------------- Devalidate courseresdata
 4390: 
 4391: sub devalidatecourseresdata {
 4392:     my ($coursenum,$coursedomain)=@_;
 4393:     my $hashid=$coursenum.':'.$coursedomain;
 4394:     &devalidate_cache_new('courseres',$hashid);
 4395: }
 4396: 
 4397: # --------------------------------------------------- Course Resourcedata Query
 4398: 
 4399: sub get_courseresdata {
 4400:     my ($coursenum,$coursedomain)=@_;
 4401:     my $coursehom=&homeserver($coursenum,$coursedomain);
 4402:     my $hashid=$coursenum.':'.$coursedomain;
 4403:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 4404:     my %dumpreply;
 4405:     unless (defined($cached)) {
 4406: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 4407: 	$result=\%dumpreply;
 4408: 	my ($tmp) = keys(%dumpreply);
 4409: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 4410: 	    &do_cache_new('courseres',$hashid,$result,600);
 4411: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 4412: 	    return $tmp;
 4413: 	} elsif ($tmp =~ /^(error)/) {
 4414: 	    $result=undef;
 4415: 	    &do_cache_new('courseres',$hashid,$result,600);
 4416: 	}
 4417:     }
 4418:     return $result;
 4419: }
 4420: 
 4421: sub devalidateuserresdata {
 4422:     my ($uname,$udom)=@_;
 4423:     my $hashid="$udom:$uname";
 4424:     &devalidate_cache_new('userres',$hashid);
 4425: }
 4426: 
 4427: sub get_userresdata {
 4428:     my ($uname,$udom)=@_;
 4429:     #most student don\'t have any data set, check if there is some data
 4430:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 4431: 
 4432:     my $hashid="$udom:$uname";
 4433:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 4434:     if (!defined($cached)) {
 4435: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 4436: 	$result=\%resourcedata;
 4437: 	&do_cache_new('userres',$hashid,$result,600);
 4438:     }
 4439:     my ($tmp)=keys(%$result);
 4440:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 4441: 	return $result;
 4442:     }
 4443:     #error 2 occurs when the .db doesn't exist
 4444:     if ($tmp!~/error: 2 /) {
 4445: 	&logthis("<font color=blue>WARNING:".
 4446: 		 " Trying to get resource data for ".
 4447: 		 $uname." at ".$udom.": ".
 4448: 		 $tmp."</font>");
 4449:     } elsif ($tmp=~/error: 2 /) {
 4450: 	#&EXT_cache_set($udom,$uname);
 4451: 	&do_cache_new('userres',$hashid,undef,600);
 4452: 	undef($tmp); # not really an error so don't send it back
 4453:     }
 4454:     return $tmp;
 4455: }
 4456: 
 4457: sub resdata {
 4458:     my ($name,$domain,$type,@which)=@_;
 4459:     my $result;
 4460:     if ($type eq 'course') {
 4461: 	$result=&get_courseresdata($name,$domain);
 4462:     } elsif ($type eq 'user') {
 4463: 	$result=&get_userresdata($name,$domain);
 4464:     }
 4465:     if (!ref($result)) { return $result; }    
 4466:     foreach my $item (@which) {
 4467: 	if (defined($result->{$item})) {
 4468: 	    return $result->{$item};
 4469: 	}
 4470:     }
 4471:     return undef;
 4472: }
 4473: 
 4474: #
 4475: # EXT resource caching routines
 4476: #
 4477: 
 4478: sub clear_EXT_cache_status {
 4479:     &delenv('cache.EXT.');
 4480: }
 4481: 
 4482: sub EXT_cache_status {
 4483:     my ($target_domain,$target_user) = @_;
 4484:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 4485:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 4486:         # We know already the user has no data
 4487:         return 1;
 4488:     } else {
 4489:         return 0;
 4490:     }
 4491: }
 4492: 
 4493: sub EXT_cache_set {
 4494:     my ($target_domain,$target_user) = @_;
 4495:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 4496:     #&appenv($cachename => time);
 4497: }
 4498: 
 4499: # --------------------------------------------------------- Value of a Variable
 4500: sub EXT {
 4501:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 4502: 
 4503:     unless ($varname) { return ''; }
 4504:     #get real user name/domain, courseid and symb
 4505:     my $courseid;
 4506:     my $publicuser;
 4507:     if ($symbparm) {
 4508: 	$symbparm=&get_symb_from_alias($symbparm);
 4509:     }
 4510:     if (!($uname && $udom)) {
 4511:       (my $cursymb,$courseid,$udom,$uname,$publicuser)=
 4512: 	  &Apache::lonxml::whichuser($symbparm);
 4513:       if (!$symbparm) {	$symbparm=$cursymb; }
 4514:     } else {
 4515: 	$courseid=$env{'request.course.id'};
 4516:     }
 4517:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 4518:     my $rest;
 4519:     if (defined($therest[0])) {
 4520:        $rest=join('.',@therest);
 4521:     } else {
 4522:        $rest='';
 4523:     }
 4524: 
 4525:     my $qualifierrest=$qualifier;
 4526:     if ($rest) { $qualifierrest.='.'.$rest; }
 4527:     my $spacequalifierrest=$space;
 4528:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 4529:     if ($realm eq 'user') {
 4530: # --------------------------------------------------------------- user.resource
 4531: 	if ($space eq 'resource') {
 4532: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 4533: 		  || defined($Apache::lonhomework::parsing_a_task))
 4534: 		 &&
 4535: 		 ($symbparm eq &symbread()) ) {
 4536: 		return $Apache::lonhomework::history{$qualifierrest};
 4537: 	    } else {
 4538: 		my %restored;
 4539: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 4540: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 4541: 		} else {
 4542: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 4543: 		}
 4544: 		return $restored{$qualifierrest};
 4545: 	    }
 4546: # ----------------------------------------------------------------- user.access
 4547:         } elsif ($space eq 'access') {
 4548: 	    # FIXME - not supporting calls for a specific user
 4549:             return &allowed($qualifier,$rest);
 4550: # ------------------------------------------ user.preferences, user.environment
 4551:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 4552: 	    if (($uname eq $env{'user.name'}) &&
 4553: 		($udom eq $env{'user.domain'})) {
 4554: 		return $env{join('.',('environment',$qualifierrest))};
 4555: 	    } else {
 4556: 		my %returnhash;
 4557: 		if (!$publicuser) {
 4558: 		    %returnhash=&userenvironment($udom,$uname,
 4559: 						 $qualifierrest);
 4560: 		}
 4561: 		return $returnhash{$qualifierrest};
 4562: 	    }
 4563: # ----------------------------------------------------------------- user.course
 4564:         } elsif ($space eq 'course') {
 4565: 	    # FIXME - not supporting calls for a specific user
 4566:             return $env{join('.',('request.course',$qualifier))};
 4567: # ------------------------------------------------------------------- user.role
 4568:         } elsif ($space eq 'role') {
 4569: 	    # FIXME - not supporting calls for a specific user
 4570:             my ($role,$where)=split(/\./,$env{'request.role'});
 4571:             if ($qualifier eq 'value') {
 4572: 		return $role;
 4573:             } elsif ($qualifier eq 'extent') {
 4574:                 return $where;
 4575:             }
 4576: # ----------------------------------------------------------------- user.domain
 4577:         } elsif ($space eq 'domain') {
 4578:             return $udom;
 4579: # ------------------------------------------------------------------- user.name
 4580:         } elsif ($space eq 'name') {
 4581:             return $uname;
 4582: # ---------------------------------------------------- Any other user namespace
 4583:         } else {
 4584: 	    my %reply;
 4585: 	    if (!$publicuser) {
 4586: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 4587: 	    }
 4588: 	    return $reply{$qualifierrest};
 4589:         }
 4590:     } elsif ($realm eq 'query') {
 4591: # ---------------------------------------------- pull stuff out of query string
 4592:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 4593: 						[$spacequalifierrest]);
 4594: 	return $env{'form.'.$spacequalifierrest}; 
 4595:    } elsif ($realm eq 'request') {
 4596: # ------------------------------------------------------------- request.browser
 4597:         if ($space eq 'browser') {
 4598: 	    if ($qualifier eq 'textremote') {
 4599: 		if (&mt('textual_remote_display') eq 'on') {
 4600: 		    return 1;
 4601: 		} else {
 4602: 		    return 0;
 4603: 		}
 4604: 	    } else {
 4605: 		return $env{'browser.'.$qualifier};
 4606: 	    }
 4607: # ------------------------------------------------------------ request.filename
 4608:         } else {
 4609:             return $env{'request.'.$spacequalifierrest};
 4610:         }
 4611:     } elsif ($realm eq 'course') {
 4612: # ---------------------------------------------------------- course.description
 4613:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 4614:     } elsif ($realm eq 'resource') {
 4615: 
 4616: 	my $section;
 4617: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 4618: 	    if (!$symbparm) { $symbparm=&symbread(); }
 4619: 	}
 4620: 	my ($courselevelm,$courselevel);
 4621: 	if ($symbparm && defined($courseid) && 
 4622: 	    $courseid eq $env{'request.course.id'}) {
 4623: 
 4624: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 4625: 
 4626: # ----------------------------------------------------- Cascading lookup scheme
 4627: 	    my $symbp=$symbparm;
 4628: 	    my $mapp=(&decode_symb($symbp))[0];
 4629: 
 4630: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 4631: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 4632: 
 4633: 	    if (($env{'user.name'} eq $uname) &&
 4634: 		($env{'user.domain'} eq $udom)) {
 4635: 		$section=$env{'request.course.sec'};
 4636: 	    } else {
 4637: 		if (! defined($usection)) {
 4638: 		    $section=&getsection($udom,$uname,$courseid);
 4639: 		} else {
 4640: 		    $section = $usection;
 4641: 		}
 4642: 	    }
 4643: 
 4644: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 4645: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 4646: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 4647: 
 4648: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 4649: 	    my $courselevelr=$courseid.'.'.$symbparm;
 4650: 	    $courselevelm=$courseid.'.'.$mapparm;
 4651: 
 4652: # ----------------------------------------------------------- first, check user
 4653: 
 4654: 	    my $userreply=&resdata($uname,$udom,'user',
 4655: 				       ($courselevelr,$courselevelm,
 4656: 					$courselevel));
 4657: 
 4658: 	    if (defined($userreply)) { return $userreply; }
 4659: 
 4660: # ------------------------------------------------ second, check some of course
 4661: 
 4662: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 4663: 				     $env{'course.'.$courseid.'.domain'},
 4664: 				     'course',
 4665: 				     ($seclevelr,$seclevelm,$seclevel,
 4666: 				      $courselevelr));
 4667: 	    if (defined($coursereply)) { return $coursereply; }
 4668: 
 4669: # ------------------------------------------------------ third, check map parms
 4670: 	    my %parmhash=();
 4671: 	    my $thisparm='';
 4672: 	    if (tie(%parmhash,'GDBM_File',
 4673: 		    $env{'request.course.fn'}.'_parms.db',
 4674: 		    &GDBM_READER(),0640)) {
 4675: 		$thisparm=$parmhash{$symbparm};
 4676: 		untie(%parmhash);
 4677: 	    }
 4678: 	    if ($thisparm) { return $thisparm; }
 4679: 	}
 4680: # ------------------------------------------ fourth, look in resource metadata
 4681: 
 4682: 	$spacequalifierrest=~s/\./\_/;
 4683: 	my $filename;
 4684: 	if (!$symbparm) { $symbparm=&symbread(); }
 4685: 	if ($symbparm) {
 4686: 	    $filename=(&decode_symb($symbparm))[2];
 4687: 	} else {
 4688: 	    $filename=$env{'request.filename'};
 4689: 	}
 4690: 	my $metadata=&metadata($filename,$spacequalifierrest);
 4691: 	if (defined($metadata)) { return $metadata; }
 4692: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 4693: 	if (defined($metadata)) { return $metadata; }
 4694: 
 4695: # ---------------------------------------------- fourth, look in rest pf course
 4696: 	if ($symbparm && defined($courseid) && 
 4697: 	    $courseid eq $env{'request.course.id'}) {
 4698: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 4699: 				     $env{'course.'.$courseid.'.domain'},
 4700: 				     'course',
 4701: 				     ($courselevelm,$courselevel));
 4702: 	    if (defined($coursereply)) { return $coursereply; }
 4703: 	}
 4704: # ------------------------------------------------------------------ Cascade up
 4705: 	unless ($space eq '0') {
 4706: 	    my @parts=split(/_/,$space);
 4707: 	    my $id=pop(@parts);
 4708: 	    my $part=join('_',@parts);
 4709: 	    if ($part eq '') { $part='0'; }
 4710: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 4711: 				 $symbparm,$udom,$uname,$section,1);
 4712: 	    if (defined($partgeneral)) { return $partgeneral; }
 4713: 	}
 4714: 	if ($recurse) { return undef; }
 4715: 	my $pack_def=&packages_tab_default($filename,$varname);
 4716: 	if (defined($pack_def)) { return $pack_def; }
 4717: 
 4718: # ---------------------------------------------------- Any other user namespace
 4719:     } elsif ($realm eq 'environment') {
 4720: # ----------------------------------------------------------------- environment
 4721: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 4722: 	    return $env{'environment.'.$spacequalifierrest};
 4723: 	} else {
 4724: 	    my %returnhash=&userenvironment($udom,$uname,
 4725: 					    $spacequalifierrest);
 4726: 	    return $returnhash{$spacequalifierrest};
 4727: 	}
 4728:     } elsif ($realm eq 'system') {
 4729: # ----------------------------------------------------------------- system.time
 4730: 	if ($space eq 'time') {
 4731: 	    return time;
 4732:         }
 4733:     }
 4734:     return '';
 4735: }
 4736: 
 4737: sub packages_tab_default {
 4738:     my ($uri,$varname)=@_;
 4739:     my (undef,$part,$name)=split(/\./,$varname);
 4740:     my $packages=&metadata($uri,'packages');
 4741:     foreach my $package (split(/,/,$packages)) {
 4742: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 4743: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 4744: 	    return $packagetab{"$pack_type&$name&default"};
 4745: 	}
 4746: 	if ($pack_type eq 'part') { $pack_part='0'; }
 4747: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 4748: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 4749: 	}
 4750:     }
 4751:     return undef;
 4752: }
 4753: 
 4754: sub add_prefix_and_part {
 4755:     my ($prefix,$part)=@_;
 4756:     my $keyroot;
 4757:     if (defined($prefix) && $prefix !~ /^__/) {
 4758: 	# prefix that has a part already
 4759: 	$keyroot=$prefix;
 4760:     } elsif (defined($prefix)) {
 4761: 	# prefix that is missing a part
 4762: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 4763:     } else {
 4764: 	# no prefix at all
 4765: 	if (defined($part)) { $keyroot='_'.$part; }
 4766:     }
 4767:     return $keyroot;
 4768: }
 4769: 
 4770: # ---------------------------------------------------------------- Get metadata
 4771: 
 4772: my %metaentry;
 4773: sub metadata {
 4774:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 4775:     $uri=&declutter($uri);
 4776:     # if it is a non metadata possible uri return quickly
 4777:     if (($uri eq '') || 
 4778: 	(($uri =~ m|^/*adm/|) && 
 4779: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 4780:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 4781: 	($uri =~ m|home/[^/]+/public_html/|)) {
 4782: 	return undef;
 4783:     }
 4784:     my $filename=$uri;
 4785:     $uri=~s/\.meta$//;
 4786: #
 4787: # Is the metadata already cached?
 4788: # Look at timestamp of caching
 4789: # Everything is cached by the main uri, libraries are never directly cached
 4790: #
 4791:     if (!defined($liburi)) {
 4792: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 4793: 	if (defined($cached)) { return $result->{':'.$what}; }
 4794:     }
 4795:     {
 4796: #
 4797: # Is this a recursive call for a library?
 4798: #
 4799: #	if (! exists($metacache{$uri})) {
 4800: #	    $metacache{$uri}={};
 4801: #	}
 4802:         if ($liburi) {
 4803: 	    $liburi=&declutter($liburi);
 4804:             $filename=$liburi;
 4805:         } else {
 4806: 	    &devalidate_cache_new('meta',$uri);
 4807: 	    undef(%metaentry);
 4808: 	}
 4809:         my %metathesekeys=();
 4810:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 4811: 	my $metastring;
 4812: 	if ($uri !~ m -^(uploaded|editupload)/-) {
 4813: 	    my $file=&filelocation('',&clutter($filename));
 4814: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 4815: 	    $metastring=&getfile($file);
 4816: 	}
 4817:         my $parser=HTML::LCParser->new(\$metastring);
 4818:         my $token;
 4819:         undef %metathesekeys;
 4820:         while ($token=$parser->get_token) {
 4821: 	    if ($token->[0] eq 'S') {
 4822: 		if (defined($token->[2]->{'package'})) {
 4823: #
 4824: # This is a package - get package info
 4825: #
 4826: 		    my $package=$token->[2]->{'package'};
 4827: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 4828: 		    if (defined($token->[2]->{'id'})) { 
 4829: 			$keyroot.='_'.$token->[2]->{'id'}; 
 4830: 		    }
 4831: 		    if ($metaentry{':packages'}) {
 4832: 			$metaentry{':packages'}.=','.$package.$keyroot;
 4833: 		    } else {
 4834: 			$metaentry{':packages'}=$package.$keyroot;
 4835: 		    }
 4836: 		    foreach (sort keys %packagetab) {
 4837: 			my $part=$keyroot;
 4838: 			$part=~s/^\_//;
 4839: 			if ($_=~/^\Q$package\E\&/ || 
 4840: 			    $_=~/^\Q$package\E_0\&/) {
 4841: 			    my ($pack,$name,$subp)=split(/\&/,$_);
 4842: 			    # ignore package.tab specified default values
 4843:                             # here &package_tab_default() will fetch those
 4844: 			    if ($subp eq 'default') { next; }
 4845: 			    my $value=$packagetab{$_};
 4846: 			    my $unikey;
 4847: 			    if ($pack =~ /_0$/) {
 4848: 				$unikey='parameter_0_'.$name;
 4849: 				$part=0;
 4850: 			    } else {
 4851: 				$unikey='parameter'.$keyroot.'_'.$name;
 4852: 			    }
 4853: 			    if ($subp eq 'display') {
 4854: 				$value.=' [Part: '.$part.']';
 4855: 			    }
 4856: 			    $metaentry{':'.$unikey.'.part'}=$part;
 4857: 			    $metathesekeys{$unikey}=1;
 4858: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 4859: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 4860: 			    }
 4861: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 4862: 				$metaentry{':'.$unikey}=
 4863: 				    $metaentry{':'.$unikey.'.default'};
 4864: 			    }
 4865: 			}
 4866: 		    }
 4867: 		} else {
 4868: #
 4869: # This is not a package - some other kind of start tag
 4870: #
 4871: 		    my $entry=$token->[1];
 4872: 		    my $unikey;
 4873: 		    if ($entry eq 'import') {
 4874: 			$unikey='';
 4875: 		    } else {
 4876: 			$unikey=$entry;
 4877: 		    }
 4878: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 4879: 
 4880: 		    if (defined($token->[2]->{'id'})) { 
 4881: 			$unikey.='_'.$token->[2]->{'id'}; 
 4882: 		    }
 4883: 
 4884: 		    if ($entry eq 'import') {
 4885: #
 4886: # Importing a library here
 4887: #
 4888: 			if ($depthcount<20) {
 4889: 			    my $location=$parser->get_text('/import');
 4890: 			    my $dir=$filename;
 4891: 			    $dir=~s|[^/]*$||;
 4892: 			    $location=&filelocation($dir,$location);
 4893: 			    foreach (sort(split(/\,/,&metadata($uri,'keys',
 4894: 							       $location,$unikey,
 4895: 							       $depthcount+1)))) {
 4896: 				$metaentry{':'.$_}=$metaentry{':'.$_};
 4897: 				$metathesekeys{$_}=1;
 4898: 			    }
 4899: 			}
 4900: 		    } else { 
 4901: 			
 4902: 			if (defined($token->[2]->{'name'})) { 
 4903: 			    $unikey.='_'.$token->[2]->{'name'}; 
 4904: 			}
 4905: 			$metathesekeys{$unikey}=1;
 4906: 			foreach (@{$token->[3]}) {
 4907: 			    $metaentry{':'.$unikey.'.'.$_}=$token->[2]->{$_};
 4908: 			}
 4909: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 4910: 			my $default=$metaentry{':'.$unikey.'.default'};
 4911: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 4912: 		 # only ws inside the tag, and not in default, so use default
 4913: 		 # as value
 4914: 			    $metaentry{':'.$unikey}=$default;
 4915: 			} else {
 4916: 		  # either something interesting inside the tag or default
 4917:                   # uninteresting
 4918: 			    $metaentry{':'.$unikey}=$internaltext;
 4919: 			}
 4920: # end of not-a-package not-a-library import
 4921: 		    }
 4922: # end of not-a-package start tag
 4923: 		}
 4924: # the next is the end of "start tag"
 4925: 	    }
 4926: 	}
 4927: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 4928: 	foreach my $key (sort(keys(%packagetab))) {
 4929: 	    #no specific packages #how's our extension
 4930: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 4931: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 4932: 					 \%metathesekeys);
 4933: 	}
 4934: 	if (!exists($metaentry{':packages'})) {
 4935: 	    foreach my $key (sort(keys(%packagetab))) {
 4936: 		#no specific packages well let's get default then
 4937: 		if ($key!~/^default&/) { next; }
 4938: 		&metadata_create_package_def($uri,$key,'default',
 4939: 					     \%metathesekeys);
 4940: 	    }
 4941: 	}
 4942: # are there custom rights to evaluate
 4943: 	if ($metaentry{':copyright'} eq 'custom') {
 4944: 
 4945:     #
 4946:     # Importing a rights file here
 4947:     #
 4948: 	    unless ($depthcount) {
 4949: 		my $location=$metaentry{':customdistributionfile'};
 4950: 		my $dir=$filename;
 4951: 		$dir=~s|[^/]*$||;
 4952: 		$location=&filelocation($dir,$location);
 4953: 		foreach (sort(split(/\,/,&metadata($uri,'keys',
 4954: 						   $location,'_rights',
 4955: 						   $depthcount+1)))) {
 4956: 		    #$metaentry{':'.$_}=$metacache{$uri}->{':'.$_};
 4957: 		    $metathesekeys{$_}=1;
 4958: 		}
 4959: 	    }
 4960: 	}
 4961: 	$metaentry{':keys'}=join(',',keys %metathesekeys);
 4962: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 4963: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 4964: 	&do_cache_new('meta',$uri,\%metaentry,60*60*24);
 4965: # this is the end of "was not already recently cached
 4966:     }
 4967:     return $metaentry{':'.$what};
 4968: }
 4969: 
 4970: sub metadata_create_package_def {
 4971:     my ($uri,$key,$package,$metathesekeys)=@_;
 4972:     my ($pack,$name,$subp)=split(/\&/,$key);
 4973:     if ($subp eq 'default') { next; }
 4974:     
 4975:     if (defined($metaentry{':packages'})) {
 4976: 	$metaentry{':packages'}.=','.$package;
 4977:     } else {
 4978: 	$metaentry{':packages'}=$package;
 4979:     }
 4980:     my $value=$packagetab{$key};
 4981:     my $unikey;
 4982:     $unikey='parameter_0_'.$name;
 4983:     $metaentry{':'.$unikey.'.part'}=0;
 4984:     $$metathesekeys{$unikey}=1;
 4985:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 4986: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 4987:     }
 4988:     if (defined($metaentry{':'.$unikey.'.default'})) {
 4989: 	$metaentry{':'.$unikey}=
 4990: 	    $metaentry{':'.$unikey.'.default'};
 4991:     }
 4992: }
 4993: 
 4994: sub metadata_generate_part0 {
 4995:     my ($metadata,$metacache,$uri) = @_;
 4996:     my %allnames;
 4997:     foreach my $metakey (sort keys %$metadata) {
 4998: 	if ($metakey=~/^parameter\_(.*)/) {
 4999: 	  my $part=$$metacache{':'.$metakey.'.part'};
 5000: 	  my $name=$$metacache{':'.$metakey.'.name'};
 5001: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 5002: 	    $allnames{$name}=$part;
 5003: 	  }
 5004: 	}
 5005:     }
 5006:     foreach my $name (keys(%allnames)) {
 5007:       $$metadata{"parameter_0_$name"}=1;
 5008:       my $key=":parameter_0_$name";
 5009:       $$metacache{"$key.part"}='0';
 5010:       $$metacache{"$key.name"}=$name;
 5011:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 5012: 					   $allnames{$name}.'_'.$name.
 5013: 					   '.type'};
 5014:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 5015: 			     '.display'};
 5016:       my $expr='[Part: '.$allnames{$name}.']';
 5017:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 5018:       $$metacache{"$key.display"}=$olddis;
 5019:     }
 5020: }
 5021: 
 5022: # ------------------------------------------------- Get the title of a resource
 5023: 
 5024: sub gettitle {
 5025:     my $urlsymb=shift;
 5026:     my $symb=&symbread($urlsymb);
 5027:     if ($symb) {
 5028: 	my $key=$env{'request.course.id'}."\0".$symb;
 5029: 	my ($result,$cached)=&is_cached_new('title',$key);
 5030: 	if (defined($cached)) { 
 5031: 	    return $result;
 5032: 	}
 5033: 	my ($map,$resid,$url)=&decode_symb($symb);
 5034: 	my $title='';
 5035: 	my %bighash;
 5036: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5037: 		&GDBM_READER(),0640)) {
 5038: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 5039: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 5040: 	    untie %bighash;
 5041: 	}
 5042: 	$title=~s/\&colon\;/\:/gs;
 5043: 	if ($title) {
 5044: 	    return &do_cache_new('title',$key,$title,600);
 5045: 	}
 5046: 	$urlsymb=$url;
 5047:     }
 5048:     my $title=&metadata($urlsymb,'title');
 5049:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 5050:     return $title;
 5051: }
 5052: 
 5053: sub get_slot {
 5054:     my ($which,$cnum,$cdom)=@_;
 5055:     if (!$cnum || !$cdom) {
 5056: 	(undef,my $courseid)=&Apache::lonxml::whichuser();
 5057: 	$cdom=$env{'course.'.$courseid.'.domain'};
 5058: 	$cnum=$env{'course.'.$courseid.'.num'};
 5059:     }
 5060:     my %slotinfo=&get('slots',[$which],$cdom,$cnum);
 5061:     &Apache::lonhomework::showhash(%slotinfo);
 5062:     my ($tmp)=keys(%slotinfo);
 5063:     if ($tmp=~/^error:/) { return (); }
 5064:     if (ref($slotinfo{$which}) eq 'HASH') {
 5065: 	return %{$slotinfo{$which}};
 5066:     }
 5067:     return $slotinfo{$which};
 5068: }
 5069: # ------------------------------------------------- Update symbolic store links
 5070: 
 5071: sub symblist {
 5072:     my ($mapname,%newhash)=@_;
 5073:     $mapname=&deversion(&declutter($mapname));
 5074:     my %hash;
 5075:     if (($env{'request.course.fn'}) && (%newhash)) {
 5076:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 5077:                       &GDBM_WRCREAT(),0640)) {
 5078: 	    foreach (keys %newhash) {
 5079:                 $hash{declutter($_)}=&encode_symb($mapname,$newhash{$_}->[1],
 5080: 						  $newhash{$_}->[0]);
 5081:             }
 5082:             if (untie(%hash)) {
 5083: 		return 'ok';
 5084:             }
 5085:         }
 5086:     }
 5087:     return 'error';
 5088: }
 5089: 
 5090: # --------------------------------------------------------------- Verify a symb
 5091: 
 5092: sub symbverify {
 5093:     my ($symb,$thisurl)=@_;
 5094:     my $thisfn=$thisurl;
 5095: # wrapper not part of symbs
 5096:     $thisfn=~s/^\/adm\/wrapper//;
 5097:     $thisfn=&declutter($thisfn);
 5098: # direct jump to resource in page or to a sequence - will construct own symbs
 5099:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 5100: # check URL part
 5101:     my ($map,$resid,$url)=&decode_symb($symb);
 5102: 
 5103:     unless ($url eq $thisfn) { return 0; }
 5104: 
 5105:     $symb=&symbclean($symb);
 5106:     $thisurl=&deversion($thisurl);
 5107:     $thisfn=&deversion($thisfn);
 5108: 
 5109:     my %bighash;
 5110:     my $okay=0;
 5111: 
 5112:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5113:                             &GDBM_READER(),0640)) {
 5114:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 5115:         unless ($ids) { 
 5116:            $ids=$bighash{'ids_/'.$thisurl};
 5117:         }
 5118:         if ($ids) {
 5119: # ------------------------------------------------------------------- Has ID(s)
 5120: 	    foreach (split(/\,/,$ids)) {
 5121: 	       my ($mapid,$resid)=split(/\./,$_);
 5122:                if (
 5123:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 5124:    eq $symb) { 
 5125: 		   if (($env{'request.role.adv'}) ||
 5126: 		       $bighash{'encrypted_'.$_} eq $env{'request.enc'}) {
 5127: 		       $okay=1; 
 5128: 		   }
 5129: 	       }
 5130: 	   }
 5131:         }
 5132: 	untie(%bighash);
 5133:     }
 5134:     return $okay;
 5135: }
 5136: 
 5137: # --------------------------------------------------------------- Clean-up symb
 5138: 
 5139: sub symbclean {
 5140:     my $symb=shift;
 5141:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 5142: # remove version from map
 5143:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 5144: 
 5145: # remove version from URL
 5146:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 5147: 
 5148: # remove wrapper
 5149: 
 5150:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 5151:     return $symb;
 5152: }
 5153: 
 5154: # ---------------------------------------------- Split symb to find map and url
 5155: 
 5156: sub encode_symb {
 5157:     my ($map,$resid,$url)=@_;
 5158:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 5159: }
 5160: 
 5161: sub decode_symb {
 5162:     my $symb=shift;
 5163:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 5164:     my ($map,$resid,$url)=split(/___/,$symb);
 5165:     return (&fixversion($map),$resid,&fixversion($url));
 5166: }
 5167: 
 5168: sub fixversion {
 5169:     my $fn=shift;
 5170:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 5171:     my %bighash;
 5172:     my $uri=&clutter($fn);
 5173:     my $key=$env{'request.course.id'}.'_'.$uri;
 5174: # is this cached?
 5175:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 5176:     if (defined($cached)) { return $result; }
 5177: # unfortunately not cached, or expired
 5178:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5179: 	    &GDBM_READER(),0640)) {
 5180:  	if ($bighash{'version_'.$uri}) {
 5181:  	    my $version=$bighash{'version_'.$uri};
 5182:  	    unless (($version eq 'mostrecent') || 
 5183: 		    ($version==&getversion($uri))) {
 5184:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 5185:  	    }
 5186:  	}
 5187:  	untie %bighash;
 5188:     }
 5189:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 5190: }
 5191: 
 5192: sub deversion {
 5193:     my $url=shift;
 5194:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 5195:     return $url;
 5196: }
 5197: 
 5198: # ------------------------------------------------------ Return symb list entry
 5199: 
 5200: sub symbread {
 5201:     my ($thisfn,$donotrecurse)=@_;
 5202:     my $cache_str='request.symbread.cached.'.$thisfn;
 5203:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 5204: # no filename provided? try from environment
 5205:     unless ($thisfn) {
 5206:         if ($env{'request.symb'}) {
 5207: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 5208: 	}
 5209: 	$thisfn=$env{'request.filename'};
 5210:     }
 5211:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 5212: # is that filename actually a symb? Verify, clean, and return
 5213:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 5214: 	if (&symbverify($thisfn,$1)) {
 5215: 	    return $env{$cache_str}=&symbclean($thisfn);
 5216: 	}
 5217:     }
 5218:     $thisfn=declutter($thisfn);
 5219:     my %hash;
 5220:     my %bighash;
 5221:     my $syval='';
 5222:     if (($env{'request.course.fn'}) && ($thisfn)) {
 5223:         my $targetfn = $thisfn;
 5224:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 5225:             $targetfn = 'adm/wrapper/'.$thisfn;
 5226:         }
 5227:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 5228:                       &GDBM_READER(),0640)) {
 5229: 	    $syval=$hash{$targetfn};
 5230:             untie(%hash);
 5231:         }
 5232: # ---------------------------------------------------------- There was an entry
 5233:         if ($syval) {
 5234: 	    #unless ($syval=~/\_\d+$/) {
 5235: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 5236: 		    #&appenv('request.ambiguous' => $thisfn);
 5237: 		    #return $env{$cache_str}='';
 5238: 		#}    
 5239: 		#$syval.=$1;
 5240: 	    #}
 5241:         } else {
 5242: # ------------------------------------------------------- Was not in symb table
 5243:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5244:                             &GDBM_READER(),0640)) {
 5245: # ---------------------------------------------- Get ID(s) for current resource
 5246:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 5247:               unless ($ids) { 
 5248:                  $ids=$bighash{'ids_/'.$thisfn};
 5249:               }
 5250:               unless ($ids) {
 5251: # alias?
 5252: 		  $ids=$bighash{'mapalias_'.$thisfn};
 5253:               }
 5254:               if ($ids) {
 5255: # ------------------------------------------------------------------- Has ID(s)
 5256:                  my @possibilities=split(/\,/,$ids);
 5257:                  if ($#possibilities==0) {
 5258: # ----------------------------------------------- There is only one possibility
 5259: 		     my ($mapid,$resid)=split(/\./,$ids);
 5260: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 5261: 						    $resid,$thisfn);
 5262:                  } elsif (!$donotrecurse) {
 5263: # ------------------------------------------ There is more than one possibility
 5264:                      my $realpossible=0;
 5265:                      foreach (@possibilities) {
 5266: 			 my $file=$bighash{'src_'.$_};
 5267:                          if (&allowed('bre',$file)) {
 5268:          		    my ($mapid,$resid)=split(/\./,$_);
 5269:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 5270: 				$realpossible++;
 5271:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 5272: 						    $resid,$thisfn);
 5273:                             }
 5274: 			 }
 5275:                      }
 5276: 		     if ($realpossible!=1) { $syval=''; }
 5277:                  } else {
 5278:                      $syval='';
 5279:                  }
 5280: 	      }
 5281:               untie(%bighash)
 5282:            }
 5283:         }
 5284:         if ($syval) {
 5285: 	    return $env{$cache_str}=$syval;
 5286:         }
 5287:     }
 5288:     &appenv('request.ambiguous' => $thisfn);
 5289:     return $env{$cache_str}='';
 5290: }
 5291: 
 5292: # ---------------------------------------------------------- Return random seed
 5293: 
 5294: sub numval {
 5295:     my $txt=shift;
 5296:     $txt=~tr/A-J/0-9/;
 5297:     $txt=~tr/a-j/0-9/;
 5298:     $txt=~tr/K-T/0-9/;
 5299:     $txt=~tr/k-t/0-9/;
 5300:     $txt=~tr/U-Z/0-5/;
 5301:     $txt=~tr/u-z/0-5/;
 5302:     $txt=~s/\D//g;
 5303:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 5304:     return int($txt);
 5305: }
 5306: 
 5307: sub numval2 {
 5308:     my $txt=shift;
 5309:     $txt=~tr/A-J/0-9/;
 5310:     $txt=~tr/a-j/0-9/;
 5311:     $txt=~tr/K-T/0-9/;
 5312:     $txt=~tr/k-t/0-9/;
 5313:     $txt=~tr/U-Z/0-5/;
 5314:     $txt=~tr/u-z/0-5/;
 5315:     $txt=~s/\D//g;
 5316:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 5317:     my $total;
 5318:     foreach my $val (@txts) { $total+=$val; }
 5319:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 5320:     return int($total);
 5321: }
 5322: 
 5323: sub numval3 {
 5324:     use integer;
 5325:     my $txt=shift;
 5326:     $txt=~tr/A-J/0-9/;
 5327:     $txt=~tr/a-j/0-9/;
 5328:     $txt=~tr/K-T/0-9/;
 5329:     $txt=~tr/k-t/0-9/;
 5330:     $txt=~tr/U-Z/0-5/;
 5331:     $txt=~tr/u-z/0-5/;
 5332:     $txt=~s/\D//g;
 5333:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 5334:     my $total;
 5335:     foreach my $val (@txts) { $total+=$val; }
 5336:     if ($_64bit) { $total=(($total<<32)>>32); }
 5337:     return $total;
 5338: }
 5339: 
 5340: sub latest_rnd_algorithm_id {
 5341:     return '64bit4';
 5342: }
 5343: 
 5344: sub get_rand_alg {
 5345:     my ($courseid)=@_;
 5346:     if (!$courseid) { $courseid=(&Apache::lonxml::whichuser())[1]; }
 5347:     if ($courseid) {
 5348: 	return $env{"course.$courseid.rndseed"};
 5349:     }
 5350:     return &latest_rnd_algorithm_id();
 5351: }
 5352: 
 5353: sub validCODE {
 5354:     my ($CODE)=@_;
 5355:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 5356:     return 0;
 5357: }
 5358: 
 5359: sub getCODE {
 5360:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 5361:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 5362: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 5363: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 5364: 	return $Apache::lonhomework::history{'resource.CODE'};
 5365:     }
 5366:     return undef;
 5367: }
 5368: 
 5369: sub rndseed {
 5370:     my ($symb,$courseid,$domain,$username)=@_;
 5371: 
 5372:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&Apache::lonxml::whichuser();
 5373:     if (!$symb) {
 5374: 	unless ($symb=$wsymb) { return time; }
 5375:     }
 5376:     if (!$courseid) { $courseid=$wcourseid; }
 5377:     if (!$domain) { $domain=$wdomain; }
 5378:     if (!$username) { $username=$wusername }
 5379:     my $which=&get_rand_alg();
 5380:     if (defined(&getCODE())) {
 5381: 	if ($which eq '64bit4') {
 5382: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 5383: 	} else {
 5384: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 5385: 	}
 5386:     } elsif ($which eq '64bit4') {
 5387: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 5388:     } elsif ($which eq '64bit3') {
 5389: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 5390:     } elsif ($which eq '64bit2') {
 5391: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 5392:     } elsif ($which eq '64bit') {
 5393: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 5394:     }
 5395:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 5396: }
 5397: 
 5398: sub rndseed_32bit {
 5399:     my ($symb,$courseid,$domain,$username)=@_;
 5400:     {
 5401: 	use integer;
 5402: 	my $symbchck=unpack("%32C*",$symb) << 27;
 5403: 	my $symbseed=numval($symb) << 22;
 5404: 	my $namechck=unpack("%32C*",$username) << 17;
 5405: 	my $nameseed=numval($username) << 12;
 5406: 	my $domainseed=unpack("%32C*",$domain) << 7;
 5407: 	my $courseseed=unpack("%32C*",$courseid);
 5408: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 5409: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5410: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 5411: 	if ($_64bit) { $num=(($num<<32)>>32); }
 5412: 	return $num;
 5413:     }
 5414: }
 5415: 
 5416: sub rndseed_64bit {
 5417:     my ($symb,$courseid,$domain,$username)=@_;
 5418:     {
 5419: 	use integer;
 5420: 	my $symbchck=unpack("%32S*",$symb) << 21;
 5421: 	my $symbseed=numval($symb) << 10;
 5422: 	my $namechck=unpack("%32S*",$username);
 5423: 	
 5424: 	my $nameseed=numval($username) << 21;
 5425: 	my $domainseed=unpack("%32S*",$domain) << 10;
 5426: 	my $courseseed=unpack("%32S*",$courseid);
 5427: 	
 5428: 	my $num1=$symbchck+$symbseed+$namechck;
 5429: 	my $num2=$nameseed+$domainseed+$courseseed;
 5430: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5431: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 5432: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 5433: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 5434: 	return "$num1,$num2";
 5435:     }
 5436: }
 5437: 
 5438: sub rndseed_64bit2 {
 5439:     my ($symb,$courseid,$domain,$username)=@_;
 5440:     {
 5441: 	use integer;
 5442: 	# strings need to be an even # of cahracters long, it it is odd the
 5443:         # last characters gets thrown away
 5444: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 5445: 	my $symbseed=numval($symb) << 10;
 5446: 	my $namechck=unpack("%32S*",$username.' ');
 5447: 	
 5448: 	my $nameseed=numval($username) << 21;
 5449: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 5450: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5451: 	
 5452: 	my $num1=$symbchck+$symbseed+$namechck;
 5453: 	my $num2=$nameseed+$domainseed+$courseseed;
 5454: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5455: 	#&Apache::lonxml::debug("rndseed :$num:$symb");
 5456: 	return "$num1,$num2";
 5457:     }
 5458: }
 5459: 
 5460: sub rndseed_64bit3 {
 5461:     my ($symb,$courseid,$domain,$username)=@_;
 5462:     {
 5463: 	use integer;
 5464: 	# strings need to be an even # of cahracters long, it it is odd the
 5465:         # last characters gets thrown away
 5466: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 5467: 	my $symbseed=numval2($symb) << 10;
 5468: 	my $namechck=unpack("%32S*",$username.' ');
 5469: 	
 5470: 	my $nameseed=numval2($username) << 21;
 5471: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 5472: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5473: 	
 5474: 	my $num1=$symbchck+$symbseed+$namechck;
 5475: 	my $num2=$nameseed+$domainseed+$courseseed;
 5476: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5477: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 5478: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 5479: 	
 5480: 	return "$num1:$num2";
 5481:     }
 5482: }
 5483: 
 5484: sub rndseed_64bit4 {
 5485:     my ($symb,$courseid,$domain,$username)=@_;
 5486:     {
 5487: 	use integer;
 5488: 	# strings need to be an even # of cahracters long, it it is odd the
 5489:         # last characters gets thrown away
 5490: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 5491: 	my $symbseed=numval3($symb) << 10;
 5492: 	my $namechck=unpack("%32S*",$username.' ');
 5493: 	
 5494: 	my $nameseed=numval3($username) << 21;
 5495: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 5496: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5497: 	
 5498: 	my $num1=$symbchck+$symbseed+$namechck;
 5499: 	my $num2=$nameseed+$domainseed+$courseseed;
 5500: 	#&Apache::lonxml::debug("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 5501: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$_64bit");
 5502: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 5503: 	
 5504: 	return "$num1:$num2";
 5505:     }
 5506: }
 5507: 
 5508: sub rndseed_CODE_64bit {
 5509:     my ($symb,$courseid,$domain,$username)=@_;
 5510:     {
 5511: 	use integer;
 5512: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 5513: 	my $symbseed=numval2($symb);
 5514: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 5515: 	my $CODEseed=numval(&getCODE());
 5516: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5517: 	my $num1=$symbseed+$CODEchck;
 5518: 	my $num2=$CODEseed+$courseseed+$symbchck;
 5519: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 5520: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 5521: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 5522: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 5523: 	return "$num1:$num2";
 5524:     }
 5525: }
 5526: 
 5527: sub rndseed_CODE_64bit4 {
 5528:     my ($symb,$courseid,$domain,$username)=@_;
 5529:     {
 5530: 	use integer;
 5531: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 5532: 	my $symbseed=numval3($symb);
 5533: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 5534: 	my $CODEseed=numval3(&getCODE());
 5535: 	my $courseseed=unpack("%32S*",$courseid.' ');
 5536: 	my $num1=$symbseed+$CODEchck;
 5537: 	my $num2=$CODEseed+$courseseed+$symbchck;
 5538: 	#&Apache::lonxml::debug("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 5539: 	#&Apache::lonxml::debug("rndseed :$num1:$num2:$symb");
 5540: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 5541: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 5542: 	return "$num1:$num2";
 5543:     }
 5544: }
 5545: 
 5546: sub setup_random_from_rndseed {
 5547:     my ($rndseed)=@_;
 5548:     if ($rndseed =~/([,:])/) {
 5549: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 5550: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 5551:     } else {
 5552: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 5553:     }
 5554: }
 5555: 
 5556: sub latest_receipt_algorithm_id {
 5557:     return 'receipt2';
 5558: }
 5559: 
 5560: sub recunique {
 5561:     my $fucourseid=shift;
 5562:     my $unique;
 5563:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 5564: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 5565:     } else {
 5566: 	$unique=$perlvar{'lonReceipt'};
 5567:     }
 5568:     return unpack("%32C*",$unique);
 5569: }
 5570: 
 5571: sub recprefix {
 5572:     my $fucourseid=shift;
 5573:     my $prefix;
 5574:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 5575: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 5576:     } else {
 5577: 	$prefix=$perlvar{'lonHostID'};
 5578:     }
 5579:     return unpack("%32C*",$prefix);
 5580: }
 5581: 
 5582: sub ireceipt {
 5583:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 5584:     my $cuname=unpack("%32C*",$funame);
 5585:     my $cudom=unpack("%32C*",$fudom);
 5586:     my $cucourseid=unpack("%32C*",$fucourseid);
 5587:     my $cusymb=unpack("%32C*",$fusymb);
 5588:     my $cunique=&recunique($fucourseid);
 5589:     my $cpart=unpack("%32S*",$part);
 5590:     my $return =&recprefix($fucourseid).'-';
 5591:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 5592: 	$env{'request.state'} eq 'construct') {
 5593: 	&Apache::lonxml::debug("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname).
 5594: 			       " and ".($cpart%$cudom));
 5595: 			       
 5596: 	$return.= ($cunique%$cuname+
 5597: 		   $cunique%$cudom+
 5598: 		   $cusymb%$cuname+
 5599: 		   $cusymb%$cudom+
 5600: 		   $cucourseid%$cuname+
 5601: 		   $cucourseid%$cudom+
 5602: 		   $cpart%$cuname+
 5603: 		   $cpart%$cudom);
 5604:     } else {
 5605: 	$return.= ($cunique%$cuname+
 5606: 		   $cunique%$cudom+
 5607: 		   $cusymb%$cuname+
 5608: 		   $cusymb%$cudom+
 5609: 		   $cucourseid%$cuname+
 5610: 		   $cucourseid%$cudom);
 5611:     }
 5612:     return $return;
 5613: }
 5614: 
 5615: sub receipt {
 5616:     my ($part)=@_;
 5617:     my ($symb,$courseid,$domain,$name) = &Apache::lonxml::whichuser();
 5618:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 5619: }
 5620: 
 5621: # ------------------------------------------------------------ Serves up a file
 5622: # returns either the contents of the file or 
 5623: # -1 if the file doesn't exist
 5624: #
 5625: # if the target is a file that was uploaded via DOCS, 
 5626: # a check will be made to see if a current copy exists on the local server,
 5627: # if it does this will be served, otherwise a copy will be retrieved from
 5628: # the home server for the course and stored in /home/httpd/html/userfiles on
 5629: # the local server.   
 5630: 
 5631: sub getfile {
 5632:     my ($file) = @_;
 5633:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 5634:     &repcopy($file);
 5635:     return &readfile($file);
 5636: }
 5637: 
 5638: sub repcopy_userfile {
 5639:     my ($file)=@_;
 5640:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 5641:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 5642:     my ($cdom,$cnum,$filename) = 
 5643: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+([^/]+)/+([^/]+)/+(.*)|);
 5644:     my ($info,$rtncode);
 5645:     my $uri="/uploaded/$cdom/$cnum/$filename";
 5646:     if (-e "$file") {
 5647: 	my @fileinfo = stat($file);
 5648: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 5649: 	if ($lwpresp ne 'ok') {
 5650: 	    if ($rtncode eq '404') {
 5651: 		unlink($file);
 5652: 	    }
 5653: 	    #my $ua=new LWP::UserAgent;
 5654: 	    #my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 5655: 	    #my $response=$ua->request($request);
 5656: 	    #if ($response->is_success()) {
 5657: 	#	return $response->content;
 5658: 	#    } else {
 5659: 	#	return -1;
 5660: 	#    }
 5661: 	    return -1;
 5662: 	}
 5663: 	if ($info < $fileinfo[9]) {
 5664: 	    return 'ok';
 5665: 	}
 5666: 	$info = '';
 5667: 	$lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 5668: 	if ($lwpresp ne 'ok') {
 5669: 	    return -1;
 5670: 	}
 5671:     } else {
 5672: 	my $lwpresp = &getuploaded('GET',$uri,$cdom,$cnum,\$info,\$rtncode);
 5673: 	if ($lwpresp ne 'ok') {
 5674: 	    my $ua=new LWP::UserAgent;
 5675: 	    my $request=new HTTP::Request('GET',&tokenwrapper($uri));
 5676: 	    my $response=$ua->request($request);
 5677: 	    if ($response->is_success()) {
 5678: 		$info=$response->content;
 5679: 	    } else {
 5680: 		return -1;
 5681: 	    }
 5682: 	}
 5683: 	my @parts = ($cdom,$cnum); 
 5684: 	if ($filename =~ m|^(.+)/[^/]+$|) {
 5685: 	    push @parts, split(/\//,$1);
 5686: 	}
 5687: 	my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 5688: 	foreach my $part (@parts) {
 5689: 	    $path .= '/'.$part;
 5690: 	    if (!-e $path) {
 5691: 		mkdir($path,0770);
 5692: 	    }
 5693: 	}
 5694:     }
 5695:     open(FILE,">$file");
 5696:     print FILE $info;
 5697:     close(FILE);
 5698:     return 'ok';
 5699: }
 5700: 
 5701: sub tokenwrapper {
 5702:     my $uri=shift;
 5703:     $uri=~s|^http\://([^/]+)||;
 5704:     $uri=~s|^/||;
 5705:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 5706:     my $token=$1;
 5707:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 5708:     if ($udom && $uname && $file) {
 5709: 	$file=~s|(\?\.*)*$||;
 5710:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 5711:         return 'http://'.$hostname{ &homeserver($uname,$udom)}.'/'.$uri.
 5712:                (($uri=~/\?/)?'&':'?').'token='.$token.
 5713:                                '&tokenissued='.$perlvar{'lonHostID'};
 5714:     } else {
 5715:         return '/adm/notfound.html';
 5716:     }
 5717: }
 5718: 
 5719: sub getuploaded {
 5720:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 5721:     $uri=~s/^\///;
 5722:     $uri = 'http://'.$hostname{ &homeserver($cnum,$cdom)}.'/raw/'.$uri;
 5723:     my $ua=new LWP::UserAgent;
 5724:     my $request=new HTTP::Request($reqtype,$uri);
 5725:     my $response=$ua->request($request);
 5726:     $$rtncode = $response->code;
 5727:     if (! $response->is_success()) {
 5728: 	return 'failed';
 5729:     }      
 5730:     if ($reqtype eq 'HEAD') {
 5731: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 5732:     } elsif ($reqtype eq 'GET') {
 5733: 	$$info = $response->content;
 5734:     }
 5735:     return 'ok';
 5736: }
 5737: 
 5738: sub readfile {
 5739:     my $file = shift;
 5740:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 5741:     my $fh;
 5742:     open($fh,"<$file");
 5743:     my $a='';
 5744:     while (<$fh>) { $a .=$_; }
 5745:     return $a;
 5746: }
 5747: 
 5748: sub filelocation {
 5749:     my ($dir,$file) = @_;
 5750:     my $location;
 5751:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 5752:     if ($file=~m:^/~:) { # is a contruction space reference
 5753:         $location = $file;
 5754:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 5755:     } elsif ($file=~m:^/home/[^/]*/public_html/:) {
 5756: 	# is a correct contruction space reference
 5757:         $location = $file;
 5758:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 5759:         my ($udom,$uname,$filename)=
 5760:   	    ($file=~m -^/+(?:uploaded|editupload)/+([^/]+)/+([^/]+)/+(.*)$-);
 5761:         my $home=&homeserver($uname,$udom);
 5762:         my $is_me=0;
 5763:         my @ids=&current_machine_ids();
 5764:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 5765:         if ($is_me) {
 5766:   	    $location=&Apache::loncommon::propath($udom,$uname).
 5767:   	      '/userfiles/'.$filename;
 5768:         } else {
 5769:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 5770:   	      $udom.'/'.$uname.'/'.$filename;
 5771:         }
 5772:     } else {
 5773:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 5774:         $file=~s:^/res/:/:;
 5775:         if ( !( $file =~ m:^/:) ) {
 5776:             $location = $dir. '/'.$file;
 5777:         } else {
 5778:             $location = '/home/httpd/html/res'.$file;
 5779:         }
 5780:     }
 5781:     $location=~s://+:/:g; # remove duplicate /
 5782:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 5783:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 5784:     return $location;
 5785: }
 5786: 
 5787: sub hreflocation {
 5788:     my ($dir,$file)=@_;
 5789:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 5790: 	$file=filelocation($dir,$file);
 5791:     }
 5792:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 5793: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 5794:     } elsif ($file=~m-/home/(\w+)/public_html/-) {
 5795: 	$file=~s-^/home/(\w+)/public_html/-/~$1/-;
 5796:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 5797: 	$file=~s-^/home/httpd/lonUsers/([^/]*)/./././([^/]*)/userfiles/
 5798: 	    -/uploaded/$1/$2/-x;
 5799:     }
 5800:     return $file;
 5801: }
 5802: 
 5803: sub current_machine_domains {
 5804:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 5805:     my @domains;
 5806:     while( my($id, $name) = each(%hostname)) {
 5807: #	&logthis("-$id-$name-$hostname-");
 5808: 	if ($hostname eq $name) {
 5809: 	    push(@domains,$hostdom{$id});
 5810: 	}
 5811:     }
 5812:     return @domains;
 5813: }
 5814: 
 5815: sub current_machine_ids {
 5816:     my $hostname=$hostname{$perlvar{'lonHostID'}};
 5817:     my @ids;
 5818:     while( my($id, $name) = each(%hostname)) {
 5819: #	&logthis("-$id-$name-$hostname-");
 5820: 	if ($hostname eq $name) {
 5821: 	    push(@ids,$id);
 5822: 	}
 5823:     }
 5824:     return @ids;
 5825: }
 5826: 
 5827: # ------------------------------------------------------------- Declutters URLs
 5828: 
 5829: sub declutter {
 5830:     my $thisfn=shift;
 5831:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 5832:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 5833:     $thisfn=~s/^\///;
 5834:     $thisfn=~s/^res\///;
 5835:     $thisfn=~s/\?.+$//;
 5836:     return $thisfn;
 5837: }
 5838: 
 5839: # ------------------------------------------------------------- Clutter up URLs
 5840: 
 5841: sub clutter {
 5842:     my $thisfn='/'.&declutter(shift);
 5843:     unless ($thisfn=~/^\/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)\//) { 
 5844:        $thisfn='/res'.$thisfn; 
 5845:     }
 5846:     return $thisfn;
 5847: }
 5848: 
 5849: sub freeze_escape {
 5850:     my ($value)=@_;
 5851:     if (ref($value)) {
 5852: 	$value=&nfreeze($value);
 5853: 	return '__FROZEN__'.&escape($value);
 5854:     }
 5855:     return &escape($value);
 5856: }
 5857: 
 5858: # -------------------------------------------------------- Escape Special Chars
 5859: 
 5860: sub escape {
 5861:     my $str=shift;
 5862:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
 5863:     return $str;
 5864: }
 5865: 
 5866: # ----------------------------------------------------- Un-Escape Special Chars
 5867: 
 5868: sub unescape {
 5869:     my $str=shift;
 5870:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
 5871:     return $str;
 5872: }
 5873: 
 5874: sub thaw_unescape {
 5875:     my ($value)=@_;
 5876:     if ($value =~ /^__FROZEN__/) {
 5877: 	substr($value,0,10,undef);
 5878: 	$value=&unescape($value);
 5879: 	return &thaw($value);
 5880:     }
 5881:     return &unescape($value);
 5882: }
 5883: 
 5884: sub mod_perl_version {
 5885:     return 1;
 5886:     if (defined($perlvar{'MODPERL2'})) {
 5887: 	return 2;
 5888:     }
 5889: }
 5890: 
 5891: sub correct_line_ends {
 5892:     my ($result)=@_;
 5893:     $$result =~s/\r\n/\n/mg;
 5894:     $$result =~s/\r/\n/mg;
 5895: }
 5896: # ================================================================ Main Program
 5897: 
 5898: sub goodbye {
 5899:    &logthis("Starting Shut down");
 5900: #not converted to using infrastruture and probably shouldn't be
 5901:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&freeze(\%badServerCache))));
 5902: #converted
 5903: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 5904:    &logthis(sprintf("%-20s is %s",'%homecache',length(&freeze(\%homecache))));
 5905: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&freeze(\%titlecache))));
 5906: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&freeze(\%courseresdatacache))));
 5907: #1.1 only
 5908: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&freeze(\%userresdatacache))));
 5909: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&freeze(\%getsectioncache))));
 5910: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&freeze(\%courseresversioncache))));
 5911: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&freeze(\%resversioncache))));
 5912:    &logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 5913:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 5914:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 5915:    &flushcourselogs();
 5916:    &logthis("Shutting down");
 5917:    return DONE;
 5918: }
 5919: 
 5920: BEGIN {
 5921: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 5922:     unless ($readit) {
 5923: {
 5924:     # FIXME: Use LONCAPA::Configuration::read_conf here and omit next block
 5925:     open(my $config,"</etc/httpd/conf/loncapa.conf");
 5926: 
 5927:     while (my $configline=<$config>) {
 5928:         if ($configline=~/\S/ && $configline =~ /^[^\#]*PerlSetVar/) {
 5929: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 5930:            chomp($varvalue);
 5931:            $perlvar{$varname}=$varvalue;
 5932:         }
 5933:     }
 5934:     close($config);
 5935: }
 5936: {
 5937:     open(my $config,"</etc/httpd/conf/loncapa_apache.conf");
 5938: 
 5939:     while (my $configline=<$config>) {
 5940:         if ($configline =~ /^[^\#]*PerlSetVar/) {
 5941: 	   my ($dummy,$varname,$varvalue)=split(/\s+/,$configline);
 5942:            chomp($varvalue);
 5943:            $perlvar{$varname}=$varvalue;
 5944:         }
 5945:     }
 5946:     close($config);
 5947: }
 5948: 
 5949: # ------------------------------------------------------------ Read domain file
 5950: {
 5951:     %domaindescription = ();
 5952:     %domain_auth_def = ();
 5953:     %domain_auth_arg_def = ();
 5954:     my $fh;
 5955:     if (open($fh,"<".$Apache::lonnet::perlvar{'lonTabDir'}.'/domain.tab')) {
 5956:        while (<$fh>) {
 5957:            next if (/^(\#|\s*$)/);
 5958: #           next if /^\#/;
 5959:            chomp;
 5960:            my ($domain, $domain_description, $def_auth, $def_auth_arg,
 5961: 	       $def_lang, $city, $longi, $lati) = split(/:/,$_);
 5962: 	   $domain_auth_def{$domain}=$def_auth;
 5963:            $domain_auth_arg_def{$domain}=$def_auth_arg;
 5964: 	   $domaindescription{$domain}=$domain_description;
 5965: 	   $domain_lang_def{$domain}=$def_lang;
 5966: 	   $domain_city{$domain}=$city;
 5967: 	   $domain_longi{$domain}=$longi;
 5968: 	   $domain_lati{$domain}=$lati;
 5969: 
 5970:  #         &logthis("Domain.tab: $domain, $domain_auth_def{$domain}, $domain_auth_arg_def{$domain},$domaindescription{$domain}");
 5971: #          &logthis("Domain.tab: $domain ".$domaindescription{$domain} );
 5972: 	}
 5973:     }
 5974:     close ($fh);
 5975: }
 5976: 
 5977: 
 5978: # ------------------------------------------------------------- Read hosts file
 5979: {
 5980:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 5981: 
 5982:     while (my $configline=<$config>) {
 5983:        next if ($configline =~ /^(\#|\s*$)/);
 5984:        chomp($configline);
 5985:        my ($id,$domain,$role,$name)=split(/:/,$configline);
 5986:        $name=~s/\s//g;
 5987:        if ($id && $domain && $role && $name) {
 5988: 	 $hostname{$id}=$name;
 5989: 	 $hostdom{$id}=$domain;
 5990: 	 if ($role eq 'library') { $libserv{$id}=$name; }
 5991:        }
 5992:     }
 5993:     close($config);
 5994:     # FIXME: dev server don't want this, production servers _do_ want this
 5995:     #&get_iphost();
 5996: }
 5997: 
 5998: sub get_iphost {
 5999:     if (%iphost) { return %iphost; }
 6000:     my %name_to_ip;
 6001:     foreach my $id (keys(%hostname)) {
 6002: 	my $name=$hostname{$id};
 6003: 	my $ip;
 6004: 	if (!exists($name_to_ip{$name})) {
 6005: 	    $ip = gethostbyname($name);
 6006: 	    if (!$ip || length($ip) ne 4) {
 6007: 		&logthis("Skipping host $id name $name no IP found\n");
 6008: 		next;
 6009: 	    }
 6010: 	    $ip=inet_ntoa($ip);
 6011: 	    $name_to_ip{$name} = $ip;
 6012: 	} else {
 6013: 	    $ip = $name_to_ip{$name};
 6014: 	}
 6015: 	push(@{$iphost{$ip}},$id);
 6016:     }
 6017:     return %iphost;
 6018: }
 6019: 
 6020: # ------------------------------------------------------ Read spare server file
 6021: {
 6022:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 6023: 
 6024:     while (my $configline=<$config>) {
 6025:        chomp($configline);
 6026:        if ($configline) {
 6027:           $spareid{$configline}=1;
 6028:        }
 6029:     }
 6030:     close($config);
 6031: }
 6032: # ------------------------------------------------------------ Read permissions
 6033: {
 6034:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 6035: 
 6036:     while (my $configline=<$config>) {
 6037: 	chomp($configline);
 6038: 	if ($configline) {
 6039: 	    my ($role,$perm)=split(/ /,$configline);
 6040: 	    if ($perm ne '') { $pr{$role}=$perm; }
 6041: 	}
 6042:     }
 6043:     close($config);
 6044: }
 6045: 
 6046: # -------------------------------------------- Read plain texts for permissions
 6047: {
 6048:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 6049: 
 6050:     while (my $configline=<$config>) {
 6051: 	chomp($configline);
 6052: 	if ($configline) {
 6053: 	    my ($short,$plain)=split(/:/,$configline);
 6054: 	    if ($plain ne '') { $prp{$short}=$plain; }
 6055: 	}
 6056:     }
 6057:     close($config);
 6058: }
 6059: 
 6060: # ---------------------------------------------------------- Read package table
 6061: {
 6062:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 6063: 
 6064:     while (my $configline=<$config>) {
 6065: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 6066: 	chomp($configline);
 6067: 	my ($short,$plain)=split(/:/,$configline);
 6068: 	my ($pack,$name)=split(/\&/,$short);
 6069: 	if ($plain ne '') {
 6070: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 6071: 	    $packagetab{$short}=$plain; 
 6072: 	}
 6073:     }
 6074:     close($config);
 6075: }
 6076: 
 6077: # ------------- set up temporary directory
 6078: {
 6079:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 6080: 
 6081: }
 6082: 
 6083: $memcache=new Cache::Memcached({'servers'=>['127.0.0.1:11211']});
 6084: 
 6085: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 6086: $dumpcount=0;
 6087: 
 6088: &logtouch();
 6089: &logthis('<font color=yellow>INFO: Read configuration</font>');
 6090: $readit=1;
 6091:     {
 6092: 	use integer;
 6093: 	my $test=(2**32)+1;
 6094: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 6095: 	&logthis(" Detected 64bit platform ($_64bit)");
 6096:     }
 6097: }
 6098: }
 6099: 
 6100: 1;
 6101: __END__
 6102: 
 6103: =pod
 6104: 
 6105: =head1 NAME
 6106: 
 6107: Apache::lonnet - Subroutines to ask questions about things in the network.
 6108: 
 6109: =head1 SYNOPSIS
 6110: 
 6111: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 6112: 
 6113:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 6114: 
 6115: Common parameters:
 6116: 
 6117: =over 4
 6118: 
 6119: =item *
 6120: 
 6121: $uname : an internal username (if $cname expecting a course Id specifically)
 6122: 
 6123: =item *
 6124: 
 6125: $udom : a domain (if $cdom expecting a course's domain specifically)
 6126: 
 6127: =item *
 6128: 
 6129: $symb : a resource instance identifier
 6130: 
 6131: =item *
 6132: 
 6133: $namespace : the name of a .db file that contains the data needed or
 6134: being set.
 6135: 
 6136: =back
 6137: 
 6138: =head1 OVERVIEW
 6139: 
 6140: lonnet provides subroutines which interact with the
 6141: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 6142: about classes, users, and resources.
 6143: 
 6144: For many of these objects you can also use this to store data about
 6145: them or modify them in various ways.
 6146: 
 6147: =head2 Symbs
 6148: 
 6149: To identify a specific instance of a resource, LON-CAPA uses symbols
 6150: or "symbs"X<symb>. These identifiers are built from the URL of the
 6151: map, the resource number of the resource in the map, and the URL of
 6152: the resource itself. The latter is somewhat redundant, but might help
 6153: if maps change.
 6154: 
 6155: An example is
 6156: 
 6157:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 6158: 
 6159: The respective map entry is
 6160: 
 6161:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 6162:   title="Problem 2">
 6163:  </resource>
 6164: 
 6165: Symbs are used by the random number generator, as well as to store and
 6166: restore data specific to a certain instance of for example a problem.
 6167: 
 6168: =head2 Storing And Retrieving Data
 6169: 
 6170: X<store()>X<cstore()>X<restore()>Three of the most important functions
 6171: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 6172: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 6173: is is the non-critical message twin of cstore. These functions are for
 6174: handlers to store a perl hash to a user's permanent data space in an
 6175: easy manner, and to retrieve it again on another call. It is expected
 6176: that a handler would use this once at the beginning to retrieve data,
 6177: and then again once at the end to send only the new data back.
 6178: 
 6179: The data is stored in the user's data directory on the user's
 6180: homeserver under the ID of the course.
 6181: 
 6182: The hash that is returned by restore will have all of the previous
 6183: value for all of the elements of the hash.
 6184: 
 6185: Example:
 6186: 
 6187:  #creating a hash
 6188:  my %hash;
 6189:  $hash{'foo'}='bar';
 6190: 
 6191:  #storing it
 6192:  &Apache::lonnet::cstore(\%hash);
 6193: 
 6194:  #changing a value
 6195:  $hash{'foo'}='notbar';
 6196: 
 6197:  #adding a new value
 6198:  $hash{'bar'}='foo';
 6199:  &Apache::lonnet::cstore(\%hash);
 6200: 
 6201:  #retrieving the hash
 6202:  my %history=&Apache::lonnet::restore();
 6203: 
 6204:  #print the hash
 6205:  foreach my $key (sort(keys(%history))) {
 6206:    print("\%history{$key} = $history{$key}");
 6207:  }
 6208: 
 6209: Will print out:
 6210: 
 6211:  %history{1:foo} = bar
 6212:  %history{1:keys} = foo:timestamp
 6213:  %history{1:timestamp} = 990455579
 6214:  %history{2:bar} = foo
 6215:  %history{2:foo} = notbar
 6216:  %history{2:keys} = foo:bar:timestamp
 6217:  %history{2:timestamp} = 990455580
 6218:  %history{bar} = foo
 6219:  %history{foo} = notbar
 6220:  %history{timestamp} = 990455580
 6221:  %history{version} = 2
 6222: 
 6223: Note that the special hash entries C<keys>, C<version> and
 6224: C<timestamp> were added to the hash. C<version> will be equal to the
 6225: total number of versions of the data that have been stored. The
 6226: C<timestamp> attribute will be the UNIX time the hash was
 6227: stored. C<keys> is available in every historical section to list which
 6228: keys were added or changed at a specific historical revision of a
 6229: hash.
 6230: 
 6231: B<Warning>: do not store the hash that restore returns directly. This
 6232: will cause a mess since it will restore the historical keys as if the
 6233: were new keys. I.E. 1:foo will become 1:1:foo etc.
 6234: 
 6235: Calling convention:
 6236: 
 6237:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 6238:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 6239: 
 6240: For more detailed information, see lonnet specific documentation.
 6241: 
 6242: =head1 RETURN MESSAGES
 6243: 
 6244: =over 4
 6245: 
 6246: =item * B<con_lost>: unable to contact remote host
 6247: 
 6248: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 6249: when the connection is brought back up
 6250: 
 6251: =item * B<con_failed>: unable to contact remote host and unable to save message
 6252: for later delivery
 6253: 
 6254: =item * B<error:>: an error a occured, a description of the error follows the :
 6255: 
 6256: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 6257: that was requested
 6258: 
 6259: =back
 6260: 
 6261: =head1 PUBLIC SUBROUTINES
 6262: 
 6263: =head2 Session Environment Functions
 6264: 
 6265: =over 4
 6266: 
 6267: =item * 
 6268: X<appenv()>
 6269: B<appenv(%hash)>: the value of %hash is written to
 6270: the user envirnoment file, and will be restored for each access this
 6271: user makes during this session, also modifies the %env for the current
 6272: process
 6273: 
 6274: =item *
 6275: X<delenv()>
 6276: B<delenv($regexp)>: removes all items from the session
 6277: environment file that matches the regular expression in $regexp. The
 6278: values are also delted from the current processes %env.
 6279: 
 6280: =back
 6281: 
 6282: =head2 User Information
 6283: 
 6284: =over 4
 6285: 
 6286: =item *
 6287: X<queryauthenticate()>
 6288: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 6289: authentication scheme
 6290: 
 6291: =item *
 6292: X<authenticate()>
 6293: B<authenticate($uname,$upass,$udom)>: try to
 6294: authenticate user from domain's lib servers (first use the current
 6295: one). C<$upass> should be the users password.
 6296: 
 6297: =item *
 6298: X<homeserver()>
 6299: B<homeserver($uname,$udom)>: find the server which has
 6300: the user's directory and files (there must be only one), this caches
 6301: the answer, and also caches if there is a borken connection.
 6302: 
 6303: =item *
 6304: X<idget()>
 6305: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 6306: (IDs are a unique resource in a domain, there must be only 1 ID per
 6307: username, and only 1 username per ID in a specific domain) (returns
 6308: hash: id=>name,id=>name)
 6309: 
 6310: =item *
 6311: X<idrget()>
 6312: B<idrget($udom,@unames)>: find the IDs behind a list of
 6313: usernames (returns hash: name=>id,name=>id)
 6314: 
 6315: =item *
 6316: X<idput()>
 6317: B<idput($udom,%ids)>: store away a list of names and associated IDs
 6318: 
 6319: =item *
 6320: X<rolesinit()>
 6321: B<rolesinit($udom,$username,$authhost)>: get user privileges
 6322: 
 6323: =item *
 6324: X<getsection()>
 6325: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 6326: course $cname, return section name/number or '' for "not in course"
 6327: and '-1' for "no section"
 6328: 
 6329: =item *
 6330: X<userenvironment()>
 6331: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 6332: passed in @what from the requested user's environment, returns a hash
 6333: 
 6334: =back
 6335: 
 6336: =head2 User Roles
 6337: 
 6338: =over 4
 6339: 
 6340: =item *
 6341: 
 6342: allowed($priv,$uri) : check for a user privilege; returns codes for allowed
 6343: actions
 6344:  F: full access
 6345:  U,I,K: authentication modes (cxx only)
 6346:  '': forbidden
 6347:  1: user needs to choose course
 6348:  2: browse allowed
 6349: 
 6350: =item *
 6351: 
 6352: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 6353: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 6354: and course level
 6355: 
 6356: =item *
 6357: 
 6358: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 6359: explanation of a user role term
 6360: 
 6361: =back
 6362: 
 6363: =head2 User Modification
 6364: 
 6365: =over 4
 6366: 
 6367: =item *
 6368: 
 6369: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 6370: user for the level given by URL.  Optional start and end dates (leave empty
 6371: string or zero for "no date")
 6372: 
 6373: =item *
 6374: 
 6375: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 6376: change a users, password, possible return values are: ok,
 6377: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 6378: refused
 6379: 
 6380: =item *
 6381: 
 6382: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 6383: 
 6384: =item *
 6385: 
 6386: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 6387: modify user
 6388: 
 6389: =item *
 6390: 
 6391: modifystudent
 6392: 
 6393: modify a students enrollment and identification information.
 6394: The course id is resolved based on the current users environment.  
 6395: This means the envoking user must be a course coordinator or otherwise
 6396: associated with a course.
 6397: 
 6398: This call is essentially a wrapper for lonnet::modifyuser and
 6399: lonnet::modify_student_enrollment
 6400: 
 6401: Inputs: 
 6402: 
 6403: =over 4
 6404: 
 6405: =item B<$udom> Students loncapa domain
 6406: 
 6407: =item B<$uname> Students loncapa login name
 6408: 
 6409: =item B<$uid> Students id/student number
 6410: 
 6411: =item B<$umode> Students authentication mode
 6412: 
 6413: =item B<$upass> Students password
 6414: 
 6415: =item B<$first> Students first name
 6416: 
 6417: =item B<$middle> Students middle name
 6418: 
 6419: =item B<$last> Students last name
 6420: 
 6421: =item B<$gene> Students generation
 6422: 
 6423: =item B<$usec> Students section in course
 6424: 
 6425: =item B<$end> Unix time of the roles expiration
 6426: 
 6427: =item B<$start> Unix time of the roles start date
 6428: 
 6429: =item B<$forceid> If defined, allow $uid to be changed
 6430: 
 6431: =item B<$desiredhome> server to use as home server for student
 6432: 
 6433: =back
 6434: 
 6435: =item *
 6436: 
 6437: modify_student_enrollment
 6438: 
 6439: Change a students enrollment status in a class.  The environment variable
 6440: 'role.request.course' must be defined for this function to proceed.
 6441: 
 6442: Inputs:
 6443: 
 6444: =over 4
 6445: 
 6446: =item $udom, students domain
 6447: 
 6448: =item $uname, students name
 6449: 
 6450: =item $uid, students user id
 6451: 
 6452: =item $first, students first name
 6453: 
 6454: =item $middle
 6455: 
 6456: =item $last
 6457: 
 6458: =item $gene
 6459: 
 6460: =item $usec
 6461: 
 6462: =item $end
 6463: 
 6464: =item $start
 6465: 
 6466: =back
 6467: 
 6468: 
 6469: =item *
 6470: 
 6471: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 6472: custom role; give a custom role to a user for the level given by URL.  Specify
 6473: name and domain of role author, and role name
 6474: 
 6475: =item *
 6476: 
 6477: revokerole($udom,$uname,$url,$role) : revoke a role for url
 6478: 
 6479: =item *
 6480: 
 6481: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 6482: 
 6483: =back
 6484: 
 6485: =head2 Course Infomation
 6486: 
 6487: =over 4
 6488: 
 6489: =item *
 6490: 
 6491: coursedescription($courseid) : returns a hash of information about the
 6492: specified course id, including all environment settings for the
 6493: course, the description of the course will be in the hash under the
 6494: key 'description'
 6495: 
 6496: =item *
 6497: 
 6498: resdata($name,$domain,$type,@which) : request for current parameter
 6499: setting for a specific $type, where $type is either 'course' or 'user',
 6500: @what should be a list of parameters to ask about. This routine caches
 6501: answers for 5 minutes.
 6502: 
 6503: =back
 6504: 
 6505: =head2 Course Modification
 6506: 
 6507: =over 4
 6508: 
 6509: =item *
 6510: 
 6511: writecoursepref($courseid,%prefs) : write preferences (environment
 6512: database) for a course
 6513: 
 6514: =item *
 6515: 
 6516: createcourse($udom,$description,$url) : make/modify course
 6517: 
 6518: =back
 6519: 
 6520: =head2 Resource Subroutines
 6521: 
 6522: =over 4
 6523: 
 6524: =item *
 6525: 
 6526: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 6527: 
 6528: =item *
 6529: 
 6530: repcopy($filename) : subscribes to the requested file, and attempts to
 6531: replicate from the owning library server, Might return
 6532: 'unavailable', 'not_found', 'forbidden', 'ok', or
 6533: 'bad_request', also attempts to grab the metadata for the
 6534: resource. Expects the local filesystem pathname
 6535: (/home/httpd/html/res/....)
 6536: 
 6537: =back
 6538: 
 6539: =head2 Resource Information
 6540: 
 6541: =over 4
 6542: 
 6543: =item *
 6544: 
 6545: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 6546: a vairety of different possible values, $varname should be a request
 6547: string, and the other parameters can be used to specify who and what
 6548: one is asking about.
 6549: 
 6550: Possible values for $varname are environment.lastname (or other item
 6551: from the envirnment hash), user.name (or someother aspect about the
 6552: user), resource.0.maxtries (or some other part and parameter of a
 6553: resource)
 6554: 
 6555: =item *
 6556: 
 6557: directcondval($number) : get current value of a condition; reads from a state
 6558: string
 6559: 
 6560: =item *
 6561: 
 6562: condval($condidx) : value of condition index based on state
 6563: 
 6564: =item *
 6565: 
 6566: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 6567: resource's metadata, $what should be either a specific key, or either
 6568: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 6569: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 6570: 
 6571: this function automatically caches all requests
 6572: 
 6573: =item *
 6574: 
 6575: metadata_query($query,$custom,$customshow) : make a metadata query against the
 6576: network of library servers; returns file handle of where SQL and regex results
 6577: will be stored for query
 6578: 
 6579: =item *
 6580: 
 6581: symbread($filename) : return symbolic list entry (filename argument optional);
 6582: returns the data handle
 6583: 
 6584: =item *
 6585: 
 6586: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 6587: a possible symb for the URL in $thisfn, and if is an encryypted
 6588: resource that the user accessed using /enc/ returns a 1 on success, 0
 6589: on failure, user must be in a course, as it assumes the existance of
 6590: the course initial hash, and uses $env('request.course.id'}
 6591: 
 6592: 
 6593: =item *
 6594: 
 6595: symbclean($symb) : removes versions numbers from a symb, returns the
 6596: cleaned symb
 6597: 
 6598: =item *
 6599: 
 6600: is_on_map($uri) : checks if the $uri is somewhere on the current
 6601: course map, user must be in a course for it to work.
 6602: 
 6603: =item *
 6604: 
 6605: numval($salt) : return random seed value (addend for rndseed)
 6606: 
 6607: =item *
 6608: 
 6609: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 6610: a random seed, all arguments are optional, if they aren't sent it uses the
 6611: environment to derive them. Note: if symb isn't sent and it can't get one
 6612: from &symbread it will use the current time as its return value
 6613: 
 6614: =item *
 6615: 
 6616: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 6617: unfakeable, receipt
 6618: 
 6619: =item *
 6620: 
 6621: receipt() : API to ireceipt working off of env values; given out to users
 6622: 
 6623: =item *
 6624: 
 6625: countacc($url) : count the number of accesses to a given URL
 6626: 
 6627: =item *
 6628: 
 6629: 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
 6630: 
 6631: =item *
 6632: 
 6633: 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)
 6634: 
 6635: =item *
 6636: 
 6637: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 6638: 
 6639: =item *
 6640: 
 6641: devalidate($symb) : devalidate temporary spreadsheet calculations,
 6642: forcing spreadsheet to reevaluate the resource scores next time.
 6643: 
 6644: =back
 6645: 
 6646: =head2 Storing/Retreiving Data
 6647: 
 6648: =over 4
 6649: 
 6650: =item *
 6651: 
 6652: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 6653: for this url; hashref needs to be given and should be a \%hashname; the
 6654: remaining args aren't required and if they aren't passed or are '' they will
 6655: be derived from the env
 6656: 
 6657: =item *
 6658: 
 6659: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 6660: uses critical subroutine
 6661: 
 6662: =item *
 6663: 
 6664: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 6665: all args are optional
 6666: 
 6667: =item *
 6668: 
 6669: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 6670: works very similar to store/cstore, but all data is stored in a
 6671: temporary location and can be reset using tmpreset, $storehash should
 6672: be a hash reference, returns nothing on success
 6673: 
 6674: =item *
 6675: 
 6676: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 6677: similar to restore, but all data is stored in a temporary location and
 6678: can be reset using tmpreset. Returns a hash of values on success,
 6679: error string otherwise.
 6680: 
 6681: =item *
 6682: 
 6683: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 6684: deltes all keys for $symb form the temporary storage hash.
 6685: 
 6686: =item *
 6687: 
 6688: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 6689: reference filled in from namesp ($udom and $uname are optional)
 6690: 
 6691: =item *
 6692: 
 6693: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 6694: namesp ($udom and $uname are optional)
 6695: 
 6696: =item *
 6697: 
 6698: dump($namespace,$udom,$uname,$regexp) : 
 6699: dumps the complete (or key matching regexp) namespace into a hash
 6700: ($udom, $uname and $regexp are optional)
 6701: 
 6702: =item *
 6703: 
 6704: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 6705: $store can be a scalar, an array reference, or if the amount to be 
 6706: incremented is > 1, a hash reference.
 6707: 
 6708: ($udom and $uname are optional)
 6709: 
 6710: =item *
 6711: 
 6712: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 6713: ($udom and $uname are optional)
 6714: 
 6715: =item *
 6716: 
 6717: putstore($namespace,$storehash,$udomain,$uname) : stores hash in namesp
 6718: keys used in storehash include version information (e.g., 1:$symb:message etc.) as
 6719: used in records written by &store and retrieved by &restore.  This function 
 6720: was created for use in editing discussion posts, without incrementing the
 6721: version number included in the key for a particular post. The colon 
 6722: separated list of attribute names (e.g., the value associated with the key 
 6723: 1:keys:$symb) is also generated and passed in the ampersand separated 
 6724: items sent to lonnet::reply().  
 6725: 
 6726: =item *
 6727: 
 6728: cput($namespace,$storehash,$udom,$uname) : critical put
 6729: ($udom and $uname are optional)
 6730: 
 6731: =item *
 6732: 
 6733: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 6734: reference filled in from namesp (encrypts the return communication)
 6735: ($udom and $uname are optional)
 6736: 
 6737: =item *
 6738: 
 6739: log($udom,$name,$home,$message) : write to permanent log for user; use
 6740: critical subroutine
 6741: 
 6742: =back
 6743: 
 6744: =head2 Network Status Functions
 6745: 
 6746: =over 4
 6747: 
 6748: =item *
 6749: 
 6750: dirlist($uri) : return directory list based on URI
 6751: 
 6752: =item *
 6753: 
 6754: spareserver() : find server with least workload from spare.tab
 6755: 
 6756: =back
 6757: 
 6758: =head2 Apache Request
 6759: 
 6760: =over 4
 6761: 
 6762: =item *
 6763: 
 6764: ssi($url,%hash) : server side include, does a complete request cycle on url to
 6765: localhost, posts hash
 6766: 
 6767: =back
 6768: 
 6769: =head2 Data to String to Data
 6770: 
 6771: =over 4
 6772: 
 6773: =item *
 6774: 
 6775: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 6776: and '&' separators, supports elements that are arrayrefs and hashrefs
 6777: 
 6778: =item *
 6779: 
 6780: hashref2str($hashref) : convert a hashref into a string complete with
 6781: escaping and '=' and '&' separators, supports elements that are
 6782: arrayrefs and hashrefs
 6783: 
 6784: =item *
 6785: 
 6786: arrayref2str($arrayref) : convert an arrayref into a string complete
 6787: with escaping and '&' separators, supports elements that are arrayrefs
 6788: and hashrefs
 6789: 
 6790: =item *
 6791: 
 6792: str2hash($string) : convert string to hash using unescaping and
 6793: splitting on '=' and '&', supports elements that are arrayrefs and
 6794: hashrefs
 6795: 
 6796: =item *
 6797: 
 6798: str2array($string) : convert string to hash using unescaping and
 6799: splitting on '&', supports elements that are arrayrefs and hashrefs
 6800: 
 6801: =back
 6802: 
 6803: =head2 Logging Routines
 6804: 
 6805: =over 4
 6806: 
 6807: These routines allow one to make log messages in the lonnet.log and
 6808: lonnet.perm logfiles.
 6809: 
 6810: =item *
 6811: 
 6812: logtouch() : make sure the logfile, lonnet.log, exists
 6813: 
 6814: =item *
 6815: 
 6816: logthis() : append message to the normal lonnet.log file, it gets
 6817: preiodically rolled over and deleted.
 6818: 
 6819: =item *
 6820: 
 6821: logperm() : append a permanent message to lonnet.perm.log, this log
 6822: file never gets deleted by any automated portion of the system, only
 6823: messages of critical importance should go in here.
 6824: 
 6825: =back
 6826: 
 6827: =head2 General File Helper Routines
 6828: 
 6829: =over 4
 6830: 
 6831: =item *
 6832: 
 6833: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 6834: (a) files in /uploaded
 6835:   (i) If a local copy of the file exists - 
 6836:       compares modification date of local copy with last-modified date for 
 6837:       definitive version stored on home server for course. If local copy is 
 6838:       stale, requests a new version from the home server and stores it. 
 6839:       If the original has been removed from the home server, then local copy 
 6840:       is unlinked.
 6841:   (ii) If local copy does not exist -
 6842:       requests the file from the home server and stores it. 
 6843:   
 6844:   If $caller is 'uploadrep':  
 6845:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 6846:     for request for files originally uploaded via DOCS. 
 6847:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 6848:   
 6849:   Otherwise:
 6850:      This indicates a call from the content generation phase of the request.
 6851:      -  returns the entire contents of the file or -1.
 6852:      
 6853: (b) files in /res
 6854:    - returns the entire contents of a file or -1; 
 6855:    it properly subscribes to and replicates the file if neccessary.
 6856: 
 6857: =item *
 6858: 
 6859: filelocation($dir,$file) : returns file system location of a file
 6860: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 6861: directory that relative $file lookups are to looked in ($dir of /a/dir
 6862: and a file of ../bob will become /a/bob)
 6863: 
 6864: =item *
 6865: 
 6866: hreflocation($dir,$file) : returns file system location or a URL; same as
 6867: filelocation except for hrefs
 6868: 
 6869: =item *
 6870: 
 6871: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 6872: 
 6873: =back
 6874: 
 6875: =head2 Usererfile file routines (/uploaded*)
 6876: 
 6877: =over 4
 6878: 
 6879: =item *
 6880: 
 6881: userfileupload(): main rotine for putting a file in a user or course's
 6882:                   filespace, arguments are,
 6883: 
 6884:  formname - required - this is the name of the element in $env where the
 6885:            filename, and the contents of the file to create/modifed exist
 6886:            the filename is in $env{'form.'.$formname.'.filename'} and the
 6887:            contents of the file is located in $env{'form.'.$formname}
 6888:  coursedoc - if true, store the file in the course of the active role
 6889:              of the current user
 6890:  subdir - required - subdirectory to put the file in under ../userfiles/
 6891:          if undefined, it will be placed in "unknown"
 6892: 
 6893:  (This routine calls clean_filename() to remove any dangerous
 6894:  characters from the filename, and then calls finuserfileupload() to
 6895:  complete the transaction)
 6896: 
 6897:  returns either the url of the uploaded file (/uploaded/....) if successful
 6898:  and /adm/notfound.html if unsuccessful
 6899: 
 6900: =item *
 6901: 
 6902: clean_filename(): routine for cleaing a filename up for storage in
 6903:                  userfile space, argument is:
 6904: 
 6905:  filename - proposed filename
 6906: 
 6907: returns: the new clean filename
 6908: 
 6909: =item *
 6910: 
 6911: finishuserfileupload(): routine that creaes and sends the file to
 6912: userspace, probably shouldn't be called directly
 6913: 
 6914:   docuname: username or courseid of destination for the file
 6915:   docudom: domain of user/course of destination for the file
 6916:   formname: same as for userfileupload()
 6917:   fname: filename (inculding subdirectories) for the file
 6918: 
 6919:  returns either the url of the uploaded file (/uploaded/....) if successful
 6920:  and /adm/notfound.html if unsuccessful
 6921: 
 6922: =item *
 6923: 
 6924: renameuserfile(): renames an existing userfile to a new name
 6925: 
 6926:   Args:
 6927:    docuname: username or courseid of destination for the file
 6928:    docudom: domain of user/course of destination for the file
 6929:    old: current file name (including any subdirs under userfiles)
 6930:    new: desired file name (including any subdirs under userfiles)
 6931: 
 6932: =item *
 6933: 
 6934: mkdiruserfile(): creates a directory is a userfiles dir
 6935: 
 6936:   Args:
 6937:    docuname: username or courseid of destination for the file
 6938:    docudom: domain of user/course of destination for the file
 6939:    dir: dir to create (including any subdirs under userfiles)
 6940: 
 6941: =item *
 6942: 
 6943: removeuserfile(): removes a file that exists in userfiles
 6944: 
 6945:   Args:
 6946:    docuname: username or courseid of destination for the file
 6947:    docudom: domain of user/course of destination for the file
 6948:    fname: filname to delete (including any subdirs under userfiles)
 6949: 
 6950: =item *
 6951: 
 6952: removeuploadedurl(): convience function for removeuserfile()
 6953: 
 6954:   Args:
 6955:    url:  a full /uploaded/... url to delete
 6956: 
 6957: =back
 6958: 
 6959: =head2 HTTP Helper Routines
 6960: 
 6961: =over 4
 6962: 
 6963: =item *
 6964: 
 6965: escape() : unpack non-word characters into CGI-compatible hex codes
 6966: 
 6967: =item *
 6968: 
 6969: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 6970: 
 6971: =back
 6972: 
 6973: =head1 PRIVATE SUBROUTINES
 6974: 
 6975: =head2 Underlying communication routines (Shouldn't call)
 6976: 
 6977: =over 4
 6978: 
 6979: =item *
 6980: 
 6981: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 6982: 
 6983: =item *
 6984: 
 6985: reply() : uses subreply to send a message to remote machine, logs all failures
 6986: 
 6987: =item *
 6988: 
 6989: critical() : passes a critical message to another server; if cannot
 6990: get through then place message in connection buffer directory and
 6991: returns con_delayed, if incapable of saving message, returns
 6992: con_failed
 6993: 
 6994: =item *
 6995: 
 6996: reconlonc() : tries to reconnect lonc client processes.
 6997: 
 6998: =back
 6999: 
 7000: =head2 Resource Access Logging
 7001: 
 7002: =over 4
 7003: 
 7004: =item *
 7005: 
 7006: flushcourselogs() : flush (save) buffer logs and access logs
 7007: 
 7008: =item *
 7009: 
 7010: courselog($what) : save message for course in hash
 7011: 
 7012: =item *
 7013: 
 7014: courseacclog($what) : save message for course using &courselog().  Perform
 7015: special processing for specific resource types (problems, exams, quizzes, etc).
 7016: 
 7017: =item *
 7018: 
 7019: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 7020: as a PerlChildExitHandler
 7021: 
 7022: =back
 7023: 
 7024: =head2 Other
 7025: 
 7026: =over 4
 7027: 
 7028: =item *
 7029: 
 7030: symblist($mapname,%newhash) : update symbolic storage links
 7031: 
 7032: =back
 7033: 
 7034: =cut

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