File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.624: download - view: text, annotated - select for diffs
Fri Apr 15 22:03:23 2005 UTC (19 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- making it easier to reuse the parm data caching in lonnet
- making lonnavmaps use lonnet to get the parm data

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

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