File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.892: download - view: text, annotated - select for diffs
Mon Jun 18 22:52:33 2007 UTC (17 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- eliminate unused pathway
- need to reset another internal cache

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.892 2007/06/18 22:52:33 albertel Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::Date;
   35: # use Date::Parse;
   36: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   37:             $_64bit %env);
   38: 
   39: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   40:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   41:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   42:     %courseownerbuf, %coursetypebuf);
   43: 
   44: use IO::Socket;
   45: use GDBM_File;
   46: use HTML::LCParser;
   47: use Fcntl qw(:flock);
   48: use Storable qw(thaw nfreeze);
   49: use Time::HiRes qw( gettimeofday tv_interval );
   50: use Cache::Memcached;
   51: use Digest::MD5;
   52: use Math::Random;
   53: use LONCAPA qw(:DEFAULT :match);
   54: use LONCAPA::Configuration;
   55: 
   56: my $readit;
   57: my $max_connection_retries = 10;     # Or some such value.
   58: 
   59: require Exporter;
   60: 
   61: our @ISA = qw (Exporter);
   62: our @EXPORT = qw(%env);
   63: 
   64: =pod
   65: 
   66: =head1 Package Variables
   67: 
   68: These are largely undocumented, so if you decipher one please note it here.
   69: 
   70: =over 4
   71: 
   72: =item $processmarker
   73: 
   74: Contains the time this process was started and this servers host id.
   75: 
   76: =item $dumpcount
   77: 
   78: Counts the number of times a message log flush has been attempted (regardless
   79: of success) by this process.  Used as part of the filename when messages are
   80: delayed.
   81: 
   82: =back
   83: 
   84: =cut
   85: 
   86: 
   87: # --------------------------------------------------------------------- Logging
   88: {
   89:     my $logid;
   90:     sub instructor_log {
   91: 	my ($hash_name,$storehash,$delflag,$uname,$udom)=@_;
   92: 	$logid++;
   93: 	my $id=time().'00000'.$$.'00000'.$logid;
   94: 	return &Apache::lonnet::put('nohist_'.$hash_name,
   95: 				    { $id => {
   96: 					'exe_uname' => $env{'user.name'},
   97: 					'exe_udom'  => $env{'user.domain'},
   98: 					'exe_time'  => time(),
   99: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  100: 					'delflag'   => $delflag,
  101: 					'logentry'  => $storehash,
  102: 					'uname'     => $uname,
  103: 					'udom'      => $udom,
  104: 				    }
  105: 				  },
  106: 				    $env{'course.'.$env{'request.course.id'}.'.domain'},
  107: 				    $env{'course.'.$env{'request.course.id'}.'.num'}
  108: 				    );
  109:     }
  110: }
  111: 
  112: sub logtouch {
  113:     my $execdir=$perlvar{'lonDaemons'};
  114:     unless (-e "$execdir/logs/lonnet.log") {	
  115: 	open(my $fh,">>$execdir/logs/lonnet.log");
  116: 	close $fh;
  117:     }
  118:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  119:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  120: }
  121: 
  122: sub logthis {
  123:     my $message=shift;
  124:     my $execdir=$perlvar{'lonDaemons'};
  125:     my $now=time;
  126:     my $local=localtime($now);
  127:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  128: 	print $fh "$local ($$): $message\n";
  129: 	close($fh);
  130:     }
  131:     return 1;
  132: }
  133: 
  134: sub logperm {
  135:     my $message=shift;
  136:     my $execdir=$perlvar{'lonDaemons'};
  137:     my $now=time;
  138:     my $local=localtime($now);
  139:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  140: 	print $fh "$now:$message:$local\n";
  141: 	close($fh);
  142:     }
  143:     return 1;
  144: }
  145: 
  146: sub create_connection {
  147:     my ($hostname,$lonid) = @_;
  148:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  149: 				     Type    => SOCK_STREAM,
  150: 				     Timeout => 10);
  151:     return 0 if (!$client);
  152:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  153:     my $result = <$client>;
  154:     chomp($result);
  155:     return 1 if ($result eq 'done');
  156:     return 0;
  157: }
  158: 
  159: 
  160: # -------------------------------------------------- Non-critical communication
  161: sub subreply {
  162:     my ($cmd,$server)=@_;
  163:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  164:     #
  165:     #  With loncnew process trimming, there's a timing hole between lonc server
  166:     #  process exit and the master server picking up the listen on the AF_UNIX
  167:     #  socket.  In that time interval, a lock file will exist:
  168: 
  169:     my $lockfile=$peerfile.".lock";
  170:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  171: 	sleep(1);
  172:     }
  173:     # At this point, either a loncnew parent is listening or an old lonc
  174:     # or loncnew child is listening so we can connect or everything's dead.
  175:     #
  176:     #   We'll give the connection a few tries before abandoning it.  If
  177:     #   connection is not possible, we'll con_lost back to the client.
  178:     #   
  179:     my $client;
  180:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  181: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  182: 				      Type    => SOCK_STREAM,
  183: 				      Timeout => 10);
  184: 	if ($client) {
  185: 	    last;		# Connected!
  186: 	} else {
  187: 	    &create_connection(&hostname($server),$server);
  188: 	}
  189:         sleep(1);		# Try again later if failed connection.
  190:     }
  191:     my $answer;
  192:     if ($client) {
  193: 	print $client "sethost:$server:$cmd\n";
  194: 	$answer=<$client>;
  195: 	if (!$answer) { $answer="con_lost"; }
  196: 	chomp($answer);
  197:     } else {
  198: 	$answer = 'con_lost';	# Failed connection.
  199:     }
  200:     return $answer;
  201: }
  202: 
  203: sub reply {
  204:     my ($cmd,$server)=@_;
  205:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  206:     my $answer=subreply($cmd,$server);
  207:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  208:        &logthis("<font color=\"blue\">WARNING:".
  209:                 " $cmd to $server returned $answer</font>");
  210:     }
  211:     return $answer;
  212: }
  213: 
  214: # ----------------------------------------------------------- Send USR1 to lonc
  215: 
  216: sub reconlonc {
  217:     my ($lonid) = @_;
  218:     my $hostname = &hostname($lonid);
  219:     if ($lonid) {
  220: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  221: 	if ($hostname && -e $peerfile) {
  222: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  223: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  224: 					     Type    => SOCK_STREAM,
  225: 					     Timeout => 10);
  226: 	    if ($client) {
  227: 		print $client ("reset_retries\n");
  228: 		my $answer=<$client>;
  229: 		#reset just this one.
  230: 	    }
  231: 	}
  232: 	return;
  233:     }
  234: 
  235:     &logthis("Trying to reconnect lonc");
  236:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  237:     if (open(my $fh,"<$loncfile")) {
  238: 	my $loncpid=<$fh>;
  239:         chomp($loncpid);
  240:         if (kill 0 => $loncpid) {
  241: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  242:             kill USR1 => $loncpid;
  243:             sleep 1;
  244:          } else {
  245: 	    &logthis(
  246:                "<font color=\"blue\">WARNING:".
  247:                " lonc at pid $loncpid not responding, giving up</font>");
  248:         }
  249:     } else {
  250: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  251:     }
  252: }
  253: 
  254: # ------------------------------------------------------ Critical communication
  255: 
  256: sub critical {
  257:     my ($cmd,$server)=@_;
  258:     unless (&hostname($server)) {
  259:         &logthis("<font color=\"blue\">WARNING:".
  260:                " Critical message to unknown server ($server)</font>");
  261:         return 'no_such_host';
  262:     }
  263:     my $answer=reply($cmd,$server);
  264:     if ($answer eq 'con_lost') {
  265: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  266: 	my $answer=reply($cmd,$server);
  267:         if ($answer eq 'con_lost') {
  268:             my $now=time;
  269:             my $middlename=$cmd;
  270:             $middlename=substr($middlename,0,16);
  271:             $middlename=~s/\W//g;
  272:             my $dfilename=
  273:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  274:             $dumpcount++;
  275:             {
  276: 		my $dfh;
  277: 		if (open($dfh,">$dfilename")) {
  278: 		    print $dfh "$cmd\n"; 
  279: 		    close($dfh);
  280: 		}
  281:             }
  282:             sleep 2;
  283:             my $wcmd='';
  284:             {
  285: 		my $dfh;
  286: 		if (open($dfh,"<$dfilename")) {
  287: 		    $wcmd=<$dfh>; 
  288: 		    close($dfh);
  289: 		}
  290:             }
  291:             chomp($wcmd);
  292:             if ($wcmd eq $cmd) {
  293: 		&logthis("<font color=\"blue\">WARNING: ".
  294:                          "Connection buffer $dfilename: $cmd</font>");
  295:                 &logperm("D:$server:$cmd");
  296: 	        return 'con_delayed';
  297:             } else {
  298:                 &logthis("<font color=\"red\">CRITICAL:"
  299:                         ." Critical connection failed: $server $cmd</font>");
  300:                 &logperm("F:$server:$cmd");
  301:                 return 'con_failed';
  302:             }
  303:         }
  304:     }
  305:     return $answer;
  306: }
  307: 
  308: # ------------------------------------------- check if return value is an error
  309: 
  310: sub error {
  311:     my ($result) = @_;
  312:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  313: 	if ($2 == 2) { return undef; }
  314: 	return $1;
  315:     }
  316:     return undef;
  317: }
  318: 
  319: sub convert_and_load_session_env {
  320:     my ($lonidsdir,$handle)=@_;
  321:     my @profile;
  322:     {
  323: 	open(my $idf,"$lonidsdir/$handle.id");
  324: 	flock($idf,LOCK_SH);
  325: 	@profile=<$idf>;
  326: 	close($idf);
  327:     }
  328:     my %temp_env;
  329:     foreach my $line (@profile) {
  330: 	if ($line !~ m/=/) {
  331: 	    return 0;
  332: 	}
  333: 	chomp($line);
  334: 	my ($envname,$envvalue)=split(/=/,$line,2);
  335: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  336:     }
  337:     unlink("$lonidsdir/$handle.id");
  338:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  339: 	    0640)) {
  340: 	%disk_env = %temp_env;
  341: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  342: 	untie(%disk_env);
  343:     }
  344:     return 1;
  345: }
  346: 
  347: # ------------------------------------------- Transfer profile into environment
  348: my $env_loaded;
  349: sub transfer_profile_to_env {
  350:     my ($lonidsdir,$handle,$force_transfer) = @_;
  351:     if (!$force_transfer && $env_loaded) { return; } 
  352: 
  353:     if (!defined($lonidsdir)) {
  354: 	$lonidsdir = $perlvar{'lonIDsDir'};
  355:     }
  356:     if (!defined($handle)) {
  357:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  358:     }
  359: 
  360:     my $convert;
  361:     {
  362:     	open(my $idf,"$lonidsdir/$handle.id");
  363: 	flock($idf,LOCK_SH);
  364: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  365: 		&GDBM_READER(),0640)) {
  366: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  367: 	    untie(%disk_env);
  368: 	} else {
  369: 	    $convert = 1;
  370: 	}
  371:     }
  372:     if ($convert) {
  373: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  374: 	    &logthis("Failed to load session, or convert session.");
  375: 	}
  376:     }
  377: 
  378:     my %remove;
  379:     while ( my $envname = each(%env) ) {
  380:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  381:             if ($time < time-300) {
  382:                 $remove{$key}++;
  383:             }
  384:         }
  385:     }
  386: 
  387:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  388:     $env_loaded=1;
  389:     foreach my $expired_key (keys(%remove)) {
  390:         &delenv($expired_key);
  391:     }
  392: }
  393: 
  394: sub timed_flock {
  395:     my ($file,$lock_type) = @_;
  396:     my $failed=0;
  397:     eval {
  398: 	local $SIG{__DIE__}='DEFAULT';
  399: 	local $SIG{ALRM}=sub {
  400: 	    $failed=1;
  401: 	    die("failed lock");
  402: 	};
  403: 	alarm(13);
  404: 	flock($file,$lock_type);
  405: 	alarm(0);
  406:     };
  407:     if ($failed) {
  408: 	return undef;
  409:     } else {
  410: 	return 1;
  411:     }
  412: }
  413: 
  414: # ---------------------------------------------------------- Append Environment
  415: 
  416: sub appenv {
  417:     my %newenv=@_;
  418:     foreach my $key (keys(%newenv)) {
  419: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  420:             &logthis("<font color=\"blue\">WARNING: ".
  421:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  422:                 .'</font>');
  423: 	    delete($newenv{$key});
  424:         } else {
  425:             $env{$key}=$newenv{$key};
  426:         }
  427:     }
  428:     open(my $env_file,$env{'user.environment'});
  429:     if (&timed_flock($env_file,LOCK_EX)
  430: 	&&
  431: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  432: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  433: 	while (my ($key,$value) = each(%newenv)) {
  434: 	    $disk_env{$key} = $value;
  435: 	}
  436: 	untie(%disk_env);
  437:     }
  438:     return 'ok';
  439: }
  440: # ----------------------------------------------------- Delete from Environment
  441: 
  442: sub delenv {
  443:     my $delthis=shift;
  444:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  445:         &logthis("<font color=\"blue\">WARNING: ".
  446:                 "Attempt to delete from environment ".$delthis);
  447:         return 'error';
  448:     }
  449:     open(my $env_file,$env{'user.environment'});
  450:     if (&timed_flock($env_file,LOCK_EX)
  451: 	&&
  452: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  453: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  454: 	foreach my $key (keys(%disk_env)) {
  455: 	    if ($key=~/^$delthis/) { 
  456:                 delete($env{$key});
  457:                 delete($disk_env{$key});
  458:             }
  459: 	}
  460: 	untie(%disk_env);
  461:     }
  462:     return 'ok';
  463: }
  464: 
  465: sub get_env_multiple {
  466:     my ($name) = @_;
  467:     my @values;
  468:     if (defined($env{$name})) {
  469:         # exists is it an array
  470:         if (ref($env{$name})) {
  471:             @values=@{ $env{$name} };
  472:         } else {
  473:             $values[0]=$env{$name};
  474:         }
  475:     }
  476:     return(@values);
  477: }
  478: 
  479: # ------------------------------------------ Find out current server userload
  480: # there is a copy in lond
  481: sub userload {
  482:     my $numusers=0;
  483:     {
  484: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  485: 	my $filename;
  486: 	my $curtime=time;
  487: 	while ($filename=readdir(LONIDS)) {
  488: 	    if ($filename eq '.' || $filename eq '..') {next;}
  489: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  490: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  491: 	}
  492: 	closedir(LONIDS);
  493:     }
  494:     my $userloadpercent=0;
  495:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  496:     if ($maxuserload) {
  497: 	$userloadpercent=100*$numusers/$maxuserload;
  498:     }
  499:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  500:     return $userloadpercent;
  501: }
  502: 
  503: # ------------------------------------------ Fight off request when overloaded
  504: 
  505: sub overloaderror {
  506:     my ($r,$checkserver)=@_;
  507:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  508:     my $loadavg;
  509:     if ($checkserver eq $perlvar{'lonHostID'}) {
  510:        open(my $loadfile,'/proc/loadavg');
  511:        $loadavg=<$loadfile>;
  512:        $loadavg =~ s/\s.*//g;
  513:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  514:        close($loadfile);
  515:     } else {
  516:        $loadavg=&reply('load',$checkserver);
  517:     }
  518:     my $overload=$loadavg-100;
  519:     if ($overload>0) {
  520: 	$r->err_headers_out->{'Retry-After'}=$overload;
  521:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  522:         return 413;
  523:     }    
  524:     return '';
  525: }
  526: 
  527: # ------------------------------ Find server with least workload from spare.tab
  528: 
  529: sub spareserver {
  530:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  531:     my $spare_server;
  532:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  533:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  534:                                                      :  $userloadpercent;
  535:     
  536:     foreach my $try_server (@{ $spareid{'primary'} }) {
  537: 	($spare_server, $lowest_load) =
  538: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  539:     }
  540: 
  541:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  542: 
  543:     if (!$found_server) {
  544: 	foreach my $try_server (@{ $spareid{'default'} }) {
  545: 	    ($spare_server, $lowest_load) =
  546: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  547: 	}
  548:     }
  549: 
  550:     if (!$want_server_name) {
  551: 	$spare_server="http://".&hostname($spare_server);
  552:     }
  553:     return $spare_server;
  554: }
  555: 
  556: sub compare_server_load {
  557:     my ($try_server, $spare_server, $lowest_load) = @_;
  558: 
  559:     my $loadans     = &reply('load',    $try_server);
  560:     my $userloadans = &reply('userload',$try_server);
  561: 
  562:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  563: 	next; #didn't get a number from the server
  564:     }
  565: 
  566:     my $load;
  567:     if ($loadans =~ /\d/) {
  568: 	if ($userloadans =~ /\d/) {
  569: 	    #both are numbers, pick the bigger one
  570: 	    $load = ($loadans > $userloadans) ? $loadans 
  571: 		                              : $userloadans;
  572: 	} else {
  573: 	    $load = $loadans;
  574: 	}
  575:     } else {
  576: 	$load = $userloadans;
  577:     }
  578: 
  579:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  580: 	$spare_server = $try_server;
  581: 	$lowest_load  = $load;
  582:     }
  583:     return ($spare_server,$lowest_load);
  584: }
  585: # --------------------------------------------- Try to change a user's password
  586: 
  587: sub changepass {
  588:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  589:     $currentpass = &escape($currentpass);
  590:     $newpass     = &escape($newpass);
  591:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  592: 		       $server);
  593:     if (! $answer) {
  594: 	&logthis("No reply on password change request to $server ".
  595: 		 "by $uname in domain $udom.");
  596:     } elsif ($answer =~ "^ok") {
  597:         &logthis("$uname in $udom successfully changed their password ".
  598: 		 "on $server.");
  599:     } elsif ($answer =~ "^pwchange_failure") {
  600: 	&logthis("$uname in $udom was unable to change their password ".
  601: 		 "on $server.  The action was blocked by either lcpasswd ".
  602: 		 "or pwchange");
  603:     } elsif ($answer =~ "^non_authorized") {
  604:         &logthis("$uname in $udom did not get their password correct when ".
  605: 		 "attempting to change it on $server.");
  606:     } elsif ($answer =~ "^auth_mode_error") {
  607:         &logthis("$uname in $udom attempted to change their password despite ".
  608: 		 "not being locally or internally authenticated on $server.");
  609:     } elsif ($answer =~ "^unknown_user") {
  610:         &logthis("$uname in $udom attempted to change their password ".
  611: 		 "on $server but were unable to because $server is not ".
  612: 		 "their home server.");
  613:     } elsif ($answer =~ "^refused") {
  614: 	&logthis("$server refused to change $uname in $udom password because ".
  615: 		 "it was sent an unencrypted request to change the password.");
  616:     }
  617:     return $answer;
  618: }
  619: 
  620: # ----------------------- Try to determine user's current authentication scheme
  621: 
  622: sub queryauthenticate {
  623:     my ($uname,$udom)=@_;
  624:     my $uhome=&homeserver($uname,$udom);
  625:     if (!$uhome) {
  626: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  627: 	return 'no_host';
  628:     }
  629:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  630:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  631: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  632:     }
  633:     return $answer;
  634: }
  635: 
  636: # --------- Try to authenticate user from domain's lib servers (first this one)
  637: 
  638: sub authenticate {
  639:     my ($uname,$upass,$udom)=@_;
  640:     $upass=&escape($upass);
  641:     $uname= &LONCAPA::clean_username($uname);
  642:     my $uhome=&homeserver($uname,$udom,1);
  643:     if ((!$uhome) || ($uhome eq 'no_host')) {
  644: # Maybe the machine was offline and only re-appeared again recently?
  645:         &reconlonc();
  646: # One more
  647: 	my $uhome=&homeserver($uname,$udom,1);
  648: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  649: 	    &logthis("User $uname at $udom is unknown in authenticate");
  650: 	}
  651: 	return 'no_host';
  652:     }
  653:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  654:     if ($answer eq 'authorized') {
  655: 	&logthis("User $uname at $udom authorized by $uhome"); 
  656: 	return $uhome; 
  657:     }
  658:     if ($answer eq 'non_authorized') {
  659: 	&logthis("User $uname at $udom rejected by $uhome");
  660: 	return 'no_host'; 
  661:     }
  662:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  663:     return 'no_host';
  664: }
  665: 
  666: # ---------------------- Find the homebase for a user from domain's lib servers
  667: 
  668: my %homecache;
  669: sub homeserver {
  670:     my ($uname,$udom,$ignoreBadCache)=@_;
  671:     my $index="$uname:$udom";
  672: 
  673:     if (exists($homecache{$index})) { return $homecache{$index}; }
  674: 
  675:     my %servers = &get_servers($udom,'library');
  676:     foreach my $tryserver (keys(%servers)) {
  677:         next if ($ignoreBadCache ne 'true' && 
  678: 		 exists($badServerCache{$tryserver}));
  679: 
  680: 	my $answer=reply("home:$udom:$uname",$tryserver);
  681: 	if ($answer eq 'found') {
  682: 	    delete($badServerCache{$tryserver}); 
  683: 	    return $homecache{$index}=$tryserver;
  684: 	} elsif ($answer eq 'no_host') {
  685: 	    $badServerCache{$tryserver}=1;
  686: 	}
  687:     }    
  688:     return 'no_host';
  689: }
  690: 
  691: # ------------------------------------- Find the usernames behind a list of IDs
  692: 
  693: sub idget {
  694:     my ($udom,@ids)=@_;
  695:     my %returnhash=();
  696:     
  697:     my %servers = &get_servers($udom,'library');
  698:     foreach my $tryserver (keys(%servers)) {
  699: 	my $idlist=join('&',@ids);
  700: 	$idlist=~tr/A-Z/a-z/; 
  701: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  702: 	my @answer=();
  703: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  704: 	    @answer=split(/\&/,$reply);
  705: 	}                    ;
  706: 	my $i;
  707: 	for ($i=0;$i<=$#ids;$i++) {
  708: 	    if ($answer[$i]) {
  709: 		$returnhash{$ids[$i]}=$answer[$i];
  710: 	    } 
  711: 	}
  712:     } 
  713:     return %returnhash;
  714: }
  715: 
  716: # ------------------------------------- Find the IDs behind a list of usernames
  717: 
  718: sub idrget {
  719:     my ($udom,@unames)=@_;
  720:     my %returnhash=();
  721:     foreach my $uname (@unames) {
  722:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  723:     }
  724:     return %returnhash;
  725: }
  726: 
  727: # ------------------------------- Store away a list of names and associated IDs
  728: 
  729: sub idput {
  730:     my ($udom,%ids)=@_;
  731:     my %servers=();
  732:     foreach my $uname (keys(%ids)) {
  733: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  734:         my $uhom=&homeserver($uname,$udom);
  735:         if ($uhom ne 'no_host') {
  736:             my $id=&escape($ids{$uname});
  737:             $id=~tr/A-Z/a-z/;
  738:             my $esc_unam=&escape($uname);
  739: 	    if ($servers{$uhom}) {
  740: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  741:             } else {
  742:                 $servers{$uhom}=$id.'='.$esc_unam;
  743:             }
  744:         }
  745:     }
  746:     foreach my $server (keys(%servers)) {
  747:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  748:     }
  749: }
  750: 
  751: # ------------------------------------------- get items from domain db files   
  752: 
  753: sub get_dom {
  754:     my ($namespace,$storearr,$udom,$uhome)=@_;
  755:     my $items='';
  756:     foreach my $item (@$storearr) {
  757:         $items.=&escape($item).'&';
  758:     }
  759:     $items=~s/\&$//;
  760:     if (!$udom) {
  761:         $udom=$env{'user.domain'};
  762:         if (defined(&domain($udom,'primary'))) {
  763:             $uhome=&domain($udom,'primary');
  764:         } else {
  765:             undef($uhome);
  766:         }
  767:     } else {
  768:         if (!$uhome) {
  769:             if (defined(&domain($udom,'primary'))) {
  770:                 $uhome=&domain($udom,'primary');
  771:             }
  772:         }
  773:     }
  774:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  775:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  776:         my %returnhash;
  777:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  778:             return %returnhash;
  779:         }
  780:         my @pairs=split(/\&/,$rep);
  781:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  782:             return @pairs;
  783:         }
  784:         my $i=0;
  785:         foreach my $item (@$storearr) {
  786:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  787:             $i++;
  788:         }
  789:         return %returnhash;
  790:     } else {
  791:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  792:     }
  793: }
  794: 
  795: # -------------------------------------------- put items in domain db files 
  796: 
  797: sub put_dom {
  798:     my ($namespace,$storehash,$udom,$uhome)=@_;
  799:     if (!$udom) {
  800:         $udom=$env{'user.domain'};
  801:         if (defined(&domain($udom,'primary'))) {
  802:             $uhome=&domain($udom,'primary');
  803:         } else {
  804:             undef($uhome);
  805:         }
  806:     } else {
  807:         if (!$uhome) {
  808:             if (defined(&domain($udom,'primary'))) {
  809:                 $uhome=&domain($udom,'primary');
  810:             }
  811:         }
  812:     } 
  813:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  814:         my $items='';
  815:         foreach my $item (keys(%$storehash)) {
  816:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  817:         }
  818:         $items=~s/\&$//;
  819:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  820:     } else {
  821:         &logthis("put_dom failed - no homeserver and/or domain");
  822:     }
  823: }
  824: 
  825: sub retrieve_inst_usertypes {
  826:     my ($udom) = @_;
  827:     my (%returnhash,@order);
  828:     if (defined(&domain($udom,'primary'))) {
  829:         my $uhome=&domain($udom,'primary');
  830:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  831:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  832:         my @pairs=split(/\&/,$hashitems);
  833:         foreach my $item (@pairs) {
  834:             my ($key,$value)=split(/=/,$item,2);
  835:             $key = &unescape($key);
  836:             next if ($key =~ /^error: 2 /);
  837:             $returnhash{$key}=&thaw_unescape($value);
  838:         }
  839:         my @esc_order = split(/\&/,$orderitems);
  840:         foreach my $item (@esc_order) {
  841:             push(@order,&unescape($item));
  842:         }
  843:     } else {
  844:         &logthis("get_dom failed - no primary domain server for $udom");
  845:     }
  846:     return (\%returnhash,\@order);
  847: }
  848: 
  849: sub is_domainimage {
  850:     my ($url) = @_;
  851:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
  852:         if (&domain($1) ne '') {
  853:             return '1';
  854:         }
  855:     }
  856:     return;
  857: }
  858: 
  859: # --------------------------------------------------- Assign a key to a student
  860: 
  861: sub assign_access_key {
  862: #
  863: # a valid key looks like uname:udom#comments
  864: # comments are being appended
  865: #
  866:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
  867:     $kdom=
  868:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
  869:     $knum=
  870:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
  871:     $cdom=
  872:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  873:     $cnum=
  874:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  875:     $udom=$env{'user.name'} unless (defined($udom));
  876:     $uname=$env{'user.domain'} unless (defined($uname));
  877:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
  878:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
  879:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
  880:                                                   # assigned to this person
  881:                                                   # - this should not happen,
  882:                                                   # unless something went wrong
  883:                                                   # the first time around
  884: # ready to assign
  885:         $logentry=$1.'; '.$logentry;
  886:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
  887:                                                  $kdom,$knum) eq 'ok') {
  888: # key now belongs to user
  889: 	    my $envkey='key.'.$cdom.'_'.$cnum;
  890:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
  891:                 &appenv('environment.'.$envkey => $ckey);
  892:                 return 'ok';
  893:             } else {
  894:                 return 
  895:   'error: Count not permanently assign key, will need to be re-entered later.';
  896: 	    }
  897:         } else {
  898:             return 'error: Could not assign key, try again later.';
  899:         }
  900:     } elsif (!$existing{$ckey}) {
  901: # the key does not exist
  902: 	return 'error: The key does not exist';
  903:     } else {
  904: # the key is somebody else's
  905: 	return 'error: The key is already in use';
  906:     }
  907: }
  908: 
  909: # ------------------------------------------ put an additional comment on a key
  910: 
  911: sub comment_access_key {
  912: #
  913: # a valid key looks like uname:udom#comments
  914: # comments are being appended
  915: #
  916:     my ($ckey,$cdom,$cnum,$logentry)=@_;
  917:     $cdom=
  918:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  919:     $cnum=
  920:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  921:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  922:     if ($existing{$ckey}) {
  923:         $existing{$ckey}.='; '.$logentry;
  924: # ready to assign
  925:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
  926:                                                  $cdom,$cnum) eq 'ok') {
  927: 	    return 'ok';
  928:         } else {
  929: 	    return 'error: Count not store comment.';
  930:         }
  931:     } else {
  932: # the key does not exist
  933: 	return 'error: The key does not exist';
  934:     }
  935: }
  936: 
  937: # ------------------------------------------------------ Generate a set of keys
  938: 
  939: sub generate_access_keys {
  940:     my ($number,$cdom,$cnum,$logentry)=@_;
  941:     $cdom=
  942:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  943:     $cnum=
  944:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  945:     unless (&allowed('mky',$cdom)) { return 0; }
  946:     unless (($cdom) && ($cnum)) { return 0; }
  947:     if ($number>10000) { return 0; }
  948:     sleep(2); # make sure don't get same seed twice
  949:     srand(time()^($$+($$<<15))); # from "Programming Perl"
  950:     my $total=0;
  951:     for (my $i=1;$i<=$number;$i++) {
  952:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
  953:                   sprintf("%lx",int(100000*rand)).'-'.
  954:                   sprintf("%lx",int(100000*rand));
  955:        $newkey=~s/1/g/g; # folks mix up 1 and l
  956:        $newkey=~s/0/h/g; # and also 0 and O
  957:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
  958:        if ($existing{$newkey}) {
  959:            $i--;
  960:        } else {
  961: 	  if (&put('accesskeys',
  962:               { $newkey => '# generated '.localtime().
  963:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
  964:                            '; '.$logentry },
  965: 		   $cdom,$cnum) eq 'ok') {
  966:               $total++;
  967: 	  }
  968:        }
  969:     }
  970:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
  971:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
  972:     return $total;
  973: }
  974: 
  975: # ------------------------------------------------------- Validate an accesskey
  976: 
  977: sub validate_access_key {
  978:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
  979:     $cdom=
  980:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
  981:     $cnum=
  982:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
  983:     $udom=$env{'user.domain'} unless (defined($udom));
  984:     $uname=$env{'user.name'} unless (defined($uname));
  985:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
  986:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
  987: }
  988: 
  989: # ------------------------------------- Find the section of student in a course
  990: sub devalidate_getsection_cache {
  991:     my ($udom,$unam,$courseid)=@_;
  992:     my $hashid="$udom:$unam:$courseid";
  993:     &devalidate_cache_new('getsection',$hashid);
  994: }
  995: 
  996: sub courseid_to_courseurl {
  997:     my ($courseid) = @_;
  998:     #already url style courseid
  999:     return $courseid if ($courseid =~ m{^/});
 1000: 
 1001:     if (exists($env{'course.'.$courseid.'.num'})) {
 1002: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1003: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1004: 	return "/$cdom/$cnum";
 1005:     }
 1006: 
 1007:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1008:     if (exists($courseinfo{'num'})) {
 1009: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1010:     }
 1011: 
 1012:     return undef;
 1013: }
 1014: 
 1015: sub getsection {
 1016:     my ($udom,$unam,$courseid)=@_;
 1017:     my $cachetime=1800;
 1018: 
 1019:     my $hashid="$udom:$unam:$courseid";
 1020:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1021:     if (defined($cached)) { return $result; }
 1022: 
 1023:     my %Pending; 
 1024:     my %Expired;
 1025:     #
 1026:     # Each role can either have not started yet (pending), be active, 
 1027:     #    or have expired.
 1028:     #
 1029:     # If there is an active role, we are done.
 1030:     #
 1031:     # If there is more than one role which has not started yet, 
 1032:     #     choose the one which will start sooner
 1033:     # If there is one role which has not started yet, return it.
 1034:     #
 1035:     # If there is more than one expired role, choose the one which ended last.
 1036:     # If there is a role which has expired, return it.
 1037:     #
 1038:     $courseid = &courseid_to_courseurl($courseid);
 1039:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1040:     foreach my $key (keys(%roleshash)) {
 1041:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1042:         my $section=$1;
 1043:         if ($key eq $courseid.'_st') { $section=''; }
 1044:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1045:         my $now=time;
 1046:         if (defined($end) && $end && ($now > $end)) {
 1047:             $Expired{$end}=$section;
 1048:             next;
 1049:         }
 1050:         if (defined($start) && $start && ($now < $start)) {
 1051:             $Pending{$start}=$section;
 1052:             next;
 1053:         }
 1054:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1055:     }
 1056:     #
 1057:     # Presumedly there will be few matching roles from the above
 1058:     # loop and the sorting time will be negligible.
 1059:     if (scalar(keys(%Pending))) {
 1060:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1061:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1062:     } 
 1063:     if (scalar(keys(%Expired))) {
 1064:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1065:         my $time = pop(@sorted);
 1066:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1067:     }
 1068:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1069: }
 1070: 
 1071: sub save_cache {
 1072:     &purge_remembered();
 1073:     #&Apache::loncommon::validate_page();
 1074:     undef(%env);
 1075:     undef($env_loaded);
 1076: }
 1077: 
 1078: my $to_remember=-1;
 1079: my %remembered;
 1080: my %accessed;
 1081: my $kicks=0;
 1082: my $hits=0;
 1083: sub make_key {
 1084:     my ($name,$id) = @_;
 1085:     if (length($id) > 65 
 1086: 	&& length(&escape($id)) > 200) {
 1087: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1088:     }
 1089:     return &escape($name.':'.$id);
 1090: }
 1091: 
 1092: sub devalidate_cache_new {
 1093:     my ($name,$id,$debug) = @_;
 1094:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1095:     $id=&make_key($name,$id);
 1096:     $memcache->delete($id);
 1097:     delete($remembered{$id});
 1098:     delete($accessed{$id});
 1099: }
 1100: 
 1101: sub is_cached_new {
 1102:     my ($name,$id,$debug) = @_;
 1103:     $id=&make_key($name,$id);
 1104:     if (exists($remembered{$id})) {
 1105: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1106: 	$accessed{$id}=[&gettimeofday()];
 1107: 	$hits++;
 1108: 	return ($remembered{$id},1);
 1109:     }
 1110:     my $value = $memcache->get($id);
 1111:     if (!(defined($value))) {
 1112: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1113: 	return (undef,undef);
 1114:     }
 1115:     if ($value eq '__undef__') {
 1116: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1117: 	$value=undef;
 1118:     }
 1119:     &make_room($id,$value,$debug);
 1120:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1121:     return ($value,1);
 1122: }
 1123: 
 1124: sub do_cache_new {
 1125:     my ($name,$id,$value,$time,$debug) = @_;
 1126:     $id=&make_key($name,$id);
 1127:     my $setvalue=$value;
 1128:     if (!defined($setvalue)) {
 1129: 	$setvalue='__undef__';
 1130:     }
 1131:     if (!defined($time) ) {
 1132: 	$time=600;
 1133:     }
 1134:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1135:     if (!($memcache->set($id,$setvalue,$time))) {
 1136: 	&logthis("caching of id -> $id  failed");
 1137:     }
 1138:     # need to make a copy of $value
 1139:     #&make_room($id,$value,$debug);
 1140:     return $value;
 1141: }
 1142: 
 1143: sub make_room {
 1144:     my ($id,$value,$debug)=@_;
 1145:     $remembered{$id}=$value;
 1146:     if ($to_remember<0) { return; }
 1147:     $accessed{$id}=[&gettimeofday()];
 1148:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1149:     my $to_kick;
 1150:     my $max_time=0;
 1151:     foreach my $other (keys(%accessed)) {
 1152: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1153: 	    $to_kick=$other;
 1154: 	    $max_time=&tv_interval($accessed{$other});
 1155: 	}
 1156:     }
 1157:     delete($remembered{$to_kick});
 1158:     delete($accessed{$to_kick});
 1159:     $kicks++;
 1160:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1161:     return;
 1162: }
 1163: 
 1164: sub purge_remembered {
 1165:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1166:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1167:     undef(%remembered);
 1168:     undef(%accessed);
 1169: }
 1170: # ------------------------------------- Read an entry from a user's environment
 1171: 
 1172: sub userenvironment {
 1173:     my ($udom,$unam,@what)=@_;
 1174:     my %returnhash=();
 1175:     my @answer=split(/\&/,
 1176:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1177:                       &homeserver($unam,$udom)));
 1178:     my $i;
 1179:     for ($i=0;$i<=$#what;$i++) {
 1180: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1181:     }
 1182:     return %returnhash;
 1183: }
 1184: 
 1185: # ---------------------------------------------------------- Get a studentphoto
 1186: sub studentphoto {
 1187:     my ($udom,$unam,$ext) = @_;
 1188:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1189:     if (defined($env{'request.course.id'})) {
 1190:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1191:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1192:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1193:             } else {
 1194:                 my ($result,$perm_reqd)=
 1195: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1196:                 if ($result eq 'ok') {
 1197:                     if (!($perm_reqd eq 'yes')) {
 1198:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1199:                     }
 1200:                 }
 1201:             }
 1202:         }
 1203:     } else {
 1204:         my ($result,$perm_reqd) = 
 1205: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1206:         if ($result eq 'ok') {
 1207:             if (!($perm_reqd eq 'yes')) {
 1208:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1209:             }
 1210:         }
 1211:     }
 1212:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1213: }
 1214: 
 1215: sub retrievestudentphoto {
 1216:     my ($udom,$unam,$ext,$type) = @_;
 1217:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1218:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1219:     if ($ret eq 'ok') {
 1220:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1221:         if ($type eq 'thumbnail') {
 1222:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1223:         }
 1224:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1225:         return $tokenurl;
 1226:     } else {
 1227:         if ($type eq 'thumbnail') {
 1228:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1229:         } else { 
 1230:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1231:         }
 1232:     }
 1233: }
 1234: 
 1235: # -------------------------------------------------------------------- New chat
 1236: 
 1237: sub chatsend {
 1238:     my ($newentry,$anon,$group)=@_;
 1239:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1240:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1241:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1242:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1243: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1244: 		   &escape($newentry)).':'.$group,$chome);
 1245: }
 1246: 
 1247: # ------------------------------------------ Find current version of a resource
 1248: 
 1249: sub getversion {
 1250:     my $fname=&clutter(shift);
 1251:     unless ($fname=~/^\/res\//) { return -1; }
 1252:     return &currentversion(&filelocation('',$fname));
 1253: }
 1254: 
 1255: sub currentversion {
 1256:     my $fname=shift;
 1257:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1258:     if (defined($cached)) { return $result; }
 1259:     my $author=$fname;
 1260:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1261:     my ($udom,$uname)=split(/\//,$author);
 1262:     my $home=homeserver($uname,$udom);
 1263:     if ($home eq 'no_host') { 
 1264:         return -1; 
 1265:     }
 1266:     my $answer=reply("currentversion:$fname",$home);
 1267:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1268: 	return -1;
 1269:     }
 1270:     return &do_cache_new('resversion',$fname,$answer,600);
 1271: }
 1272: 
 1273: # ----------------------------- Subscribe to a resource, return URL if possible
 1274: 
 1275: sub subscribe {
 1276:     my $fname=shift;
 1277:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1278:     $fname=~s/[\n\r]//g;
 1279:     my $author=$fname;
 1280:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1281:     my ($udom,$uname)=split(/\//,$author);
 1282:     my $home=homeserver($uname,$udom);
 1283:     if ($home eq 'no_host') {
 1284:         return 'not_found';
 1285:     }
 1286:     my $answer=reply("sub:$fname",$home);
 1287:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1288: 	$answer.=' by '.$home;
 1289:     }
 1290:     return $answer;
 1291: }
 1292:     
 1293: # -------------------------------------------------------------- Replicate file
 1294: 
 1295: sub repcopy {
 1296:     my $filename=shift;
 1297:     $filename=~s/\/+/\//g;
 1298:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1299:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1300:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1301: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1302: 	return &repcopy_userfile($filename);
 1303:     }
 1304:     $filename=~s/[\n\r]//g;
 1305:     my $transname="$filename.in.transfer";
 1306: # FIXME: this should flock
 1307:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1308:     my $remoteurl=subscribe($filename);
 1309:     if ($remoteurl =~ /^con_lost by/) {
 1310: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1311:            return 'unavailable';
 1312:     } elsif ($remoteurl eq 'not_found') {
 1313: 	   #&logthis("Subscribe returned not_found: $filename");
 1314: 	   return 'not_found';
 1315:     } elsif ($remoteurl =~ /^rejected by/) {
 1316: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1317:            return 'forbidden';
 1318:     } elsif ($remoteurl eq 'directory') {
 1319:            return 'ok';
 1320:     } else {
 1321:         my $author=$filename;
 1322:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1323:         my ($udom,$uname)=split(/\//,$author);
 1324:         my $home=homeserver($uname,$udom);
 1325:         unless ($home eq $perlvar{'lonHostID'}) {
 1326:            my @parts=split(/\//,$filename);
 1327:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1328:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1329:                &logthis("Malconfiguration for replication: $filename");
 1330: 	       return 'bad_request';
 1331:            }
 1332:            my $count;
 1333:            for ($count=5;$count<$#parts;$count++) {
 1334:                $path.="/$parts[$count]";
 1335:                if ((-e $path)!=1) {
 1336: 		   mkdir($path,0777);
 1337:                }
 1338:            }
 1339:            my $ua=new LWP::UserAgent;
 1340:            my $request=new HTTP::Request('GET',"$remoteurl");
 1341:            my $response=$ua->request($request,$transname);
 1342:            if ($response->is_error()) {
 1343: 	       unlink($transname);
 1344:                my $message=$response->status_line;
 1345:                &logthis("<font color=\"blue\">WARNING:"
 1346:                        ." LWP get: $message: $filename</font>");
 1347:                return 'unavailable';
 1348:            } else {
 1349: 	       if ($remoteurl!~/\.meta$/) {
 1350:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1351:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1352:                   if ($mresponse->is_error()) {
 1353: 		      unlink($filename.'.meta');
 1354:                       &logthis(
 1355:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1356:                   }
 1357: 	       }
 1358:                rename($transname,$filename);
 1359:                return 'ok';
 1360:            }
 1361:        }
 1362:     }
 1363: }
 1364: 
 1365: # ------------------------------------------------ Get server side include body
 1366: sub ssi_body {
 1367:     my ($filelink,%form)=@_;
 1368:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1369:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1370:     }
 1371:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1372:                                      &ssi($filelink,%form));
 1373:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1374:     $output=~s/^.*?\<body[^\>]*\>//si;
 1375:     $output=~s/(.*)\<\/body\s*\>.*?$/$1/si;
 1376:     return $output;
 1377: }
 1378: 
 1379: # --------------------------------------------------------- Server Side Include
 1380: 
 1381: sub absolute_url {
 1382:     my ($host_name) = @_;
 1383:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1384:     if ($host_name eq '') {
 1385: 	$host_name = $ENV{'SERVER_NAME'};
 1386:     }
 1387:     return $protocol.$host_name;
 1388: }
 1389: 
 1390: sub ssi {
 1391: 
 1392:     my ($fn,%form)=@_;
 1393: 
 1394:     my $ua=new LWP::UserAgent;
 1395:     
 1396:     my $request;
 1397: 
 1398:     $form{'no_update_last_known'}=1;
 1399: 
 1400:     if (%form) {
 1401:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1402:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1403:     } else {
 1404:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1405:     }
 1406: 
 1407:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1408:     my $response=$ua->request($request);
 1409: 
 1410:     return $response->content;
 1411: }
 1412: 
 1413: sub externalssi {
 1414:     my ($url)=@_;
 1415:     my $ua=new LWP::UserAgent;
 1416:     my $request=new HTTP::Request('GET',$url);
 1417:     my $response=$ua->request($request);
 1418:     return $response->content;
 1419: }
 1420: 
 1421: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1422: 
 1423: sub allowuploaded {
 1424:     my ($srcurl,$url)=@_;
 1425:     $url=&clutter(&declutter($url));
 1426:     my $dir=$url;
 1427:     $dir=~s/\/[^\/]+$//;
 1428:     my %httpref=();
 1429:     my $httpurl=&hreflocation('',$url);
 1430:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1431:     &Apache::lonnet::appenv(%httpref);
 1432: }
 1433: 
 1434: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1435: # input: action, courseID, current domain, intended
 1436: #        path to file, source of file, instruction to parse file for objects,
 1437: #        ref to hash for embedded objects,
 1438: #        ref to hash for codebase of java objects.
 1439: #
 1440: # output: url to file (if action was uploaddoc), 
 1441: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1442: #
 1443: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1444: # course.
 1445: #
 1446: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1447: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1448: #          course's home server.
 1449: #
 1450: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1451: #          be copied from $source (current location) to 
 1452: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1453: #         and will then be copied to
 1454: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1455: #         course's home server.
 1456: #
 1457: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1458: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1459: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1460: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1461: #         in course's home server.
 1462: #
 1463: 
 1464: sub process_coursefile {
 1465:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1466:     my $fetchresult;
 1467:     my $home=&homeserver($docuname,$docudom);
 1468:     if ($action eq 'propagate') {
 1469:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1470: 			     $home);
 1471:     } else {
 1472:         my $fpath = '';
 1473:         my $fname = $file;
 1474:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1475:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1476:         my $filepath = &build_filepath($fpath);
 1477:         if ($action eq 'copy') {
 1478:             if ($source eq '') {
 1479:                 $fetchresult = 'no source file';
 1480:                 return $fetchresult;
 1481:             } else {
 1482:                 my $destination = $filepath.'/'.$fname;
 1483:                 rename($source,$destination);
 1484:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1485:                                  $home);
 1486:             }
 1487:         } elsif ($action eq 'uploaddoc') {
 1488:             open(my $fh,'>'.$filepath.'/'.$fname);
 1489:             print $fh $env{'form.'.$source};
 1490:             close($fh);
 1491:             if ($parser eq 'parse') {
 1492:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1493:                 unless ($parse_result eq 'ok') {
 1494:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1495:                 }
 1496:             }
 1497:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1498:                                  $home);
 1499:             if ($fetchresult eq 'ok') {
 1500:                 return '/uploaded/'.$fpath.'/'.$fname;
 1501:             } else {
 1502:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1503:                         ' to host '.$home.': '.$fetchresult);
 1504:                 return '/adm/notfound.html';
 1505:             }
 1506:         }
 1507:     }
 1508:     unless ( $fetchresult eq 'ok') {
 1509:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1510:              ' to host '.$home.': '.$fetchresult);
 1511:     }
 1512:     return $fetchresult;
 1513: }
 1514: 
 1515: sub build_filepath {
 1516:     my ($fpath) = @_;
 1517:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1518:     unless ($fpath eq '') {
 1519:         my @parts=split('/',$fpath);
 1520:         foreach my $part (@parts) {
 1521:             $filepath.= '/'.$part;
 1522:             if ((-e $filepath)!=1) {
 1523:                 mkdir($filepath,0777);
 1524:             }
 1525:         }
 1526:     }
 1527:     return $filepath;
 1528: }
 1529: 
 1530: sub store_edited_file {
 1531:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1532:     my $file = $primary_url;
 1533:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1534:     my $fpath = '';
 1535:     my $fname = $file;
 1536:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1537:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1538:     my $filepath = &build_filepath($fpath);
 1539:     open(my $fh,'>'.$filepath.'/'.$fname);
 1540:     print $fh $content;
 1541:     close($fh);
 1542:     my $home=&homeserver($docuname,$docudom);
 1543:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1544: 			  $home);
 1545:     if ($$fetchresult eq 'ok') {
 1546:         return '/uploaded/'.$fpath.'/'.$fname;
 1547:     } else {
 1548:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1549: 		 ' to host '.$home.': '.$$fetchresult);
 1550:         return '/adm/notfound.html';
 1551:     }
 1552: }
 1553: 
 1554: sub clean_filename {
 1555:     my ($fname,$args)=@_;
 1556: # Replace Windows backslashes by forward slashes
 1557:     $fname=~s/\\/\//g;
 1558:     if (!$args->{'keep_path'}) {
 1559:         # Get rid of everything but the actual filename
 1560: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1561:     }
 1562: # Replace spaces by underscores
 1563:     $fname=~s/\s+/\_/g;
 1564: # Replace all other weird characters by nothing
 1565:     $fname=~s{[^/\w\.\-]}{}g;
 1566: # Replace all .\d. sequences with _\d. so they no longer look like version
 1567: # numbers
 1568:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1569:     return $fname;
 1570: }
 1571: 
 1572: # --------------- Take an uploaded file and put it into the userfiles directory
 1573: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1574: #                    the desired filenam is in $env{"form.$formname.filename"}
 1575: #        $coursedoc - if true up to the current course
 1576: #                     if false
 1577: #        $subdir - directory in userfile to store the file into
 1578: #        $parser - instruction to parse file for objects ($parser = parse)    
 1579: #        $allfiles - reference to hash for embedded objects
 1580: #        $codebase - reference to hash for codebase of java objects
 1581: #        $desuname - username for permanent storage of uploaded file
 1582: #        $dsetudom - domain for permanaent storage of uploaded file
 1583: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1584: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1585: # 
 1586: # output: url of file in userspace, or error: <message> 
 1587: #             or /adm/notfound.html if failure to upload occurse
 1588: 
 1589: 
 1590: sub userfileupload {
 1591:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1592:         $destudom,$thumbwidth,$thumbheight)=@_;
 1593:     if (!defined($subdir)) { $subdir='unknown'; }
 1594:     my $fname=$env{'form.'.$formname.'.filename'};
 1595:     $fname=&clean_filename($fname);
 1596: # See if there is anything left
 1597:     unless ($fname) { return 'error: no uploaded file'; }
 1598:     chop($env{'form.'.$formname});
 1599:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1600:         my $now = time;
 1601:         my $filepath = 'tmp/helprequests/'.$now;
 1602:         my @parts=split(/\//,$filepath);
 1603:         my $fullpath = $perlvar{'lonDaemons'};
 1604:         for (my $i=0;$i<@parts;$i++) {
 1605:             $fullpath .= '/'.$parts[$i];
 1606:             if ((-e $fullpath)!=1) {
 1607:                 mkdir($fullpath,0777);
 1608:             }
 1609:         }
 1610:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1611:         print $fh $env{'form.'.$formname};
 1612:         close($fh);
 1613:         return $fullpath.'/'.$fname;
 1614:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1615:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1616:                        '_'.$env{'user.domain'}.'/pending';
 1617:         my @parts=split(/\//,$filepath);
 1618:         my $fullpath = $perlvar{'lonDaemons'};
 1619:         for (my $i=0;$i<@parts;$i++) {
 1620:             $fullpath .= '/'.$parts[$i];
 1621:             if ((-e $fullpath)!=1) {
 1622:                 mkdir($fullpath,0777);
 1623:             }
 1624:         }
 1625:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1626:         print $fh $env{'form.'.$formname};
 1627:         close($fh);
 1628:         return $fullpath.'/'.$fname;
 1629:     }
 1630:     
 1631: # Create the directory if not present
 1632:     $fname="$subdir/$fname";
 1633:     if ($coursedoc) {
 1634: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1635: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1636:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1637:             return &finishuserfileupload($docuname,$docudom,
 1638: 					 $formname,$fname,$parser,$allfiles,
 1639: 					 $codebase,$thumbwidth,$thumbheight);
 1640:         } else {
 1641:             $fname=$env{'form.folder'}.'/'.$fname;
 1642:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1643: 				       $fname,$formname,$parser,
 1644: 				       $allfiles,$codebase);
 1645:         }
 1646:     } elsif (defined($destuname)) {
 1647:         my $docuname=$destuname;
 1648:         my $docudom=$destudom;
 1649: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1650: 				     $parser,$allfiles,$codebase,
 1651:                                      $thumbwidth,$thumbheight);
 1652:         
 1653:     } else {
 1654:         my $docuname=$env{'user.name'};
 1655:         my $docudom=$env{'user.domain'};
 1656:         if (exists($env{'form.group'})) {
 1657:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1658:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1659:         }
 1660: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1661: 				     $parser,$allfiles,$codebase,
 1662:                                      $thumbwidth,$thumbheight);
 1663:     }
 1664: }
 1665: 
 1666: sub finishuserfileupload {
 1667:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1668:         $thumbwidth,$thumbheight) = @_;
 1669:     my $path=$docudom.'/'.$docuname.'/';
 1670:     my $filepath=$perlvar{'lonDocRoot'};
 1671:     my ($fnamepath,$file,$fetchthumb);
 1672:     $file=$fname;
 1673:     if ($fname=~m|/|) {
 1674:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1675: 	$path.=$fnamepath.'/';
 1676:     }
 1677:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1678:     my $count;
 1679:     for ($count=4;$count<=$#parts;$count++) {
 1680:         $filepath.="/$parts[$count]";
 1681:         if ((-e $filepath)!=1) {
 1682: 	    mkdir($filepath,0777);
 1683:         }
 1684:     }
 1685: # Save the file
 1686:     {
 1687: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1688: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1689: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1690: 	    return '/adm/notfound.html';
 1691: 	}
 1692: 	if (!print FH ($env{'form.'.$formname})) {
 1693: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1694: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1695: 	    return '/adm/notfound.html';
 1696: 	}
 1697: 	close(FH);
 1698:     }
 1699:     if ($parser eq 'parse') {
 1700:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1701: 						   $codebase);
 1702:         unless ($parse_result eq 'ok') {
 1703:             &logthis('Failed to parse '.$filepath.$file.
 1704: 		     ' for embedded media: '.$parse_result); 
 1705:         }
 1706:     }
 1707:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 1708:         my $input = $filepath.'/'.$file;
 1709:         my $output = $filepath.'/'.'tn-'.$file;
 1710:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 1711:         system("convert -sample $thumbsize $input $output");
 1712:         if (-e $filepath.'/'.'tn-'.$file) {
 1713:             $fetchthumb  = 1; 
 1714:         }
 1715:     }
 1716:  
 1717: # Notify homeserver to grep it
 1718: #
 1719:     my $docuhome=&homeserver($docuname,$docudom);
 1720:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 1721:     if ($fetchresult eq 'ok') {
 1722:         if ($fetchthumb) {
 1723:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 1724:             if ($thumbresult ne 'ok') {
 1725:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 1726:                          $docuhome.': '.$thumbresult);
 1727:             }
 1728:         }
 1729: #
 1730: # Return the URL to it
 1731:         return '/uploaded/'.$path.$file;
 1732:     } else {
 1733:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 1734: 		 ': '.$fetchresult);
 1735:         return '/adm/notfound.html';
 1736:     }
 1737: }
 1738: 
 1739: sub extract_embedded_items {
 1740:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 1741:     my @state = ();
 1742:     my %javafiles = (
 1743:                       codebase => '',
 1744:                       code => '',
 1745:                       archive => ''
 1746:                     );
 1747:     my %mediafiles = (
 1748:                       src => '',
 1749:                       movie => '',
 1750:                      );
 1751:     my $p;
 1752:     if ($content) {
 1753:         $p = HTML::LCParser->new($content);
 1754:     } else {
 1755:         $p = HTML::LCParser->new($filepath.'/'.$file);
 1756:     }
 1757:     while (my $t=$p->get_token()) {
 1758: 	if ($t->[0] eq 'S') {
 1759: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 1760: 	    push(@state, $tagname);
 1761:             if (lc($tagname) eq 'allow') {
 1762:                 &add_filetype($allfiles,$attr->{'src'},'src');
 1763:             }
 1764: 	    if (lc($tagname) eq 'img') {
 1765: 		&add_filetype($allfiles,$attr->{'src'},'src');
 1766: 	    }
 1767: 	    if (lc($tagname) eq 'a') {
 1768: 		&add_filetype($allfiles,$attr->{'href'},'href');
 1769: 	    }
 1770:             if (lc($tagname) eq 'script') {
 1771:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 1772:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 1773:                 } else {
 1774:                     &add_filetype($allfiles,$attr->{'src'},'src');
 1775:                 }
 1776:             }
 1777:             if (lc($tagname) eq 'link') {
 1778:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 1779:                     &add_filetype($allfiles,$attr->{'href'},'href');
 1780:                 }
 1781:             }
 1782: 	    if (lc($tagname) eq 'object' ||
 1783: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 1784: 		foreach my $item (keys(%javafiles)) {
 1785: 		    $javafiles{$item} = '';
 1786: 		}
 1787: 	    }
 1788: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 1789: 		my $name = lc($attr->{'name'});
 1790: 		foreach my $item (keys(%javafiles)) {
 1791: 		    if ($name eq $item) {
 1792: 			$javafiles{$item} = $attr->{'value'};
 1793: 			last;
 1794: 		    }
 1795: 		}
 1796: 		foreach my $item (keys(%mediafiles)) {
 1797: 		    if ($name eq $item) {
 1798: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 1799: 			last;
 1800: 		    }
 1801: 		}
 1802: 	    }
 1803: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 1804: 		foreach my $item (keys(%javafiles)) {
 1805: 		    if ($attr->{$item}) {
 1806: 			$javafiles{$item} = $attr->{$item};
 1807: 			last;
 1808: 		    }
 1809: 		}
 1810: 		foreach my $item (keys(%mediafiles)) {
 1811: 		    if ($attr->{$item}) {
 1812: 			&add_filetype($allfiles,$attr->{$item},$item);
 1813: 			last;
 1814: 		    }
 1815: 		}
 1816: 	    }
 1817: 	} elsif ($t->[0] eq 'E') {
 1818: 	    my ($tagname) = ($t->[1]);
 1819: 	    if ($javafiles{'codebase'} ne '') {
 1820: 		$javafiles{'codebase'} .= '/';
 1821: 	    }  
 1822: 	    if (lc($tagname) eq 'applet' ||
 1823: 		lc($tagname) eq 'object' ||
 1824: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 1825: 		) {
 1826: 		foreach my $item (keys(%javafiles)) {
 1827: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 1828: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 1829: 			&add_filetype($allfiles,$file,$item);
 1830: 		    }
 1831: 		}
 1832: 	    } 
 1833: 	    pop @state;
 1834: 	}
 1835:     }
 1836:     return 'ok';
 1837: }
 1838: 
 1839: sub add_filetype {
 1840:     my ($allfiles,$file,$type)=@_;
 1841:     if (exists($allfiles->{$file})) {
 1842: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 1843: 	    push(@{$allfiles->{$file}}, &escape($type));
 1844: 	}
 1845:     } else {
 1846: 	@{$allfiles->{$file}} = (&escape($type));
 1847:     }
 1848: }
 1849: 
 1850: sub removeuploadedurl {
 1851:     my ($url)=@_;
 1852:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 1853:     return &removeuserfile($uname,$udom,$fname);
 1854: }
 1855: 
 1856: sub removeuserfile {
 1857:     my ($docuname,$docudom,$fname)=@_;
 1858:     my $home=&homeserver($docuname,$docudom);
 1859:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 1860:     if ($result eq 'ok') {
 1861:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 1862:             my $metafile = $fname.'.meta';
 1863:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 1864: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 1865:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1866:             my $sqlresult = 
 1867:                 &update_portfolio_table($docuname,$docudom,$file,
 1868:                                         'portfolio_metadata',$group,
 1869:                                         'delete');
 1870:         }
 1871:     }
 1872:     return $result;
 1873: }
 1874: 
 1875: sub mkdiruserfile {
 1876:     my ($docuname,$docudom,$dir)=@_;
 1877:     my $home=&homeserver($docuname,$docudom);
 1878:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 1879: }
 1880: 
 1881: sub renameuserfile {
 1882:     my ($docuname,$docudom,$old,$new)=@_;
 1883:     my $home=&homeserver($docuname,$docudom);
 1884:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 1885:                         &escape("$old").':'.&escape("$new"),$home);
 1886:     if ($result eq 'ok') {
 1887:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 1888:             my $oldmeta = $old.'.meta';
 1889:             my $newmeta = $new.'.meta';
 1890:             my $metaresult = 
 1891:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 1892: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 1893:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 1894:             my $sqlresult = 
 1895:                 &update_portfolio_table($docuname,$docudom,$file,
 1896:                                         'portfolio_metadata',$group,
 1897:                                         'delete');
 1898:         }
 1899:     }
 1900:     return $result;
 1901: }
 1902: 
 1903: # ------------------------------------------------------------------------- Log
 1904: 
 1905: sub log {
 1906:     my ($dom,$nam,$hom,$what)=@_;
 1907:     return critical("log:$dom:$nam:$what",$hom);
 1908: }
 1909: 
 1910: # ------------------------------------------------------------------ Course Log
 1911: #
 1912: # This routine flushes several buffers of non-mission-critical nature
 1913: #
 1914: 
 1915: sub flushcourselogs {
 1916:     &logthis('Flushing log buffers');
 1917: #
 1918: # course logs
 1919: # This is a log of all transactions in a course, which can be used
 1920: # for data mining purposes
 1921: #
 1922: # It also collects the courseid database, which lists last transaction
 1923: # times and course titles for all courseids
 1924: #
 1925:     my %courseidbuffer=();
 1926:     foreach my $crsid (keys %courselogs) {
 1927:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 1928: 		          &escape($courselogs{$crsid}),
 1929: 		          $coursehombuf{$crsid}) eq 'ok') {
 1930: 	    delete $courselogs{$crsid};
 1931:         } else {
 1932:             &logthis('Failed to flush log buffer for '.$crsid);
 1933:             if (length($courselogs{$crsid})>40000) {
 1934:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 1935:                         " exceeded maximum size, deleting.</font>");
 1936:                delete $courselogs{$crsid};
 1937:             }
 1938:         }
 1939:         if ($courseidbuffer{$coursehombuf{$crsid}}) {
 1940:            $courseidbuffer{$coursehombuf{$crsid}}.='&'.
 1941: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1942:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1943:         } else {
 1944:            $courseidbuffer{$coursehombuf{$crsid}}=
 1945: 			 &escape($crsid).'='.&escape($coursedescrbuf{$crsid}).
 1946:                          ':'.&escape($courseinstcodebuf{$crsid}).':'.&escape($courseownerbuf{$crsid}).':'.&escape($coursetypebuf{$crsid});
 1947:         }
 1948:     }
 1949: #
 1950: # Write course id database (reverse lookup) to homeserver of courses 
 1951: # Is used in pickcourse
 1952: #
 1953:     foreach my $crs_home (keys(%courseidbuffer)) {
 1954:         &courseidput(&host_domain($crs_home),$courseidbuffer{$crs_home},
 1955: 		     $crs_home);
 1956:     }
 1957: #
 1958: # File accesses
 1959: # Writes to the dynamic metadata of resources to get hit counts, etc.
 1960: #
 1961:     foreach my $entry (keys(%accesshash)) {
 1962:         if ($entry =~ /___count$/) {
 1963:             my ($dom,$name);
 1964:             ($dom,$name,undef)=
 1965: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 1966:             if (! defined($dom) || $dom eq '' || 
 1967:                 ! defined($name) || $name eq '') {
 1968:                 my $cid = $env{'request.course.id'};
 1969:                 $dom  = $env{'request.'.$cid.'.domain'};
 1970:                 $name = $env{'request.'.$cid.'.num'};
 1971:             }
 1972:             my $value = $accesshash{$entry};
 1973:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 1974:             my %temphash=($url => $value);
 1975:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 1976:             if ($result eq 'ok') {
 1977:                 delete $accesshash{$entry};
 1978:             } elsif ($result eq 'unknown_cmd') {
 1979:                 # Target server has old code running on it.
 1980:                 my %temphash=($entry => $value);
 1981:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1982:                     delete $accesshash{$entry};
 1983:                 }
 1984:             }
 1985:         } else {
 1986:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 1987:             my %temphash=($entry => $accesshash{$entry});
 1988:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 1989:                 delete $accesshash{$entry};
 1990:             }
 1991:         }
 1992:     }
 1993: #
 1994: # Roles
 1995: # Reverse lookup of user roles for course faculty/staff and co-authorship
 1996: #
 1997:     foreach my $entry (keys(%userrolehash)) {
 1998:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 1999: 	    split(/\:/,$entry);
 2000:         if (&Apache::lonnet::put('nohist_userroles',
 2001:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2002:                 $rudom,$runame) eq 'ok') {
 2003: 	    delete $userrolehash{$entry};
 2004:         }
 2005:     }
 2006: #
 2007: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2008: #
 2009:     my %domrolebuffer = ();
 2010:     foreach my $entry (keys %domainrolehash) {
 2011:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split/:/,$entry;
 2012:         if ($domrolebuffer{$rudom}) {
 2013:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2014:                       '='.&escape($domainrolehash{$entry});
 2015:         } else {
 2016:             $domrolebuffer{$rudom}.=&escape($entry).
 2017:                       '='.&escape($domainrolehash{$entry});
 2018:         }
 2019:         delete $domainrolehash{$entry};
 2020:     }
 2021:     foreach my $dom (keys(%domrolebuffer)) {
 2022: 	my %servers = &get_servers($dom,'library');
 2023: 	foreach my $tryserver (keys(%servers)) {
 2024: 	    unless (&reply('domroleput:'.$dom.':'.
 2025: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2026: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2027: 	    }
 2028:         }
 2029:     }
 2030:     $dumpcount++;
 2031: }
 2032: 
 2033: sub courselog {
 2034:     my $what=shift;
 2035:     $what=time.':'.$what;
 2036:     unless ($env{'request.course.id'}) { return ''; }
 2037:     $coursedombuf{$env{'request.course.id'}}=
 2038:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2039:     $coursenumbuf{$env{'request.course.id'}}=
 2040:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2041:     $coursehombuf{$env{'request.course.id'}}=
 2042:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2043:     $coursedescrbuf{$env{'request.course.id'}}=
 2044:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2045:     $courseinstcodebuf{$env{'request.course.id'}}=
 2046:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2047:     $courseownerbuf{$env{'request.course.id'}}=
 2048:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2049:     $coursetypebuf{$env{'request.course.id'}}=
 2050:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2051:     if (defined $courselogs{$env{'request.course.id'}}) {
 2052: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2053:     } else {
 2054: 	$courselogs{$env{'request.course.id'}}.=$what;
 2055:     }
 2056:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2057: 	&flushcourselogs();
 2058:     }
 2059: }
 2060: 
 2061: sub courseacclog {
 2062:     my $fnsymb=shift;
 2063:     unless ($env{'request.course.id'}) { return ''; }
 2064:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2065:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2066:         $what.=':POST';
 2067:         # FIXME: Probably ought to escape things....
 2068: 	foreach my $key (keys(%env)) {
 2069:             if ($key=~/^form\.(.*)/) {
 2070: 		$what.=':'.$1.'='.$env{$key};
 2071:             }
 2072:         }
 2073:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2074:         # FIXME: We should not be depending on a form parameter that someone
 2075:         # editing lonsearchcat.pm might change in the future.
 2076:         if ($env{'form.phase'} eq 'course_search') {
 2077:             $what.= ':POST';
 2078:             # FIXME: Probably ought to escape things....
 2079:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2080:                                  'crsdiscuss') {
 2081:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2082:             }
 2083:         }
 2084:     }
 2085:     &courselog($what);
 2086: }
 2087: 
 2088: sub countacc {
 2089:     my $url=&declutter(shift);
 2090:     return if (! defined($url) || $url eq '');
 2091:     unless ($env{'request.course.id'}) { return ''; }
 2092:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2093:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2094:     $accesshash{$key}++;
 2095: }
 2096: 
 2097: sub linklog {
 2098:     my ($from,$to)=@_;
 2099:     $from=&declutter($from);
 2100:     $to=&declutter($to);
 2101:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2102:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2103: }
 2104:   
 2105: sub userrolelog {
 2106:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2107:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2108:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2109:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2110:         ($trole=~/^ta/)) {
 2111:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2112:        $userrolehash
 2113:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2114:                     =$tend.':'.$tstart;
 2115:     }
 2116:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2117:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2118:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2119:         ($trole=~/^sc/)) {
 2120:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2121:        $domainrolehash
 2122:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2123:                     = $tend.':'.$tstart;
 2124:     }
 2125: }
 2126: 
 2127: sub get_course_adv_roles {
 2128:     my $cid=shift;
 2129:     $cid=$env{'request.course.id'} unless (defined($cid));
 2130:     my %coursehash=&coursedescription($cid);
 2131:     my %nothide=();
 2132:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2133: 	$nothide{join(':',split(/[\@\:]/,$user))}=1;
 2134:     }
 2135:     my %returnhash=();
 2136:     my %dumphash=
 2137:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2138:     my $now=time;
 2139:     foreach my $entry (keys %dumphash) {
 2140: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2141:         if (($tstart) && ($tstart<0)) { next; }
 2142:         if (($tend) && ($tend<$now)) { next; }
 2143:         if (($tstart) && ($now<$tstart)) { next; }
 2144:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2145: 	if ($username eq '' || $domain eq '') { next; }
 2146: 	if ((&privileged($username,$domain)) && 
 2147: 	    (!$nothide{$username.':'.$domain})) { next; }
 2148: 	if ($role eq 'cr') { next; }
 2149:         my $key=&plaintext($role);
 2150:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2151:         if ($returnhash{$key}) {
 2152: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2153:         } else {
 2154:             $returnhash{$key}=$username.':'.$domain;
 2155:         }
 2156:      }
 2157:     return %returnhash;
 2158: }
 2159: 
 2160: sub get_my_roles {
 2161:     my ($uname,$udom,$context,$types,$roles,$roledoms)=@_;
 2162:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2163:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2164:     my %dumphash;
 2165:     if ($context eq 'userroles') { 
 2166:         %dumphash = &dump('roles',$udom,$uname);
 2167:     } else {
 2168:         %dumphash=
 2169:             &dump('nohist_userroles',$udom,$uname);
 2170:     }
 2171:     my %returnhash=();
 2172:     my $now=time;
 2173:     foreach my $entry (keys(%dumphash)) {
 2174:         my ($role,$tend,$tstart);
 2175:         if ($context eq 'userroles') {
 2176: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2177:         } else {
 2178:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2179:         }
 2180:         if (($tstart) && ($tstart<0)) { next; }
 2181:         my $status = 'active';
 2182:         if (($tend) && ($tend<$now)) {
 2183:             $status = 'previous';
 2184:         } 
 2185:         if (($tstart) && ($now<$tstart)) {
 2186:             $status = 'future';
 2187:         }
 2188:         if (ref($types) eq 'ARRAY') {
 2189:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2190:                 next;
 2191:             } 
 2192:         } else {
 2193:             if ($status ne 'active') {
 2194:                 next;
 2195:             }
 2196:         }
 2197:         my ($rolecode,$username,$domain,$section,$area);
 2198:         if ($context eq 'userroles') {
 2199:             ($area,$rolecode) = split(/_/,$entry);
 2200:             (undef,$domain,$username,$section) = split(/\//,$area);
 2201:         } else {
 2202:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2203:         }
 2204:         if (ref($roledoms) eq 'ARRAY') {
 2205:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2206:                 next;
 2207:             }
 2208:         }
 2209:         if (ref($roles) eq 'ARRAY') {
 2210:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2211:                 next;
 2212:             }
 2213:         }
 2214: 	$returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2215:     }
 2216:     return %returnhash;
 2217: }
 2218: 
 2219: # ----------------------------------------------------- Frontpage Announcements
 2220: #
 2221: #
 2222: 
 2223: sub postannounce {
 2224:     my ($server,$text)=@_;
 2225:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2226:     unless ($text=~/\w/) { $text=''; }
 2227:     return &reply('setannounce:'.&escape($text),$server);
 2228: }
 2229: 
 2230: sub getannounce {
 2231: 
 2232:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2233: 	my $announcement='';
 2234: 	while (my $line = <$fh>) { $announcement .= $line; }
 2235: 	close($fh);
 2236: 	if ($announcement=~/\w/) { 
 2237: 	    return 
 2238:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2239:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2240: 	} else {
 2241: 	    return '';
 2242: 	}
 2243:     } else {
 2244: 	return '';
 2245:     }
 2246: }
 2247: 
 2248: # ---------------------------------------------------------- Course ID routines
 2249: # Deal with domain's nohist_courseid.db files
 2250: #
 2251: 
 2252: sub courseidput {
 2253:     my ($domain,$what,$coursehome)=@_;
 2254:     return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2255: }
 2256: 
 2257: sub courseiddump {
 2258:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,$coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2259:     my %returnhash=();
 2260:     unless ($domfilter) { $domfilter=''; }
 2261:     my %libserv = &all_library();
 2262:     foreach my $tryserver (keys(%libserv)) {
 2263:         if ( (  $hostidflag == 1 
 2264: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2265: 	     || (!defined($hostidflag)) ) {
 2266: 
 2267: 	    if ($domfilter eq ''
 2268: 		|| (&host_domain($tryserver) eq $domfilter)) {
 2269: 	        foreach my $line (
 2270:                  split(/\&/,&reply('courseiddump:'.&host_domain($tryserver).':'.
 2271: 			       $sincefilter.':'.&escape($descfilter).':'.
 2272:                                &escape($instcodefilter).':'.&escape($ownerfilter).':'.&escape($coursefilter).':'.&escape($typefilter).':'.&escape($regexp_ok),
 2273:                                $tryserver))) {
 2274: 		    my ($key,$value)=split(/\=/,$line,2);
 2275:                     if (($key) && ($value)) {
 2276: 		        $returnhash{&unescape($key)}=$value;
 2277:                     }
 2278:                 }
 2279:             }
 2280:         }
 2281:     }
 2282:     return %returnhash;
 2283: }
 2284: 
 2285: # ---------------------------------------------------------- DC e-mail
 2286: 
 2287: sub dcmailput {
 2288:     my ($domain,$msgid,$message,$server)=@_;
 2289:     my $status = &Apache::lonnet::critical(
 2290:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2291:        &escape($message),$server);
 2292:     return $status;
 2293: }
 2294: 
 2295: sub dcmaildump {
 2296:     my ($dom,$startdate,$enddate,$senders) = @_;
 2297:     my %returnhash=();
 2298: 
 2299:     if (defined(&domain($dom,'primary'))) {
 2300:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2301:                                                          &escape($enddate).':';
 2302: 	my @esc_senders=map { &escape($_)} @$senders;
 2303: 	$cmd.=&escape(join('&',@esc_senders));
 2304: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2305:             my ($key,$value) = split(/\=/,$line,2);
 2306:             if (($key) && ($value)) {
 2307:                 $returnhash{&unescape($key)} = &unescape($value);
 2308:             }
 2309:         }
 2310:     }
 2311:     return %returnhash;
 2312: }
 2313: # ---------------------------------------------------------- Domain roles
 2314: 
 2315: sub get_domain_roles {
 2316:     my ($dom,$roles,$startdate,$enddate)=@_;
 2317:     if (undef($startdate) || $startdate eq '') {
 2318:         $startdate = '.';
 2319:     }
 2320:     if (undef($enddate) || $enddate eq '') {
 2321:         $enddate = '.';
 2322:     }
 2323:     my $rolelist = join(':',@{$roles});
 2324:     my %personnel = ();
 2325: 
 2326:     my %servers = &get_servers($dom,'library');
 2327:     foreach my $tryserver (keys(%servers)) {
 2328: 	%{$personnel{$tryserver}}=();
 2329: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2330: 					    &escape($startdate).':'.
 2331: 					    &escape($enddate).':'.
 2332: 					    &escape($rolelist), $tryserver))) {
 2333: 	    my ($key,$value) = split(/\=/,$line,2);
 2334: 	    if (($key) && ($value)) {
 2335: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2336: 	    }
 2337: 	}
 2338:     }
 2339:     return %personnel;
 2340: }
 2341: 
 2342: # ----------------------------------------------------------- Check out an item
 2343: 
 2344: sub get_first_access {
 2345:     my ($type,$argsymb)=@_;
 2346:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2347:     if ($argsymb) { $symb=$argsymb; }
 2348:     my ($map,$id,$res)=&decode_symb($symb);
 2349:     if ($type eq 'map') {
 2350: 	$res=&symbread($map);
 2351:     } else {
 2352: 	$res=$symb;
 2353:     }
 2354:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2355:     return $times{"$courseid\0$res"};
 2356: }
 2357: 
 2358: sub set_first_access {
 2359:     my ($type)=@_;
 2360:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2361:     my ($map,$id,$res)=&decode_symb($symb);
 2362:     if ($type eq 'map') {
 2363: 	$res=&symbread($map);
 2364:     } else {
 2365: 	$res=$symb;
 2366:     }
 2367:     my $firstaccess=&get_first_access($type,$symb);
 2368:     if (!$firstaccess) {
 2369: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2370:     }
 2371:     return 'already_set';
 2372: }
 2373: 
 2374: sub checkout {
 2375:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2376:     my $now=time;
 2377:     my $lonhost=$perlvar{'lonHostID'};
 2378:     my $infostr=&escape(
 2379:                  'CHECKOUTTOKEN&'.
 2380:                  $tuname.'&'.
 2381:                  $tudom.'&'.
 2382:                  $tcrsid.'&'.
 2383:                  $symb.'&'.
 2384: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2385:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2386:     if ($token=~/^error\:/) { 
 2387:         &logthis("<font color=\"blue\">WARNING: ".
 2388:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2389:                  "</font>");
 2390:         return ''; 
 2391:     }
 2392: 
 2393:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2394:     $token=~tr/a-z/A-Z/;
 2395: 
 2396:     my %infohash=('resource.0.outtoken' => $token,
 2397:                   'resource.0.checkouttime' => $now,
 2398:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2399: 
 2400:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2401:        return '';
 2402:     } else {
 2403:         &logthis("<font color=\"blue\">WARNING: ".
 2404:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2405:                  "</font>");
 2406:     }    
 2407: 
 2408:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2409:                          &escape('Checkout '.$infostr.' - '.
 2410:                                                  $token)) ne 'ok') {
 2411: 	return '';
 2412:     } else {
 2413:         &logthis("<font color=\"blue\">WARNING: ".
 2414:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2415:                  "</font>");
 2416:     }
 2417:     return $token;
 2418: }
 2419: 
 2420: # ------------------------------------------------------------ Check in an item
 2421: 
 2422: sub checkin {
 2423:     my $token=shift;
 2424:     my $now=time;
 2425:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2426:     $lonhost=~tr/A-Z/a-z/;
 2427:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2428:     $dtoken=~s/\W/\_/g;
 2429:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2430:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2431: 
 2432:     unless (($tuname) && ($tudom)) {
 2433:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2434:         return '';
 2435:     }
 2436:     
 2437:     unless (&allowed('mgr',$tcrsid)) {
 2438:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2439:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2440:         return '';
 2441:     }
 2442: 
 2443:     my %infohash=('resource.0.intoken' => $token,
 2444:                   'resource.0.checkintime' => $now,
 2445:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2446: 
 2447:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2448:        return '';
 2449:     }    
 2450: 
 2451:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2452:                          &escape('Checkin - '.$token)) ne 'ok') {
 2453: 	return '';
 2454:     }
 2455: 
 2456:     return ($symb,$tuname,$tudom,$tcrsid);    
 2457: }
 2458: 
 2459: # --------------------------------------------- Set Expire Date for Spreadsheet
 2460: 
 2461: sub expirespread {
 2462:     my ($uname,$udom,$stype,$usymb)=@_;
 2463:     my $cid=$env{'request.course.id'}; 
 2464:     if ($cid) {
 2465:        my $now=time;
 2466:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2467:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2468:                             $env{'course.'.$cid.'.num'}.
 2469: 	        	    ':nohist_expirationdates:'.
 2470:                             &escape($key).'='.$now,
 2471:                             $env{'course.'.$cid.'.home'})
 2472:     }
 2473:     return 'ok';
 2474: }
 2475: 
 2476: # ----------------------------------------------------- Devalidate Spreadsheets
 2477: 
 2478: sub devalidate {
 2479:     my ($symb,$uname,$udom)=@_;
 2480:     my $cid=$env{'request.course.id'}; 
 2481:     if ($cid) {
 2482:         # delete the stored spreadsheets for
 2483:         # - the student level sheet of this user in course's homespace
 2484:         # - the assessment level sheet for this resource 
 2485:         #   for this user in user's homespace
 2486: 	# - current conditional state info
 2487: 	my $key=$uname.':'.$udom.':';
 2488:         my $status=
 2489: 	    &del('nohist_calculatedsheets',
 2490: 		 [$key.'studentcalc:'],
 2491: 		 $env{'course.'.$cid.'.domain'},
 2492: 		 $env{'course.'.$cid.'.num'})
 2493: 		.' '.
 2494: 	    &del('nohist_calculatedsheets_'.$cid,
 2495: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2496:         unless ($status eq 'ok ok') {
 2497:            &logthis('Could not devalidate spreadsheet '.
 2498:                     $uname.' at '.$udom.' for '.
 2499: 		    $symb.': '.$status);
 2500:         }
 2501: 	&delenv('user.state.'.$cid);
 2502:     }
 2503: }
 2504: 
 2505: sub get_scalar {
 2506:     my ($string,$end) = @_;
 2507:     my $value;
 2508:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2509: 	$value = $1;
 2510:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2511: 	$value = $1;
 2512:     }
 2513:     return &unescape($value);
 2514: }
 2515: 
 2516: sub array2str {
 2517:   my (@array) = @_;
 2518:   my $result=&arrayref2str(\@array);
 2519:   $result=~s/^__ARRAY_REF__//;
 2520:   $result=~s/__END_ARRAY_REF__$//;
 2521:   return $result;
 2522: }
 2523: 
 2524: sub arrayref2str {
 2525:   my ($arrayref) = @_;
 2526:   my $result='__ARRAY_REF__';
 2527:   foreach my $elem (@$arrayref) {
 2528:     if(ref($elem) eq 'ARRAY') {
 2529:       $result.=&arrayref2str($elem).'&';
 2530:     } elsif(ref($elem) eq 'HASH') {
 2531:       $result.=&hashref2str($elem).'&';
 2532:     } elsif(ref($elem)) {
 2533:       #print("Got a ref of ".(ref($elem))." skipping.");
 2534:     } else {
 2535:       $result.=&escape($elem).'&';
 2536:     }
 2537:   }
 2538:   $result=~s/\&$//;
 2539:   $result .= '__END_ARRAY_REF__';
 2540:   return $result;
 2541: }
 2542: 
 2543: sub hash2str {
 2544:   my (%hash) = @_;
 2545:   my $result=&hashref2str(\%hash);
 2546:   $result=~s/^__HASH_REF__//;
 2547:   $result=~s/__END_HASH_REF__$//;
 2548:   return $result;
 2549: }
 2550: 
 2551: sub hashref2str {
 2552:   my ($hashref)=@_;
 2553:   my $result='__HASH_REF__';
 2554:   foreach my $key (sort(keys(%$hashref))) {
 2555:     if (ref($key) eq 'ARRAY') {
 2556:       $result.=&arrayref2str($key).'=';
 2557:     } elsif (ref($key) eq 'HASH') {
 2558:       $result.=&hashref2str($key).'=';
 2559:     } elsif (ref($key)) {
 2560:       $result.='=';
 2561:       #print("Got a ref of ".(ref($key))." skipping.");
 2562:     } else {
 2563: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2564:     }
 2565: 
 2566:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2567:       $result.=&arrayref2str($hashref->{$key}).'&';
 2568:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2569:       $result.=&hashref2str($hashref->{$key}).'&';
 2570:     } elsif(ref($hashref->{$key})) {
 2571:        $result.='&';
 2572:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2573:     } else {
 2574:       $result.=&escape($hashref->{$key}).'&';
 2575:     }
 2576:   }
 2577:   $result=~s/\&$//;
 2578:   $result .= '__END_HASH_REF__';
 2579:   return $result;
 2580: }
 2581: 
 2582: sub str2hash {
 2583:     my ($string)=@_;
 2584:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2585:     return %$hash;
 2586: }
 2587: 
 2588: sub str2hashref {
 2589:   my ($string) = @_;
 2590: 
 2591:   my %hash;
 2592: 
 2593:   if($string !~ /^__HASH_REF__/) {
 2594:       if (! ($string eq '' || !defined($string))) {
 2595: 	  $hash{'error'}='Not hash reference';
 2596:       }
 2597:       return (\%hash, $string);
 2598:   }
 2599: 
 2600:   $string =~ s/^__HASH_REF__//;
 2601: 
 2602:   while($string !~ /^__END_HASH_REF__/) {
 2603:       #key
 2604:       my $key='';
 2605:       if($string =~ /^__HASH_REF__/) {
 2606:           ($key, $string)=&str2hashref($string);
 2607:           if(defined($key->{'error'})) {
 2608:               $hash{'error'}='Bad data';
 2609:               return (\%hash, $string);
 2610:           }
 2611:       } elsif($string =~ /^__ARRAY_REF__/) {
 2612:           ($key, $string)=&str2arrayref($string);
 2613:           if($key->[0] eq 'Array reference error') {
 2614:               $hash{'error'}='Bad data';
 2615:               return (\%hash, $string);
 2616:           }
 2617:       } else {
 2618:           $string =~ s/^(.*?)=//;
 2619: 	  $key=&unescape($1);
 2620:       }
 2621:       $string =~ s/^=//;
 2622: 
 2623:       #value
 2624:       my $value='';
 2625:       if($string =~ /^__HASH_REF__/) {
 2626:           ($value, $string)=&str2hashref($string);
 2627:           if(defined($value->{'error'})) {
 2628:               $hash{'error'}='Bad data';
 2629:               return (\%hash, $string);
 2630:           }
 2631:       } elsif($string =~ /^__ARRAY_REF__/) {
 2632:           ($value, $string)=&str2arrayref($string);
 2633:           if($value->[0] eq 'Array reference error') {
 2634:               $hash{'error'}='Bad data';
 2635:               return (\%hash, $string);
 2636:           }
 2637:       } else {
 2638: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 2639:       }
 2640:       $string =~ s/^&//;
 2641: 
 2642:       $hash{$key}=$value;
 2643:   }
 2644: 
 2645:   $string =~ s/^__END_HASH_REF__//;
 2646: 
 2647:   return (\%hash, $string);
 2648: }
 2649: 
 2650: sub str2array {
 2651:     my ($string)=@_;
 2652:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 2653:     return @$array;
 2654: }
 2655: 
 2656: sub str2arrayref {
 2657:   my ($string) = @_;
 2658:   my @array;
 2659: 
 2660:   if($string !~ /^__ARRAY_REF__/) {
 2661:       if (! ($string eq '' || !defined($string))) {
 2662: 	  $array[0]='Array reference error';
 2663:       }
 2664:       return (\@array, $string);
 2665:   }
 2666: 
 2667:   $string =~ s/^__ARRAY_REF__//;
 2668: 
 2669:   while($string !~ /^__END_ARRAY_REF__/) {
 2670:       my $value='';
 2671:       if($string =~ /^__HASH_REF__/) {
 2672:           ($value, $string)=&str2hashref($string);
 2673:           if(defined($value->{'error'})) {
 2674:               $array[0] ='Array reference error';
 2675:               return (\@array, $string);
 2676:           }
 2677:       } elsif($string =~ /^__ARRAY_REF__/) {
 2678:           ($value, $string)=&str2arrayref($string);
 2679:           if($value->[0] eq 'Array reference error') {
 2680:               $array[0] ='Array reference error';
 2681:               return (\@array, $string);
 2682:           }
 2683:       } else {
 2684: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 2685:       }
 2686:       $string =~ s/^&//;
 2687: 
 2688:       push(@array, $value);
 2689:   }
 2690: 
 2691:   $string =~ s/^__END_ARRAY_REF__//;
 2692: 
 2693:   return (\@array, $string);
 2694: }
 2695: 
 2696: # -------------------------------------------------------------------Temp Store
 2697: 
 2698: sub tmpreset {
 2699:   my ($symb,$namespace,$domain,$stuname) = @_;
 2700:   if (!$symb) {
 2701:     $symb=&symbread();
 2702:     if (!$symb) { $symb= $env{'request.url'}; }
 2703:   }
 2704:   $symb=escape($symb);
 2705: 
 2706:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2707:   $namespace=~s/\//\_/g;
 2708:   $namespace=~s/\W//g;
 2709: 
 2710:   if (!$domain) { $domain=$env{'user.domain'}; }
 2711:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2712:   if ($domain eq 'public' && $stuname eq 'public') {
 2713:       $stuname=$ENV{'REMOTE_ADDR'};
 2714:   }
 2715:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2716:   my %hash;
 2717:   if (tie(%hash,'GDBM_File',
 2718: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2719: 	  &GDBM_WRCREAT(),0640)) {
 2720:     foreach my $key (keys %hash) {
 2721:       if ($key=~ /:$symb/) {
 2722: 	delete($hash{$key});
 2723:       }
 2724:     }
 2725:   }
 2726: }
 2727: 
 2728: sub tmpstore {
 2729:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2730: 
 2731:   if (!$symb) {
 2732:     $symb=&symbread();
 2733:     if (!$symb) { $symb= $env{'request.url'}; }
 2734:   }
 2735:   $symb=escape($symb);
 2736: 
 2737:   if (!$namespace) {
 2738:     # I don't think we would ever want to store this for a course.
 2739:     # it seems this will only be used if we don't have a course.
 2740:     #$namespace=$env{'request.course.id'};
 2741:     #if (!$namespace) {
 2742:       $namespace=$env{'request.state'};
 2743:     #}
 2744:   }
 2745:   $namespace=~s/\//\_/g;
 2746:   $namespace=~s/\W//g;
 2747:   if (!$domain) { $domain=$env{'user.domain'}; }
 2748:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2749:   if ($domain eq 'public' && $stuname eq 'public') {
 2750:       $stuname=$ENV{'REMOTE_ADDR'};
 2751:   }
 2752:   my $now=time;
 2753:   my %hash;
 2754:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2755:   if (tie(%hash,'GDBM_File',
 2756: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2757: 	  &GDBM_WRCREAT(),0640)) {
 2758:     $hash{"version:$symb"}++;
 2759:     my $version=$hash{"version:$symb"};
 2760:     my $allkeys=''; 
 2761:     foreach my $key (keys(%$storehash)) {
 2762:       $allkeys.=$key.':';
 2763:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 2764:     }
 2765:     $hash{"$version:$symb:timestamp"}=$now;
 2766:     $allkeys.='timestamp';
 2767:     $hash{"$version:keys:$symb"}=$allkeys;
 2768:     if (untie(%hash)) {
 2769:       return 'ok';
 2770:     } else {
 2771:       return "error:$!";
 2772:     }
 2773:   } else {
 2774:     return "error:$!";
 2775:   }
 2776: }
 2777: 
 2778: # -----------------------------------------------------------------Temp Restore
 2779: 
 2780: sub tmprestore {
 2781:   my ($symb,$namespace,$domain,$stuname) = @_;
 2782: 
 2783:   if (!$symb) {
 2784:     $symb=&symbread();
 2785:     if (!$symb) { $symb= $env{'request.url'}; }
 2786:   }
 2787:   $symb=escape($symb);
 2788: 
 2789:   if (!$namespace) { $namespace=$env{'request.state'}; }
 2790: 
 2791:   if (!$domain) { $domain=$env{'user.domain'}; }
 2792:   if (!$stuname) { $stuname=$env{'user.name'}; }
 2793:   if ($domain eq 'public' && $stuname eq 'public') {
 2794:       $stuname=$ENV{'REMOTE_ADDR'};
 2795:   }
 2796:   my %returnhash;
 2797:   $namespace=~s/\//\_/g;
 2798:   $namespace=~s/\W//g;
 2799:   my %hash;
 2800:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 2801:   if (tie(%hash,'GDBM_File',
 2802: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 2803: 	  &GDBM_READER(),0640)) {
 2804:     my $version=$hash{"version:$symb"};
 2805:     $returnhash{'version'}=$version;
 2806:     my $scope;
 2807:     for ($scope=1;$scope<=$version;$scope++) {
 2808:       my $vkeys=$hash{"$scope:keys:$symb"};
 2809:       my @keys=split(/:/,$vkeys);
 2810:       my $key;
 2811:       $returnhash{"$scope:keys"}=$vkeys;
 2812:       foreach $key (@keys) {
 2813: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2814: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 2815:       }
 2816:     }
 2817:     if (!(untie(%hash))) {
 2818:       return "error:$!";
 2819:     }
 2820:   } else {
 2821:     return "error:$!";
 2822:   }
 2823:   return %returnhash;
 2824: }
 2825: 
 2826: # ----------------------------------------------------------------------- Store
 2827: 
 2828: sub store {
 2829:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2830:     my $home='';
 2831: 
 2832:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2833: 
 2834:     $symb=&symbclean($symb);
 2835:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2836: 
 2837:     if (!$domain) { $domain=$env{'user.domain'}; }
 2838:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2839: 
 2840:     &devalidate($symb,$stuname,$domain);
 2841: 
 2842:     $symb=escape($symb);
 2843:     if (!$namespace) { 
 2844:        unless ($namespace=$env{'request.course.id'}) { 
 2845:           return ''; 
 2846:        } 
 2847:     }
 2848:     if (!$home) { $home=$env{'user.home'}; }
 2849: 
 2850:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2851:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2852: 
 2853:     my $namevalue='';
 2854:     foreach my $key (keys(%$storehash)) {
 2855:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2856:     }
 2857:     $namevalue=~s/\&$//;
 2858:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 2859:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2860: }
 2861: 
 2862: # -------------------------------------------------------------- Critical Store
 2863: 
 2864: sub cstore {
 2865:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 2866:     my $home='';
 2867: 
 2868:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2869: 
 2870:     $symb=&symbclean($symb);
 2871:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 2872: 
 2873:     if (!$domain) { $domain=$env{'user.domain'}; }
 2874:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2875: 
 2876:     &devalidate($symb,$stuname,$domain);
 2877: 
 2878:     $symb=escape($symb);
 2879:     if (!$namespace) { 
 2880:        unless ($namespace=$env{'request.course.id'}) { 
 2881:           return ''; 
 2882:        } 
 2883:     }
 2884:     if (!$home) { $home=$env{'user.home'}; }
 2885: 
 2886:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 2887:     $$storehash{'host'}=$perlvar{'lonHostID'};
 2888: 
 2889:     my $namevalue='';
 2890:     foreach my $key (keys(%$storehash)) {
 2891:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 2892:     }
 2893:     $namevalue=~s/\&$//;
 2894:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 2895:     return critical
 2896:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 2897: }
 2898: 
 2899: # --------------------------------------------------------------------- Restore
 2900: 
 2901: sub restore {
 2902:     my ($symb,$namespace,$domain,$stuname) = @_;
 2903:     my $home='';
 2904: 
 2905:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 2906: 
 2907:     if (!$symb) {
 2908:       unless ($symb=escape(&symbread())) { return ''; }
 2909:     } else {
 2910:       $symb=&escape(&symbclean($symb));
 2911:     }
 2912:     if (!$namespace) { 
 2913:        unless ($namespace=$env{'request.course.id'}) { 
 2914:           return ''; 
 2915:        } 
 2916:     }
 2917:     if (!$domain) { $domain=$env{'user.domain'}; }
 2918:     if (!$stuname) { $stuname=$env{'user.name'}; }
 2919:     if (!$home) { $home=$env{'user.home'}; }
 2920:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 2921: 
 2922:     my %returnhash=();
 2923:     foreach my $line (split(/\&/,$answer)) {
 2924: 	my ($name,$value)=split(/\=/,$line);
 2925:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 2926:     }
 2927:     my $version;
 2928:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 2929:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 2930:           $returnhash{$item}=$returnhash{$version.':'.$item};
 2931:        }
 2932:     }
 2933:     return %returnhash;
 2934: }
 2935: 
 2936: # ---------------------------------------------------------- Course Description
 2937: 
 2938: sub coursedescription {
 2939:     my ($courseid,$args)=@_;
 2940:     $courseid=~s/^\///;
 2941:     $courseid=~s/\_/\//g;
 2942:     my ($cdomain,$cnum)=split(/\//,$courseid);
 2943:     my $chome=&homeserver($cnum,$cdomain);
 2944:     my $normalid=$cdomain.'_'.$cnum;
 2945:     # need to always cache even if we get errors otherwise we keep 
 2946:     # trying and trying and trying to get the course description.
 2947:     my %envhash=();
 2948:     my %returnhash=();
 2949:     
 2950:     my $expiretime=600;
 2951:     if ($env{'request.course.id'} eq $normalid) {
 2952: 	$expiretime=120;
 2953:     }
 2954: 
 2955:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 2956:     if (!$args->{'freshen_cache'}
 2957: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 2958: 	foreach my $key (keys(%env)) {
 2959: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 2960: 	    my ($setting) = $1;
 2961: 	    $returnhash{$setting} = $env{$key};
 2962: 	}
 2963: 	return %returnhash;
 2964:     }
 2965: 
 2966:     # get the data agin
 2967:     if (!$args->{'one_time'}) {
 2968: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 2969:     }
 2970: 
 2971:     if ($chome ne 'no_host') {
 2972:        %returnhash=&dump('environment',$cdomain,$cnum);
 2973:        if (!exists($returnhash{'con_lost'})) {
 2974:            $returnhash{'home'}= $chome;
 2975: 	   $returnhash{'domain'} = $cdomain;
 2976: 	   $returnhash{'num'} = $cnum;
 2977:            if (!defined($returnhash{'type'})) {
 2978:                $returnhash{'type'} = 'Course';
 2979:            }
 2980:            while (my ($name,$value) = each %returnhash) {
 2981:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 2982:            }
 2983:            $returnhash{'url'}=&clutter($returnhash{'url'});
 2984:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 2985: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 2986:            $envhash{'course.'.$normalid.'.home'}=$chome;
 2987:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 2988:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 2989:        }
 2990:     }
 2991:     if (!$args->{'one_time'}) {
 2992: 	&appenv(%envhash);
 2993:     }
 2994:     return %returnhash;
 2995: }
 2996: 
 2997: # -------------------------------------------------See if a user is privileged
 2998: 
 2999: sub privileged {
 3000:     my ($username,$domain)=@_;
 3001:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3002: 			&homeserver($username,$domain));
 3003:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3004:     my $now=time;
 3005:     if ($rolesdump ne '') {
 3006:         foreach my $entry (split(/&/,$rolesdump)) {
 3007: 	    if ($entry!~/^rolesdef_/) {
 3008: 		my ($area,$role)=split(/=/,$entry);
 3009: 		$area=~s/\_\w\w$//;
 3010: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3011: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3012: 		    my $active=1;
 3013: 		    if ($tend) {
 3014: 			if ($tend<$now) { $active=0; }
 3015: 		    }
 3016: 		    if ($tstart) {
 3017: 			if ($tstart>$now) { $active=0; }
 3018: 		    }
 3019: 		    if ($active) { return 1; }
 3020: 		}
 3021: 	    }
 3022: 	}
 3023:     }
 3024:     return 0;
 3025: }
 3026: 
 3027: # -------------------------------------------------------- Get user privileges
 3028: 
 3029: sub rolesinit {
 3030:     my ($domain,$username,$authhost)=@_;
 3031:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3032:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3033:     my %allroles=();
 3034:     my %allgroups=();   
 3035:     my $now=time;
 3036:     my %userroles = ('user.login.time' => $now);
 3037:     my $group_privs;
 3038: 
 3039:     if ($rolesdump ne '') {
 3040:         foreach my $entry (split(/&/,$rolesdump)) {
 3041: 	  if ($entry!~/^rolesdef_/) {
 3042:             my ($area,$role)=split(/=/,$entry);
 3043: 	    $area=~s/\_\w\w$//;
 3044:             my ($trole,$tend,$tstart,$group_privs);
 3045: 	    if ($role=~/^cr/) { 
 3046: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3047: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3048: 		    ($tend,$tstart)=split('_',$trest);
 3049: 		} else {
 3050: 		    $trole=$role;
 3051: 		}
 3052:             } elsif ($role =~ m|^gr/|) {
 3053:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3054:                 ($trole,$group_privs) = split(/\//,$trole);
 3055:                 $group_privs = &unescape($group_privs);
 3056: 	    } else {
 3057: 		($trole,$tend,$tstart)=split(/_/,$role);
 3058: 	    }
 3059: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3060: 					 $username);
 3061: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3062:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3063:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3064:             if (($area ne '') && ($trole ne '')) {
 3065: 		my $spec=$trole.'.'.$area;
 3066: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3067: 		if ($trole =~ /^cr\//) {
 3068:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3069:                 } elsif ($trole eq 'gr') {
 3070:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3071: 		} else {
 3072:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3073: 		}
 3074:             }
 3075:           }
 3076:         }
 3077:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3078:         $userroles{'user.adv'}    = $adv;
 3079: 	$userroles{'user.author'} = $author;
 3080:         $env{'user.adv'}=$adv;
 3081:     }
 3082:     return \%userroles;  
 3083: }
 3084: 
 3085: sub set_arearole {
 3086:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3087: # log the associated role with the area
 3088:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3089:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3090: }
 3091: 
 3092: sub custom_roleprivs {
 3093:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3094:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3095:     my $homsvr=homeserver($rauthor,$rdomain);
 3096:     if (&hostname($homsvr) ne '') {
 3097:         my ($rdummy,$roledef)=
 3098:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3099:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3100:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3101:             if (defined($syspriv)) {
 3102:                 $$allroles{'cm./'}.=':'.$syspriv;
 3103:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3104:             }
 3105:             if ($tdomain ne '') {
 3106:                 if (defined($dompriv)) {
 3107:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3108:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3109:                 }
 3110:                 if (($trest ne '') && (defined($coursepriv))) {
 3111:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3112:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3113:                 }
 3114:             }
 3115:         }
 3116:     }
 3117: }
 3118: 
 3119: sub group_roleprivs {
 3120:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3121:     my $access = 1;
 3122:     my $now = time;
 3123:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3124:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3125:     if ($access) {
 3126:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3127:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3128:     }
 3129: }
 3130: 
 3131: sub standard_roleprivs {
 3132:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3133:     if (defined($pr{$trole.':s'})) {
 3134:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3135:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3136:     }
 3137:     if ($tdomain ne '') {
 3138:         if (defined($pr{$trole.':d'})) {
 3139:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3140:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3141:         }
 3142:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3143:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3144:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3145:         }
 3146:     }
 3147: }
 3148: 
 3149: sub set_userprivs {
 3150:     my ($userroles,$allroles,$allgroups) = @_; 
 3151:     my $author=0;
 3152:     my $adv=0;
 3153:     my %grouproles = ();
 3154:     if (keys(%{$allgroups}) > 0) {
 3155:         foreach my $role (keys %{$allroles}) {
 3156:             my ($trole,$area,$sec,$extendedarea);
 3157:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3158:                 $trole = $1;
 3159:                 $area = $2;
 3160:                 $sec = $3;
 3161:                 $extendedarea = $area.$sec;
 3162:                 if (exists($$allgroups{$area})) {
 3163:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3164:                         my $spec = $trole.'.'.$extendedarea;
 3165:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3166:                                                 $$allgroups{$area}{$group};
 3167:                     }
 3168:                 }
 3169:             }
 3170:         }
 3171:     }
 3172:     foreach my $group (keys(%grouproles)) {
 3173:         $$allroles{$group} = $grouproles{$group};
 3174:     }
 3175:     foreach my $role (keys(%{$allroles})) {
 3176:         my %thesepriv;
 3177:         if (($role=~/^au/) || ($role=~/^ca/)) { $author=1; }
 3178:         foreach my $item (split(/:/,$$allroles{$role})) {
 3179:             if ($item ne '') {
 3180:                 my ($privilege,$restrictions)=split(/&/,$item);
 3181:                 if ($restrictions eq '') {
 3182:                     $thesepriv{$privilege}='F';
 3183:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3184:                     $thesepriv{$privilege}.=$restrictions;
 3185:                 }
 3186:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3187:             }
 3188:         }
 3189:         my $thesestr='';
 3190:         foreach my $priv (keys(%thesepriv)) {
 3191: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3192: 	}
 3193:         $userroles->{'user.priv.'.$role} = $thesestr;
 3194:     }
 3195:     return ($author,$adv);
 3196: }
 3197: 
 3198: # --------------------------------------------------------------- get interface
 3199: 
 3200: sub get {
 3201:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3202:    my $items='';
 3203:    foreach my $item (@$storearr) {
 3204:        $items.=&escape($item).'&';
 3205:    }
 3206:    $items=~s/\&$//;
 3207:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3208:    if (!$uname) { $uname=$env{'user.name'}; }
 3209:    my $uhome=&homeserver($uname,$udomain);
 3210: 
 3211:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3212:    my @pairs=split(/\&/,$rep);
 3213:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3214:      return @pairs;
 3215:    }
 3216:    my %returnhash=();
 3217:    my $i=0;
 3218:    foreach my $item (@$storearr) {
 3219:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3220:       $i++;
 3221:    }
 3222:    return %returnhash;
 3223: }
 3224: 
 3225: # --------------------------------------------------------------- del interface
 3226: 
 3227: sub del {
 3228:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3229:    my $items='';
 3230:    foreach my $item (@$storearr) {
 3231:        $items.=&escape($item).'&';
 3232:    }
 3233:    $items=~s/\&$//;
 3234:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3235:    if (!$uname) { $uname=$env{'user.name'}; }
 3236:    my $uhome=&homeserver($uname,$udomain);
 3237: 
 3238:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3239: }
 3240: 
 3241: # -------------------------------------------------------------- dump interface
 3242: 
 3243: sub dump {
 3244:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3245:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3246:     if (!$uname) { $uname=$env{'user.name'}; }
 3247:     my $uhome=&homeserver($uname,$udomain);
 3248:     if ($regexp) {
 3249: 	$regexp=&escape($regexp);
 3250:     } else {
 3251: 	$regexp='.';
 3252:     }
 3253:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3254:     my @pairs=split(/\&/,$rep);
 3255:     my %returnhash=();
 3256:     foreach my $item (@pairs) {
 3257: 	my ($key,$value)=split(/=/,$item,2);
 3258: 	$key = &unescape($key);
 3259: 	next if ($key =~ /^error: 2 /);
 3260: 	$returnhash{$key}=&thaw_unescape($value);
 3261:     }
 3262:     return %returnhash;
 3263: }
 3264: 
 3265: # --------------------------------------------------------- dumpstore interface
 3266: 
 3267: sub dumpstore {
 3268:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3269:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3270:    if (!$uname) { $uname=$env{'user.name'}; }
 3271:    my $uhome=&homeserver($uname,$udomain);
 3272:    if ($regexp) {
 3273:        $regexp=&escape($regexp);
 3274:    } else {
 3275:        $regexp='.';
 3276:    }
 3277:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3278:    my @pairs=split(/\&/,$rep);
 3279:    my %returnhash=();
 3280:    foreach my $item (@pairs) {
 3281:        my ($key,$value)=split(/=/,$item,2);
 3282:        next if ($key =~ /^error: 2 /);
 3283:        $returnhash{$key}=&thaw_unescape($value);
 3284:    }
 3285:    return %returnhash;
 3286: }
 3287: 
 3288: # -------------------------------------------------------------- keys interface
 3289: 
 3290: sub getkeys {
 3291:    my ($namespace,$udomain,$uname)=@_;
 3292:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3293:    if (!$uname) { $uname=$env{'user.name'}; }
 3294:    my $uhome=&homeserver($uname,$udomain);
 3295:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3296:    my @keyarray=();
 3297:    foreach my $key (split(/\&/,$rep)) {
 3298:       next if ($key =~ /^error: 2 /);
 3299:       push(@keyarray,&unescape($key));
 3300:    }
 3301:    return @keyarray;
 3302: }
 3303: 
 3304: # --------------------------------------------------------------- currentdump
 3305: sub currentdump {
 3306:    my ($courseid,$sdom,$sname)=@_;
 3307:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3308:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3309:    $sname    = $env{'user.name'}         if (! defined($sname));
 3310:    my $uhome = &homeserver($sname,$sdom);
 3311:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3312:    return if ($rep =~ /^(error:|no_such_host)/);
 3313:    #
 3314:    my %returnhash=();
 3315:    #
 3316:    if ($rep eq "unknown_cmd") { 
 3317:        # an old lond will not know currentdump
 3318:        # Do a dump and make it look like a currentdump
 3319:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3320:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3321:        my %hash = @tmp;
 3322:        @tmp=();
 3323:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3324:    } else {
 3325:        my @pairs=split(/\&/,$rep);
 3326:        foreach my $pair (@pairs) {
 3327:            my ($key,$value)=split(/=/,$pair,2);
 3328:            my ($symb,$param) = split(/:/,$key);
 3329:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3330:                                                         &thaw_unescape($value);
 3331:        }
 3332:    }
 3333:    return %returnhash;
 3334: }
 3335: 
 3336: sub convert_dump_to_currentdump{
 3337:     my %hash = %{shift()};
 3338:     my %returnhash;
 3339:     # Code ripped from lond, essentially.  The only difference
 3340:     # here is the unescaping done by lonnet::dump().  Conceivably
 3341:     # we might run in to problems with parameter names =~ /^v\./
 3342:     while (my ($key,$value) = each(%hash)) {
 3343:         my ($v,$symb,$param) = split(/:/,$key);
 3344: 	$symb  = &unescape($symb);
 3345: 	$param = &unescape($param);
 3346:         next if ($v eq 'version' || $symb eq 'keys');
 3347:         next if (exists($returnhash{$symb}) &&
 3348:                  exists($returnhash{$symb}->{$param}) &&
 3349:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3350:         $returnhash{$symb}->{$param}=$value;
 3351:         $returnhash{$symb}->{'v.'.$param}=$v;
 3352:     }
 3353:     #
 3354:     # Remove all of the keys in the hashes which keep track of
 3355:     # the version of the parameter.
 3356:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3357:         # use a foreach because we are going to delete from the hash.
 3358:         foreach my $key (keys(%$param_hash)) {
 3359:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3360:         }
 3361:     }
 3362:     return \%returnhash;
 3363: }
 3364: 
 3365: # ------------------------------------------------------ critical inc interface
 3366: 
 3367: sub cinc {
 3368:     return &inc(@_,'critical');
 3369: }
 3370: 
 3371: # --------------------------------------------------------------- inc interface
 3372: 
 3373: sub inc {
 3374:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3375:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3376:     if (!$uname) { $uname=$env{'user.name'}; }
 3377:     my $uhome=&homeserver($uname,$udomain);
 3378:     my $items='';
 3379:     if (! ref($store)) {
 3380:         # got a single value, so use that instead
 3381:         $items = &escape($store).'=&';
 3382:     } elsif (ref($store) eq 'SCALAR') {
 3383:         $items = &escape($$store).'=&';        
 3384:     } elsif (ref($store) eq 'ARRAY') {
 3385:         $items = join('=&',map {&escape($_);} @{$store});
 3386:     } elsif (ref($store) eq 'HASH') {
 3387:         while (my($key,$value) = each(%{$store})) {
 3388:             $items.= &escape($key).'='.&escape($value).'&';
 3389:         }
 3390:     }
 3391:     $items=~s/\&$//;
 3392:     if ($critical) {
 3393: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3394:     } else {
 3395: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3396:     }
 3397: }
 3398: 
 3399: # --------------------------------------------------------------- put interface
 3400: 
 3401: sub put {
 3402:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3403:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3404:    if (!$uname) { $uname=$env{'user.name'}; }
 3405:    my $uhome=&homeserver($uname,$udomain);
 3406:    my $items='';
 3407:    foreach my $item (keys(%$storehash)) {
 3408:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3409:    }
 3410:    $items=~s/\&$//;
 3411:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3412: }
 3413: 
 3414: # ------------------------------------------------------------ newput interface
 3415: 
 3416: sub newput {
 3417:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3418:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3419:    if (!$uname) { $uname=$env{'user.name'}; }
 3420:    my $uhome=&homeserver($uname,$udomain);
 3421:    my $items='';
 3422:    foreach my $key (keys(%$storehash)) {
 3423:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3424:    }
 3425:    $items=~s/\&$//;
 3426:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3427: }
 3428: 
 3429: # ---------------------------------------------------------  putstore interface
 3430: 
 3431: sub putstore {
 3432:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3433:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3434:    if (!$uname) { $uname=$env{'user.name'}; }
 3435:    my $uhome=&homeserver($uname,$udomain);
 3436:    my $items='';
 3437:    foreach my $key (keys(%$storehash)) {
 3438:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3439:    }
 3440:    $items=~s/\&$//;
 3441:    my $esc_symb=&escape($symb);
 3442:    my $esc_v=&escape($version);
 3443:    my $reply =
 3444:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3445: 	      $uhome);
 3446:    if ($reply eq 'unknown_cmd') {
 3447:        # gfall back to way things use to be done
 3448:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3449: 			    $uname);
 3450:    }
 3451:    return $reply;
 3452: }
 3453: 
 3454: sub old_putstore {
 3455:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3456:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3457:     if (!$uname) { $uname=$env{'user.name'}; }
 3458:     my $uhome=&homeserver($uname,$udomain);
 3459:     my %newstorehash;
 3460:     foreach my $item (keys(%$storehash)) {
 3461: 	my $key = $version.':'.&escape($symb).':'.$item;
 3462: 	$newstorehash{$key} = $storehash->{$item};
 3463:     }
 3464:     my $items='';
 3465:     my %allitems = ();
 3466:     foreach my $item (keys(%newstorehash)) {
 3467: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3468: 	    my $key = $1.':keys:'.$2;
 3469: 	    $allitems{$key} .= $3.':';
 3470: 	}
 3471: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3472:     }
 3473:     foreach my $item (keys(%allitems)) {
 3474: 	$allitems{$item} =~ s/\:$//;
 3475: 	$items.= $item.'='.$allitems{$item}.'&';
 3476:     }
 3477:     $items=~s/\&$//;
 3478:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3479: }
 3480: 
 3481: # ------------------------------------------------------ critical put interface
 3482: 
 3483: sub cput {
 3484:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3485:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3486:    if (!$uname) { $uname=$env{'user.name'}; }
 3487:    my $uhome=&homeserver($uname,$udomain);
 3488:    my $items='';
 3489:    foreach my $item (keys(%$storehash)) {
 3490:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3491:    }
 3492:    $items=~s/\&$//;
 3493:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3494: }
 3495: 
 3496: # -------------------------------------------------------------- eget interface
 3497: 
 3498: sub eget {
 3499:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3500:    my $items='';
 3501:    foreach my $item (@$storearr) {
 3502:        $items.=&escape($item).'&';
 3503:    }
 3504:    $items=~s/\&$//;
 3505:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3506:    if (!$uname) { $uname=$env{'user.name'}; }
 3507:    my $uhome=&homeserver($uname,$udomain);
 3508:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3509:    my @pairs=split(/\&/,$rep);
 3510:    my %returnhash=();
 3511:    my $i=0;
 3512:    foreach my $item (@$storearr) {
 3513:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3514:       $i++;
 3515:    }
 3516:    return %returnhash;
 3517: }
 3518: 
 3519: # ------------------------------------------------------------ tmpput interface
 3520: sub tmpput {
 3521:     my ($storehash,$server,$context)=@_;
 3522:     my $items='';
 3523:     foreach my $item (keys(%$storehash)) {
 3524: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3525:     }
 3526:     $items=~s/\&$//;
 3527:     if (defined($context)) {
 3528:         $items .= ':'.&escape($context);
 3529:     }
 3530:     return &reply("tmpput:$items",$server);
 3531: }
 3532: 
 3533: # ------------------------------------------------------------ tmpget interface
 3534: sub tmpget {
 3535:     my ($token,$server)=@_;
 3536:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3537:     my $rep=&reply("tmpget:$token",$server);
 3538:     my %returnhash;
 3539:     foreach my $item (split(/\&/,$rep)) {
 3540: 	my ($key,$value)=split(/=/,$item);
 3541: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3542:     }
 3543:     return %returnhash;
 3544: }
 3545: 
 3546: # ------------------------------------------------------------ tmpget interface
 3547: sub tmpdel {
 3548:     my ($token,$server)=@_;
 3549:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3550:     return &reply("tmpdel:$token",$server);
 3551: }
 3552: 
 3553: # -------------------------------------------------- portfolio access checking
 3554: 
 3555: sub portfolio_access {
 3556:     my ($requrl) = @_;
 3557:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3558:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3559:     if ($result) {
 3560:         my %setters;
 3561:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3562:             my ($startblock,$endblock) =
 3563:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3564:             if ($startblock && $endblock) {
 3565:                 return 'B';
 3566:             }
 3567:         } else {
 3568:             my ($startblock,$endblock) =
 3569:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3570:             if ($startblock && $endblock) {
 3571:                 return 'B';
 3572:             }
 3573:         }
 3574:     }
 3575:     if ($result eq 'ok') {
 3576:        return 'F';
 3577:     } elsif ($result =~ /^[^:]+:guest_/) {
 3578:        return 'A';
 3579:     }
 3580:     return '';
 3581: }
 3582: 
 3583: sub get_portfolio_access {
 3584:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3585: 
 3586:     if (!ref($access_hash)) {
 3587: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3588: 	my %access_controls = &get_access_controls($current_perms,$group,
 3589: 						   $file_name);
 3590: 	$access_hash = $access_controls{$file_name};
 3591:     }
 3592: 
 3593:     my ($public,$guest,@domains,@users,@courses,@groups);
 3594:     my $now = time;
 3595:     if (ref($access_hash) eq 'HASH') {
 3596:         foreach my $key (keys(%{$access_hash})) {
 3597:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3598:             if ($start > $now) {
 3599:                 next;
 3600:             }
 3601:             if ($end && $end<$now) {
 3602:                 next;
 3603:             }
 3604:             if ($scope eq 'public') {
 3605:                 $public = $key;
 3606:                 last;
 3607:             } elsif ($scope eq 'guest') {
 3608:                 $guest = $key;
 3609:             } elsif ($scope eq 'domains') {
 3610:                 push(@domains,$key);
 3611:             } elsif ($scope eq 'users') {
 3612:                 push(@users,$key);
 3613:             } elsif ($scope eq 'course') {
 3614:                 push(@courses,$key);
 3615:             } elsif ($scope eq 'group') {
 3616:                 push(@groups,$key);
 3617:             }
 3618:         }
 3619:         if ($public) {
 3620:             return 'ok';
 3621:         }
 3622:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3623:             if ($guest) {
 3624:                 return $guest;
 3625:             }
 3626:         } else {
 3627:             if (@domains > 0) {
 3628:                 foreach my $domkey (@domains) {
 3629:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 3630:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 3631:                             return 'ok';
 3632:                         }
 3633:                     }
 3634:                 }
 3635:             }
 3636:             if (@users > 0) {
 3637:                 foreach my $userkey (@users) {
 3638:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 3639:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 3640:                             if (ref($item) eq 'HASH') {
 3641:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 3642:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 3643:                                     return 'ok';
 3644:                                 }
 3645:                             }
 3646:                         }
 3647:                     } 
 3648:                 }
 3649:             }
 3650:             my %roleshash;
 3651:             my @courses_and_groups = @courses;
 3652:             push(@courses_and_groups,@groups); 
 3653:             if (@courses_and_groups > 0) {
 3654:                 my (%allgroups,%allroles); 
 3655:                 my ($start,$end,$role,$sec,$group);
 3656:                 foreach my $envkey (%env) {
 3657:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3658:                         my $cid = $2.'_'.$3; 
 3659:                         if ($1 eq 'gr') {
 3660:                             $group = $4;
 3661:                             $allgroups{$cid}{$group} = $env{$envkey};
 3662:                         } else {
 3663:                             if ($4 eq '') {
 3664:                                 $sec = 'none';
 3665:                             } else {
 3666:                                 $sec = $4;
 3667:                             }
 3668:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3669:                         }
 3670:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 3671:                         my $cid = $2.'_'.$3;
 3672:                         if ($4 eq '') {
 3673:                             $sec = 'none';
 3674:                         } else {
 3675:                             $sec = $4;
 3676:                         }
 3677:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 3678:                     }
 3679:                 }
 3680:                 if (keys(%allroles) == 0) {
 3681:                     return;
 3682:                 }
 3683:                 foreach my $key (@courses_and_groups) {
 3684:                     my %content = %{$$access_hash{$key}};
 3685:                     my $cnum = $content{'number'};
 3686:                     my $cdom = $content{'domain'};
 3687:                     my $cid = $cdom.'_'.$cnum;
 3688:                     if (!exists($allroles{$cid})) {
 3689:                         next;
 3690:                     }    
 3691:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 3692:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 3693:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 3694:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 3695:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 3696:                         foreach my $role (keys(%{$allroles{$cid}})) {
 3697:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 3698:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 3699:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 3700:                                         if (grep/^all$/,@sections) {
 3701:                                             return 'ok';
 3702:                                         } else {
 3703:                                             if (grep/^$sec$/,@sections) {
 3704:                                                 return 'ok';
 3705:                                             }
 3706:                                         }
 3707:                                     }
 3708:                                 }
 3709:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 3710:                                     if (grep/^none$/,@groups) {
 3711:                                         return 'ok';
 3712:                                     }
 3713:                                 } else {
 3714:                                     if (grep/^all$/,@groups) {
 3715:                                         return 'ok';
 3716:                                     } 
 3717:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 3718:                                         if (grep/^$group$/,@groups) {
 3719:                                             return 'ok';
 3720:                                         }
 3721:                                     }
 3722:                                 } 
 3723:                             }
 3724:                         }
 3725:                     }
 3726:                 }
 3727:             }
 3728:             if ($guest) {
 3729:                 return $guest;
 3730:             }
 3731:         }
 3732:     }
 3733:     return;
 3734: }
 3735: 
 3736: sub course_group_datechecker {
 3737:     my ($dates,$now,$status) = @_;
 3738:     my ($start,$end) = split(/\./,$dates);
 3739:     if (!$start && !$end) {
 3740:         return 'ok';
 3741:     }
 3742:     if (grep/^active$/,@{$status}) {
 3743:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 3744:             return 'ok';
 3745:         }
 3746:     }
 3747:     if (grep/^previous$/,@{$status}) {
 3748:         if ($end > $now ) {
 3749:             return 'ok';
 3750:         }
 3751:     }
 3752:     if (grep/^future$/,@{$status}) {
 3753:         if ($start > $now) {
 3754:             return 'ok';
 3755:         }
 3756:     }
 3757:     return; 
 3758: }
 3759: 
 3760: sub parse_portfolio_url {
 3761:     my ($url) = @_;
 3762: 
 3763:     my ($type,$udom,$unum,$group,$file_name);
 3764:     
 3765:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 3766: 	$type = 1;
 3767:         $udom = $1;
 3768:         $unum = $2;
 3769:         $file_name = $3;
 3770:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 3771: 	$type = 2;
 3772:         $udom = $1;
 3773:         $unum = $2;
 3774:         $group = $3;
 3775:         $file_name = $3.'/'.$4;
 3776:     }
 3777:     if (wantarray) {
 3778: 	return ($type,$udom,$unum,$file_name,$group);
 3779:     }
 3780:     return $type;
 3781: }
 3782: 
 3783: sub is_portfolio_url {
 3784:     my ($url) = @_;
 3785:     return scalar(&parse_portfolio_url($url));
 3786: }
 3787: 
 3788: sub is_portfolio_file {
 3789:     my ($file) = @_;
 3790:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 3791:         return 1;
 3792:     }
 3793:     return;
 3794: }
 3795: 
 3796: 
 3797: # ---------------------------------------------- Custom access rule evaluation
 3798: 
 3799: sub customaccess {
 3800:     my ($priv,$uri)=@_;
 3801:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 3802:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 3803:     $udom = &LONCAPA::clean_domain($udom);
 3804:     $ucrs = &LONCAPA::clean_username($ucrs);
 3805:     my $access=0;
 3806:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 3807: 	my ($effect,$realm,$role)=split(/\:/,$right);
 3808:         if ($role) {
 3809: 	   if ($role ne $urole) { next; }
 3810:         }
 3811:         foreach my $scope (split(/\s*\,\s*/,$realm)) {
 3812:             my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 3813:             if ($tdom) {
 3814: 		if ($tdom ne $udom) { next; }
 3815:             }
 3816:             if ($tcrs) {
 3817: 		if ($tcrs ne $ucrs) { next; }
 3818:             }
 3819:             if ($tsec) {
 3820: 		if ($tsec ne $usec) { next; }
 3821:             }
 3822:             $access=($effect eq 'allow');
 3823:             last;
 3824:         }
 3825: 	if ($realm eq '' && $role eq '') {
 3826:             $access=($effect eq 'allow');
 3827: 	}
 3828:     }
 3829:     return $access;
 3830: }
 3831: 
 3832: # ------------------------------------------------- Check for a user privilege
 3833: 
 3834: sub allowed {
 3835:     my ($priv,$uri,$symb,$role)=@_;
 3836:     my $ver_orguri=$uri;
 3837:     $uri=&deversion($uri);
 3838:     my $orguri=$uri;
 3839:     $uri=&declutter($uri);
 3840: 
 3841:     if ($priv eq 'evb') {
 3842: # Evade communication block restrictions for specified role in a course
 3843:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 3844:             return $1;
 3845:         } else {
 3846:             return;
 3847:         }
 3848:     }
 3849: 
 3850:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 3851: # Free bre access to adm and meta resources
 3852:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 3853: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 3854: 	&& ($priv eq 'bre')) {
 3855: 	return 'F';
 3856:     }
 3857: 
 3858: # Free bre access to user's own portfolio contents
 3859:     my ($space,$domain,$name,@dir)=split('/',$uri);
 3860:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 3861: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 3862:         my %setters;
 3863:         my ($startblock,$endblock) = 
 3864:             &Apache::loncommon::blockcheck(\%setters,'port');
 3865:         if ($startblock && $endblock) {
 3866:             return 'B';
 3867:         } else {
 3868:             return 'F';
 3869:         }
 3870:     }
 3871: 
 3872: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 3873:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 3874:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 3875:         if (exists($env{'request.course.id'})) {
 3876:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3877:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3878:             if (($domain eq $cdom) && ($name eq $cnum)) {
 3879:                 my $courseprivid=$env{'request.course.id'};
 3880:                 $courseprivid=~s/\_/\//;
 3881:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 3882:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 3883:                     return $1; 
 3884:                 } else {
 3885:                     if ($env{'request.course.sec'}) {
 3886:                         $courseprivid.='/'.$env{'request.course.sec'};
 3887:                     }
 3888:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 3889:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 3890:                         return $2;
 3891:                     }
 3892:                 }
 3893:             }
 3894:         }
 3895:     }
 3896: 
 3897: # Free bre to public access
 3898: 
 3899:     if ($priv eq 'bre') {
 3900:         my $copyright=&metadata($uri,'copyright');
 3901: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 3902:            return 'F'; 
 3903:         }
 3904:         if ($copyright eq 'priv') {
 3905:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3906: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 3907: 		return '';
 3908:             }
 3909:         }
 3910:         if ($copyright eq 'domain') {
 3911:             $uri=~/([^\/]+)\/([^\/]+)\//;
 3912: 	    unless (($env{'user.domain'} eq $1) ||
 3913:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 3914: 		return '';
 3915:             }
 3916:         }
 3917:         if ($env{'request.role'}=~ /li\.\//) {
 3918:             # Library role, so allow browsing of resources in this domain.
 3919:             return 'F';
 3920:         }
 3921:         if ($copyright eq 'custom') {
 3922: 	    unless (&customaccess($priv,$uri)) { return ''; }
 3923:         }
 3924:     }
 3925:     # Domain coordinator is trying to create a course
 3926:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 3927:         # uri is the requested domain in this case.
 3928:         # comparison to 'request.role.domain' shows if the user has selected
 3929:         # a role of dc for the domain in question.
 3930:         return 'F' if ($uri eq $env{'request.role.domain'});
 3931:     }
 3932: 
 3933:     my $thisallowed='';
 3934:     my $statecond=0;
 3935:     my $courseprivid='';
 3936: 
 3937: # Course
 3938: 
 3939:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 3940:        $thisallowed.=$1;
 3941:     }
 3942: 
 3943: # Domain
 3944: 
 3945:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 3946:        =~/\Q$priv\E\&([^\:]*)/) {
 3947:        $thisallowed.=$1;
 3948:     }
 3949: 
 3950: # Course: uri itself is a course
 3951:     my $courseuri=$uri;
 3952:     $courseuri=~s/\_(\d)/\/$1/;
 3953:     $courseuri=~s/^([^\/])/\/$1/;
 3954: 
 3955:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 3956:        =~/\Q$priv\E\&([^\:]*)/) {
 3957:        $thisallowed.=$1;
 3958:     }
 3959: 
 3960: # URI is an uploaded document for this course, default permissions don't matter
 3961: # not allowing 'edit' access (editupload) to uploaded course docs
 3962:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 3963: 	$thisallowed='';
 3964:         my ($match)=&is_on_map($uri);
 3965:         if ($match) {
 3966:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 3967:                   =~/\Q$priv\E\&([^\:]*)/) {
 3968:                 $thisallowed.=$1;
 3969:             }
 3970:         } else {
 3971:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 3972:             if ($refuri) {
 3973:                 if ($refuri =~ m|^/adm/|) {
 3974:                     $thisallowed='F';
 3975:                 } else {
 3976:                     $refuri=&declutter($refuri);
 3977:                     my ($match) = &is_on_map($refuri);
 3978:                     if ($match) {
 3979:                         $thisallowed='F';
 3980:                     }
 3981:                 }
 3982:             }
 3983:         }
 3984:     }
 3985: 
 3986:     if ($priv eq 'bre'
 3987: 	&& $thisallowed ne 'F' 
 3988: 	&& $thisallowed ne '2'
 3989: 	&& &is_portfolio_url($uri)) {
 3990: 	$thisallowed = &portfolio_access($uri);
 3991:     }
 3992:     
 3993: # Full access at system, domain or course-wide level? Exit.
 3994: 
 3995:     if ($thisallowed=~/F/) {
 3996: 	return 'F';
 3997:     }
 3998: 
 3999: # If this is generating or modifying users, exit with special codes
 4000: 
 4001:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4002: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4003: 	    my ($audom,$auname)=split('/',$uri);
 4004: # no author name given, so this just checks on the general right to make a co-author in this domain
 4005: 	    unless ($auname) { return $thisallowed; }
 4006: # an author name is given, so we are about to actually make a co-author for a certain account
 4007: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4008: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4009: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4010: 	}
 4011: 	return $thisallowed;
 4012:     }
 4013: #
 4014: # Gathered so far: system, domain and course wide privileges
 4015: #
 4016: # Course: See if uri or referer is an individual resource that is part of 
 4017: # the course
 4018: 
 4019:     if ($env{'request.course.id'}) {
 4020: 
 4021:        $courseprivid=$env{'request.course.id'};
 4022:        if ($env{'request.course.sec'}) {
 4023:           $courseprivid.='/'.$env{'request.course.sec'};
 4024:        }
 4025:        $courseprivid=~s/\_/\//;
 4026:        my $checkreferer=1;
 4027:        my ($match,$cond)=&is_on_map($uri);
 4028:        if ($match) {
 4029:            $statecond=$cond;
 4030:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4031:                =~/\Q$priv\E\&([^\:]*)/) {
 4032:                $thisallowed.=$1;
 4033:                $checkreferer=0;
 4034:            }
 4035:        }
 4036:        
 4037:        if ($checkreferer) {
 4038: 	  my $refuri=$env{'httpref.'.$orguri};
 4039:             unless ($refuri) {
 4040:                 foreach my $key (keys(%env)) {
 4041: 		    if ($key=~/^httpref\..*\*/) {
 4042: 			my $pattern=$key;
 4043:                         $pattern=~s/^httpref\.\/res\///;
 4044:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4045:                         $pattern=~s/\//\\\//g;
 4046:                         if ($orguri=~/$pattern/) {
 4047: 			    $refuri=$env{$key};
 4048:                         }
 4049:                     }
 4050:                 }
 4051:             }
 4052: 
 4053:          if ($refuri) { 
 4054: 	  $refuri=&declutter($refuri);
 4055:           my ($match,$cond)=&is_on_map($refuri);
 4056:             if ($match) {
 4057:               my $refstatecond=$cond;
 4058:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4059:                   =~/\Q$priv\E\&([^\:]*)/) {
 4060:                   $thisallowed.=$1;
 4061:                   $uri=$refuri;
 4062:                   $statecond=$refstatecond;
 4063:               }
 4064:           }
 4065:         }
 4066:        }
 4067:    }
 4068: 
 4069: #
 4070: # Gathered now: all privileges that could apply, and condition number
 4071: # 
 4072: #
 4073: # Full or no access?
 4074: #
 4075: 
 4076:     if ($thisallowed=~/F/) {
 4077: 	return 'F';
 4078:     }
 4079: 
 4080:     unless ($thisallowed) {
 4081:         return '';
 4082:     }
 4083: 
 4084: # Restrictions exist, deal with them
 4085: #
 4086: #   C:according to course preferences
 4087: #   R:according to resource settings
 4088: #   L:unless locked
 4089: #   X:according to user session state
 4090: #
 4091: 
 4092: # Possibly locked functionality, check all courses
 4093: # Locks might take effect only after 10 minutes cache expiration for other
 4094: # courses, and 2 minutes for current course
 4095: 
 4096:     my $envkey;
 4097:     if ($thisallowed=~/L/) {
 4098:         foreach $envkey (keys %env) {
 4099:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4100:                my $courseid=$2;
 4101:                my $roleid=$1.'.'.$2;
 4102:                $courseid=~s/^\///;
 4103:                my $expiretime=600;
 4104:                if ($env{'request.role'} eq $roleid) {
 4105: 		  $expiretime=120;
 4106:                }
 4107: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4108:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4109:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4110: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4111:                }
 4112:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4113:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4114: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4115:                        &log($env{'user.domain'},$env{'user.name'},
 4116:                             $env{'user.home'},
 4117:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4118:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4119:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4120: 		       return '';
 4121:                    }
 4122:                }
 4123:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4124:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4125: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4126:                        &log($env{'user.domain'},$env{'user.name'},
 4127:                             $env{'user.home'},
 4128:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4129:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4130:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4131: 		       return '';
 4132:                    }
 4133:                }
 4134: 	   }
 4135:        }
 4136:     }
 4137:    
 4138: #
 4139: # Rest of the restrictions depend on selected course
 4140: #
 4141: 
 4142:     unless ($env{'request.course.id'}) {
 4143: 	if ($thisallowed eq 'A') {
 4144: 	    return 'A';
 4145:         } elsif ($thisallowed eq 'B') {
 4146:             return 'B';
 4147: 	} else {
 4148: 	    return '1';
 4149: 	}
 4150:     }
 4151: 
 4152: #
 4153: # Now user is definitely in a course
 4154: #
 4155: 
 4156: 
 4157: # Course preferences
 4158: 
 4159:    if ($thisallowed=~/C/) {
 4160:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4161:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4162:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4163: 	   =~/\Q$rolecode\E/) {
 4164: 	   if ($priv ne 'pch') { 
 4165: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4166: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4167: 			$env{'request.course.id'});
 4168: 	   }
 4169:            return '';
 4170:        }
 4171: 
 4172:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4173: 	   =~/\Q$unamedom\E/) {
 4174: 	   if ($priv ne 'pch') { 
 4175: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4176: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4177: 			$env{'request.course.id'});
 4178: 	   }
 4179:            return '';
 4180:        }
 4181:    }
 4182: 
 4183: # Resource preferences
 4184: 
 4185:    if ($thisallowed=~/R/) {
 4186:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4187:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4188: 	   if ($priv ne 'pch') { 
 4189: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4190: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4191: 	   }
 4192: 	   return '';
 4193:        }
 4194:    }
 4195: 
 4196: # Restricted by state or randomout?
 4197: 
 4198:    if ($thisallowed=~/X/) {
 4199:       if ($env{'acc.randomout'}) {
 4200: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4201:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4202:             return ''; 
 4203:          }
 4204:       }
 4205:       if (&condval($statecond)) {
 4206: 	 return '2';
 4207:       } else {
 4208:          return '';
 4209:       }
 4210:    }
 4211: 
 4212:     if ($thisallowed eq 'A') {
 4213: 	return 'A';
 4214:     } elsif ($thisallowed eq 'B') {
 4215:         return 'B';
 4216:     }
 4217:    return 'F';
 4218: }
 4219: 
 4220: sub split_uri_for_cond {
 4221:     my $uri=&deversion(&declutter(shift));
 4222:     my @uriparts=split(/\//,$uri);
 4223:     my $filename=pop(@uriparts);
 4224:     my $pathname=join('/',@uriparts);
 4225:     return ($pathname,$filename);
 4226: }
 4227: # --------------------------------------------------- Is a resource on the map?
 4228: 
 4229: sub is_on_map {
 4230:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4231:     #Trying to find the conditional for the file
 4232:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4233: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4234:     if ($match) {
 4235: 	return (1,$1);
 4236:     } else {
 4237: 	return (0,0);
 4238:     }
 4239: }
 4240: 
 4241: # --------------------------------------------------------- Get symb from alias
 4242: 
 4243: sub get_symb_from_alias {
 4244:     my $symb=shift;
 4245:     my ($map,$resid,$url)=&decode_symb($symb);
 4246: # Already is a symb
 4247:     if ($url) { return $symb; }
 4248: # Must be an alias
 4249:     my $aliassymb='';
 4250:     my %bighash;
 4251:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4252:                             &GDBM_READER(),0640)) {
 4253:         my $rid=$bighash{'mapalias_'.$symb};
 4254: 	if ($rid) {
 4255: 	    my ($mapid,$resid)=split(/\./,$rid);
 4256: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4257: 				    $resid,$bighash{'src_'.$rid});
 4258: 	}
 4259:         untie %bighash;
 4260:     }
 4261:     return $aliassymb;
 4262: }
 4263: 
 4264: # ----------------------------------------------------------------- Define Role
 4265: 
 4266: sub definerole {
 4267:   if (allowed('mcr','/')) {
 4268:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4269:     foreach my $role (split(':',$sysrole)) {
 4270: 	my ($crole,$cqual)=split(/\&/,$role);
 4271:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4272:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4273: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4274:                return "refused:s:$crole&$cqual"; 
 4275:             }
 4276:         }
 4277:     }
 4278:     foreach my $role (split(':',$domrole)) {
 4279: 	my ($crole,$cqual)=split(/\&/,$role);
 4280:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4281:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4282: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4283:                return "refused:d:$crole&$cqual"; 
 4284:             }
 4285:         }
 4286:     }
 4287:     foreach my $role (split(':',$courole)) {
 4288: 	my ($crole,$cqual)=split(/\&/,$role);
 4289:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4290:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4291: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4292:                return "refused:c:$crole&$cqual"; 
 4293:             }
 4294:         }
 4295:     }
 4296:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4297:                 "$env{'user.domain'}:$env{'user.name'}:".
 4298: 	        "rolesdef_$rolename=".
 4299:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4300:     return reply($command,$env{'user.home'});
 4301:   } else {
 4302:     return 'refused';
 4303:   }
 4304: }
 4305: 
 4306: # ---------------- Make a metadata query against the network of library servers
 4307: 
 4308: sub metadata_query {
 4309:     my ($query,$custom,$customshow,$server_array)=@_;
 4310:     my %rhash;
 4311:     my %libserv = &all_library();
 4312:     my @server_list = (defined($server_array) ? @$server_array
 4313:                                               : keys(%libserv) );
 4314:     for my $server (@server_list) {
 4315: 	unless ($custom or $customshow) {
 4316: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4317: 	    $rhash{$server}=$reply;
 4318: 	}
 4319: 	else {
 4320: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4321: 			     &escape($custom).':'.&escape($customshow),
 4322: 			     $server);
 4323: 	    $rhash{$server}=$reply;
 4324: 	}
 4325:     }
 4326:     return \%rhash;
 4327: }
 4328: 
 4329: # ----------------------------------------- Send log queries and wait for reply
 4330: 
 4331: sub log_query {
 4332:     my ($uname,$udom,$query,%filters)=@_;
 4333:     my $uhome=&homeserver($uname,$udom);
 4334:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4335:     my $uhost=&hostname($uhome);
 4336:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4337:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4338:                        $uhome);
 4339:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4340:     return get_query_reply($queryid);
 4341: }
 4342: 
 4343: # -------------------------- Update MySQL table for portfolio file
 4344: 
 4345: sub update_portfolio_table {
 4346:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4347:     my $homeserver = &homeserver($uname,$udom);
 4348:     my $queryid=
 4349:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4350:                ':'.&escape($file_name).':'.$action,$homeserver);
 4351:     my $reply = &get_query_reply($queryid);
 4352:     return $reply;
 4353: }
 4354: 
 4355: # ------- Request retrieval of institutional classlists for course(s)
 4356: 
 4357: sub fetch_enrollment_query {
 4358:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4359:     my $homeserver;
 4360:     my $maxtries = 1;
 4361:     if ($context eq 'automated') {
 4362:         $homeserver = $perlvar{'lonHostID'};
 4363:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4364:     } else {
 4365:         $homeserver = &homeserver($cnum,$dom);
 4366:     }
 4367:     my $host=&hostname($homeserver);
 4368:     my $cmd = '';
 4369:     foreach my $affiliate (keys %{$affiliatesref}) {
 4370:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4371:     }
 4372:     $cmd =~ s/%%$//;
 4373:     $cmd = &escape($cmd);
 4374:     my $query = 'fetchenrollment';
 4375:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4376:     unless ($queryid=~/^\Q$host\E\_/) { 
 4377:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4378:         return 'error: '.$queryid;
 4379:     }
 4380:     my $reply = &get_query_reply($queryid);
 4381:     my $tries = 1;
 4382:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4383:         $reply = &get_query_reply($queryid);
 4384:         $tries ++;
 4385:     }
 4386:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4387:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4388:     } else {
 4389:         my @responses = split/:/,$reply;
 4390:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4391:             foreach my $line (@responses) {
 4392:                 my ($key,$value) = split(/=/,$line,2);
 4393:                 $$replyref{$key} = $value;
 4394:             }
 4395:         } else {
 4396:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4397:             foreach my $line (@responses) {
 4398:                 my ($key,$value) = split(/=/,$line);
 4399:                 $$replyref{$key} = $value;
 4400:                 if ($value > 0) {
 4401:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4402:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4403:                         my $destname = $pathname.'/'.$filename;
 4404:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4405:                         if ($xml_classlist =~ /^error/) {
 4406:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4407:                         } else {
 4408:                             if ( open(FILE,">$destname") ) {
 4409:                                 print FILE &unescape($xml_classlist);
 4410:                                 close(FILE);
 4411:                             } else {
 4412:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4413:                             }
 4414:                         }
 4415:                     }
 4416:                 }
 4417:             }
 4418:         }
 4419:         return 'ok';
 4420:     }
 4421:     return 'error';
 4422: }
 4423: 
 4424: sub get_query_reply {
 4425:     my $queryid=shift;
 4426:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4427:     my $reply='';
 4428:     for (1..100) {
 4429: 	sleep 2;
 4430:         if (-e $replyfile.'.end') {
 4431: 	    if (open(my $fh,$replyfile)) {
 4432:                $reply.=<$fh>;
 4433:                close($fh);
 4434: 	   } else { return 'error: reply_file_error'; }
 4435:            return &unescape($reply);
 4436: 	}
 4437:     }
 4438:     return 'timeout:'.$queryid;
 4439: }
 4440: 
 4441: sub courselog_query {
 4442: #
 4443: # possible filters:
 4444: # url: url or symb
 4445: # username
 4446: # domain
 4447: # action: view, submit, grade
 4448: # start: timestamp
 4449: # end: timestamp
 4450: #
 4451:     my (%filters)=@_;
 4452:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4453:     if ($filters{'url'}) {
 4454: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4455:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4456:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4457:     }
 4458:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4459:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4460:     return &log_query($cname,$cdom,'courselog',%filters);
 4461: }
 4462: 
 4463: sub userlog_query {
 4464: #
 4465: # possible filters:
 4466: # action: log check role
 4467: # start: timestamp
 4468: # end: timestamp
 4469: #
 4470:     my ($uname,$udom,%filters)=@_;
 4471:     return &log_query($uname,$udom,'userlog',%filters);
 4472: }
 4473: 
 4474: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4475: 
 4476: sub auto_run {
 4477:     my ($cnum,$cdom) = @_;
 4478:     my $response = 0;
 4479:     my $settings;
 4480:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 4481:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4482:         $settings = $domconfig{'autoenroll'};
 4483:         if ($settings->{'run'} eq '1') {
 4484:             $response = 1;
 4485:         }
 4486:     } else {
 4487:         my $homeserver = &homeserver($cnum,$cdom);
 4488:         $response = &reply('autorun:'.$cdom,$homeserver);
 4489:     }
 4490:     return $response;
 4491: }
 4492: 
 4493: sub auto_get_sections {
 4494:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4495:     my $homeserver = &homeserver($cnum,$cdom);
 4496:     my @secs = ();
 4497:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4498:     unless ($response eq 'refused') {
 4499:         @secs = split/:/,$response;
 4500:     }
 4501:     return @secs;
 4502: }
 4503: 
 4504: sub auto_new_course {
 4505:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4506:     my $homeserver = &homeserver($cnum,$cdom);
 4507:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4508:     return $response;
 4509: }
 4510: 
 4511: sub auto_validate_courseID {
 4512:     my ($cnum,$cdom,$inst_course_id) = @_;
 4513:     my $homeserver = &homeserver($cnum,$cdom);
 4514:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4515:     return $response;
 4516: }
 4517: 
 4518: sub auto_create_password {
 4519:     my ($cnum,$cdom,$authparam,$udom) = @_;
 4520:     my ($homeserver,$response);
 4521:     my $create_passwd = 0;
 4522:     my $authchk = '';
 4523:     if ($udom =~ /^$match_domain$/) {
 4524:         $homeserver = &domain($udom,'primary');
 4525:     }
 4526:     if ($homeserver eq '') {
 4527:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 4528:             $homeserver = &homeserver($cnum,$cdom);
 4529:         }
 4530:     }
 4531:     if ($homeserver eq '') {
 4532:         $authchk = 'nodomain';
 4533:     } else {
 4534:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4535:         if ($response eq 'refused') {
 4536:             $authchk = 'refused';
 4537:         } else {
 4538:             ($authparam,$create_passwd,$authchk) = split/:/,$response;
 4539:         }
 4540:     }
 4541:     return ($authparam,$create_passwd,$authchk);
 4542: }
 4543: 
 4544: sub auto_photo_permission {
 4545:     my ($cnum,$cdom,$students) = @_;
 4546:     my $homeserver = &homeserver($cnum,$cdom);
 4547:     my ($outcome,$perm_reqd,$conditions) = 
 4548: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4549:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4550: 	return (undef,undef);
 4551:     }
 4552:     return ($outcome,$perm_reqd,$conditions);
 4553: }
 4554: 
 4555: sub auto_checkphotos {
 4556:     my ($uname,$udom,$pid) = @_;
 4557:     my $homeserver = &homeserver($uname,$udom);
 4558:     my ($result,$resulttype);
 4559:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4560: 				   &escape($uname).':'.&escape($pid),
 4561: 				   $homeserver));
 4562:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4563: 	return (undef,undef);
 4564:     }
 4565:     if ($outcome) {
 4566:         ($result,$resulttype) = split(/:/,$outcome);
 4567:     } 
 4568:     return ($result,$resulttype);
 4569: }
 4570: 
 4571: sub auto_photochoice {
 4572:     my ($cnum,$cdom) = @_;
 4573:     my $homeserver = &homeserver($cnum,$cdom);
 4574:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4575: 						       &escape($cdom),
 4576: 						       $homeserver)));
 4577:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4578: 	return (undef,undef);
 4579:     }
 4580:     return ($update,$comment);
 4581: }
 4582: 
 4583: sub auto_photoupdate {
 4584:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 4585:     my $homeserver = &homeserver($cnum,$dom);
 4586:     my $host=&hostname($homeserver);
 4587:     my $cmd = '';
 4588:     my $maxtries = 1;
 4589:     foreach my $affiliate (keys(%{$affiliatesref})) {
 4590:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4591:     }
 4592:     $cmd =~ s/%%$//;
 4593:     $cmd = &escape($cmd);
 4594:     my $query = 'institutionalphotos';
 4595:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 4596:     unless ($queryid=~/^\Q$host\E\_/) {
 4597:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 4598:         return 'error: '.$queryid;
 4599:     }
 4600:     my $reply = &get_query_reply($queryid);
 4601:     my $tries = 1;
 4602:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4603:         $reply = &get_query_reply($queryid);
 4604:         $tries ++;
 4605:     }
 4606:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4607:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4608:     } else {
 4609:         my @responses = split(/:/,$reply);
 4610:         my $outcome = shift(@responses); 
 4611:         foreach my $item (@responses) {
 4612:             my ($key,$value) = split(/=/,$item);
 4613:             $$photo{$key} = $value;
 4614:         }
 4615:         return $outcome;
 4616:     }
 4617:     return 'error';
 4618: }
 4619: 
 4620: sub auto_instcode_format {
 4621:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 4622: 	$cat_order) = @_;
 4623:     my $courses = '';
 4624:     my @homeservers;
 4625:     if ($caller eq 'global') {
 4626: 	my %servers = &get_servers($codedom,'library');
 4627: 	foreach my $tryserver (keys(%servers)) {
 4628: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4629: 		push(@homeservers,$tryserver);
 4630: 	    }
 4631:         }
 4632:     } else {
 4633:         push(@homeservers,&homeserver($caller,$codedom));
 4634:     }
 4635:     foreach my $code (keys(%{$instcodes})) {
 4636:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 4637:     }
 4638:     chop($courses);
 4639:     my $ok_response = 0;
 4640:     my $response;
 4641:     while (@homeservers > 0 && $ok_response == 0) {
 4642:         my $server = shift(@homeservers); 
 4643:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 4644:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 4645:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 4646: 		split/:/,$response;
 4647:             %{$codes} = (%{$codes},&str2hash($codes_str));
 4648:             push(@{$codetitles},&str2array($codetitles_str));
 4649:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 4650:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 4651:             $ok_response = 1;
 4652:         }
 4653:     }
 4654:     if ($ok_response) {
 4655:         return 'ok';
 4656:     } else {
 4657:         return $response;
 4658:     }
 4659: }
 4660: 
 4661: sub auto_instcode_defaults {
 4662:     my ($domain,$returnhash,$code_order) = @_;
 4663:     my @homeservers;
 4664: 
 4665:     my %servers = &get_servers($domain,'library');
 4666:     foreach my $tryserver (keys(%servers)) {
 4667: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 4668: 	    push(@homeservers,$tryserver);
 4669: 	}
 4670:     }
 4671: 
 4672:     my $response;
 4673:     foreach my $server (@homeservers) {
 4674:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 4675:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 4676: 	
 4677: 	foreach my $pair (split(/\&/,$response)) {
 4678: 	    my ($name,$value)=split(/\=/,$pair);
 4679: 	    if ($name eq 'code_order') {
 4680: 		@{$code_order} = split(/\&/,&unescape($value));
 4681: 	    } else {
 4682: 		$returnhash->{&unescape($name)}=&unescape($value);
 4683: 	    }
 4684: 	}
 4685: 	return 'ok';
 4686:     }
 4687: 
 4688:     return $response;
 4689: } 
 4690: 
 4691: sub auto_validate_class_sec {
 4692:     my ($cdom,$cnum,$owner,$inst_class) = @_;
 4693:     my $homeserver = &homeserver($cnum,$cdom);
 4694:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 4695:                         &escape($owner).':'.$cdom,$homeserver);
 4696:     return $response;
 4697: }
 4698: 
 4699: # ------------------------------------------------------- Course Group routines
 4700: 
 4701: sub get_coursegroups {
 4702:     my ($cdom,$cnum,$group,$namespace) = @_;
 4703:     return(&dump($namespace,$cdom,$cnum,$group));
 4704: }
 4705: 
 4706: sub modify_coursegroup {
 4707:     my ($cdom,$cnum,$groupsettings) = @_;
 4708:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 4709: }
 4710: 
 4711: sub toggle_coursegroup_status {
 4712:     my ($cdom,$cnum,$group,$action) = @_;
 4713:     my ($from_namespace,$to_namespace);
 4714:     if ($action eq 'delete') {
 4715:         $from_namespace = 'coursegroups';
 4716:         $to_namespace = 'deleted_groups';
 4717:     } else {
 4718:         $from_namespace = 'deleted_groups';
 4719:         $to_namespace = 'coursegroups';
 4720:     }
 4721:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 4722:     if (my $tmp = &error(%curr_group)) {
 4723:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 4724:         return ('read error',$tmp);
 4725:     } else {
 4726:         my %savedsettings = %curr_group; 
 4727:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 4728:         my $deloutcome;
 4729:         if ($result eq 'ok') {
 4730:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 4731:         } else {
 4732:             return ('write error',$result);
 4733:         }
 4734:         if ($deloutcome eq 'ok') {
 4735:             return 'ok';
 4736:         } else {
 4737:             return ('delete error',$deloutcome);
 4738:         }
 4739:     }
 4740: }
 4741: 
 4742: sub modify_group_roles {
 4743:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 4744:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 4745:     my $role = 'gr/'.&escape($userprivs);
 4746:     my ($uname,$udom) = split(/:/,$user);
 4747:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 4748:     if ($result eq 'ok') {
 4749:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 4750:     }
 4751:     return $result;
 4752: }
 4753: 
 4754: sub modify_coursegroup_membership {
 4755:     my ($cdom,$cnum,$membership) = @_;
 4756:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 4757:     return $result;
 4758: }
 4759: 
 4760: sub get_active_groups {
 4761:     my ($udom,$uname,$cdom,$cnum) = @_;
 4762:     my $now = time;
 4763:     my %groups = ();
 4764:     foreach my $key (keys(%env)) {
 4765:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 4766:             my ($start,$end) = split(/\./,$env{$key});
 4767:             if (($end!=0) && ($end<$now)) { next; }
 4768:             if (($start!=0) && ($start>$now)) { next; }
 4769:             if ($1 eq $cdom && $2 eq $cnum) {
 4770:                 $groups{$3} = $env{$key} ;
 4771:             }
 4772:         }
 4773:     }
 4774:     return %groups;
 4775: }
 4776: 
 4777: sub get_group_membership {
 4778:     my ($cdom,$cnum,$group) = @_;
 4779:     return(&dump('groupmembership',$cdom,$cnum,$group));
 4780: }
 4781: 
 4782: sub get_users_groups {
 4783:     my ($udom,$uname,$courseid) = @_;
 4784:     my @usersgroups;
 4785:     my $cachetime=1800;
 4786: 
 4787:     my $hashid="$udom:$uname:$courseid";
 4788:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 4789:     if (defined($cached)) {
 4790:         @usersgroups = split(/:/,$grouplist);
 4791:     } else {  
 4792:         $grouplist = '';
 4793:         my $courseurl = &courseid_to_courseurl($courseid);
 4794:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 4795:         my $access_end = $env{'course.'.$courseid.
 4796:                               '.default_enrollment_end_date'};
 4797:         my $now = time;
 4798:         foreach my $key (keys(%roleshash)) {
 4799:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 4800:                 my $group = $1;
 4801:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 4802:                     my $start = $2;
 4803:                     my $end = $1;
 4804:                     if ($start == -1) { next; } # deleted from group
 4805:                     if (($start!=0) && ($start>$now)) { next; }
 4806:                     if (($end!=0) && ($end<$now)) {
 4807:                         if ($access_end && $access_end < $now) {
 4808:                             if ($access_end - $end < 86400) {
 4809:                                 push(@usersgroups,$group);
 4810:                             }
 4811:                         }
 4812:                         next;
 4813:                     }
 4814:                     push(@usersgroups,$group);
 4815:                 }
 4816:             }
 4817:         }
 4818:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 4819:         $grouplist = join(':',@usersgroups);
 4820:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 4821:     }
 4822:     return @usersgroups;
 4823: }
 4824: 
 4825: sub devalidate_getgroups_cache {
 4826:     my ($udom,$uname,$cdom,$cnum)=@_;
 4827:     my $courseid = $cdom.'_'.$cnum;
 4828: 
 4829:     my $hashid="$udom:$uname:$courseid";
 4830:     &devalidate_cache_new('getgroups',$hashid);
 4831: }
 4832: 
 4833: # ------------------------------------------------------------------ Plain Text
 4834: 
 4835: sub plaintext {
 4836:     my ($short,$type,$cid) = @_;
 4837:     if ($short =~ /^cr/) {
 4838: 	return (split('/',$short))[-1];
 4839:     }
 4840:     if (!defined($cid)) {
 4841:         $cid = $env{'request.course.id'};
 4842:     }
 4843:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 4844:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 4845:                                           '.plaintext'});
 4846:     }
 4847:     my %rolenames = (
 4848:                       Course => 'std',
 4849:                       Group => 'alt1',
 4850:                     );
 4851:     if (defined($type) && 
 4852:          defined($rolenames{$type}) && 
 4853:          defined($prp{$short}{$rolenames{$type}})) {
 4854:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 4855:     } else {
 4856:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 4857:     }
 4858: }
 4859: 
 4860: # ----------------------------------------------------------------- Assign Role
 4861: 
 4862: sub assignrole {
 4863:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 4864:     my $mrole;
 4865:     if ($role =~ /^cr\//) {
 4866:         my $cwosec=$url;
 4867:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4868: 	unless (&allowed('ccr',$cwosec)) {
 4869:            &logthis('Refused custom assignrole: '.
 4870:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4871: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4872:            return 'refused'; 
 4873:         }
 4874:         $mrole='cr';
 4875:     } elsif ($role =~ /^gr\//) {
 4876:         my $cwogrp=$url;
 4877:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 4878:         unless (&allowed('mdg',$cwogrp)) {
 4879:             &logthis('Refused group assignrole: '.
 4880:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4881:                     $env{'user.name'}.' at '.$env{'user.domain'});
 4882:             return 'refused';
 4883:         }
 4884:         $mrole='gr';
 4885:     } else {
 4886:         my $cwosec=$url;
 4887:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 4888:         unless ((&allowed('c'.$role,$cwosec)) || &allowed('c'.$role,$udom)) { 
 4889:            &logthis('Refused assignrole: '.
 4890:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 4891: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 4892:            return 'refused'; 
 4893:         }
 4894:         $mrole=$role;
 4895:     }
 4896:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4897:                 "$udom:$uname:$url".'_'."$mrole=$role";
 4898:     if ($end) { $command.='_'.$end; }
 4899:     if ($start) {
 4900: 	if ($end) { 
 4901:            $command.='_'.$start; 
 4902:         } else {
 4903:            $command.='_0_'.$start;
 4904:         }
 4905:     }
 4906:     my $origstart = $start;
 4907:     my $origend = $end;
 4908: # actually delete
 4909:     if ($deleteflag) {
 4910: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 4911: # modify command to delete the role
 4912:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 4913:                 "$udom:$uname:$url".'_'."$mrole";
 4914: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 4915: # set start and finish to negative values for userrolelog
 4916:            $start=-1;
 4917:            $end=-1;
 4918:         }
 4919:     }
 4920: # send command
 4921:     my $answer=&reply($command,&homeserver($uname,$udom));
 4922: # log new user role if status is ok
 4923:     if ($answer eq 'ok') {
 4924: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 4925: # for course roles, perform group memberships changes triggered by role change.
 4926:         unless ($role =~ /^gr/) {
 4927:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 4928:                                              $origstart);
 4929:         }
 4930:     }
 4931:     return $answer;
 4932: }
 4933: 
 4934: # -------------------------------------------------- Modify user authentication
 4935: # Overrides without validation
 4936: 
 4937: sub modifyuserauth {
 4938:     my ($udom,$uname,$umode,$upass)=@_;
 4939:     my $uhome=&homeserver($uname,$udom);
 4940:     unless (&allowed('mau',$udom)) { return 'refused'; }
 4941:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 4942:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4943:              ' in domain '.$env{'request.role.domain'});  
 4944:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 4945: 		     &escape($upass),$uhome);
 4946:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 4947:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 4948:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4949:     &log($udom,,$uname,$uhome,
 4950:         'Authentication changed by '.$env{'user.domain'}.', '.
 4951:                                      $env{'user.name'}.', '.$umode.
 4952:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 4953:     unless ($reply eq 'ok') {
 4954:         &logthis('Authentication mode error: '.$reply);
 4955: 	return 'error: '.$reply;
 4956:     }   
 4957:     return 'ok';
 4958: }
 4959: 
 4960: # --------------------------------------------------------------- Modify a user
 4961: 
 4962: sub modifyuser {
 4963:     my ($udom,    $uname, $uid,
 4964:         $umode,   $upass, $first,
 4965:         $middle,  $last,  $gene,
 4966:         $forceid, $desiredhome, $email)=@_;
 4967:     $udom= &LONCAPA::clean_domain($udom);
 4968:     $uname=&LONCAPA::clean_username($uname);
 4969:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 4970:              $umode.', '.$first.', '.$middle.', '.
 4971: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 4972:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 4973:                                      ' desiredhome not specified'). 
 4974:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 4975:              ' in domain '.$env{'request.role.domain'});
 4976:     my $uhome=&homeserver($uname,$udom,'true');
 4977: # ----------------------------------------------------------------- Create User
 4978:     if (($uhome eq 'no_host') && 
 4979: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 4980:         my $unhome='';
 4981:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 4982:             $unhome = $desiredhome;
 4983: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 4984: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 4985:         } else { # load balancing routine for determining $unhome
 4986:             my $loadm=10000000;
 4987: 	    my %servers = &get_servers($udom,'library');
 4988: 	    foreach my $tryserver (keys(%servers)) {
 4989: 		my $answer=reply('load',$tryserver);
 4990: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 4991: 		    $loadm=$answer;
 4992: 		    $unhome=$tryserver;
 4993: 		}
 4994: 	    }
 4995:         }
 4996:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 4997: 	    return 'error: unable to find a home server for '.$uname.
 4998:                    ' in domain '.$udom;
 4999:         }
 5000:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5001:                          &escape($upass),$unhome);
 5002: 	unless ($reply eq 'ok') {
 5003:             return 'error: '.$reply;
 5004:         }   
 5005:         $uhome=&homeserver($uname,$udom,'true');
 5006:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5007: 	    return 'error: unable verify users home machine.';
 5008:         }
 5009:     }   # End of creation of new user
 5010: # ---------------------------------------------------------------------- Add ID
 5011:     if ($uid) {
 5012:        $uid=~tr/A-Z/a-z/;
 5013:        my %uidhash=&idrget($udom,$uname);
 5014:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5015:          && (!$forceid)) {
 5016: 	  unless ($uid eq $uidhash{$uname}) {
 5017: 	      return 'error: user id "'.$uid.'" does not match '.
 5018:                   'current user id "'.$uidhash{$uname}.'".';
 5019:           }
 5020:        } else {
 5021: 	  &idput($udom,($uname => $uid));
 5022:        }
 5023:     }
 5024: # -------------------------------------------------------------- Add names, etc
 5025:     my @tmp=&get('environment',
 5026: 		   ['firstname','middlename','lastname','generation'],
 5027: 		   $udom,$uname);
 5028:     my %names;
 5029:     if ($tmp[0] =~ m/^error:.*/) { 
 5030:         %names=(); 
 5031:     } else {
 5032:         %names = @tmp;
 5033:     }
 5034: #
 5035: # Make sure to not trash student environment if instructor does not bother
 5036: # to supply name and email information
 5037: #
 5038:     if ($first)  { $names{'firstname'}  = $first; }
 5039:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5040:     if ($last)   { $names{'lastname'}   = $last; }
 5041:     if (defined($gene))   { $names{'generation'} = $gene; }
 5042:     if ($email) {
 5043:        $email=~s/[^\w\@\.\-\,]//gs;
 5044:        if ($email=~/\@/) { $names{'notification'} = $email;
 5045: 			   $names{'critnotification'} = $email;
 5046: 			   $names{'permanentemail'} = $email; }
 5047:     }
 5048:     my $reply = &put('environment', \%names, $udom,$uname);
 5049:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5050:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5051:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5052:              $umode.', '.$first.', '.$middle.', '.
 5053: 	     $last.', '.$gene.' by '.
 5054:              $env{'user.name'}.' at '.$env{'user.domain'});
 5055:     return 'ok';
 5056: }
 5057: 
 5058: # -------------------------------------------------------------- Modify student
 5059: 
 5060: sub modifystudent {
 5061:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5062:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5063:     if (!$cid) {
 5064: 	unless ($cid=$env{'request.course.id'}) {
 5065: 	    return 'not_in_class';
 5066: 	}
 5067:     }
 5068: # --------------------------------------------------------------- Make the user
 5069:     my $reply=&modifyuser
 5070: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5071:          $desiredhome,$email);
 5072:     unless ($reply eq 'ok') { return $reply; }
 5073:     # This will cause &modify_student_enrollment to get the uid from the
 5074:     # students environment
 5075:     $uid = undef if (!$forceid);
 5076:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5077: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5078:     return $reply;
 5079: }
 5080: 
 5081: sub modify_student_enrollment {
 5082:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 5083:     my ($cdom,$cnum,$chome);
 5084:     if (!$cid) {
 5085: 	unless ($cid=$env{'request.course.id'}) {
 5086: 	    return 'not_in_class';
 5087: 	}
 5088: 	$cdom=$env{'course.'.$cid.'.domain'};
 5089: 	$cnum=$env{'course.'.$cid.'.num'};
 5090:     } else {
 5091: 	($cdom,$cnum)=split(/_/,$cid);
 5092:     }
 5093:     $chome=$env{'course.'.$cid.'.home'};
 5094:     if (!$chome) {
 5095: 	$chome=&homeserver($cnum,$cdom);
 5096:     }
 5097:     if (!$chome) { return 'unknown_course'; }
 5098:     # Make sure the user exists
 5099:     my $uhome=&homeserver($uname,$udom);
 5100:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5101: 	return 'error: no such user';
 5102:     }
 5103:     # Get student data if we were not given enough information
 5104:     if (!defined($first)  || $first  eq '' || 
 5105:         !defined($last)   || $last   eq '' || 
 5106:         !defined($uid)    || $uid    eq '' || 
 5107:         !defined($middle) || $middle eq '' || 
 5108:         !defined($gene)   || $gene   eq '') {
 5109:         # They did not supply us with enough data to enroll the student, so
 5110:         # we need to pick up more information.
 5111:         my %tmp = &get('environment',
 5112:                        ['firstname','middlename','lastname', 'generation','id']
 5113:                        ,$udom,$uname);
 5114: 
 5115:         #foreach my $key (keys(%tmp)) {
 5116:         #    &logthis("key $key = ".$tmp{$key});
 5117:         #}
 5118:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5119:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5120:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5121:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5122:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5123:     }
 5124:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5125:     my $reply=cput('classlist',
 5126: 		   {"$uname:$udom" => 
 5127: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5128: 		   $cdom,$cnum);
 5129:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5130: 	return 'error: '.$reply;
 5131:     } else {
 5132: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5133:     }
 5134:     # Add student role to user
 5135:     my $uurl='/'.$cid;
 5136:     $uurl=~s/\_/\//g;
 5137:     if ($usec) {
 5138: 	$uurl.='/'.$usec;
 5139:     }
 5140:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5141: }
 5142: 
 5143: sub format_name {
 5144:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5145:     my $name;
 5146:     if ($first ne 'lastname') {
 5147: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5148:     } else {
 5149: 	if ($lastname=~/\S/) {
 5150: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5151: 	    $name=~s/\s+,/,/;
 5152: 	} else {
 5153: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5154: 	}
 5155:     }
 5156:     $name=~s/^\s+//;
 5157:     $name=~s/\s+$//;
 5158:     $name=~s/\s+/ /g;
 5159:     return $name;
 5160: }
 5161: 
 5162: # ------------------------------------------------- Write to course preferences
 5163: 
 5164: sub writecoursepref {
 5165:     my ($courseid,%prefs)=@_;
 5166:     $courseid=~s/^\///;
 5167:     $courseid=~s/\_/\//g;
 5168:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5169:     my $chome=homeserver($cnum,$cdomain);
 5170:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5171: 	return 'error: no such course';
 5172:     }
 5173:     my $cstring='';
 5174:     foreach my $pref (keys(%prefs)) {
 5175: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5176:     }
 5177:     $cstring=~s/\&$//;
 5178:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5179: }
 5180: 
 5181: # ---------------------------------------------------------- Make/modify course
 5182: 
 5183: sub createcourse {
 5184:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5185:         $course_owner,$crstype)=@_;
 5186:     $url=&declutter($url);
 5187:     my $cid='';
 5188:     unless (&allowed('ccc',$udom)) {
 5189:         return 'refused';
 5190:     }
 5191: # ------------------------------------------------------------------- Create ID
 5192:    my $uname=int(1+rand(9)).
 5193:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5194:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5195:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5196: # ----------------------------------------------- Make sure that does not exist
 5197:    my $uhome=&homeserver($uname,$udom,'true');
 5198:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5199:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5200:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5201:        $uhome=&homeserver($uname,$udom,'true');       
 5202:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5203:            return 'error: unable to generate unique course-ID';
 5204:        } 
 5205:    }
 5206: # ------------------------------------------------ Check supplied server name
 5207:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5208:     if (! &is_library($course_server)) {
 5209:         return 'error:bad server name '.$course_server;
 5210:     }
 5211: # ------------------------------------------------------------- Make the course
 5212:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5213:                       $course_server);
 5214:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5215:     $uhome=&homeserver($uname,$udom,'true');
 5216:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5217: 	return 'error: no such course';
 5218:     }
 5219: # ----------------------------------------------------------------- Course made
 5220: # log existence
 5221:     &courseidput($udom,&escape($udom.'_'.$uname).'='.&escape($description).
 5222:                  ':'.&escape($inst_code).':'.&escape($course_owner).':'.
 5223:                   &escape($crstype),$uhome);
 5224:     &flushcourselogs();
 5225: # set toplevel url
 5226:     my $topurl=$url;
 5227:     unless ($nonstandard) {
 5228: # ------------------------------------------ For standard courses, make top url
 5229:         my $mapurl=&clutter($url);
 5230:         if ($mapurl eq '/res/') { $mapurl=''; }
 5231:         $env{'form.initmap'}=(<<ENDINITMAP);
 5232: <map>
 5233: <resource id="1" type="start"></resource>
 5234: <resource id="2" src="$mapurl"></resource>
 5235: <resource id="3" type="finish"></resource>
 5236: <link index="1" from="1" to="2"></link>
 5237: <link index="2" from="2" to="3"></link>
 5238: </map>
 5239: ENDINITMAP
 5240:         $topurl=&declutter(
 5241:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5242:                           );
 5243:     }
 5244: # ----------------------------------------------------------- Write preferences
 5245:     &writecoursepref($udom.'_'.$uname,
 5246:                      ('description' => $description,
 5247:                       'url'         => $topurl));
 5248:     return '/'.$udom.'/'.$uname;
 5249: }
 5250: 
 5251: sub is_course {
 5252:     my ($cdom,$cnum) = @_;
 5253:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5254: 				undef,'.');
 5255:     if (exists($courses{$cdom.'_'.$cnum})) {
 5256:         return 1;
 5257:     }
 5258:     return 0;
 5259: }
 5260: 
 5261: # ---------------------------------------------------------- Assign Custom Role
 5262: 
 5263: sub assigncustomrole {
 5264:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5265:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5266:                        $end,$start,$deleteflag);
 5267: }
 5268: 
 5269: # ----------------------------------------------------------------- Revoke Role
 5270: 
 5271: sub revokerole {
 5272:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5273:     my $now=time;
 5274:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5275: }
 5276: 
 5277: # ---------------------------------------------------------- Revoke Custom Role
 5278: 
 5279: sub revokecustomrole {
 5280:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5281:     my $now=time;
 5282:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5283:            $deleteflag);
 5284: }
 5285: 
 5286: # ------------------------------------------------------------ Disk usage
 5287: sub diskusage {
 5288:     my ($udom,$uname,$directoryRoot)=@_;
 5289:     $directoryRoot =~ s/\/$//;
 5290:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5291:     return $listing;
 5292: }
 5293: 
 5294: sub is_locked {
 5295:     my ($file_name, $domain, $user) = @_;
 5296:     my @check;
 5297:     my $is_locked;
 5298:     push @check, $file_name;
 5299:     my %locked = &get('file_permissions',\@check,
 5300: 		      $env{'user.domain'},$env{'user.name'});
 5301:     my ($tmp)=keys(%locked);
 5302:     if ($tmp=~/^error:/) { undef(%locked); }
 5303:     
 5304:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5305:         $is_locked = 'false';
 5306:         foreach my $entry (@{$locked{$file_name}}) {
 5307:            if (ref($entry) eq 'ARRAY') { 
 5308:                $is_locked = 'true';
 5309:                last;
 5310:            }
 5311:        }
 5312:     } else {
 5313:         $is_locked = 'false';
 5314:     }
 5315: }
 5316: 
 5317: sub declutter_portfile {
 5318:     my ($file) = @_;
 5319:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5320:     return $file;
 5321: }
 5322: 
 5323: # ------------------------------------------------------------- Mark as Read Only
 5324: 
 5325: sub mark_as_readonly {
 5326:     my ($domain,$user,$files,$what) = @_;
 5327:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5328:     my ($tmp)=keys(%current_permissions);
 5329:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5330:     foreach my $file (@{$files}) {
 5331: 	$file = &declutter_portfile($file);
 5332:         push(@{$current_permissions{$file}},$what);
 5333:     }
 5334:     &put('file_permissions',\%current_permissions,$domain,$user);
 5335:     return;
 5336: }
 5337: 
 5338: # ------------------------------------------------------------Save Selected Files
 5339: 
 5340: sub save_selected_files {
 5341:     my ($user, $path, @files) = @_;
 5342:     my $filename = $user."savedfiles";
 5343:     my @other_files = &files_not_in_path($user, $path);
 5344:     open (OUT, '>'.$tmpdir.$filename);
 5345:     foreach my $file (@files) {
 5346:         print (OUT $env{'form.currentpath'}.$file."\n");
 5347:     }
 5348:     foreach my $file (@other_files) {
 5349:         print (OUT $file."\n");
 5350:     }
 5351:     close (OUT);
 5352:     return 'ok';
 5353: }
 5354: 
 5355: sub clear_selected_files {
 5356:     my ($user) = @_;
 5357:     my $filename = $user."savedfiles";
 5358:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5359:     print (OUT undef);
 5360:     close (OUT);
 5361:     return ("ok");    
 5362: }
 5363: 
 5364: sub files_in_path {
 5365:     my ($user, $path) = @_;
 5366:     my $filename = $user."savedfiles";
 5367:     my %return_files;
 5368:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5369:     while (my $line_in = <IN>) {
 5370:         chomp ($line_in);
 5371:         my @paths_and_file = split (m!/!, $line_in);
 5372:         my $file_part = pop (@paths_and_file);
 5373:         my $path_part = join ('/', @paths_and_file);
 5374:         $path_part.='/';
 5375:         my $path_and_file = $path_part.$file_part;
 5376:         if ($path_part eq $path) {
 5377:             $return_files{$file_part}= 'selected';
 5378:         }
 5379:     }
 5380:     close (IN);
 5381:     return (\%return_files);
 5382: }
 5383: 
 5384: # called in portfolio select mode, to show files selected NOT in current directory
 5385: sub files_not_in_path {
 5386:     my ($user, $path) = @_;
 5387:     my $filename = $user."savedfiles";
 5388:     my @return_files;
 5389:     my $path_part;
 5390:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5391:     while (my $line = <IN>) {
 5392:         #ok, I know it's clunky, but I want it to work
 5393:         my @paths_and_file = split(m|/|, $line);
 5394:         my $file_part = pop(@paths_and_file);
 5395:         chomp($file_part);
 5396:         my $path_part = join('/', @paths_and_file);
 5397:         $path_part .= '/';
 5398:         my $path_and_file = $path_part.$file_part;
 5399:         if ($path_part ne $path) {
 5400:             push(@return_files, ($path_and_file));
 5401:         }
 5402:     }
 5403:     close(OUT);
 5404:     return (@return_files);
 5405: }
 5406: 
 5407: #----------------------------------------------Get portfolio file permissions
 5408: 
 5409: sub get_portfile_permissions {
 5410:     my ($domain,$user) = @_;
 5411:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5412:     my ($tmp)=keys(%current_permissions);
 5413:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5414:     return \%current_permissions;
 5415: }
 5416: 
 5417: #---------------------------------------------Get portfolio file access controls
 5418: 
 5419: sub get_access_controls {
 5420:     my ($current_permissions,$group,$file) = @_;
 5421:     my %access;
 5422:     my $real_file = $file;
 5423:     $file =~ s/\.meta$//;
 5424:     if (defined($file)) {
 5425:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5426:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5427:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5428:             }
 5429:         }
 5430:     } else {
 5431:         foreach my $key (keys(%{$current_permissions})) {
 5432:             if ($key =~ /\0accesscontrol$/) {
 5433:                 if (defined($group)) {
 5434:                     if ($key !~ m-^\Q$group\E/-) {
 5435:                         next;
 5436:                     }
 5437:                 }
 5438:                 my ($fullpath) = split(/\0/,$key);
 5439:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5440:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5441:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5442:                     }
 5443:                 }
 5444:             }
 5445:         }
 5446:     }
 5447:     return %access;
 5448: }
 5449: 
 5450: sub modify_access_controls {
 5451:     my ($file_name,$changes,$domain,$user)=@_;
 5452:     my ($outcome,$deloutcome);
 5453:     my %store_permissions;
 5454:     my %new_values;
 5455:     my %new_control;
 5456:     my %translation;
 5457:     my @deletions = ();
 5458:     my $now = time;
 5459:     if (exists($$changes{'activate'})) {
 5460:         if (ref($$changes{'activate'}) eq 'HASH') {
 5461:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5462:             my $numnew = scalar(@newitems);
 5463:             for (my $i=0; $i<$numnew; $i++) {
 5464:                 my $newkey = $newitems[$i];
 5465:                 my $newid = &Apache::loncommon::get_cgi_id();
 5466:                 if ($newkey =~ /^\d+:/) { 
 5467:                     $newkey =~ s/^(\d+)/$newid/;
 5468:                     $translation{$1} = $newid;
 5469:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5470:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5471:                     $translation{$1} = $newid;
 5472:                 }
 5473:                 $new_values{$file_name."\0".$newkey} = 
 5474:                                           $$changes{'activate'}{$newitems[$i]};
 5475:                 $new_control{$newkey} = $now;
 5476:             }
 5477:         }
 5478:     }
 5479:     my %todelete;
 5480:     my %changed_items;
 5481:     foreach my $action ('delete','update') {
 5482:         if (exists($$changes{$action})) {
 5483:             if (ref($$changes{$action}) eq 'HASH') {
 5484:                 foreach my $key (keys(%{$$changes{$action}})) {
 5485:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5486:                     if ($action eq 'delete') { 
 5487:                         $todelete{$itemnum} = 1;
 5488:                     } else {
 5489:                         $changed_items{$itemnum} = $key;
 5490:                     }
 5491:                 }
 5492:             }
 5493:         }
 5494:     }
 5495:     # get lock on access controls for file.
 5496:     my $lockhash = {
 5497:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5498:                                                        ':'.$env{'user.domain'},
 5499:                    }; 
 5500:     my $tries = 0;
 5501:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5502:    
 5503:     while (($gotlock ne 'ok') && $tries <3) {
 5504:         $tries ++;
 5505:         sleep 1;
 5506:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5507:     }
 5508:     if ($gotlock eq 'ok') {
 5509:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5510:         my ($tmp)=keys(%curr_permissions);
 5511:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5512:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5513:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5514:             if (ref($curr_controls) eq 'HASH') {
 5515:                 foreach my $control_item (keys(%{$curr_controls})) {
 5516:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5517:                     if (defined($todelete{$itemnum})) {
 5518:                         push(@deletions,$file_name."\0".$control_item);
 5519:                     } else {
 5520:                         if (defined($changed_items{$itemnum})) {
 5521:                             $new_control{$changed_items{$itemnum}} = $now;
 5522:                             push(@deletions,$file_name."\0".$control_item);
 5523:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5524:                         } else {
 5525:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5526:                         }
 5527:                     }
 5528:                 }
 5529:             }
 5530:         }
 5531:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5532:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5533:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5534:         #  remove lock
 5535:         my @del_lock = ($file_name."\0".'locked_access_records');
 5536:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5537:         my ($file,$group);
 5538:         if (&is_course($domain,$user)) {
 5539:             ($group,$file) = split(/\//,$file_name,2);
 5540:         } else {
 5541:             $file = $file_name;
 5542:         }
 5543:         my $sqlresult =
 5544:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5545:                                     $group);
 5546:     } else {
 5547:         $outcome = "error: could not obtain lockfile\n";  
 5548:     }
 5549:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5550: }
 5551: 
 5552: sub make_public_indefinitely {
 5553:     my ($requrl) = @_;
 5554:     my $now = time;
 5555:     my $action = 'activate';
 5556:     my $aclnum = 0;
 5557:     if (&is_portfolio_url($requrl)) {
 5558:         my (undef,$udom,$unum,$file_name,$group) =
 5559:             &parse_portfolio_url($requrl);
 5560:         my $current_perms = &get_portfile_permissions($udom,$unum);
 5561:         my %access_controls = &get_access_controls($current_perms,
 5562:                                                    $group,$file_name);
 5563:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 5564:             my ($num,$scope,$end,$start) = 
 5565:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5566:             if ($scope eq 'public') {
 5567:                 if ($start <= $now && $end == 0) {
 5568:                     $action = 'none';
 5569:                 } else {
 5570:                     $action = 'update';
 5571:                     $aclnum = $num;
 5572:                 }
 5573:                 last;
 5574:             }
 5575:         }
 5576:         if ($action eq 'none') {
 5577:              return 'ok';
 5578:         } else {
 5579:             my %changes;
 5580:             my $newend = 0;
 5581:             my $newstart = $now;
 5582:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 5583:             $changes{$action}{$newkey} = {
 5584:                 type => 'public',
 5585:                 time => {
 5586:                     start => $newstart,
 5587:                     end   => $newend,
 5588:                 },
 5589:             };
 5590:             my ($outcome,$deloutcome,$new_values,$translation) =
 5591:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 5592:             return $outcome;
 5593:         }
 5594:     } else {
 5595:         return 'invalid';
 5596:     }
 5597: }
 5598: 
 5599: #------------------------------------------------------Get Marked as Read Only
 5600: 
 5601: sub get_marked_as_readonly {
 5602:     my ($domain,$user,$what,$group) = @_;
 5603:     my $current_permissions = &get_portfile_permissions($domain,$user);
 5604:     my @readonly_files;
 5605:     my $cmp1=$what;
 5606:     if (ref($what)) { $cmp1=join('',@{$what}) };
 5607:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5608:         if (defined($group)) {
 5609:             if ($file_name !~ m-^\Q$group\E/-) {
 5610:                 next;
 5611:             }
 5612:         }
 5613:         if (ref($value) eq "ARRAY"){
 5614:             foreach my $stored_what (@{$value}) {
 5615:                 my $cmp2=$stored_what;
 5616:                 if (ref($stored_what) eq 'ARRAY') {
 5617:                     $cmp2=join('',@{$stored_what});
 5618:                 }
 5619:                 if ($cmp1 eq $cmp2) {
 5620:                     push(@readonly_files, $file_name);
 5621:                     last;
 5622:                 } elsif (!defined($what)) {
 5623:                     push(@readonly_files, $file_name);
 5624:                     last;
 5625:                 }
 5626:             }
 5627:         }
 5628:     }
 5629:     return @readonly_files;
 5630: }
 5631: #-----------------------------------------------------------Get Marked as Read Only Hash
 5632: 
 5633: sub get_marked_as_readonly_hash {
 5634:     my ($current_permissions,$group,$what) = @_;
 5635:     my %readonly_files;
 5636:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 5637:         if (defined($group)) {
 5638:             if ($file_name !~ m-^\Q$group\E/-) {
 5639:                 next;
 5640:             }
 5641:         }
 5642:         if (ref($value) eq "ARRAY"){
 5643:             foreach my $stored_what (@{$value}) {
 5644:                 if (ref($stored_what) eq 'ARRAY') {
 5645:                     foreach my $lock_descriptor(@{$stored_what}) {
 5646:                         if ($lock_descriptor eq 'graded') {
 5647:                             $readonly_files{$file_name} = 'graded';
 5648:                         } elsif ($lock_descriptor eq 'handback') {
 5649:                             $readonly_files{$file_name} = 'handback';
 5650:                         } else {
 5651:                             if (!exists($readonly_files{$file_name})) {
 5652:                                 $readonly_files{$file_name} = 'locked';
 5653:                             }
 5654:                         }
 5655:                     }
 5656:                 } 
 5657:             }
 5658:         } 
 5659:     }
 5660:     return %readonly_files;
 5661: }
 5662: # ------------------------------------------------------------ Unmark as Read Only
 5663: 
 5664: sub unmark_as_readonly {
 5665:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 5666:     # for portfolio submissions, $what contains [$symb,$crsid] 
 5667:     my ($domain,$user,$what,$file_name,$group) = @_;
 5668:     $file_name = &declutter_portfile($file_name);
 5669:     my $symb_crs = $what;
 5670:     if (ref($what)) { $symb_crs=join('',@$what); }
 5671:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 5672:     my ($tmp)=keys(%current_permissions);
 5673:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5674:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 5675:     foreach my $file (@readonly_files) {
 5676: 	my $clean_file = &declutter_portfile($file);
 5677: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 5678: 	my $current_locks = $current_permissions{$file};
 5679:         my @new_locks;
 5680:         my @del_keys;
 5681:         if (ref($current_locks) eq "ARRAY"){
 5682:             foreach my $locker (@{$current_locks}) {
 5683:                 my $compare=$locker;
 5684:                 if (ref($locker) eq 'ARRAY') {
 5685:                     $compare=join('',@{$locker});
 5686:                     if ($compare ne $symb_crs) {
 5687:                         push(@new_locks, $locker);
 5688:                     }
 5689:                 }
 5690:             }
 5691:             if (scalar(@new_locks) > 0) {
 5692:                 $current_permissions{$file} = \@new_locks;
 5693:             } else {
 5694:                 push(@del_keys, $file);
 5695:                 &del('file_permissions',\@del_keys, $domain, $user);
 5696:                 delete($current_permissions{$file});
 5697:             }
 5698:         }
 5699:     }
 5700:     &put('file_permissions',\%current_permissions,$domain,$user);
 5701:     return;
 5702: }
 5703: 
 5704: # ------------------------------------------------------------ Directory lister
 5705: 
 5706: sub dirlist {
 5707:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 5708: 
 5709:     $uri=~s/^\///;
 5710:     $uri=~s/\/$//;
 5711:     my ($udom, $uname);
 5712:     (undef,$udom,$uname)=split(/\//,$uri);
 5713:     if(defined($userdomain)) {
 5714:         $udom = $userdomain;
 5715:     }
 5716:     if(defined($username)) {
 5717:         $uname = $username;
 5718:     }
 5719: 
 5720:     my $dirRoot = $perlvar{'lonDocRoot'};
 5721:     if(defined($alternateDirectoryRoot)) {
 5722:         $dirRoot = $alternateDirectoryRoot;
 5723:         $dirRoot =~ s/\/$//;
 5724:     }
 5725: 
 5726:     if($udom) {
 5727:         if($uname) {
 5728:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 5729: 				 &homeserver($uname,$udom));
 5730:             my @listing_results;
 5731:             if ($listing eq 'unknown_cmd') {
 5732:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 5733: 				  &homeserver($uname,$udom));
 5734:                 @listing_results = split(/:/,$listing);
 5735:             } else {
 5736:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 5737:             }
 5738:             return @listing_results;
 5739:         } elsif(!defined($alternateDirectoryRoot)) {
 5740:             my %allusers;
 5741: 	    my %servers = &get_servers($udom,'library');
 5742: 	    foreach my $tryserver (keys(%servers)) {
 5743: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 5744: 				     $udom, $tryserver);
 5745: 		my @listing_results;
 5746: 		if ($listing eq 'unknown_cmd') {
 5747: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 5748: 				      $udom, $tryserver);
 5749: 		    @listing_results = split(/:/,$listing);
 5750: 		} else {
 5751: 		    @listing_results =
 5752: 			map { &unescape($_); } split(/:/,$listing);
 5753: 		}
 5754: 		if ($listing_results[0] ne 'no_such_dir' && 
 5755: 		    $listing_results[0] ne 'empty'       &&
 5756: 		    $listing_results[0] ne 'con_lost') {
 5757: 		    foreach my $line (@listing_results) {
 5758: 			my ($entry) = split(/&/,$line,2);
 5759: 			$allusers{$entry} = 1;
 5760: 		    }
 5761: 		}
 5762:             }
 5763:             my $alluserstr='';
 5764:             foreach my $user (sort(keys(%allusers))) {
 5765:                 $alluserstr.=$user.'&user:';
 5766:             }
 5767:             $alluserstr=~s/:$//;
 5768:             return split(/:/,$alluserstr);
 5769:         } else {
 5770:             return ('missing user name');
 5771:         }
 5772:     } elsif(!defined($alternateDirectoryRoot)) {
 5773:         my @all_domains = sort(&all_domains());
 5774:          foreach my $domain (@all_domains) {
 5775:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 5776:          }
 5777:          return @all_domains;
 5778:      } else {
 5779:         return ('missing domain');
 5780:     }
 5781: }
 5782: 
 5783: # --------------------------------------------- GetFileTimestamp
 5784: # This function utilizes dirlist and returns the date stamp for
 5785: # when it was last modified.  It will also return an error of -1
 5786: # if an error occurs
 5787: 
 5788: ##
 5789: ## FIXME: This subroutine assumes its caller knows something about the
 5790: ## directory structure of the home server for the student ($root).
 5791: ## Not a good assumption to make.  Since this is for looking up files
 5792: ## in user directories, the full path should be constructed by lond, not
 5793: ## whatever machine we request data from.
 5794: ##
 5795: sub GetFileTimestamp {
 5796:     my ($studentDomain,$studentName,$filename,$root)=@_;
 5797:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 5798:     $studentName   = &LONCAPA::clean_username($studentName);
 5799:     my $subdir=$studentName.'__';
 5800:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 5801:     my $proname="$studentDomain/$subdir/$studentName";
 5802:     $proname .= '/'.$filename;
 5803:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 5804:                                               $studentName, $root);
 5805:     my @stats = split('&', $fileStat);
 5806:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5807:         # @stats contains first the filename, then the stat output
 5808:         return $stats[10]; # so this is 10 instead of 9.
 5809:     } else {
 5810:         return -1;
 5811:     }
 5812: }
 5813: 
 5814: sub stat_file {
 5815:     my ($uri) = @_;
 5816:     $uri = &clutter_with_no_wrapper($uri);
 5817: 
 5818:     my ($udom,$uname,$file,$dir);
 5819:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 5820: 	($udom,$uname,$file) =
 5821: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 5822: 	$file = 'userfiles/'.$file;
 5823: 	$dir = &propath($udom,$uname);
 5824:     }
 5825:     if ($uri =~ m-^/res/-) {
 5826: 	($udom,$uname) = 
 5827: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 5828: 	$file = $uri;
 5829:     }
 5830: 
 5831:     if (!$udom || !$uname || !$file) {
 5832: 	# unable to handle the uri
 5833: 	return ();
 5834:     }
 5835: 
 5836:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 5837:     my @stats = split('&', $result);
 5838:     
 5839:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 5840: 	shift(@stats); #filename is first
 5841: 	return @stats;
 5842:     }
 5843:     return ();
 5844: }
 5845: 
 5846: # -------------------------------------------------------- Value of a Condition
 5847: 
 5848: # gets the value of a specific preevaluated condition
 5849: #    stored in the string  $env{user.state.<cid>}
 5850: # or looks up a condition reference in the bighash and if if hasn't
 5851: # already been evaluated recurses into docondval to get the value of
 5852: # the condition, then memoizing it to 
 5853: #   $env{user.state.<cid>.<condition>}
 5854: sub directcondval {
 5855:     my $number=shift;
 5856:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 5857: 	&Apache::lonuserstate::evalstate();
 5858:     }
 5859:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 5860: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 5861:     } elsif ($number =~ /^_/) {
 5862: 	my $sub_condition;
 5863: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5864: 		&GDBM_READER(),0640)) {
 5865: 	    $sub_condition=$bighash{'conditions'.$number};
 5866: 	    untie(%bighash);
 5867: 	}
 5868: 	my $value = &docondval($sub_condition);
 5869: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 5870: 	return $value;
 5871:     }
 5872:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 5873:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 5874:     } else {
 5875:        return 2;
 5876:     }
 5877: }
 5878: 
 5879: # get the collection of conditions for this resource
 5880: sub condval {
 5881:     my $condidx=shift;
 5882:     my $allpathcond='';
 5883:     foreach my $cond (split(/\|/,$condidx)) {
 5884: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 5885: 	    $allpathcond.=
 5886: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 5887: 	}
 5888:     }
 5889:     $allpathcond=~s/\|$//;
 5890:     return &docondval($allpathcond);
 5891: }
 5892: 
 5893: #evaluates an expression of conditions
 5894: sub docondval {
 5895:     my ($allpathcond) = @_;
 5896:     my $result=0;
 5897:     if ($env{'request.course.id'}
 5898: 	&& defined($allpathcond)) {
 5899: 	my $operand='|';
 5900: 	my @stack;
 5901: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 5902: 	    if ($chunk eq '(') {
 5903: 		push @stack,($operand,$result);
 5904: 	    } elsif ($chunk eq ')') {
 5905: 		my $before=pop @stack;
 5906: 		if (pop @stack eq '&') {
 5907: 		    $result=$result>$before?$before:$result;
 5908: 		} else {
 5909: 		    $result=$result>$before?$result:$before;
 5910: 		}
 5911: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 5912: 		$operand=$chunk;
 5913: 	    } else {
 5914: 		my $new=directcondval($chunk);
 5915: 		if ($operand eq '&') {
 5916: 		    $result=$result>$new?$new:$result;
 5917: 		} else {
 5918: 		    $result=$result>$new?$result:$new;
 5919: 		}
 5920: 	    }
 5921: 	}
 5922:     }
 5923:     return $result;
 5924: }
 5925: 
 5926: # ---------------------------------------------------- Devalidate courseresdata
 5927: 
 5928: sub devalidatecourseresdata {
 5929:     my ($coursenum,$coursedomain)=@_;
 5930:     my $hashid=$coursenum.':'.$coursedomain;
 5931:     &devalidate_cache_new('courseres',$hashid);
 5932: }
 5933: 
 5934: 
 5935: # --------------------------------------------------- Course Resourcedata Query
 5936: #
 5937: #  Parameters:
 5938: #      $coursenum    - Number of the course.
 5939: #      $coursedomain - Domain at which the course was created.
 5940: #  Returns:
 5941: #     A hash of the course parameters along (I think) with timestamps
 5942: #     and version info.
 5943: 
 5944: sub get_courseresdata {
 5945:     my ($coursenum,$coursedomain)=@_;
 5946:     my $coursehom=&homeserver($coursenum,$coursedomain);
 5947:     my $hashid=$coursenum.':'.$coursedomain;
 5948:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 5949:     my %dumpreply;
 5950:     unless (defined($cached)) {
 5951: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 5952: 	$result=\%dumpreply;
 5953: 	my ($tmp) = keys(%dumpreply);
 5954: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 5955: 	    &do_cache_new('courseres',$hashid,$result,600);
 5956: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 5957: 	    return $tmp;
 5958: 	} elsif ($tmp =~ /^(error)/) {
 5959: 	    $result=undef;
 5960: 	    &do_cache_new('courseres',$hashid,$result,600);
 5961: 	}
 5962:     }
 5963:     return $result;
 5964: }
 5965: 
 5966: sub devalidateuserresdata {
 5967:     my ($uname,$udom)=@_;
 5968:     my $hashid="$udom:$uname";
 5969:     &devalidate_cache_new('userres',$hashid);
 5970: }
 5971: 
 5972: sub get_userresdata {
 5973:     my ($uname,$udom)=@_;
 5974:     #most student don\'t have any data set, check if there is some data
 5975:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 5976: 
 5977:     my $hashid="$udom:$uname";
 5978:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 5979:     if (!defined($cached)) {
 5980: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 5981: 	$result=\%resourcedata;
 5982: 	&do_cache_new('userres',$hashid,$result,600);
 5983:     }
 5984:     my ($tmp)=keys(%$result);
 5985:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 5986: 	return $result;
 5987:     }
 5988:     #error 2 occurs when the .db doesn't exist
 5989:     if ($tmp!~/error: 2 /) {
 5990: 	&logthis("<font color=\"blue\">WARNING:".
 5991: 		 " Trying to get resource data for ".
 5992: 		 $uname." at ".$udom.": ".
 5993: 		 $tmp."</font>");
 5994:     } elsif ($tmp=~/error: 2 /) {
 5995: 	#&EXT_cache_set($udom,$uname);
 5996: 	&do_cache_new('userres',$hashid,undef,600);
 5997: 	undef($tmp); # not really an error so don't send it back
 5998:     }
 5999:     return $tmp;
 6000: }
 6001: #----------------------------------------------- resdata - return resource data
 6002: #  Purpose:
 6003: #    Return resource data for either users or for a course.
 6004: #  Parameters:
 6005: #     $name      - Course/user name.
 6006: #     $domain    - Name of the domain the user/course is registered on.
 6007: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6008: #     @which     - Array of names of resources desired.
 6009: #  Returns:
 6010: #     The value of the first reasource in @which that is found in the
 6011: #     resource hash.
 6012: #  Exceptional Conditions:
 6013: #     If the $type passed in is not valid (not the string 'course' or 
 6014: #     'user', an undefined  reference is returned.
 6015: #     If none of the resources are found, an undef is returned
 6016: sub resdata {
 6017:     my ($name,$domain,$type,@which)=@_;
 6018:     my $result;
 6019:     if ($type eq 'course') {
 6020: 	$result=&get_courseresdata($name,$domain);
 6021:     } elsif ($type eq 'user') {
 6022: 	$result=&get_userresdata($name,$domain);
 6023:     }
 6024:     if (!ref($result)) { return $result; }    
 6025:     foreach my $item (@which) {
 6026: 	if (defined($result->{$item})) {
 6027: 	    return $result->{$item};
 6028: 	}
 6029:     }
 6030:     return undef;
 6031: }
 6032: 
 6033: #
 6034: # EXT resource caching routines
 6035: #
 6036: 
 6037: sub clear_EXT_cache_status {
 6038:     &delenv('cache.EXT.');
 6039: }
 6040: 
 6041: sub EXT_cache_status {
 6042:     my ($target_domain,$target_user) = @_;
 6043:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6044:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6045:         # We know already the user has no data
 6046:         return 1;
 6047:     } else {
 6048:         return 0;
 6049:     }
 6050: }
 6051: 
 6052: sub EXT_cache_set {
 6053:     my ($target_domain,$target_user) = @_;
 6054:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6055:     #&appenv($cachename => time);
 6056: }
 6057: 
 6058: # --------------------------------------------------------- Value of a Variable
 6059: sub EXT {
 6060: 
 6061:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6062:     unless ($varname) { return ''; }
 6063:     #get real user name/domain, courseid and symb
 6064:     my $courseid;
 6065:     my $publicuser;
 6066:     if ($symbparm) {
 6067: 	$symbparm=&get_symb_from_alias($symbparm);
 6068:     }
 6069:     if (!($uname && $udom)) {
 6070:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6071:       if (!$symbparm) {	$symbparm=$cursymb; }
 6072:     } else {
 6073: 	$courseid=$env{'request.course.id'};
 6074:     }
 6075:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6076:     my $rest;
 6077:     if (defined($therest[0])) {
 6078:        $rest=join('.',@therest);
 6079:     } else {
 6080:        $rest='';
 6081:     }
 6082: 
 6083:     my $qualifierrest=$qualifier;
 6084:     if ($rest) { $qualifierrest.='.'.$rest; }
 6085:     my $spacequalifierrest=$space;
 6086:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6087:     if ($realm eq 'user') {
 6088: # --------------------------------------------------------------- user.resource
 6089: 	if ($space eq 'resource') {
 6090: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6091: 		  || defined($Apache::lonhomework::parsing_a_task))
 6092: 		 &&
 6093: 		 ($symbparm eq &symbread()) ) {	
 6094: 		# if we are in the middle of processing the resource the
 6095: 		# get the value we are planning on committing
 6096:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6097:                     return $Apache::lonhomework::results{$qualifierrest};
 6098:                 } else {
 6099:                     return $Apache::lonhomework::history{$qualifierrest};
 6100:                 }
 6101: 	    } else {
 6102: 		my %restored;
 6103: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6104: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6105: 		} else {
 6106: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6107: 		}
 6108: 		return $restored{$qualifierrest};
 6109: 	    }
 6110: # ----------------------------------------------------------------- user.access
 6111:         } elsif ($space eq 'access') {
 6112: 	    # FIXME - not supporting calls for a specific user
 6113:             return &allowed($qualifier,$rest);
 6114: # ------------------------------------------ user.preferences, user.environment
 6115:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6116: 	    if (($uname eq $env{'user.name'}) &&
 6117: 		($udom eq $env{'user.domain'})) {
 6118: 		return $env{join('.',('environment',$qualifierrest))};
 6119: 	    } else {
 6120: 		my %returnhash;
 6121: 		if (!$publicuser) {
 6122: 		    %returnhash=&userenvironment($udom,$uname,
 6123: 						 $qualifierrest);
 6124: 		}
 6125: 		return $returnhash{$qualifierrest};
 6126: 	    }
 6127: # ----------------------------------------------------------------- user.course
 6128:         } elsif ($space eq 'course') {
 6129: 	    # FIXME - not supporting calls for a specific user
 6130:             return $env{join('.',('request.course',$qualifier))};
 6131: # ------------------------------------------------------------------- user.role
 6132:         } elsif ($space eq 'role') {
 6133: 	    # FIXME - not supporting calls for a specific user
 6134:             my ($role,$where)=split(/\./,$env{'request.role'});
 6135:             if ($qualifier eq 'value') {
 6136: 		return $role;
 6137:             } elsif ($qualifier eq 'extent') {
 6138:                 return $where;
 6139:             }
 6140: # ----------------------------------------------------------------- user.domain
 6141:         } elsif ($space eq 'domain') {
 6142:             return $udom;
 6143: # ------------------------------------------------------------------- user.name
 6144:         } elsif ($space eq 'name') {
 6145:             return $uname;
 6146: # ---------------------------------------------------- Any other user namespace
 6147:         } else {
 6148: 	    my %reply;
 6149: 	    if (!$publicuser) {
 6150: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6151: 	    }
 6152: 	    return $reply{$qualifierrest};
 6153:         }
 6154:     } elsif ($realm eq 'query') {
 6155: # ---------------------------------------------- pull stuff out of query string
 6156:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6157: 						[$spacequalifierrest]);
 6158: 	return $env{'form.'.$spacequalifierrest}; 
 6159:    } elsif ($realm eq 'request') {
 6160: # ------------------------------------------------------------- request.browser
 6161:         if ($space eq 'browser') {
 6162: 	    if ($qualifier eq 'textremote') {
 6163: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6164: 		    return 1;
 6165: 		} else {
 6166: 		    return 0;
 6167: 		}
 6168: 	    } else {
 6169: 		return $env{'browser.'.$qualifier};
 6170: 	    }
 6171: # ------------------------------------------------------------ request.filename
 6172:         } else {
 6173:             return $env{'request.'.$spacequalifierrest};
 6174:         }
 6175:     } elsif ($realm eq 'course') {
 6176: # ---------------------------------------------------------- course.description
 6177:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6178:     } elsif ($realm eq 'resource') {
 6179: 
 6180: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6181: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6182: 	}
 6183: 
 6184: 	if ($space eq 'title') {
 6185: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6186: 	    return &gettitle($symbparm);
 6187: 	}
 6188: 	
 6189: 	if ($space eq 'map') {
 6190: 	    my ($map) = &decode_symb($symbparm);
 6191: 	    return &symbread($map);
 6192: 	}
 6193: 
 6194: 	my ($section, $group, @groups);
 6195: 	my ($courselevelm,$courselevel);
 6196: 	if ($symbparm && defined($courseid) && 
 6197: 	    $courseid eq $env{'request.course.id'}) {
 6198: 
 6199: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6200: 
 6201: # ----------------------------------------------------- Cascading lookup scheme
 6202: 	    my $symbp=$symbparm;
 6203: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6204: 
 6205: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6206: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6207: 
 6208: 	    if (($env{'user.name'} eq $uname) &&
 6209: 		($env{'user.domain'} eq $udom)) {
 6210: 		$section=$env{'request.course.sec'};
 6211:                 @groups = split(/:/,$env{'request.course.groups'});  
 6212:                 @groups=&sort_course_groups($courseid,@groups); 
 6213: 	    } else {
 6214: 		if (! defined($usection)) {
 6215: 		    $section=&getsection($udom,$uname,$courseid);
 6216: 		} else {
 6217: 		    $section = $usection;
 6218: 		}
 6219:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6220: 	    }
 6221: 
 6222: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6223: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6224: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6225: 
 6226: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6227: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6228: 	    $courselevelm=$courseid.'.'.$mapparm;
 6229: 
 6230: # ----------------------------------------------------------- first, check user
 6231: 
 6232: 	    my $userreply=&resdata($uname,$udom,'user',
 6233: 				       ($courselevelr,$courselevelm,
 6234: 					$courselevel));
 6235: 	    if (defined($userreply)) { return $userreply; }
 6236: 
 6237: # ------------------------------------------------ second, check some of course
 6238:             my $coursereply;
 6239:             if (@groups > 0) {
 6240:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6241:                                        $mapparm,$spacequalifierrest);
 6242:                 if (defined($coursereply)) { return $coursereply; }
 6243:             }
 6244: 
 6245: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6246: 				     $env{'course.'.$courseid.'.domain'},
 6247: 				     'course',
 6248: 				     ($seclevelr,$seclevelm,$seclevel,
 6249: 				      $courselevelr));
 6250: 	    if (defined($coursereply)) { return $coursereply; }
 6251: 
 6252: # ------------------------------------------------------ third, check map parms
 6253: 	    my %parmhash=();
 6254: 	    my $thisparm='';
 6255: 	    if (tie(%parmhash,'GDBM_File',
 6256: 		    $env{'request.course.fn'}.'_parms.db',
 6257: 		    &GDBM_READER(),0640)) {
 6258: 		$thisparm=$parmhash{$symbparm};
 6259: 		untie(%parmhash);
 6260: 	    }
 6261: 	    if ($thisparm) { return $thisparm; }
 6262: 	}
 6263: # ------------------------------------------ fourth, look in resource metadata
 6264: 
 6265: 	$spacequalifierrest=~s/\./\_/;
 6266: 	my $filename;
 6267: 	if (!$symbparm) { $symbparm=&symbread(); }
 6268: 	if ($symbparm) {
 6269: 	    $filename=(&decode_symb($symbparm))[2];
 6270: 	} else {
 6271: 	    $filename=$env{'request.filename'};
 6272: 	}
 6273: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6274: 	if (defined($metadata)) { return $metadata; }
 6275: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6276: 	if (defined($metadata)) { return $metadata; }
 6277: 
 6278: # ---------------------------------------------- fourth, look in rest pf course
 6279: 	if ($symbparm && defined($courseid) && 
 6280: 	    $courseid eq $env{'request.course.id'}) {
 6281: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6282: 				     $env{'course.'.$courseid.'.domain'},
 6283: 				     'course',
 6284: 				     ($courselevelm,$courselevel));
 6285: 	    if (defined($coursereply)) { return $coursereply; }
 6286: 	}
 6287: # ------------------------------------------------------------------ Cascade up
 6288: 	unless ($space eq '0') {
 6289: 	    my @parts=split(/_/,$space);
 6290: 	    my $id=pop(@parts);
 6291: 	    my $part=join('_',@parts);
 6292: 	    if ($part eq '') { $part='0'; }
 6293: 	    my $partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6294: 				 $symbparm,$udom,$uname,$section,1);
 6295: 	    if (defined($partgeneral)) { return $partgeneral; }
 6296: 	}
 6297: 	if ($recurse) { return undef; }
 6298: 	my $pack_def=&packages_tab_default($filename,$varname);
 6299: 	if (defined($pack_def)) { return $pack_def; }
 6300: 
 6301: # ---------------------------------------------------- Any other user namespace
 6302:     } elsif ($realm eq 'environment') {
 6303: # ----------------------------------------------------------------- environment
 6304: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6305: 	    return $env{'environment.'.$spacequalifierrest};
 6306: 	} else {
 6307: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6308: 		return '';
 6309: 	    }
 6310: 	    my %returnhash=&userenvironment($udom,$uname,
 6311: 					    $spacequalifierrest);
 6312: 	    return $returnhash{$spacequalifierrest};
 6313: 	}
 6314:     } elsif ($realm eq 'system') {
 6315: # ----------------------------------------------------------------- system.time
 6316: 	if ($space eq 'time') {
 6317: 	    return time;
 6318:         }
 6319:     } elsif ($realm eq 'server') {
 6320: # ----------------------------------------------------------------- system.time
 6321: 	if ($space eq 'name') {
 6322: 	    return $ENV{'SERVER_NAME'};
 6323:         }
 6324:     }
 6325:     return '';
 6326: }
 6327: 
 6328: sub check_group_parms {
 6329:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6330:     my @groupitems = ();
 6331:     my $resultitem;
 6332:     my @levels = ($symbparm,$mapparm,$what);
 6333:     foreach my $group (@{$groups}) {
 6334:         foreach my $level (@levels) {
 6335:              my $item = $courseid.'.['.$group.'].'.$level;
 6336:              push(@groupitems,$item);
 6337:         }
 6338:     }
 6339:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6340:                             $env{'course.'.$courseid.'.domain'},
 6341:                                      'course',@groupitems);
 6342:     return $coursereply;
 6343: }
 6344: 
 6345: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6346:     my ($courseid,@groups) = @_;
 6347:     @groups = sort(@groups);
 6348:     return @groups;
 6349: }
 6350: 
 6351: sub packages_tab_default {
 6352:     my ($uri,$varname)=@_;
 6353:     my (undef,$part,$name)=split(/\./,$varname);
 6354: 
 6355:     my (@extension,@specifics,$do_default);
 6356:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6357: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6358: 	if ($pack_type eq 'default') {
 6359: 	    $do_default=1;
 6360: 	} elsif ($pack_type eq 'extension') {
 6361: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6362: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 6363: 	    # only look at packages defaults for packages that this id is
 6364: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6365: 	}
 6366:     }
 6367:     # first look for a package that matches the requested part id
 6368:     foreach my $package (@specifics) {
 6369: 	my (undef,$pack_type,$pack_part)=@{$package};
 6370: 	next if ($pack_part ne $part);
 6371: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6372: 	    return $packagetab{"$pack_type&$name&default"};
 6373: 	}
 6374:     }
 6375:     # look for any possible matching non extension_ package
 6376:     foreach my $package (@specifics) {
 6377: 	my (undef,$pack_type,$pack_part)=@{$package};
 6378: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6379: 	    return $packagetab{"$pack_type&$name&default"};
 6380: 	}
 6381: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6382: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6383: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6384: 	}
 6385:     }
 6386:     # look for any posible extension_ match
 6387:     foreach my $package (@extension) {
 6388: 	my ($package,$pack_type)=@{$package};
 6389: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6390: 	    return $packagetab{"$pack_type&$name&default"};
 6391: 	}
 6392: 	if (defined($packagetab{$package."&$name&default"})) {
 6393: 	    return $packagetab{$package."&$name&default"};
 6394: 	}
 6395:     }
 6396:     # look for a global default setting
 6397:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6398: 	return $packagetab{"default&$name&default"};
 6399:     }
 6400:     return undef;
 6401: }
 6402: 
 6403: sub add_prefix_and_part {
 6404:     my ($prefix,$part)=@_;
 6405:     my $keyroot;
 6406:     if (defined($prefix) && $prefix !~ /^__/) {
 6407: 	# prefix that has a part already
 6408: 	$keyroot=$prefix;
 6409:     } elsif (defined($prefix)) {
 6410: 	# prefix that is missing a part
 6411: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6412:     } else {
 6413: 	# no prefix at all
 6414: 	if (defined($part)) { $keyroot='_'.$part; }
 6415:     }
 6416:     return $keyroot;
 6417: }
 6418: 
 6419: # ---------------------------------------------------------------- Get metadata
 6420: 
 6421: my %metaentry;
 6422: sub metadata {
 6423:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6424:     $uri=&declutter($uri);
 6425:     # if it is a non metadata possible uri return quickly
 6426:     if (($uri eq '') || 
 6427: 	(($uri =~ m|^/*adm/|) && 
 6428: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6429:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ /^~/) ||
 6430: 	($uri =~ m|home/$match_username/public_html/|)) {
 6431: 	return undef;
 6432:     }
 6433:     my $filename=$uri;
 6434:     $uri=~s/\.meta$//;
 6435: #
 6436: # Is the metadata already cached?
 6437: # Look at timestamp of caching
 6438: # Everything is cached by the main uri, libraries are never directly cached
 6439: #
 6440:     if (!defined($liburi)) {
 6441: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6442: 	if (defined($cached)) { return $result->{':'.$what}; }
 6443:     }
 6444:     {
 6445: #
 6446: # Is this a recursive call for a library?
 6447: #
 6448: #	if (! exists($metacache{$uri})) {
 6449: #	    $metacache{$uri}={};
 6450: #	}
 6451:         if ($liburi) {
 6452: 	    $liburi=&declutter($liburi);
 6453:             $filename=$liburi;
 6454:         } else {
 6455: 	    &devalidate_cache_new('meta',$uri);
 6456: 	    undef(%metaentry);
 6457: 	}
 6458:         my %metathesekeys=();
 6459:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6460: 	my $metastring;
 6461: 	if ($uri !~ m -^(editupload)/-) {
 6462: 	    my $file=&filelocation('',&clutter($filename));
 6463: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6464: 	    $metastring=&getfile($file);
 6465: 	}
 6466:         my $parser=HTML::LCParser->new(\$metastring);
 6467:         my $token;
 6468:         undef %metathesekeys;
 6469:         while ($token=$parser->get_token) {
 6470: 	    if ($token->[0] eq 'S') {
 6471: 		if (defined($token->[2]->{'package'})) {
 6472: #
 6473: # This is a package - get package info
 6474: #
 6475: 		    my $package=$token->[2]->{'package'};
 6476: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6477: 		    if (defined($token->[2]->{'id'})) { 
 6478: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6479: 		    }
 6480: 		    if ($metaentry{':packages'}) {
 6481: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6482: 		    } else {
 6483: 			$metaentry{':packages'}=$package.$keyroot;
 6484: 		    }
 6485: 		    foreach my $pack_entry (keys(%packagetab)) {
 6486: 			my $part=$keyroot;
 6487: 			$part=~s/^\_//;
 6488: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6489: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6490: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6491: 			    # ignore package.tab specified default values
 6492:                             # here &package_tab_default() will fetch those
 6493: 			    if ($subp eq 'default') { next; }
 6494: 			    my $value=$packagetab{$pack_entry};
 6495: 			    my $unikey;
 6496: 			    if ($pack =~ /_0$/) {
 6497: 				$unikey='parameter_0_'.$name;
 6498: 				$part=0;
 6499: 			    } else {
 6500: 				$unikey='parameter'.$keyroot.'_'.$name;
 6501: 			    }
 6502: 			    if ($subp eq 'display') {
 6503: 				$value.=' [Part: '.$part.']';
 6504: 			    }
 6505: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6506: 			    $metathesekeys{$unikey}=1;
 6507: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6508: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6509: 			    }
 6510: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6511: 				$metaentry{':'.$unikey}=
 6512: 				    $metaentry{':'.$unikey.'.default'};
 6513: 			    }
 6514: 			}
 6515: 		    }
 6516: 		} else {
 6517: #
 6518: # This is not a package - some other kind of start tag
 6519: #
 6520: 		    my $entry=$token->[1];
 6521: 		    my $unikey;
 6522: 		    if ($entry eq 'import') {
 6523: 			$unikey='';
 6524: 		    } else {
 6525: 			$unikey=$entry;
 6526: 		    }
 6527: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6528: 
 6529: 		    if (defined($token->[2]->{'id'})) { 
 6530: 			$unikey.='_'.$token->[2]->{'id'}; 
 6531: 		    }
 6532: 
 6533: 		    if ($entry eq 'import') {
 6534: #
 6535: # Importing a library here
 6536: #
 6537: 			if ($depthcount<20) {
 6538: 			    my $location=$parser->get_text('/import');
 6539: 			    my $dir=$filename;
 6540: 			    $dir=~s|[^/]*$||;
 6541: 			    $location=&filelocation($dir,$location);
 6542: 			    my $metadata = 
 6543: 				&metadata($uri,'keys', $location,$unikey,
 6544: 					  $depthcount+1);
 6545: 			    foreach my $meta (split(',',$metadata)) {
 6546: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 6547: 				$metathesekeys{$meta}=1;
 6548: 			    }
 6549: 			}
 6550: 		    } else { 
 6551: 			
 6552: 			if (defined($token->[2]->{'name'})) { 
 6553: 			    $unikey.='_'.$token->[2]->{'name'}; 
 6554: 			}
 6555: 			$metathesekeys{$unikey}=1;
 6556: 			foreach my $param (@{$token->[3]}) {
 6557: 			    $metaentry{':'.$unikey.'.'.$param} =
 6558: 				$token->[2]->{$param};
 6559: 			}
 6560: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 6561: 			my $default=$metaentry{':'.$unikey.'.default'};
 6562: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 6563: 		 # only ws inside the tag, and not in default, so use default
 6564: 		 # as value
 6565: 			    $metaentry{':'.$unikey}=$default;
 6566: 			} else {
 6567: 		  # either something interesting inside the tag or default
 6568:                   # uninteresting
 6569: 			    $metaentry{':'.$unikey}=$internaltext;
 6570: 			}
 6571: # end of not-a-package not-a-library import
 6572: 		    }
 6573: # end of not-a-package start tag
 6574: 		}
 6575: # the next is the end of "start tag"
 6576: 	    }
 6577: 	}
 6578: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 6579: 	$extension = lc($extension);
 6580: 	if ($extension eq 'htm') { $extension='html'; }
 6581: 
 6582: 	foreach my $key (keys(%packagetab)) {
 6583: 	    #no specific packages #how's our extension
 6584: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 6585: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 6586: 					 \%metathesekeys);
 6587: 	}
 6588: 
 6589: 	if (!exists($metaentry{':packages'})
 6590: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 6591: 	    foreach my $key (keys(%packagetab)) {
 6592: 		#no specific packages well let's get default then
 6593: 		if ($key!~/^default&/) { next; }
 6594: 		&metadata_create_package_def($uri,$key,'default',
 6595: 					     \%metathesekeys);
 6596: 	    }
 6597: 	}
 6598: # are there custom rights to evaluate
 6599: 	if ($metaentry{':copyright'} eq 'custom') {
 6600: 
 6601:     #
 6602:     # Importing a rights file here
 6603:     #
 6604: 	    unless ($depthcount) {
 6605: 		my $location=$metaentry{':customdistributionfile'};
 6606: 		my $dir=$filename;
 6607: 		$dir=~s|[^/]*$||;
 6608: 		$location=&filelocation($dir,$location);
 6609: 		my $rights_metadata =
 6610: 		    &metadata($uri,'keys',$location,'_rights',
 6611: 			      $depthcount+1);
 6612: 		foreach my $rights (split(',',$rights_metadata)) {
 6613: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 6614: 		    $metathesekeys{$rights}=1;
 6615: 		}
 6616: 	    }
 6617: 	}
 6618: 	# uniqifiy package listing
 6619: 	my %seen;
 6620: 	my @uniq_packages =
 6621: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 6622: 	$metaentry{':packages'} = join(',',@uniq_packages);
 6623: 
 6624: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 6625: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 6626: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 6627: 	&do_cache_new('meta',$uri,\%metaentry,60*60);
 6628: # this is the end of "was not already recently cached
 6629:     }
 6630:     return $metaentry{':'.$what};
 6631: }
 6632: 
 6633: sub metadata_create_package_def {
 6634:     my ($uri,$key,$package,$metathesekeys)=@_;
 6635:     my ($pack,$name,$subp)=split(/\&/,$key);
 6636:     if ($subp eq 'default') { next; }
 6637:     
 6638:     if (defined($metaentry{':packages'})) {
 6639: 	$metaentry{':packages'}.=','.$package;
 6640:     } else {
 6641: 	$metaentry{':packages'}=$package;
 6642:     }
 6643:     my $value=$packagetab{$key};
 6644:     my $unikey;
 6645:     $unikey='parameter_0_'.$name;
 6646:     $metaentry{':'.$unikey.'.part'}=0;
 6647:     $$metathesekeys{$unikey}=1;
 6648:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6649: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 6650:     }
 6651:     if (defined($metaentry{':'.$unikey.'.default'})) {
 6652: 	$metaentry{':'.$unikey}=
 6653: 	    $metaentry{':'.$unikey.'.default'};
 6654:     }
 6655: }
 6656: 
 6657: sub metadata_generate_part0 {
 6658:     my ($metadata,$metacache,$uri) = @_;
 6659:     my %allnames;
 6660:     foreach my $metakey (keys(%$metadata)) {
 6661: 	if ($metakey=~/^parameter\_(.*)/) {
 6662: 	  my $part=$$metacache{':'.$metakey.'.part'};
 6663: 	  my $name=$$metacache{':'.$metakey.'.name'};
 6664: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 6665: 	    $allnames{$name}=$part;
 6666: 	  }
 6667: 	}
 6668:     }
 6669:     foreach my $name (keys(%allnames)) {
 6670:       $$metadata{"parameter_0_$name"}=1;
 6671:       my $key=":parameter_0_$name";
 6672:       $$metacache{"$key.part"}='0';
 6673:       $$metacache{"$key.name"}=$name;
 6674:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 6675: 					   $allnames{$name}.'_'.$name.
 6676: 					   '.type'};
 6677:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 6678: 			     '.display'};
 6679:       my $expr='[Part: '.$allnames{$name}.']';
 6680:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 6681:       $$metacache{"$key.display"}=$olddis;
 6682:     }
 6683: }
 6684: 
 6685: # ------------------------------------------------------ Devalidate title cache
 6686: 
 6687: sub devalidate_title_cache {
 6688:     my ($url)=@_;
 6689:     if (!$env{'request.course.id'}) { return; }
 6690:     my $symb=&symbread($url);
 6691:     if (!$symb) { return; }
 6692:     my $key=$env{'request.course.id'}."\0".$symb;
 6693:     &devalidate_cache_new('title',$key);
 6694: }
 6695: 
 6696: # ------------------------------------------------- Get the title of a resource
 6697: 
 6698: sub gettitle {
 6699:     my $urlsymb=shift;
 6700:     my $symb=&symbread($urlsymb);
 6701:     if ($symb) {
 6702: 	my $key=$env{'request.course.id'}."\0".$symb;
 6703: 	my ($result,$cached)=&is_cached_new('title',$key);
 6704: 	if (defined($cached)) { 
 6705: 	    return $result;
 6706: 	}
 6707: 	my ($map,$resid,$url)=&decode_symb($symb);
 6708: 	my $title='';
 6709: 	my %bighash;
 6710: 	if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6711: 		&GDBM_READER(),0640)) {
 6712: 	    my $mapid=$bighash{'map_pc_'.&clutter($map)};
 6713: 	    $title=$bighash{'title_'.$mapid.'.'.$resid};
 6714: 	    untie %bighash;
 6715: 	}
 6716: 	$title=~s/\&colon\;/\:/gs;
 6717: 	if ($title) {
 6718: 	    return &do_cache_new('title',$key,$title,600);
 6719: 	}
 6720: 	$urlsymb=$url;
 6721:     }
 6722:     my $title=&metadata($urlsymb,'title');
 6723:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 6724:     return $title;
 6725: }
 6726: 
 6727: sub get_slot {
 6728:     my ($which,$cnum,$cdom)=@_;
 6729:     if (!$cnum || !$cdom) {
 6730: 	(undef,my $courseid)=&whichuser();
 6731: 	$cdom=$env{'course.'.$courseid.'.domain'};
 6732: 	$cnum=$env{'course.'.$courseid.'.num'};
 6733:     }
 6734:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 6735:     my %slotinfo;
 6736:     if (exists($remembered{$key})) {
 6737: 	$slotinfo{$which} = $remembered{$key};
 6738:     } else {
 6739: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 6740: 	&Apache::lonhomework::showhash(%slotinfo);
 6741: 	my ($tmp)=keys(%slotinfo);
 6742: 	if ($tmp=~/^error:/) { return (); }
 6743: 	$remembered{$key} = $slotinfo{$which};
 6744:     }
 6745:     if (ref($slotinfo{$which}) eq 'HASH') {
 6746: 	return %{$slotinfo{$which}};
 6747:     }
 6748:     return $slotinfo{$which};
 6749: }
 6750: # ------------------------------------------------- Update symbolic store links
 6751: 
 6752: sub symblist {
 6753:     my ($mapname,%newhash)=@_;
 6754:     $mapname=&deversion(&declutter($mapname));
 6755:     my %hash;
 6756:     if (($env{'request.course.fn'}) && (%newhash)) {
 6757:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6758:                       &GDBM_WRCREAT(),0640)) {
 6759: 	    foreach my $url (keys %newhash) {
 6760: 		next if ($url eq 'last_known'
 6761: 			 && $env{'form.no_update_last_known'});
 6762: 		$hash{declutter($url)}=&encode_symb($mapname,
 6763: 						    $newhash{$url}->[1],
 6764: 						    $newhash{$url}->[0]);
 6765:             }
 6766:             if (untie(%hash)) {
 6767: 		return 'ok';
 6768:             }
 6769:         }
 6770:     }
 6771:     return 'error';
 6772: }
 6773: 
 6774: # --------------------------------------------------------------- Verify a symb
 6775: 
 6776: sub symbverify {
 6777:     my ($symb,$thisurl)=@_;
 6778:     my $thisfn=$thisurl;
 6779:     $thisfn=&declutter($thisfn);
 6780: # direct jump to resource in page or to a sequence - will construct own symbs
 6781:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 6782: # check URL part
 6783:     my ($map,$resid,$url)=&decode_symb($symb);
 6784: 
 6785:     unless ($url eq $thisfn) { return 0; }
 6786: 
 6787:     $symb=&symbclean($symb);
 6788:     $thisurl=&deversion($thisurl);
 6789:     $thisfn=&deversion($thisfn);
 6790: 
 6791:     my %bighash;
 6792:     my $okay=0;
 6793: 
 6794:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6795:                             &GDBM_READER(),0640)) {
 6796:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 6797:         unless ($ids) { 
 6798:            $ids=$bighash{'ids_/'.$thisurl};
 6799:         }
 6800:         if ($ids) {
 6801: # ------------------------------------------------------------------- Has ID(s)
 6802: 	    foreach my $id (split(/\,/,$ids)) {
 6803: 	       my ($mapid,$resid)=split(/\./,$id);
 6804:                if (
 6805:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 6806:    eq $symb) { 
 6807: 		   if (($env{'request.role.adv'}) ||
 6808: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 6809: 		       $okay=1; 
 6810: 		   }
 6811: 	       }
 6812: 	   }
 6813:         }
 6814: 	untie(%bighash);
 6815:     }
 6816:     return $okay;
 6817: }
 6818: 
 6819: # --------------------------------------------------------------- Clean-up symb
 6820: 
 6821: sub symbclean {
 6822:     my $symb=shift;
 6823:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6824: # remove version from map
 6825:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 6826: 
 6827: # remove version from URL
 6828:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 6829: 
 6830: # remove wrapper
 6831: 
 6832:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 6833:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 6834:     return $symb;
 6835: }
 6836: 
 6837: # ---------------------------------------------- Split symb to find map and url
 6838: 
 6839: sub encode_symb {
 6840:     my ($map,$resid,$url)=@_;
 6841:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 6842: }
 6843: 
 6844: sub decode_symb {
 6845:     my $symb=shift;
 6846:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 6847:     my ($map,$resid,$url)=split(/___/,$symb);
 6848:     return (&fixversion($map),$resid,&fixversion($url));
 6849: }
 6850: 
 6851: sub fixversion {
 6852:     my $fn=shift;
 6853:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 6854:     my %bighash;
 6855:     my $uri=&clutter($fn);
 6856:     my $key=$env{'request.course.id'}.'_'.$uri;
 6857: # is this cached?
 6858:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 6859:     if (defined($cached)) { return $result; }
 6860: # unfortunately not cached, or expired
 6861:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6862: 	    &GDBM_READER(),0640)) {
 6863:  	if ($bighash{'version_'.$uri}) {
 6864:  	    my $version=$bighash{'version_'.$uri};
 6865:  	    unless (($version eq 'mostrecent') || 
 6866: 		    ($version==&getversion($uri))) {
 6867:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 6868:  	    }
 6869:  	}
 6870:  	untie %bighash;
 6871:     }
 6872:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 6873: }
 6874: 
 6875: sub deversion {
 6876:     my $url=shift;
 6877:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 6878:     return $url;
 6879: }
 6880: 
 6881: # ------------------------------------------------------ Return symb list entry
 6882: 
 6883: sub symbread {
 6884:     my ($thisfn,$donotrecurse)=@_;
 6885:     my $cache_str='request.symbread.cached.'.$thisfn;
 6886:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 6887: # no filename provided? try from environment
 6888:     unless ($thisfn) {
 6889:         if ($env{'request.symb'}) {
 6890: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 6891: 	}
 6892: 	$thisfn=$env{'request.filename'};
 6893:     }
 6894:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 6895: # is that filename actually a symb? Verify, clean, and return
 6896:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 6897: 	if (&symbverify($thisfn,$1)) {
 6898: 	    return $env{$cache_str}=&symbclean($thisfn);
 6899: 	}
 6900:     }
 6901:     $thisfn=declutter($thisfn);
 6902:     my %hash;
 6903:     my %bighash;
 6904:     my $syval='';
 6905:     if (($env{'request.course.fn'}) && ($thisfn)) {
 6906:         my $targetfn = $thisfn;
 6907:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 6908:             $targetfn = 'adm/wrapper/'.$thisfn;
 6909:         }
 6910: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 6911: 	    $targetfn=$1;
 6912: 	}
 6913:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 6914:                       &GDBM_READER(),0640)) {
 6915: 	    $syval=$hash{$targetfn};
 6916:             untie(%hash);
 6917:         }
 6918: # ---------------------------------------------------------- There was an entry
 6919:         if ($syval) {
 6920: 	    #unless ($syval=~/\_\d+$/) {
 6921: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 6922: 		    #&appenv('request.ambiguous' => $thisfn);
 6923: 		    #return $env{$cache_str}='';
 6924: 		#}    
 6925: 		#$syval.=$1;
 6926: 	    #}
 6927:         } else {
 6928: # ------------------------------------------------------- Was not in symb table
 6929:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6930:                             &GDBM_READER(),0640)) {
 6931: # ---------------------------------------------- Get ID(s) for current resource
 6932:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 6933:               unless ($ids) { 
 6934:                  $ids=$bighash{'ids_/'.$thisfn};
 6935:               }
 6936:               unless ($ids) {
 6937: # alias?
 6938: 		  $ids=$bighash{'mapalias_'.$thisfn};
 6939:               }
 6940:               if ($ids) {
 6941: # ------------------------------------------------------------------- Has ID(s)
 6942:                  my @possibilities=split(/\,/,$ids);
 6943:                  if ($#possibilities==0) {
 6944: # ----------------------------------------------- There is only one possibility
 6945: 		     my ($mapid,$resid)=split(/\./,$ids);
 6946: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6947: 						    $resid,$thisfn);
 6948:                  } elsif (!$donotrecurse) {
 6949: # ------------------------------------------ There is more than one possibility
 6950:                      my $realpossible=0;
 6951:                      foreach my $id (@possibilities) {
 6952: 			 my $file=$bighash{'src_'.$id};
 6953:                          if (&allowed('bre',$file)) {
 6954:          		    my ($mapid,$resid)=split(/\./,$id);
 6955:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 6956: 				$realpossible++;
 6957:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 6958: 						    $resid,$thisfn);
 6959:                             }
 6960: 			 }
 6961:                      }
 6962: 		     if ($realpossible!=1) { $syval=''; }
 6963:                  } else {
 6964:                      $syval='';
 6965:                  }
 6966: 	      }
 6967:               untie(%bighash)
 6968:            }
 6969:         }
 6970:         if ($syval) {
 6971: 	    return $env{$cache_str}=$syval;
 6972:         }
 6973:     }
 6974:     &appenv('request.ambiguous' => $thisfn);
 6975:     return $env{$cache_str}='';
 6976: }
 6977: 
 6978: # ---------------------------------------------------------- Return random seed
 6979: 
 6980: sub numval {
 6981:     my $txt=shift;
 6982:     $txt=~tr/A-J/0-9/;
 6983:     $txt=~tr/a-j/0-9/;
 6984:     $txt=~tr/K-T/0-9/;
 6985:     $txt=~tr/k-t/0-9/;
 6986:     $txt=~tr/U-Z/0-5/;
 6987:     $txt=~tr/u-z/0-5/;
 6988:     $txt=~s/\D//g;
 6989:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 6990:     return int($txt);
 6991: }
 6992: 
 6993: sub numval2 {
 6994:     my $txt=shift;
 6995:     $txt=~tr/A-J/0-9/;
 6996:     $txt=~tr/a-j/0-9/;
 6997:     $txt=~tr/K-T/0-9/;
 6998:     $txt=~tr/k-t/0-9/;
 6999:     $txt=~tr/U-Z/0-5/;
 7000:     $txt=~tr/u-z/0-5/;
 7001:     $txt=~s/\D//g;
 7002:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7003:     my $total;
 7004:     foreach my $val (@txts) { $total+=$val; }
 7005:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7006:     return int($total);
 7007: }
 7008: 
 7009: sub numval3 {
 7010:     use integer;
 7011:     my $txt=shift;
 7012:     $txt=~tr/A-J/0-9/;
 7013:     $txt=~tr/a-j/0-9/;
 7014:     $txt=~tr/K-T/0-9/;
 7015:     $txt=~tr/k-t/0-9/;
 7016:     $txt=~tr/U-Z/0-5/;
 7017:     $txt=~tr/u-z/0-5/;
 7018:     $txt=~s/\D//g;
 7019:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7020:     my $total;
 7021:     foreach my $val (@txts) { $total+=$val; }
 7022:     if ($_64bit) { $total=(($total<<32)>>32); }
 7023:     return $total;
 7024: }
 7025: 
 7026: sub digest {
 7027:     my ($data)=@_;
 7028:     my $digest=&Digest::MD5::md5($data);
 7029:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7030:     my ($e,$f);
 7031:     {
 7032:         use integer;
 7033:         $e=($a+$b);
 7034:         $f=($c+$d);
 7035:         if ($_64bit) {
 7036:             $e=(($e<<32)>>32);
 7037:             $f=(($f<<32)>>32);
 7038:         }
 7039:     }
 7040:     if (wantarray) {
 7041: 	return ($e,$f);
 7042:     } else {
 7043: 	my $g;
 7044: 	{
 7045: 	    use integer;
 7046: 	    $g=($e+$f);
 7047: 	    if ($_64bit) {
 7048: 		$g=(($g<<32)>>32);
 7049: 	    }
 7050: 	}
 7051: 	return $g;
 7052:     }
 7053: }
 7054: 
 7055: sub latest_rnd_algorithm_id {
 7056:     return '64bit5';
 7057: }
 7058: 
 7059: sub get_rand_alg {
 7060:     my ($courseid)=@_;
 7061:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7062:     if ($courseid) {
 7063: 	return $env{"course.$courseid.rndseed"};
 7064:     }
 7065:     return &latest_rnd_algorithm_id();
 7066: }
 7067: 
 7068: sub validCODE {
 7069:     my ($CODE)=@_;
 7070:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7071:     return 0;
 7072: }
 7073: 
 7074: sub getCODE {
 7075:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7076:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7077: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7078: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7079: 	return $Apache::lonhomework::history{'resource.CODE'};
 7080:     }
 7081:     return undef;
 7082: }
 7083: 
 7084: sub rndseed {
 7085:     my ($symb,$courseid,$domain,$username)=@_;
 7086:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7087:     if (!$symb) {
 7088: 	unless ($symb=$wsymb) { return time; }
 7089:     }
 7090:     if (!$courseid) { $courseid=$wcourseid; }
 7091:     if (!$domain) { $domain=$wdomain; }
 7092:     if (!$username) { $username=$wusername }
 7093:     my $which=&get_rand_alg();
 7094: 
 7095:     if (defined(&getCODE())) {
 7096: 	if ($which eq '64bit5') {
 7097: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7098: 	} elsif ($which eq '64bit4') {
 7099: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7100: 	} else {
 7101: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7102: 	}
 7103:     } elsif ($which eq '64bit5') {
 7104: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7105:     } elsif ($which eq '64bit4') {
 7106: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7107:     } elsif ($which eq '64bit3') {
 7108: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7109:     } elsif ($which eq '64bit2') {
 7110: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7111:     } elsif ($which eq '64bit') {
 7112: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7113:     }
 7114:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7115: }
 7116: 
 7117: sub rndseed_32bit {
 7118:     my ($symb,$courseid,$domain,$username)=@_;
 7119:     {
 7120: 	use integer;
 7121: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7122: 	my $symbseed=numval($symb) << 22;
 7123: 	my $namechck=unpack("%32C*",$username) << 17;
 7124: 	my $nameseed=numval($username) << 12;
 7125: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7126: 	my $courseseed=unpack("%32C*",$courseid);
 7127: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7128: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7129: 	#&logthis("rndseed :$num:$symb");
 7130: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7131: 	return $num;
 7132:     }
 7133: }
 7134: 
 7135: sub rndseed_64bit {
 7136:     my ($symb,$courseid,$domain,$username)=@_;
 7137:     {
 7138: 	use integer;
 7139: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7140: 	my $symbseed=numval($symb) << 10;
 7141: 	my $namechck=unpack("%32S*",$username);
 7142: 	
 7143: 	my $nameseed=numval($username) << 21;
 7144: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7145: 	my $courseseed=unpack("%32S*",$courseid);
 7146: 	
 7147: 	my $num1=$symbchck+$symbseed+$namechck;
 7148: 	my $num2=$nameseed+$domainseed+$courseseed;
 7149: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7150: 	#&logthis("rndseed :$num:$symb");
 7151: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7152: 	return "$num1,$num2";
 7153:     }
 7154: }
 7155: 
 7156: sub rndseed_64bit2 {
 7157:     my ($symb,$courseid,$domain,$username)=@_;
 7158:     {
 7159: 	use integer;
 7160: 	# strings need to be an even # of cahracters long, it it is odd the
 7161:         # last characters gets thrown away
 7162: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7163: 	my $symbseed=numval($symb) << 10;
 7164: 	my $namechck=unpack("%32S*",$username.' ');
 7165: 	
 7166: 	my $nameseed=numval($username) << 21;
 7167: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7168: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7169: 	
 7170: 	my $num1=$symbchck+$symbseed+$namechck;
 7171: 	my $num2=$nameseed+$domainseed+$courseseed;
 7172: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7173: 	#&logthis("rndseed :$num:$symb");
 7174: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7175: 	return "$num1,$num2";
 7176:     }
 7177: }
 7178: 
 7179: sub rndseed_64bit3 {
 7180:     my ($symb,$courseid,$domain,$username)=@_;
 7181:     {
 7182: 	use integer;
 7183: 	# strings need to be an even # of cahracters long, it it is odd the
 7184:         # last characters gets thrown away
 7185: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7186: 	my $symbseed=numval2($symb) << 10;
 7187: 	my $namechck=unpack("%32S*",$username.' ');
 7188: 	
 7189: 	my $nameseed=numval2($username) << 21;
 7190: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7191: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7192: 	
 7193: 	my $num1=$symbchck+$symbseed+$namechck;
 7194: 	my $num2=$nameseed+$domainseed+$courseseed;
 7195: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7196: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7197: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7198: 	
 7199: 	return "$num1:$num2";
 7200:     }
 7201: }
 7202: 
 7203: sub rndseed_64bit4 {
 7204:     my ($symb,$courseid,$domain,$username)=@_;
 7205:     {
 7206: 	use integer;
 7207: 	# strings need to be an even # of cahracters long, it it is odd the
 7208:         # last characters gets thrown away
 7209: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7210: 	my $symbseed=numval3($symb) << 10;
 7211: 	my $namechck=unpack("%32S*",$username.' ');
 7212: 	
 7213: 	my $nameseed=numval3($username) << 21;
 7214: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7215: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7216: 	
 7217: 	my $num1=$symbchck+$symbseed+$namechck;
 7218: 	my $num2=$nameseed+$domainseed+$courseseed;
 7219: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7220: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7221: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7222: 	
 7223: 	return "$num1:$num2";
 7224:     }
 7225: }
 7226: 
 7227: sub rndseed_64bit5 {
 7228:     my ($symb,$courseid,$domain,$username)=@_;
 7229:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7230:     return "$num1:$num2";
 7231: }
 7232: 
 7233: sub rndseed_CODE_64bit {
 7234:     my ($symb,$courseid,$domain,$username)=@_;
 7235:     {
 7236: 	use integer;
 7237: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7238: 	my $symbseed=numval2($symb);
 7239: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7240: 	my $CODEseed=numval(&getCODE());
 7241: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7242: 	my $num1=$symbseed+$CODEchck;
 7243: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7244: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7245: 	#&logthis("rndseed :$num1:$num2:$symb");
 7246: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7247: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7248: 	return "$num1:$num2";
 7249:     }
 7250: }
 7251: 
 7252: sub rndseed_CODE_64bit4 {
 7253:     my ($symb,$courseid,$domain,$username)=@_;
 7254:     {
 7255: 	use integer;
 7256: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7257: 	my $symbseed=numval3($symb);
 7258: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7259: 	my $CODEseed=numval3(&getCODE());
 7260: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7261: 	my $num1=$symbseed+$CODEchck;
 7262: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7263: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7264: 	#&logthis("rndseed :$num1:$num2:$symb");
 7265: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7266: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7267: 	return "$num1:$num2";
 7268:     }
 7269: }
 7270: 
 7271: sub rndseed_CODE_64bit5 {
 7272:     my ($symb,$courseid,$domain,$username)=@_;
 7273:     my $code = &getCODE();
 7274:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7275:     return "$num1:$num2";
 7276: }
 7277: 
 7278: sub setup_random_from_rndseed {
 7279:     my ($rndseed)=@_;
 7280:     if ($rndseed =~/([,:])/) {
 7281: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7282: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7283:     } else {
 7284: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7285:     }
 7286: }
 7287: 
 7288: sub latest_receipt_algorithm_id {
 7289:     return 'receipt3';
 7290: }
 7291: 
 7292: sub recunique {
 7293:     my $fucourseid=shift;
 7294:     my $unique;
 7295:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7296: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7297: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7298:     } else {
 7299: 	$unique=$perlvar{'lonReceipt'};
 7300:     }
 7301:     return unpack("%32C*",$unique);
 7302: }
 7303: 
 7304: sub recprefix {
 7305:     my $fucourseid=shift;
 7306:     my $prefix;
 7307:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7308: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7309: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7310:     } else {
 7311: 	$prefix=$perlvar{'lonHostID'};
 7312:     }
 7313:     return unpack("%32C*",$prefix);
 7314: }
 7315: 
 7316: sub ireceipt {
 7317:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7318: 
 7319:     my $return =&recprefix($fucourseid).'-';
 7320: 
 7321:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7322: 	$env{'request.state'} eq 'construct') {
 7323: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7324: 	return $return;
 7325:     }
 7326: 
 7327:     my $cuname=unpack("%32C*",$funame);
 7328:     my $cudom=unpack("%32C*",$fudom);
 7329:     my $cucourseid=unpack("%32C*",$fucourseid);
 7330:     my $cusymb=unpack("%32C*",$fusymb);
 7331:     my $cunique=&recunique($fucourseid);
 7332:     my $cpart=unpack("%32S*",$part);
 7333:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7334: 
 7335: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7336: 			       
 7337: 	$return.= ($cunique%$cuname+
 7338: 		   $cunique%$cudom+
 7339: 		   $cusymb%$cuname+
 7340: 		   $cusymb%$cudom+
 7341: 		   $cucourseid%$cuname+
 7342: 		   $cucourseid%$cudom+
 7343: 		   $cpart%$cuname+
 7344: 		   $cpart%$cudom);
 7345:     } else {
 7346: 	$return.= ($cunique%$cuname+
 7347: 		   $cunique%$cudom+
 7348: 		   $cusymb%$cuname+
 7349: 		   $cusymb%$cudom+
 7350: 		   $cucourseid%$cuname+
 7351: 		   $cucourseid%$cudom);
 7352:     }
 7353:     return $return;
 7354: }
 7355: 
 7356: sub receipt {
 7357:     my ($part)=@_;
 7358:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7359:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7360: }
 7361: 
 7362: sub whichuser {
 7363:     my ($passedsymb)=@_;
 7364:     my ($symb,$courseid,$domain,$name,$publicuser);
 7365:     if (defined($env{'form.grade_symb'})) {
 7366: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7367: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7368: 	if (!$allowed &&
 7369: 	    exists($env{'request.course.sec'}) &&
 7370: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7371: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7372: 			      '/'.$env{'request.course.sec'});
 7373: 	}
 7374: 	if ($allowed) {
 7375: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7376: 	    $courseid=$tmp_courseid;
 7377: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7378: 	    ($name)=&get_env_multiple('form.grade_username');
 7379: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7380: 	}
 7381:     }
 7382:     if (!$passedsymb) {
 7383: 	$symb=&symbread();
 7384:     } else {
 7385: 	$symb=$passedsymb;
 7386:     }
 7387:     $courseid=$env{'request.course.id'};
 7388:     $domain=$env{'user.domain'};
 7389:     $name=$env{'user.name'};
 7390:     if ($name eq 'public' && $domain eq 'public') {
 7391: 	if (!defined($env{'form.username'})) {
 7392: 	    $env{'form.username'}.=time.rand(10000000);
 7393: 	}
 7394: 	$name.=$env{'form.username'};
 7395:     }
 7396:     return ($symb,$courseid,$domain,$name,$publicuser);
 7397: 
 7398: }
 7399: 
 7400: # ------------------------------------------------------------ Serves up a file
 7401: # returns either the contents of the file or 
 7402: # -1 if the file doesn't exist
 7403: #
 7404: # if the target is a file that was uploaded via DOCS, 
 7405: # a check will be made to see if a current copy exists on the local server,
 7406: # if it does this will be served, otherwise a copy will be retrieved from
 7407: # the home server for the course and stored in /home/httpd/html/userfiles on
 7408: # the local server.   
 7409: 
 7410: sub getfile {
 7411:     my ($file) = @_;
 7412:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7413:     &repcopy($file);
 7414:     return &readfile($file);
 7415: }
 7416: 
 7417: sub repcopy_userfile {
 7418:     my ($file)=@_;
 7419:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7420:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7421:     my ($cdom,$cnum,$filename) = 
 7422: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7423:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7424:     if (-e "$file") {
 7425: # we already have a local copy, check it out
 7426: 	my @fileinfo = stat($file);
 7427: 	my $rtncode;
 7428: 	my $info;
 7429: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7430: 	if ($lwpresp ne 'ok') {
 7431: # there is no such file anymore, even though we had a local copy
 7432: 	    if ($rtncode eq '404') {
 7433: 		unlink($file);
 7434: 	    }
 7435: 	    return -1;
 7436: 	}
 7437: 	if ($info < $fileinfo[9]) {
 7438: # nice, the file we have is up-to-date, just say okay
 7439: 	    return 'ok';
 7440: 	} else {
 7441: # the file is outdated, get rid of it
 7442: 	    unlink($file);
 7443: 	}
 7444:     }
 7445: # one way or the other, at this point, we don't have the file
 7446: # construct the correct path for the file
 7447:     my @parts = ($cdom,$cnum); 
 7448:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7449: 	push @parts, split(/\//,$1);
 7450:     }
 7451:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7452:     foreach my $part (@parts) {
 7453: 	$path .= '/'.$part;
 7454: 	if (!-e $path) {
 7455: 	    mkdir($path,0770);
 7456: 	}
 7457:     }
 7458: # now the path exists for sure
 7459: # get a user agent
 7460:     my $ua=new LWP::UserAgent;
 7461:     my $transferfile=$file.'.in.transfer';
 7462: # FIXME: this should flock
 7463:     if (-e $transferfile) { return 'ok'; }
 7464:     my $request;
 7465:     $uri=~s/^\///;
 7466:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7467:     my $response=$ua->request($request,$transferfile);
 7468: # did it work?
 7469:     if ($response->is_error()) {
 7470: 	unlink($transferfile);
 7471: 	&logthis("Userfile repcopy failed for $uri");
 7472: 	return -1;
 7473:     }
 7474: # worked, rename the transfer file
 7475:     rename($transferfile,$file);
 7476:     return 'ok';
 7477: }
 7478: 
 7479: sub tokenwrapper {
 7480:     my $uri=shift;
 7481:     $uri=~s|^http\://([^/]+)||;
 7482:     $uri=~s|^/||;
 7483:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7484:     my $token=$1;
 7485:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7486:     if ($udom && $uname && $file) {
 7487: 	$file=~s|(\?\.*)*$||;
 7488:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7489:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7490:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7491:                                '&tokenissued='.$perlvar{'lonHostID'};
 7492:     } else {
 7493:         return '/adm/notfound.html';
 7494:     }
 7495: }
 7496: 
 7497: # call with reqtype HEAD: get last modification time
 7498: # call with reqtype GET: get the file contents
 7499: # Do not call this with reqtype GET for large files! It loads everything into memory
 7500: #
 7501: sub getuploaded {
 7502:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7503:     $uri=~s/^\///;
 7504:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7505:     my $ua=new LWP::UserAgent;
 7506:     my $request=new HTTP::Request($reqtype,$uri);
 7507:     my $response=$ua->request($request);
 7508:     $$rtncode = $response->code;
 7509:     if (! $response->is_success()) {
 7510: 	return 'failed';
 7511:     }      
 7512:     if ($reqtype eq 'HEAD') {
 7513: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7514:     } elsif ($reqtype eq 'GET') {
 7515: 	$$info = $response->content;
 7516:     }
 7517:     return 'ok';
 7518: }
 7519: 
 7520: sub readfile {
 7521:     my $file = shift;
 7522:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7523:     my $fh;
 7524:     open($fh,"<$file");
 7525:     my $a='';
 7526:     while (my $line = <$fh>) { $a .= $line; }
 7527:     return $a;
 7528: }
 7529: 
 7530: sub filelocation {
 7531:     my ($dir,$file) = @_;
 7532:     my $location;
 7533:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 7534: 
 7535:     if ($file =~ m-^/adm/-) {
 7536: 	$file=~s-^/adm/wrapper/-/-;
 7537: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7538:     }
 7539: 
 7540:     if ($file=~m:^/~:) { # is a contruction space reference
 7541:         $location = $file;
 7542:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 7543:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 7544: 	# is a correct contruction space reference
 7545:         $location = $file;
 7546:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 7547:         my ($udom,$uname,$filename)=
 7548:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 7549:         my $home=&homeserver($uname,$udom);
 7550:         my $is_me=0;
 7551:         my @ids=&current_machine_ids();
 7552:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 7553:         if ($is_me) {
 7554:   	    $location=&propath($udom,$uname).
 7555:   	      '/userfiles/'.$filename;
 7556:         } else {
 7557:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 7558:   	      $udom.'/'.$uname.'/'.$filename;
 7559:         }
 7560:     } elsif ($file =~ m-^/adm/-) {
 7561: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 7562:     } else {
 7563:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7564:         $file=~s:^/res/:/:;
 7565:         if ( !( $file =~ m:^/:) ) {
 7566:             $location = $dir. '/'.$file;
 7567:         } else {
 7568:             $location = '/home/httpd/html/res'.$file;
 7569:         }
 7570:     }
 7571:     $location=~s://+:/:g; # remove duplicate /
 7572:     while ($location=~m:/\.\./:) {$location=~ s:/[^/]+/\.\./:/:g;} #remove dir/..
 7573:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 7574:     return $location;
 7575: }
 7576: 
 7577: sub hreflocation {
 7578:     my ($dir,$file)=@_;
 7579:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 7580: 	$file=filelocation($dir,$file);
 7581:     } elsif ($file=~m-^/adm/-) {
 7582: 	$file=~s-^/adm/wrapper/-/-;
 7583: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 7584:     }
 7585:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 7586: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 7587:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 7588: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 7589:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 7590: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 7591: 	    -/uploaded/$1/$2/-x;
 7592:     }
 7593:     return $file;
 7594: }
 7595: 
 7596: sub current_machine_domains {
 7597:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 7598: }
 7599: 
 7600: sub machine_domains {
 7601:     my ($hostname) = @_;
 7602:     my @domains;
 7603:     my %hostname = &all_hostnames();
 7604:     while( my($id, $name) = each(%hostname)) {
 7605: #	&logthis("-$id-$name-$hostname-");
 7606: 	if ($hostname eq $name) {
 7607: 	    push(@domains,&host_domain($id));
 7608: 	}
 7609:     }
 7610:     return @domains;
 7611: }
 7612: 
 7613: sub current_machine_ids {
 7614:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 7615: }
 7616: 
 7617: sub machine_ids {
 7618:     my ($hostname) = @_;
 7619:     $hostname ||= &hostname($perlvar{'lonHostID'});
 7620:     my @ids;
 7621:     my %name_to_host = &all_names();
 7622:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 7623: 	return @{ $name_to_host{$hostname} };
 7624:     }
 7625:     return;
 7626: }
 7627: 
 7628: sub additional_machine_domains {
 7629:     my @domains;
 7630:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 7631:     while( my $line = <$fh>) {
 7632:         $line =~ s/\s//g;
 7633:         push(@domains,$line);
 7634:     }
 7635:     return @domains;
 7636: }
 7637: 
 7638: sub default_login_domain {
 7639:     my $domain = $perlvar{'lonDefDomain'};
 7640:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 7641:     foreach my $posdom (&current_machine_domains(),
 7642:                         &additional_machine_domains()) {
 7643:         if (lc($posdom) eq lc($testdomain)) {
 7644:             $domain=$posdom;
 7645:             last;
 7646:         }
 7647:     }
 7648:     return $domain;
 7649: }
 7650: 
 7651: # ------------------------------------------------------------- Declutters URLs
 7652: 
 7653: sub declutter {
 7654:     my $thisfn=shift;
 7655:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7656:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 7657:     $thisfn=~s/^\///;
 7658:     $thisfn=~s|^adm/wrapper/||;
 7659:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 7660:     $thisfn=~s/^res\///;
 7661:     $thisfn=~s/\?.+$//;
 7662:     return $thisfn;
 7663: }
 7664: 
 7665: # ------------------------------------------------------------- Clutter up URLs
 7666: 
 7667: sub clutter {
 7668:     my $thisfn='/'.&declutter(shift);
 7669:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 7670: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 7671:        $thisfn='/res'.$thisfn; 
 7672:     }
 7673:     if ($thisfn !~m|/adm|) {
 7674: 	if ($thisfn =~ m|/ext/|) {
 7675: 	    $thisfn='/adm/wrapper'.$thisfn;
 7676: 	} else {
 7677: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 7678: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 7679: 	    if ($embstyle eq 'ssi'
 7680: 		|| ($embstyle eq 'hdn')
 7681: 		|| ($embstyle eq 'rat')
 7682: 		|| ($embstyle eq 'prv')
 7683: 		|| ($embstyle eq 'ign')) {
 7684: 		#do nothing with these
 7685: 	    } elsif (($embstyle eq 'img') 
 7686: 		|| ($embstyle eq 'emb')
 7687: 		|| ($embstyle eq 'wrp')) {
 7688: 		$thisfn='/adm/wrapper'.$thisfn;
 7689: 	    } elsif ($embstyle eq 'unk'
 7690: 		     && $thisfn!~/\.(sequence|page)$/) {
 7691: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 7692: 	    } else {
 7693: #		&logthis("Got a blank emb style");
 7694: 	    }
 7695: 	}
 7696:     }
 7697:     return $thisfn;
 7698: }
 7699: 
 7700: sub clutter_with_no_wrapper {
 7701:     my $uri = &clutter(shift);
 7702:     if ($uri =~ m-^/adm/-) {
 7703: 	$uri =~ s-^/adm/wrapper/-/-;
 7704: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 7705:     }
 7706:     return $uri;
 7707: }
 7708: 
 7709: sub freeze_escape {
 7710:     my ($value)=@_;
 7711:     if (ref($value)) {
 7712: 	$value=&nfreeze($value);
 7713: 	return '__FROZEN__'.&escape($value);
 7714:     }
 7715:     return &escape($value);
 7716: }
 7717: 
 7718: 
 7719: sub thaw_unescape {
 7720:     my ($value)=@_;
 7721:     if ($value =~ /^__FROZEN__/) {
 7722: 	substr($value,0,10,undef);
 7723: 	$value=&unescape($value);
 7724: 	return &thaw($value);
 7725:     }
 7726:     return &unescape($value);
 7727: }
 7728: 
 7729: sub correct_line_ends {
 7730:     my ($result)=@_;
 7731:     $$result =~s/\r\n/\n/mg;
 7732:     $$result =~s/\r/\n/mg;
 7733: }
 7734: # ================================================================ Main Program
 7735: 
 7736: sub goodbye {
 7737:    &logthis("Starting Shut down");
 7738: #not converted to using infrastruture and probably shouldn't be
 7739:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 7740: #converted
 7741: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 7742:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 7743: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 7744: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 7745: #1.1 only
 7746: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 7747: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 7748: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 7749: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 7750:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 7751:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 7752:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 7753:    &flushcourselogs();
 7754:    &logthis("Shutting down");
 7755: }
 7756: 
 7757: sub get_dns {
 7758:     my ($url,$func,$ignore_cache) = @_;
 7759:     if (!$ignore_cache) {
 7760: 	my ($content,$cached)=
 7761: 	    &Apache::lonnet::is_cached_new('dns',$url);
 7762: 	if ($cached) {
 7763: 	    &$func($content);
 7764: 	    return;
 7765: 	}
 7766:     }
 7767: 
 7768:     my %alldns;
 7769:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7770:     foreach my $dns (<$config>) {
 7771: 	next if ($dns !~ /^\^(\S*)/x);
 7772: 	$alldns{$1} = 1;
 7773:     }
 7774:     while (%alldns) {
 7775: 	my ($dns) = keys(%alldns);
 7776: 	delete($alldns{$dns});
 7777: 	my $ua=new LWP::UserAgent;
 7778: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 7779: 	my $response=$ua->request($request);
 7780: 	next if ($response->is_error());
 7781: 	my @content = split("\n",$response->content);
 7782: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 7783: 	&$func(\@content);
 7784: 	return;
 7785:     }
 7786:     close($config);
 7787:     my $which = (split('/',$url))[3];
 7788:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 7789:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 7790:     my @content = <$config>;
 7791:     &$func(\@content);
 7792:     return;
 7793: }
 7794: # ------------------------------------------------------------ Read domain file
 7795: {
 7796:     my $loaded;
 7797:     my %domain;
 7798: 
 7799:     sub parse_domain_tab {
 7800: 	my ($lines) = @_;
 7801: 	foreach my $line (@$lines) {
 7802: 	    next if ($line =~ /^(\#|\s*$ )/x);
 7803: 
 7804: 	    chomp($line);
 7805: 	    my ($name,@elements) = split(/:/,$line,9);
 7806: 	    my %this_domain;
 7807: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 7808: 			       'lang_def', 'city', 'longi', 'lati',
 7809: 			       'primary') {
 7810: 		$this_domain{$field} = shift(@elements);
 7811: 	    }
 7812: 	    $domain{$name} = \%this_domain;
 7813: 	}
 7814:     }
 7815: 
 7816:     sub reset_domain_info {
 7817: 	undef($loaded);
 7818: 	undef(%domain);
 7819:     }
 7820: 
 7821:     sub load_domain_tab {
 7822: 	my ($ignore_cache) = @_;
 7823: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 7824: 	my $fh;
 7825: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 7826: 	    my @lines = <$fh>;
 7827: 	    &parse_domain_tab(\@lines);
 7828: 	}
 7829: 	close($fh);
 7830: 	$loaded = 1;
 7831:     }
 7832: 
 7833:     sub domain {
 7834: 	&load_domain_tab() if (!$loaded);
 7835: 
 7836: 	my ($name,$what) = @_;
 7837: 	return if ( !exists($domain{$name}) );
 7838: 
 7839: 	if (!$what) {
 7840: 	    return $domain{$name}{'description'};
 7841: 	}
 7842: 	return $domain{$name}{$what};
 7843:     }
 7844: }
 7845: 
 7846: 
 7847: # ------------------------------------------------------------- Read hosts file
 7848: {
 7849:     my %hostname;
 7850:     my %hostdom;
 7851:     my %libserv;
 7852:     my $loaded;
 7853:     my %name_to_host;
 7854: 
 7855:     sub parse_hosts_tab {
 7856: 	my ($file) = @_;
 7857: 	foreach my $configline (@$file) {
 7858: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 7859: 	    next if ($configline =~ /^\^/);
 7860: 	    chomp($configline);
 7861: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 7862: 	    $name=~s/\s//g;
 7863: 	    if ($id && $domain && $role && $name) {
 7864: 		$hostname{$id}=$name;
 7865: 		push(@{$name_to_host{$name}}, $id);
 7866: 		$hostdom{$id}=$domain;
 7867: 		if ($role eq 'library') { $libserv{$id}=$name; }
 7868: 	    }
 7869: 	}
 7870:     }
 7871:     
 7872:     sub reset_hosts_info {
 7873: 	&reset_domain_info();
 7874: 	&reset_hosts_ip_info();
 7875: 	undef(%name_to_host);
 7876: 	undef(%hostname);
 7877: 	undef(%hostdom);
 7878: 	undef(%libserv);
 7879: 	undef($loaded);
 7880:     }
 7881: 
 7882:     sub load_hosts_tab {
 7883: 	my ($ignore_cache) = @_;
 7884: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 7885: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 7886: 	my @config = <$config>;
 7887: 	&parse_hosts_tab(\@config);
 7888: 	close($config);
 7889: 	$loaded=1;
 7890:     }
 7891: 
 7892:     sub hostname {
 7893: 	&load_hosts_tab() if (!$loaded);
 7894: 
 7895: 	my ($lonid) = @_;
 7896: 	return $hostname{$lonid};
 7897:     }
 7898: 
 7899:     sub all_hostnames {
 7900: 	&load_hosts_tab() if (!$loaded);
 7901: 
 7902: 	return %hostname;
 7903:     }
 7904: 
 7905:     sub all_names {
 7906: 	&load_hosts_tab() if (!$loaded);
 7907: 
 7908: 	return %name_to_host;
 7909:     }
 7910: 
 7911:     sub is_library {
 7912: 	&load_hosts_tab() if (!$loaded);
 7913: 
 7914: 	return exists($libserv{$_[0]});
 7915:     }
 7916: 
 7917:     sub all_library {
 7918: 	&load_hosts_tab() if (!$loaded);
 7919: 
 7920: 	return %libserv;
 7921:     }
 7922: 
 7923:     sub get_servers {
 7924: 	&load_hosts_tab() if (!$loaded);
 7925: 
 7926: 	my ($domain,$type) = @_;
 7927: 	my %possible_hosts = ($type eq 'library') ? %libserv
 7928: 	                                          : %hostname;
 7929: 	my %result;
 7930: 	if (ref($domain) eq 'ARRAY') {
 7931: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7932: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 7933: 		    $result{$host} = $hostname;
 7934: 		}
 7935: 	    }
 7936: 	} else {
 7937: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 7938: 		if ($hostdom{$host} eq $domain) {
 7939: 		    $result{$host} = $hostname;
 7940: 		}
 7941: 	    }
 7942: 	}
 7943: 	return %result;
 7944:     }
 7945: 
 7946:     sub host_domain {
 7947: 	&load_hosts_tab() if (!$loaded);
 7948: 
 7949: 	my ($lonid) = @_;
 7950: 	return $hostdom{$lonid};
 7951:     }
 7952: 
 7953:     sub all_domains {
 7954: 	&load_hosts_tab() if (!$loaded);
 7955: 
 7956: 	my %seen;
 7957: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 7958: 	return @uniq;
 7959:     }
 7960: }
 7961: 
 7962: { 
 7963:     my %iphost;
 7964:     my %name_to_ip;
 7965:     my %lonid_to_ip;
 7966: 
 7967:     sub get_hosts_from_ip {
 7968: 	my ($ip) = @_;
 7969: 	my %iphosts = &get_iphost();
 7970: 	if (ref($iphosts{$ip})) {
 7971: 	    return @{$iphosts{$ip}};
 7972: 	}
 7973: 	return;
 7974:     }
 7975:     
 7976:     sub reset_hosts_ip_info {
 7977: 	undef(%iphost);
 7978: 	undef(%name_to_ip);
 7979: 	undef(%lonid_to_ip);
 7980:     }
 7981: 
 7982:     sub get_host_ip {
 7983: 	my ($lonid) = @_;
 7984: 	if (exists($lonid_to_ip{$lonid})) {
 7985: 	    return $lonid_to_ip{$lonid};
 7986: 	}
 7987: 	my $name=&hostname($lonid);
 7988:    	my $ip = gethostbyname($name);
 7989: 	return if (!$ip || length($ip) ne 4);
 7990: 	$ip=inet_ntoa($ip);
 7991: 	$name_to_ip{$name}   = $ip;
 7992: 	$lonid_to_ip{$lonid} = $ip;
 7993: 	return $ip;
 7994:     }
 7995:     
 7996:     sub get_iphost {
 7997: 	my ($ignore_cache) = @_;
 7998: 	if (!$ignore_cache) {
 7999: 	    if (%iphost) {
 8000: 		return %iphost;
 8001: 	    }
 8002: 	    my ($ip_info,$cached)=
 8003: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8004: 	    if ($cached) {
 8005: 		%iphost      = %{$ip_info->[0]};
 8006: 		%name_to_ip  = %{$ip_info->[1]};
 8007: 		%lonid_to_ip = %{$ip_info->[2]};
 8008: 		return %iphost;
 8009: 	    }
 8010: 	}
 8011: 	my %name_to_host = &all_names();
 8012: 	foreach my $name (keys(%name_to_host)) {
 8013: 	    my $ip;
 8014: 	    if (!exists($name_to_ip{$name})) {
 8015: 		$ip = gethostbyname($name);
 8016: 		if (!$ip || length($ip) ne 4) {
 8017: 		    &logthis("Skipping name $name no IP found");
 8018: 		    next;
 8019: 		}
 8020: 		$ip=inet_ntoa($ip);
 8021: 		$name_to_ip{$name} = $ip;
 8022: 	    } else {
 8023: 		$ip = $name_to_ip{$name};
 8024: 	    }
 8025: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8026: 		$lonid_to_ip{$id} = $ip;
 8027: 	    }
 8028: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8029: 	}
 8030: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8031: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8032: 				      24*60*60);
 8033: 
 8034: 	return %iphost;
 8035:     }
 8036: }
 8037: 
 8038: BEGIN {
 8039: 
 8040: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8041:     unless ($readit) {
 8042: {
 8043:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8044:     %perlvar = (%perlvar,%{$configvars});
 8045: }
 8046: 
 8047: 
 8048: # ------------------------------------------------------ Read spare server file
 8049: {
 8050:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8051: 
 8052:     while (my $configline=<$config>) {
 8053:        chomp($configline);
 8054:        if ($configline) {
 8055: 	   my ($host,$type) = split(':',$configline,2);
 8056: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8057: 	   push(@{ $spareid{$type} }, $host);
 8058:        }
 8059:     }
 8060:     close($config);
 8061: }
 8062: # ------------------------------------------------------------ Read permissions
 8063: {
 8064:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8065: 
 8066:     while (my $configline=<$config>) {
 8067: 	chomp($configline);
 8068: 	if ($configline) {
 8069: 	    my ($role,$perm)=split(/ /,$configline);
 8070: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8071: 	}
 8072:     }
 8073:     close($config);
 8074: }
 8075: 
 8076: # -------------------------------------------- Read plain texts for permissions
 8077: {
 8078:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8079: 
 8080:     while (my $configline=<$config>) {
 8081: 	chomp($configline);
 8082: 	if ($configline) {
 8083: 	    my ($short,@plain)=split(/:/,$configline);
 8084:             %{$prp{$short}} = ();
 8085: 	    if (@plain > 0) {
 8086:                 $prp{$short}{'std'} = $plain[0];
 8087:                 for (my $i=1; $i<@plain; $i++) {
 8088:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8089:                 }
 8090:             }
 8091: 	}
 8092:     }
 8093:     close($config);
 8094: }
 8095: 
 8096: # ---------------------------------------------------------- Read package table
 8097: {
 8098:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8099: 
 8100:     while (my $configline=<$config>) {
 8101: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8102: 	chomp($configline);
 8103: 	my ($short,$plain)=split(/:/,$configline);
 8104: 	my ($pack,$name)=split(/\&/,$short);
 8105: 	if ($plain ne '') {
 8106: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8107: 	    $packagetab{$short}=$plain; 
 8108: 	}
 8109:     }
 8110:     close($config);
 8111: }
 8112: 
 8113: # ------------- set up temporary directory
 8114: {
 8115:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8116: 
 8117: }
 8118: 
 8119: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8120: 				'compress_threshold'=> 20_000,
 8121:  			        });
 8122: 
 8123: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8124: $dumpcount=0;
 8125: 
 8126: &logtouch();
 8127: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8128: $readit=1;
 8129:     {
 8130: 	use integer;
 8131: 	my $test=(2**32)+1;
 8132: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8133: 	&logthis(" Detected 64bit platform ($_64bit)");
 8134:     }
 8135: }
 8136: }
 8137: 
 8138: 1;
 8139: __END__
 8140: 
 8141: =pod
 8142: 
 8143: =head1 NAME
 8144: 
 8145: Apache::lonnet - Subroutines to ask questions about things in the network.
 8146: 
 8147: =head1 SYNOPSIS
 8148: 
 8149: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8150: 
 8151:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8152: 
 8153: Common parameters:
 8154: 
 8155: =over 4
 8156: 
 8157: =item *
 8158: 
 8159: $uname : an internal username (if $cname expecting a course Id specifically)
 8160: 
 8161: =item *
 8162: 
 8163: $udom : a domain (if $cdom expecting a course's domain specifically)
 8164: 
 8165: =item *
 8166: 
 8167: $symb : a resource instance identifier
 8168: 
 8169: =item *
 8170: 
 8171: $namespace : the name of a .db file that contains the data needed or
 8172: being set.
 8173: 
 8174: =back
 8175: 
 8176: =head1 OVERVIEW
 8177: 
 8178: lonnet provides subroutines which interact with the
 8179: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8180: about classes, users, and resources.
 8181: 
 8182: For many of these objects you can also use this to store data about
 8183: them or modify them in various ways.
 8184: 
 8185: =head2 Symbs
 8186: 
 8187: To identify a specific instance of a resource, LON-CAPA uses symbols
 8188: or "symbs"X<symb>. These identifiers are built from the URL of the
 8189: map, the resource number of the resource in the map, and the URL of
 8190: the resource itself. The latter is somewhat redundant, but might help
 8191: if maps change.
 8192: 
 8193: An example is
 8194: 
 8195:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8196: 
 8197: The respective map entry is
 8198: 
 8199:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8200:   title="Problem 2">
 8201:  </resource>
 8202: 
 8203: Symbs are used by the random number generator, as well as to store and
 8204: restore data specific to a certain instance of for example a problem.
 8205: 
 8206: =head2 Storing And Retrieving Data
 8207: 
 8208: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8209: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8210: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8211: is is the non-critical message twin of cstore. These functions are for
 8212: handlers to store a perl hash to a user's permanent data space in an
 8213: easy manner, and to retrieve it again on another call. It is expected
 8214: that a handler would use this once at the beginning to retrieve data,
 8215: and then again once at the end to send only the new data back.
 8216: 
 8217: The data is stored in the user's data directory on the user's
 8218: homeserver under the ID of the course.
 8219: 
 8220: The hash that is returned by restore will have all of the previous
 8221: value for all of the elements of the hash.
 8222: 
 8223: Example:
 8224: 
 8225:  #creating a hash
 8226:  my %hash;
 8227:  $hash{'foo'}='bar';
 8228: 
 8229:  #storing it
 8230:  &Apache::lonnet::cstore(\%hash);
 8231: 
 8232:  #changing a value
 8233:  $hash{'foo'}='notbar';
 8234: 
 8235:  #adding a new value
 8236:  $hash{'bar'}='foo';
 8237:  &Apache::lonnet::cstore(\%hash);
 8238: 
 8239:  #retrieving the hash
 8240:  my %history=&Apache::lonnet::restore();
 8241: 
 8242:  #print the hash
 8243:  foreach my $key (sort(keys(%history))) {
 8244:    print("\%history{$key} = $history{$key}");
 8245:  }
 8246: 
 8247: Will print out:
 8248: 
 8249:  %history{1:foo} = bar
 8250:  %history{1:keys} = foo:timestamp
 8251:  %history{1:timestamp} = 990455579
 8252:  %history{2:bar} = foo
 8253:  %history{2:foo} = notbar
 8254:  %history{2:keys} = foo:bar:timestamp
 8255:  %history{2:timestamp} = 990455580
 8256:  %history{bar} = foo
 8257:  %history{foo} = notbar
 8258:  %history{timestamp} = 990455580
 8259:  %history{version} = 2
 8260: 
 8261: Note that the special hash entries C<keys>, C<version> and
 8262: C<timestamp> were added to the hash. C<version> will be equal to the
 8263: total number of versions of the data that have been stored. The
 8264: C<timestamp> attribute will be the UNIX time the hash was
 8265: stored. C<keys> is available in every historical section to list which
 8266: keys were added or changed at a specific historical revision of a
 8267: hash.
 8268: 
 8269: B<Warning>: do not store the hash that restore returns directly. This
 8270: will cause a mess since it will restore the historical keys as if the
 8271: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8272: 
 8273: Calling convention:
 8274: 
 8275:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8276:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8277: 
 8278: For more detailed information, see lonnet specific documentation.
 8279: 
 8280: =head1 RETURN MESSAGES
 8281: 
 8282: =over 4
 8283: 
 8284: =item * B<con_lost>: unable to contact remote host
 8285: 
 8286: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8287: when the connection is brought back up
 8288: 
 8289: =item * B<con_failed>: unable to contact remote host and unable to save message
 8290: for later delivery
 8291: 
 8292: =item * B<error:>: an error a occured, a description of the error follows the :
 8293: 
 8294: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8295: that was requested
 8296: 
 8297: =back
 8298: 
 8299: =head1 PUBLIC SUBROUTINES
 8300: 
 8301: =head2 Session Environment Functions
 8302: 
 8303: =over 4
 8304: 
 8305: =item * 
 8306: X<appenv()>
 8307: B<appenv(%hash)>: the value of %hash is written to
 8308: the user envirnoment file, and will be restored for each access this
 8309: user makes during this session, also modifies the %env for the current
 8310: process
 8311: 
 8312: =item *
 8313: X<delenv()>
 8314: B<delenv($regexp)>: removes all items from the session
 8315: environment file that matches the regular expression in $regexp. The
 8316: values are also delted from the current processes %env.
 8317: 
 8318: =item * get_env_multiple($name) 
 8319: 
 8320: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8321: values may be defined and end up as an array ref.
 8322: 
 8323: returns an array of values
 8324: 
 8325: =back
 8326: 
 8327: =head2 User Information
 8328: 
 8329: =over 4
 8330: 
 8331: =item *
 8332: X<queryauthenticate()>
 8333: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8334: authentication scheme
 8335: 
 8336: =item *
 8337: X<authenticate()>
 8338: B<authenticate($uname,$upass,$udom)>: try to
 8339: authenticate user from domain's lib servers (first use the current
 8340: one). C<$upass> should be the users password.
 8341: 
 8342: =item *
 8343: X<homeserver()>
 8344: B<homeserver($uname,$udom)>: find the server which has
 8345: the user's directory and files (there must be only one), this caches
 8346: the answer, and also caches if there is a borken connection.
 8347: 
 8348: =item *
 8349: X<idget()>
 8350: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8351: (IDs are a unique resource in a domain, there must be only 1 ID per
 8352: username, and only 1 username per ID in a specific domain) (returns
 8353: hash: id=>name,id=>name)
 8354: 
 8355: =item *
 8356: X<idrget()>
 8357: B<idrget($udom,@unames)>: find the IDs behind a list of
 8358: usernames (returns hash: name=>id,name=>id)
 8359: 
 8360: =item *
 8361: X<idput()>
 8362: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8363: 
 8364: =item *
 8365: X<rolesinit()>
 8366: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8367: 
 8368: =item *
 8369: X<getsection()>
 8370: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8371: course $cname, return section name/number or '' for "not in course"
 8372: and '-1' for "no section"
 8373: 
 8374: =item *
 8375: X<userenvironment()>
 8376: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8377: passed in @what from the requested user's environment, returns a hash
 8378: 
 8379: =item * 
 8380: X<userlog_query()>
 8381: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8382: activity.log file. %filters defines filters applied when parsing the
 8383: log file. These can be start or end timestamps, or the type of action
 8384: - log to look for Login or Logout events, check for Checkin or
 8385: Checkout, role for role selection. The response is in the form
 8386: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8387: escaped strings of the action recorded in the activity.log file.
 8388: 
 8389: =back
 8390: 
 8391: =head2 User Roles
 8392: 
 8393: =over 4
 8394: 
 8395: =item *
 8396: 
 8397: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8398:  F: full access
 8399:  U,I,K: authentication modes (cxx only)
 8400:  '': forbidden
 8401:  1: user needs to choose course
 8402:  2: browse allowed
 8403:  A: passphrase authentication needed
 8404: 
 8405: =item *
 8406: 
 8407: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8408: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8409: and course level
 8410: 
 8411: =item *
 8412: 
 8413: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8414: explanation of a user role term
 8415: 
 8416: =item *
 8417: 
 8418: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms) :
 8419: All arguments are optional. Returns a hash of a roles, either for
 8420: co-author/assistant author roles for a user's Construction Space
 8421: (default), or if $context is 'user', roles for the user himself,
 8422: In the hash, keys are set to colon-sparated $uname,$udom,and $role,
 8423: and value is set to colon-separated start and end times for the role.
 8424: If no username and domain are specified, will default to current
 8425: user/domain. Types, roles, and roledoms are references to arrays,
 8426: of role statuses (active, future or previous), roles 
 8427: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8428: to restrict the list of roles reported. If no array ref is 
 8429: provided for types, will default to return only active roles.
 8430: 
 8431: =back
 8432: 
 8433: =head2 User Modification
 8434: 
 8435: =over 4
 8436: 
 8437: =item *
 8438: 
 8439: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8440: user for the level given by URL.  Optional start and end dates (leave empty
 8441: string or zero for "no date")
 8442: 
 8443: =item *
 8444: 
 8445: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8446: change a users, password, possible return values are: ok,
 8447: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8448: refused
 8449: 
 8450: =item *
 8451: 
 8452: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8453: 
 8454: =item *
 8455: 
 8456: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8457: modify user
 8458: 
 8459: =item *
 8460: 
 8461: modifystudent
 8462: 
 8463: modify a students enrollment and identification information.
 8464: The course id is resolved based on the current users environment.  
 8465: This means the envoking user must be a course coordinator or otherwise
 8466: associated with a course.
 8467: 
 8468: This call is essentially a wrapper for lonnet::modifyuser and
 8469: lonnet::modify_student_enrollment
 8470: 
 8471: Inputs: 
 8472: 
 8473: =over 4
 8474: 
 8475: =item B<$udom> Students loncapa domain
 8476: 
 8477: =item B<$uname> Students loncapa login name
 8478: 
 8479: =item B<$uid> Students id/student number
 8480: 
 8481: =item B<$umode> Students authentication mode
 8482: 
 8483: =item B<$upass> Students password
 8484: 
 8485: =item B<$first> Students first name
 8486: 
 8487: =item B<$middle> Students middle name
 8488: 
 8489: =item B<$last> Students last name
 8490: 
 8491: =item B<$gene> Students generation
 8492: 
 8493: =item B<$usec> Students section in course
 8494: 
 8495: =item B<$end> Unix time of the roles expiration
 8496: 
 8497: =item B<$start> Unix time of the roles start date
 8498: 
 8499: =item B<$forceid> If defined, allow $uid to be changed
 8500: 
 8501: =item B<$desiredhome> server to use as home server for student
 8502: 
 8503: =back
 8504: 
 8505: =item *
 8506: 
 8507: modify_student_enrollment
 8508: 
 8509: Change a students enrollment status in a class.  The environment variable
 8510: 'role.request.course' must be defined for this function to proceed.
 8511: 
 8512: Inputs:
 8513: 
 8514: =over 4
 8515: 
 8516: =item $udom, students domain
 8517: 
 8518: =item $uname, students name
 8519: 
 8520: =item $uid, students user id
 8521: 
 8522: =item $first, students first name
 8523: 
 8524: =item $middle
 8525: 
 8526: =item $last
 8527: 
 8528: =item $gene
 8529: 
 8530: =item $usec
 8531: 
 8532: =item $end
 8533: 
 8534: =item $start
 8535: 
 8536: =back
 8537: 
 8538: 
 8539: =item *
 8540: 
 8541: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 8542: custom role; give a custom role to a user for the level given by URL.  Specify
 8543: name and domain of role author, and role name
 8544: 
 8545: =item *
 8546: 
 8547: revokerole($udom,$uname,$url,$role) : revoke a role for url
 8548: 
 8549: =item *
 8550: 
 8551: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 8552: 
 8553: =back
 8554: 
 8555: =head2 Course Infomation
 8556: 
 8557: =over 4
 8558: 
 8559: =item *
 8560: 
 8561: coursedescription($courseid) : returns a hash of information about the
 8562: specified course id, including all environment settings for the
 8563: course, the description of the course will be in the hash under the
 8564: key 'description'
 8565: 
 8566: =item *
 8567: 
 8568: resdata($name,$domain,$type,@which) : request for current parameter
 8569: setting for a specific $type, where $type is either 'course' or 'user',
 8570: @what should be a list of parameters to ask about. This routine caches
 8571: answers for 5 minutes.
 8572: 
 8573: =item *
 8574: 
 8575: get_courseresdata($courseid, $domain) : dump the entire course resource
 8576: data base, returning a hash that is keyed by the resource name and has
 8577: values that are the resource value.  I believe that the timestamps and
 8578: versions are also returned.
 8579: 
 8580: 
 8581: =back
 8582: 
 8583: =head2 Course Modification
 8584: 
 8585: =over 4
 8586: 
 8587: =item *
 8588: 
 8589: writecoursepref($courseid,%prefs) : write preferences (environment
 8590: database) for a course
 8591: 
 8592: =item *
 8593: 
 8594: createcourse($udom,$description,$url) : make/modify course
 8595: 
 8596: =back
 8597: 
 8598: =head2 Resource Subroutines
 8599: 
 8600: =over 4
 8601: 
 8602: =item *
 8603: 
 8604: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 8605: 
 8606: =item *
 8607: 
 8608: repcopy($filename) : subscribes to the requested file, and attempts to
 8609: replicate from the owning library server, Might return
 8610: 'unavailable', 'not_found', 'forbidden', 'ok', or
 8611: 'bad_request', also attempts to grab the metadata for the
 8612: resource. Expects the local filesystem pathname
 8613: (/home/httpd/html/res/....)
 8614: 
 8615: =back
 8616: 
 8617: =head2 Resource Information
 8618: 
 8619: =over 4
 8620: 
 8621: =item *
 8622: 
 8623: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 8624: a vairety of different possible values, $varname should be a request
 8625: string, and the other parameters can be used to specify who and what
 8626: one is asking about.
 8627: 
 8628: Possible values for $varname are environment.lastname (or other item
 8629: from the envirnment hash), user.name (or someother aspect about the
 8630: user), resource.0.maxtries (or some other part and parameter of a
 8631: resource)
 8632: 
 8633: =item *
 8634: 
 8635: directcondval($number) : get current value of a condition; reads from a state
 8636: string
 8637: 
 8638: =item *
 8639: 
 8640: condval($condidx) : value of condition index based on state
 8641: 
 8642: =item *
 8643: 
 8644: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 8645: resource's metadata, $what should be either a specific key, or either
 8646: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 8647: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 8648: 
 8649: this function automatically caches all requests
 8650: 
 8651: =item *
 8652: 
 8653: metadata_query($query,$custom,$customshow) : make a metadata query against the
 8654: network of library servers; returns file handle of where SQL and regex results
 8655: will be stored for query
 8656: 
 8657: =item *
 8658: 
 8659: symbread($filename) : return symbolic list entry (filename argument optional);
 8660: returns the data handle
 8661: 
 8662: =item *
 8663: 
 8664: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 8665: a possible symb for the URL in $thisfn, and if is an encryypted
 8666: resource that the user accessed using /enc/ returns a 1 on success, 0
 8667: on failure, user must be in a course, as it assumes the existance of
 8668: the course initial hash, and uses $env('request.course.id'}
 8669: 
 8670: 
 8671: =item *
 8672: 
 8673: symbclean($symb) : removes versions numbers from a symb, returns the
 8674: cleaned symb
 8675: 
 8676: =item *
 8677: 
 8678: is_on_map($uri) : checks if the $uri is somewhere on the current
 8679: course map, user must be in a course for it to work.
 8680: 
 8681: =item *
 8682: 
 8683: numval($salt) : return random seed value (addend for rndseed)
 8684: 
 8685: =item *
 8686: 
 8687: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 8688: a random seed, all arguments are optional, if they aren't sent it uses the
 8689: environment to derive them. Note: if symb isn't sent and it can't get one
 8690: from &symbread it will use the current time as its return value
 8691: 
 8692: =item *
 8693: 
 8694: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 8695: unfakeable, receipt
 8696: 
 8697: =item *
 8698: 
 8699: receipt() : API to ireceipt working off of env values; given out to users
 8700: 
 8701: =item *
 8702: 
 8703: countacc($url) : count the number of accesses to a given URL
 8704: 
 8705: =item *
 8706: 
 8707: 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
 8708: 
 8709: =item *
 8710: 
 8711: 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)
 8712: 
 8713: =item *
 8714: 
 8715: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 8716: 
 8717: =item *
 8718: 
 8719: devalidate($symb) : devalidate temporary spreadsheet calculations,
 8720: forcing spreadsheet to reevaluate the resource scores next time.
 8721: 
 8722: =back
 8723: 
 8724: =head2 Storing/Retreiving Data
 8725: 
 8726: =over 4
 8727: 
 8728: =item *
 8729: 
 8730: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 8731: for this url; hashref needs to be given and should be a \%hashname; the
 8732: remaining args aren't required and if they aren't passed or are '' they will
 8733: be derived from the env
 8734: 
 8735: =item *
 8736: 
 8737: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 8738: uses critical subroutine
 8739: 
 8740: =item *
 8741: 
 8742: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 8743: all args are optional
 8744: 
 8745: =item *
 8746: 
 8747: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 8748: dumps the complete (or key matching regexp) namespace into a hash
 8749: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 8750: normally &store()ed into
 8751: 
 8752: $range should be either an integer '100' (give me the first 100
 8753:                                            matching records)
 8754:               or be  two integers sperated by a - with no spaces
 8755:                  '30-50' (give me the 30th through the 50th matching
 8756:                           records)
 8757: 
 8758: 
 8759: =item *
 8760: 
 8761: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 8762: replaces a &store() version of data with a replacement set of data
 8763: for a particular resource in a namespace passed in the $storehash hash 
 8764: reference
 8765: 
 8766: =item *
 8767: 
 8768: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 8769: works very similar to store/cstore, but all data is stored in a
 8770: temporary location and can be reset using tmpreset, $storehash should
 8771: be a hash reference, returns nothing on success
 8772: 
 8773: =item *
 8774: 
 8775: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 8776: similar to restore, but all data is stored in a temporary location and
 8777: can be reset using tmpreset. Returns a hash of values on success,
 8778: error string otherwise.
 8779: 
 8780: =item *
 8781: 
 8782: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 8783: deltes all keys for $symb form the temporary storage hash.
 8784: 
 8785: =item *
 8786: 
 8787: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8788: reference filled in from namesp ($udom and $uname are optional)
 8789: 
 8790: =item *
 8791: 
 8792: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 8793: namesp ($udom and $uname are optional)
 8794: 
 8795: =item *
 8796: 
 8797: dump($namespace,$udom,$uname,$regexp,$range) : 
 8798: dumps the complete (or key matching regexp) namespace into a hash
 8799: ($udom, $uname, $regexp, $range are optional)
 8800: 
 8801: $range should be either an integer '100' (give me the first 100
 8802:                                            matching records)
 8803:               or be  two integers sperated by a - with no spaces
 8804:                  '30-50' (give me the 30th through the 50th matching
 8805:                           records)
 8806: =item *
 8807: 
 8808: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 8809: $store can be a scalar, an array reference, or if the amount to be 
 8810: incremented is > 1, a hash reference.
 8811: 
 8812: ($udom and $uname are optional)
 8813: 
 8814: =item *
 8815: 
 8816: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 8817: ($udom and $uname are optional)
 8818: 
 8819: =item *
 8820: 
 8821: cput($namespace,$storehash,$udom,$uname) : critical put
 8822: ($udom and $uname are optional)
 8823: 
 8824: =item *
 8825: 
 8826: newput($namespace,$storehash,$udom,$uname) :
 8827: 
 8828: Attempts to store the items in the $storehash, but only if they don't
 8829: currently exist, if this succeeds you can be certain that you have 
 8830: successfully created a new key value pair in the $namespace db.
 8831: 
 8832: 
 8833: Args:
 8834:  $namespace: name of database to store values to
 8835:  $storehash: hashref to store to the db
 8836:  $udom: (optional) domain of user containing the db
 8837:  $uname: (optional) name of user caontaining the db
 8838: 
 8839: Returns:
 8840:  'ok' -> succeeded in storing all keys of $storehash
 8841:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 8842:                         least <key> already existed in the db (other
 8843:                         requested keys may also already exist)
 8844:  'error: <msg>' -> unable to tie the DB or other erorr occured
 8845:  'con_lost' -> unable to contact request server
 8846:  'refused' -> action was not allowed by remote machine
 8847: 
 8848: 
 8849: =item *
 8850: 
 8851: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 8852: reference filled in from namesp (encrypts the return communication)
 8853: ($udom and $uname are optional)
 8854: 
 8855: =item *
 8856: 
 8857: log($udom,$name,$home,$message) : write to permanent log for user; use
 8858: critical subroutine
 8859: 
 8860: =item *
 8861: 
 8862: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 8863: array reference filled in from namespace found in domain level on either
 8864: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 8865: 
 8866: =item *
 8867: 
 8868: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 8869: domain level either on specified domain server ($uhome) or primary domain 
 8870: server ($udom and $uhome are optional)
 8871: 
 8872: =back
 8873: 
 8874: =head2 Network Status Functions
 8875: 
 8876: =over 4
 8877: 
 8878: =item *
 8879: 
 8880: dirlist($uri) : return directory list based on URI
 8881: 
 8882: =item *
 8883: 
 8884: spareserver() : find server with least workload from spare.tab
 8885: 
 8886: =back
 8887: 
 8888: =head2 Apache Request
 8889: 
 8890: =over 4
 8891: 
 8892: =item *
 8893: 
 8894: ssi($url,%hash) : server side include, does a complete request cycle on url to
 8895: localhost, posts hash
 8896: 
 8897: =back
 8898: 
 8899: =head2 Data to String to Data
 8900: 
 8901: =over 4
 8902: 
 8903: =item *
 8904: 
 8905: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 8906: and '&' separators, supports elements that are arrayrefs and hashrefs
 8907: 
 8908: =item *
 8909: 
 8910: hashref2str($hashref) : convert a hashref into a string complete with
 8911: escaping and '=' and '&' separators, supports elements that are
 8912: arrayrefs and hashrefs
 8913: 
 8914: =item *
 8915: 
 8916: arrayref2str($arrayref) : convert an arrayref into a string complete
 8917: with escaping and '&' separators, supports elements that are arrayrefs
 8918: and hashrefs
 8919: 
 8920: =item *
 8921: 
 8922: str2hash($string) : convert string to hash using unescaping and
 8923: splitting on '=' and '&', supports elements that are arrayrefs and
 8924: hashrefs
 8925: 
 8926: =item *
 8927: 
 8928: str2array($string) : convert string to hash using unescaping and
 8929: splitting on '&', supports elements that are arrayrefs and hashrefs
 8930: 
 8931: =back
 8932: 
 8933: =head2 Logging Routines
 8934: 
 8935: =over 4
 8936: 
 8937: These routines allow one to make log messages in the lonnet.log and
 8938: lonnet.perm logfiles.
 8939: 
 8940: =item *
 8941: 
 8942: logtouch() : make sure the logfile, lonnet.log, exists
 8943: 
 8944: =item *
 8945: 
 8946: logthis() : append message to the normal lonnet.log file, it gets
 8947: preiodically rolled over and deleted.
 8948: 
 8949: =item *
 8950: 
 8951: logperm() : append a permanent message to lonnet.perm.log, this log
 8952: file never gets deleted by any automated portion of the system, only
 8953: messages of critical importance should go in here.
 8954: 
 8955: =back
 8956: 
 8957: =head2 General File Helper Routines
 8958: 
 8959: =over 4
 8960: 
 8961: =item *
 8962: 
 8963: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 8964: (a) files in /uploaded
 8965:   (i) If a local copy of the file exists - 
 8966:       compares modification date of local copy with last-modified date for 
 8967:       definitive version stored on home server for course. If local copy is 
 8968:       stale, requests a new version from the home server and stores it. 
 8969:       If the original has been removed from the home server, then local copy 
 8970:       is unlinked.
 8971:   (ii) If local copy does not exist -
 8972:       requests the file from the home server and stores it. 
 8973:   
 8974:   If $caller is 'uploadrep':  
 8975:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 8976:     for request for files originally uploaded via DOCS. 
 8977:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 8978:   
 8979:   Otherwise:
 8980:      This indicates a call from the content generation phase of the request.
 8981:      -  returns the entire contents of the file or -1.
 8982:      
 8983: (b) files in /res
 8984:    - returns the entire contents of a file or -1; 
 8985:    it properly subscribes to and replicates the file if neccessary.
 8986: 
 8987: 
 8988: =item *
 8989: 
 8990: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 8991:                   reference
 8992: 
 8993: returns either a stat() list of data about the file or an empty list
 8994: if the file doesn't exist or couldn't find out about it (connection
 8995: problems or user unknown)
 8996: 
 8997: =item *
 8998: 
 8999: filelocation($dir,$file) : returns file system location of a file
 9000: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9001: directory that relative $file lookups are to looked in ($dir of /a/dir
 9002: and a file of ../bob will become /a/bob)
 9003: 
 9004: =item *
 9005: 
 9006: hreflocation($dir,$file) : returns file system location or a URL; same as
 9007: filelocation except for hrefs
 9008: 
 9009: =item *
 9010: 
 9011: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9012: 
 9013: =back
 9014: 
 9015: =head2 Usererfile file routines (/uploaded*)
 9016: 
 9017: =over 4
 9018: 
 9019: =item *
 9020: 
 9021: userfileupload(): main rotine for putting a file in a user or course's
 9022:                   filespace, arguments are,
 9023: 
 9024:  formname - required - this is the name of the element in $env where the
 9025:            filename, and the contents of the file to create/modifed exist
 9026:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9027:            contents of the file is located in $env{'form.'.$formname}
 9028:  coursedoc - if true, store the file in the course of the active role
 9029:              of the current user
 9030:  subdir - required - subdirectory to put the file in under ../userfiles/
 9031:          if undefined, it will be placed in "unknown"
 9032: 
 9033:  (This routine calls clean_filename() to remove any dangerous
 9034:  characters from the filename, and then calls finuserfileupload() to
 9035:  complete the transaction)
 9036: 
 9037:  returns either the url of the uploaded file (/uploaded/....) if successful
 9038:  and /adm/notfound.html if unsuccessful
 9039: 
 9040: =item *
 9041: 
 9042: clean_filename(): routine for cleaing a filename up for storage in
 9043:                  userfile space, argument is:
 9044: 
 9045:  filename - proposed filename
 9046: 
 9047: returns: the new clean filename
 9048: 
 9049: =item *
 9050: 
 9051: finishuserfileupload(): routine that creaes and sends the file to
 9052: userspace, probably shouldn't be called directly
 9053: 
 9054:   docuname: username or courseid of destination for the file
 9055:   docudom: domain of user/course of destination for the file
 9056:   formname: same as for userfileupload()
 9057:   fname: filename (inculding subdirectories) for the file
 9058: 
 9059:  returns either the url of the uploaded file (/uploaded/....) if successful
 9060:  and /adm/notfound.html if unsuccessful
 9061: 
 9062: =item *
 9063: 
 9064: renameuserfile(): renames an existing userfile to a new name
 9065: 
 9066:   Args:
 9067:    docuname: username or courseid of destination for the file
 9068:    docudom: domain of user/course of destination for the file
 9069:    old: current file name (including any subdirs under userfiles)
 9070:    new: desired file name (including any subdirs under userfiles)
 9071: 
 9072: =item *
 9073: 
 9074: mkdiruserfile(): creates a directory is a userfiles dir
 9075: 
 9076:   Args:
 9077:    docuname: username or courseid of destination for the file
 9078:    docudom: domain of user/course of destination for the file
 9079:    dir: dir to create (including any subdirs under userfiles)
 9080: 
 9081: =item *
 9082: 
 9083: removeuserfile(): removes a file that exists in userfiles
 9084: 
 9085:   Args:
 9086:    docuname: username or courseid of destination for the file
 9087:    docudom: domain of user/course of destination for the file
 9088:    fname: filname to delete (including any subdirs under userfiles)
 9089: 
 9090: =item *
 9091: 
 9092: removeuploadedurl(): convience function for removeuserfile()
 9093: 
 9094:   Args:
 9095:    url:  a full /uploaded/... url to delete
 9096: 
 9097: =item * 
 9098: 
 9099: get_portfile_permissions():
 9100:   Args:
 9101:     domain: domain of user or course contain the portfolio files
 9102:     user: name of user or num of course contain the portfolio files
 9103:   Returns:
 9104:     hashref of a dump of the proper file_permissions.db
 9105:    
 9106: 
 9107: =item * 
 9108: 
 9109: get_access_controls():
 9110: 
 9111: Args:
 9112:   current_permissions: the hash ref returned from get_portfile_permissions()
 9113:   group: (optional) the group you want the files associated with
 9114:   file: (optional) the file you want access info on
 9115: 
 9116: Returns:
 9117:     a hash (keys are file names) of hashes containing
 9118:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9119:         values are XML containing access control settings (see below) 
 9120: 
 9121: Internal notes:
 9122: 
 9123:  access controls are stored in file_permissions.db as key=value pairs.
 9124:     key -> path to file/file_name\0uniqueID:scope_end_start
 9125:         where scope -> public,guest,course,group,domains or users.
 9126:               end -> UNIX time for end of access (0 -> no end date)
 9127:               start -> UNIX time for start of access
 9128: 
 9129:     value -> XML description of access control
 9130:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9131:             <start></start>
 9132:             <end></end>
 9133: 
 9134:             <password></password>  for scope type = guest
 9135: 
 9136:             <domain></domain>     for scope type = course or group
 9137:             <number></number>
 9138:             <roles id="">
 9139:              <role></role>
 9140:              <access></access>
 9141:              <section></section>
 9142:              <group></group>
 9143:             </roles>
 9144: 
 9145:             <dom></dom>         for scope type = domains
 9146: 
 9147:             <users>             for scope type = users
 9148:              <user>
 9149:               <uname></uname>
 9150:               <udom></udom>
 9151:              </user>
 9152:             </users>
 9153:            </scope> 
 9154:               
 9155:  Access data is also aggregated for each file in an additional key=value pair:
 9156:  key -> path to file/file_name\0accesscontrol 
 9157:  value -> reference to hash
 9158:           hash contains key = value pairs
 9159:           where key = uniqueID:scope_end_start
 9160:                 value = UNIX time record was last updated
 9161: 
 9162:           Used to improve speed of look-ups of access controls for each file.  
 9163:  
 9164:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9165: 
 9166: modify_access_controls():
 9167: 
 9168: Modifies access controls for a portfolio file
 9169: Args
 9170: 1. file name
 9171: 2. reference to hash of required changes,
 9172: 3. domain
 9173: 4. username
 9174:   where domain,username are the domain of the portfolio owner 
 9175:   (either a user or a course) 
 9176: 
 9177: Returns:
 9178: 1. result of additions or updates ('ok' or 'error', with error message). 
 9179: 2. result of deletions ('ok' or 'error', with error message).
 9180: 3. reference to hash of any new or updated access controls.
 9181: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9182:    key = integer (inbound ID)
 9183:    value = uniqueID  
 9184: 
 9185: =back
 9186: 
 9187: =head2 HTTP Helper Routines
 9188: 
 9189: =over 4
 9190: 
 9191: =item *
 9192: 
 9193: escape() : unpack non-word characters into CGI-compatible hex codes
 9194: 
 9195: =item *
 9196: 
 9197: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9198: 
 9199: =back
 9200: 
 9201: =head1 PRIVATE SUBROUTINES
 9202: 
 9203: =head2 Underlying communication routines (Shouldn't call)
 9204: 
 9205: =over 4
 9206: 
 9207: =item *
 9208: 
 9209: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9210: 
 9211: =item *
 9212: 
 9213: reply() : uses subreply to send a message to remote machine, logs all failures
 9214: 
 9215: =item *
 9216: 
 9217: critical() : passes a critical message to another server; if cannot
 9218: get through then place message in connection buffer directory and
 9219: returns con_delayed, if incapable of saving message, returns
 9220: con_failed
 9221: 
 9222: =item *
 9223: 
 9224: reconlonc() : tries to reconnect lonc client processes.
 9225: 
 9226: =back
 9227: 
 9228: =head2 Resource Access Logging
 9229: 
 9230: =over 4
 9231: 
 9232: =item *
 9233: 
 9234: flushcourselogs() : flush (save) buffer logs and access logs
 9235: 
 9236: =item *
 9237: 
 9238: courselog($what) : save message for course in hash
 9239: 
 9240: =item *
 9241: 
 9242: courseacclog($what) : save message for course using &courselog().  Perform
 9243: special processing for specific resource types (problems, exams, quizzes, etc).
 9244: 
 9245: =item *
 9246: 
 9247: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9248: as a PerlChildExitHandler
 9249: 
 9250: =back
 9251: 
 9252: =head2 Other
 9253: 
 9254: =over 4
 9255: 
 9256: =item *
 9257: 
 9258: symblist($mapname,%newhash) : update symbolic storage links
 9259: 
 9260: =back
 9261: 
 9262: =cut
 9263: 

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