File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.622: download - view: text, annotated - select for diffs
Tue Apr 12 00:20:00 2005 UTC (19 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: version_1_99_0_tmcc, HEAD
Bug 3912.  DCs can use courseID (e.g., 257472759ae4061msul1) as a filter when using pickcourse.

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

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