File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.599: download - view: text, annotated - select for diffs
Thu Feb 17 22:43:27 2005 UTC (19 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- merging memcached into the mainline

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

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