File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.609: download - view: text, annotated - select for diffs
Thu Mar 17 19:40:50 2005 UTC (19 years, 4 months ago) by banghart
Branches: MAIN
CVS tags: HEAD
	Teach a number of subs about editupload, to permit editing
	portfolio meta files.

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

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