File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.945: download - view: text, annotated - select for diffs
Fri Feb 29 21:01:24 2008 UTC (16 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Replace "selfenroll" with "selfcreate" in various subroutine names, and modify text which refers to self-enrollment to refer to user creation of accounts.
- Intended to clarify that these procedures relate to a user creating his/her own account in a LON-CAPA domain as opposed to self-enrolling in a course, once the user has an account.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.945 2008/02/29 21:01:24 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: package Apache::lonnet;
   31: 
   32: use strict;
   33: use LWP::UserAgent();
   34: use HTTP::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: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  324: 	if (!$opened) {
  325: 	    return 0;
  326: 	}
  327: 	flock($idf,LOCK_SH);
  328: 	@profile=<$idf>;
  329: 	close($idf);
  330:     }
  331:     my %temp_env;
  332:     foreach my $line (@profile) {
  333: 	if ($line !~ m/=/) {
  334: 	    return 0;
  335: 	}
  336: 	chomp($line);
  337: 	my ($envname,$envvalue)=split(/=/,$line,2);
  338: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  339:     }
  340:     unlink("$lonidsdir/$handle.id");
  341:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  342: 	    0640)) {
  343: 	%disk_env = %temp_env;
  344: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  345: 	untie(%disk_env);
  346:     }
  347:     return 1;
  348: }
  349: 
  350: # ------------------------------------------- Transfer profile into environment
  351: my $env_loaded;
  352: sub transfer_profile_to_env {
  353:     my ($lonidsdir,$handle,$force_transfer) = @_;
  354:     if (!$force_transfer && $env_loaded) { return; } 
  355: 
  356:     if (!defined($lonidsdir)) {
  357: 	$lonidsdir = $perlvar{'lonIDsDir'};
  358:     }
  359:     if (!defined($handle)) {
  360:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  361:     }
  362: 
  363:     my $convert;
  364:     {
  365:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  366: 	if (!$opened) {
  367: 	    return;
  368: 	}
  369: 	flock($idf,LOCK_SH);
  370: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  371: 		&GDBM_READER(),0640)) {
  372: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  373: 	    untie(%disk_env);
  374: 	} else {
  375: 	    $convert = 1;
  376: 	}
  377:     }
  378:     if ($convert) {
  379: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  380: 	    &logthis("Failed to load session, or convert session.");
  381: 	}
  382:     }
  383: 
  384:     my %remove;
  385:     while ( my $envname = each(%env) ) {
  386:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  387:             if ($time < time-300) {
  388:                 $remove{$key}++;
  389:             }
  390:         }
  391:     }
  392: 
  393:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  394:     $env_loaded=1;
  395:     foreach my $expired_key (keys(%remove)) {
  396:         &delenv($expired_key);
  397:     }
  398: }
  399: 
  400: # ---------------------------------------------------- Check for valid session 
  401: sub check_for_valid_session {
  402:     my ($r) = @_;
  403:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  404:     my $lonid=$cookies{'lonID'};
  405:     return undef if (!$lonid);
  406: 
  407:     my $handle=&LONCAPA::clean_handle($lonid->value);
  408:     my $lonidsdir=$r->dir_config('lonIDsDir');
  409:     return undef if (!-e "$lonidsdir/$handle.id");
  410: 
  411:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  412:     return undef if (!$opened);
  413: 
  414:     flock($idf,LOCK_SH);
  415:     my %disk_env;
  416:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  417: 	    &GDBM_READER(),0640)) {
  418: 	return undef;	
  419:     }
  420: 
  421:     if (!defined($disk_env{'user.name'})
  422: 	|| !defined($disk_env{'user.domain'})) {
  423: 	return undef;
  424:     }
  425:     return $handle;
  426: }
  427: 
  428: sub timed_flock {
  429:     my ($file,$lock_type) = @_;
  430:     my $failed=0;
  431:     eval {
  432: 	local $SIG{__DIE__}='DEFAULT';
  433: 	local $SIG{ALRM}=sub {
  434: 	    $failed=1;
  435: 	    die("failed lock");
  436: 	};
  437: 	alarm(13);
  438: 	flock($file,$lock_type);
  439: 	alarm(0);
  440:     };
  441:     if ($failed) {
  442: 	return undef;
  443:     } else {
  444: 	return 1;
  445:     }
  446: }
  447: 
  448: # ---------------------------------------------------------- Append Environment
  449: 
  450: sub appenv {
  451:     my %newenv=@_;
  452:     foreach my $key (keys(%newenv)) {
  453: 	if (($newenv{$key}=~/^user\.role/) || ($newenv{$key}=~/^user\.priv/)) {
  454:             &logthis("<font color=\"blue\">WARNING: ".
  455:                 "Attempt to modify environment ".$key." to ".$newenv{$key}
  456:                 .'</font>');
  457: 	    delete($newenv{$key});
  458:         } else {
  459:             $env{$key}=$newenv{$key};
  460:         }
  461:     }
  462:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  463:     if ($opened
  464: 	&& &timed_flock($env_file,LOCK_EX)
  465: 	&&
  466: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  467: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  468: 	while (my ($key,$value) = each(%newenv)) {
  469: 	    $disk_env{$key} = $value;
  470: 	}
  471: 	untie(%disk_env);
  472:     }
  473:     return 'ok';
  474: }
  475: # ----------------------------------------------------- Delete from Environment
  476: 
  477: sub delenv {
  478:     my $delthis=shift;
  479:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  480:         &logthis("<font color=\"blue\">WARNING: ".
  481:                 "Attempt to delete from environment ".$delthis);
  482:         return 'error';
  483:     }
  484:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  485:     if ($opened
  486: 	&& &timed_flock($env_file,LOCK_EX)
  487: 	&&
  488: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  489: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  490: 	foreach my $key (keys(%disk_env)) {
  491: 	    if ($key=~/^$delthis/) { 
  492: 		delete($env{$key});
  493: 		delete($disk_env{$key});
  494: 	    }
  495: 	}
  496: 	untie(%disk_env);
  497:     }
  498:     return 'ok';
  499: }
  500: 
  501: sub get_env_multiple {
  502:     my ($name) = @_;
  503:     my @values;
  504:     if (defined($env{$name})) {
  505:         # exists is it an array
  506:         if (ref($env{$name})) {
  507:             @values=@{ $env{$name} };
  508:         } else {
  509:             $values[0]=$env{$name};
  510:         }
  511:     }
  512:     return(@values);
  513: }
  514: 
  515: # ------------------------------------------ Find out current server userload
  516: sub userload {
  517:     my $numusers=0;
  518:     {
  519: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  520: 	my $filename;
  521: 	my $curtime=time;
  522: 	while ($filename=readdir(LONIDS)) {
  523: 	    next if ($filename eq '.' || $filename eq '..');
  524: 	    next if ($filename =~ /publicuser_\d+\.id/);
  525: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  526: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  527: 	}
  528: 	closedir(LONIDS);
  529:     }
  530:     my $userloadpercent=0;
  531:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  532:     if ($maxuserload) {
  533: 	$userloadpercent=100*$numusers/$maxuserload;
  534:     }
  535:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  536:     return $userloadpercent;
  537: }
  538: 
  539: # ------------------------------------------ Fight off request when overloaded
  540: 
  541: sub overloaderror {
  542:     my ($r,$checkserver)=@_;
  543:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  544:     my $loadavg;
  545:     if ($checkserver eq $perlvar{'lonHostID'}) {
  546:        open(my $loadfile,'/proc/loadavg');
  547:        $loadavg=<$loadfile>;
  548:        $loadavg =~ s/\s.*//g;
  549:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  550:        close($loadfile);
  551:     } else {
  552:        $loadavg=&reply('load',$checkserver);
  553:     }
  554:     my $overload=$loadavg-100;
  555:     if ($overload>0) {
  556: 	$r->err_headers_out->{'Retry-After'}=$overload;
  557:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  558:         return 413;
  559:     }    
  560:     return '';
  561: }
  562: 
  563: # ------------------------------ Find server with least workload from spare.tab
  564: 
  565: sub spareserver {
  566:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  567:     my $spare_server;
  568:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  569:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  570:                                                      :  $userloadpercent;
  571:     
  572:     foreach my $try_server (@{ $spareid{'primary'} }) {
  573: 	($spare_server, $lowest_load) =
  574: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  575:     }
  576: 
  577:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  578: 
  579:     if (!$found_server) {
  580: 	foreach my $try_server (@{ $spareid{'default'} }) {
  581: 	    ($spare_server, $lowest_load) =
  582: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  583: 	}
  584:     }
  585: 
  586:     if (!$want_server_name) {
  587: 	$spare_server="http://".&hostname($spare_server);
  588:     }
  589:     return $spare_server;
  590: }
  591: 
  592: sub compare_server_load {
  593:     my ($try_server, $spare_server, $lowest_load) = @_;
  594: 
  595:     my $loadans     = &reply('load',    $try_server);
  596:     my $userloadans = &reply('userload',$try_server);
  597: 
  598:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  599: 	next; #didn't get a number from the server
  600:     }
  601: 
  602:     my $load;
  603:     if ($loadans =~ /\d/) {
  604: 	if ($userloadans =~ /\d/) {
  605: 	    #both are numbers, pick the bigger one
  606: 	    $load = ($loadans > $userloadans) ? $loadans 
  607: 		                              : $userloadans;
  608: 	} else {
  609: 	    $load = $loadans;
  610: 	}
  611:     } else {
  612: 	$load = $userloadans;
  613:     }
  614: 
  615:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  616: 	$spare_server = $try_server;
  617: 	$lowest_load  = $load;
  618:     }
  619:     return ($spare_server,$lowest_load);
  620: }
  621: 
  622: # --------------------------- ask offload servers if user already has a session
  623: sub find_existing_session {
  624:     my ($udom,$uname) = @_;
  625:     foreach my $try_server (@{ $spareid{'primary'} },
  626: 			    @{ $spareid{'default'} }) {
  627: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  628:     }
  629:     return;
  630: }
  631: 
  632: # -------------------------------- ask if server already has a session for user
  633: sub has_user_session {
  634:     my ($lonid,$udom,$uname) = @_;
  635:     my $result = &reply(join(':','userhassession',
  636: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  637:     return 1 if ($result eq 'ok');
  638: 
  639:     return 0;
  640: }
  641: 
  642: # --------------------------------------------- Try to change a user's password
  643: 
  644: sub changepass {
  645:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  646:     $currentpass = &escape($currentpass);
  647:     $newpass     = &escape($newpass);
  648:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  649: 		       $server);
  650:     if (! $answer) {
  651: 	&logthis("No reply on password change request to $server ".
  652: 		 "by $uname in domain $udom.");
  653:     } elsif ($answer =~ "^ok") {
  654:         &logthis("$uname in $udom successfully changed their password ".
  655: 		 "on $server.");
  656:     } elsif ($answer =~ "^pwchange_failure") {
  657: 	&logthis("$uname in $udom was unable to change their password ".
  658: 		 "on $server.  The action was blocked by either lcpasswd ".
  659: 		 "or pwchange");
  660:     } elsif ($answer =~ "^non_authorized") {
  661:         &logthis("$uname in $udom did not get their password correct when ".
  662: 		 "attempting to change it on $server.");
  663:     } elsif ($answer =~ "^auth_mode_error") {
  664:         &logthis("$uname in $udom attempted to change their password despite ".
  665: 		 "not being locally or internally authenticated on $server.");
  666:     } elsif ($answer =~ "^unknown_user") {
  667:         &logthis("$uname in $udom attempted to change their password ".
  668: 		 "on $server but were unable to because $server is not ".
  669: 		 "their home server.");
  670:     } elsif ($answer =~ "^refused") {
  671: 	&logthis("$server refused to change $uname in $udom password because ".
  672: 		 "it was sent an unencrypted request to change the password.");
  673:     }
  674:     return $answer;
  675: }
  676: 
  677: # ----------------------- Try to determine user's current authentication scheme
  678: 
  679: sub queryauthenticate {
  680:     my ($uname,$udom)=@_;
  681:     my $uhome=&homeserver($uname,$udom);
  682:     if (!$uhome) {
  683: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  684: 	return 'no_host';
  685:     }
  686:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  687:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  688: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  689:     }
  690:     return $answer;
  691: }
  692: 
  693: # --------- Try to authenticate user from domain's lib servers (first this one)
  694: 
  695: sub authenticate {
  696:     my ($uname,$upass,$udom)=@_;
  697:     $upass=&escape($upass);
  698:     $uname= &LONCAPA::clean_username($uname);
  699:     my $uhome=&homeserver($uname,$udom,1);
  700:     if ((!$uhome) || ($uhome eq 'no_host')) {
  701: # Maybe the machine was offline and only re-appeared again recently?
  702:         &reconlonc();
  703: # One more
  704: 	my $uhome=&homeserver($uname,$udom,1);
  705: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  706: 	    &logthis("User $uname at $udom is unknown in authenticate");
  707: 	}
  708: 	return 'no_host';
  709:     }
  710:     my $answer=reply("encrypt:auth:$udom:$uname:$upass",$uhome);
  711:     if ($answer eq 'authorized') {
  712: 	&logthis("User $uname at $udom authorized by $uhome"); 
  713: 	return $uhome; 
  714:     }
  715:     if ($answer eq 'non_authorized') {
  716: 	&logthis("User $uname at $udom rejected by $uhome");
  717: 	return 'no_host'; 
  718:     }
  719:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  720:     return 'no_host';
  721: }
  722: 
  723: # ---------------------- Find the homebase for a user from domain's lib servers
  724: 
  725: my %homecache;
  726: sub homeserver {
  727:     my ($uname,$udom,$ignoreBadCache)=@_;
  728:     my $index="$uname:$udom";
  729: 
  730:     if (exists($homecache{$index})) { return $homecache{$index}; }
  731: 
  732:     my %servers = &get_servers($udom,'library');
  733:     foreach my $tryserver (keys(%servers)) {
  734:         next if ($ignoreBadCache ne 'true' && 
  735: 		 exists($badServerCache{$tryserver}));
  736: 
  737: 	my $answer=reply("home:$udom:$uname",$tryserver);
  738: 	if ($answer eq 'found') {
  739: 	    delete($badServerCache{$tryserver}); 
  740: 	    return $homecache{$index}=$tryserver;
  741: 	} elsif ($answer eq 'no_host') {
  742: 	    $badServerCache{$tryserver}=1;
  743: 	}
  744:     }    
  745:     return 'no_host';
  746: }
  747: 
  748: # ------------------------------------- Find the usernames behind a list of IDs
  749: 
  750: sub idget {
  751:     my ($udom,@ids)=@_;
  752:     my %returnhash=();
  753:     
  754:     my %servers = &get_servers($udom,'library');
  755:     foreach my $tryserver (keys(%servers)) {
  756: 	my $idlist=join('&',@ids);
  757: 	$idlist=~tr/A-Z/a-z/; 
  758: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  759: 	my @answer=();
  760: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  761: 	    @answer=split(/\&/,$reply);
  762: 	}                    ;
  763: 	my $i;
  764: 	for ($i=0;$i<=$#ids;$i++) {
  765: 	    if ($answer[$i]) {
  766: 		$returnhash{$ids[$i]}=$answer[$i];
  767: 	    } 
  768: 	}
  769:     } 
  770:     return %returnhash;
  771: }
  772: 
  773: # ------------------------------------- Find the IDs behind a list of usernames
  774: 
  775: sub idrget {
  776:     my ($udom,@unames)=@_;
  777:     my %returnhash=();
  778:     foreach my $uname (@unames) {
  779:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  780:     }
  781:     return %returnhash;
  782: }
  783: 
  784: # ------------------------------- Store away a list of names and associated IDs
  785: 
  786: sub idput {
  787:     my ($udom,%ids)=@_;
  788:     my %servers=();
  789:     foreach my $uname (keys(%ids)) {
  790: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  791:         my $uhom=&homeserver($uname,$udom);
  792:         if ($uhom ne 'no_host') {
  793:             my $id=&escape($ids{$uname});
  794:             $id=~tr/A-Z/a-z/;
  795:             my $esc_unam=&escape($uname);
  796: 	    if ($servers{$uhom}) {
  797: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  798:             } else {
  799:                 $servers{$uhom}=$id.'='.$esc_unam;
  800:             }
  801:         }
  802:     }
  803:     foreach my $server (keys(%servers)) {
  804:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  805:     }
  806: }
  807: 
  808: # ------------------------------------------- get items from domain db files   
  809: 
  810: sub get_dom {
  811:     my ($namespace,$storearr,$udom,$uhome)=@_;
  812:     my $items='';
  813:     foreach my $item (@$storearr) {
  814:         $items.=&escape($item).'&';
  815:     }
  816:     $items=~s/\&$//;
  817:     if (!$udom) {
  818:         $udom=$env{'user.domain'};
  819:         if (defined(&domain($udom,'primary'))) {
  820:             $uhome=&domain($udom,'primary');
  821:         } else {
  822:             undef($uhome);
  823:         }
  824:     } else {
  825:         if (!$uhome) {
  826:             if (defined(&domain($udom,'primary'))) {
  827:                 $uhome=&domain($udom,'primary');
  828:             }
  829:         }
  830:     }
  831:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  832:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  833:         my %returnhash;
  834:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  835:             return %returnhash;
  836:         }
  837:         my @pairs=split(/\&/,$rep);
  838:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  839:             return @pairs;
  840:         }
  841:         my $i=0;
  842:         foreach my $item (@$storearr) {
  843:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  844:             $i++;
  845:         }
  846:         return %returnhash;
  847:     } else {
  848:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  849:     }
  850: }
  851: 
  852: # -------------------------------------------- put items in domain db files 
  853: 
  854: sub put_dom {
  855:     my ($namespace,$storehash,$udom,$uhome)=@_;
  856:     if (!$udom) {
  857:         $udom=$env{'user.domain'};
  858:         if (defined(&domain($udom,'primary'))) {
  859:             $uhome=&domain($udom,'primary');
  860:         } else {
  861:             undef($uhome);
  862:         }
  863:     } else {
  864:         if (!$uhome) {
  865:             if (defined(&domain($udom,'primary'))) {
  866:                 $uhome=&domain($udom,'primary');
  867:             }
  868:         }
  869:     } 
  870:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  871:         my $items='';
  872:         foreach my $item (keys(%$storehash)) {
  873:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  874:         }
  875:         $items=~s/\&$//;
  876:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  877:     } else {
  878:         &logthis("put_dom failed - no homeserver and/or domain");
  879:     }
  880: }
  881: 
  882: sub retrieve_inst_usertypes {
  883:     my ($udom) = @_;
  884:     my (%returnhash,@order);
  885:     if (defined(&domain($udom,'primary'))) {
  886:         my $uhome=&domain($udom,'primary');
  887:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  888:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  889:         my @pairs=split(/\&/,$hashitems);
  890:         foreach my $item (@pairs) {
  891:             my ($key,$value)=split(/=/,$item,2);
  892:             $key = &unescape($key);
  893:             next if ($key =~ /^error: 2 /);
  894:             $returnhash{$key}=&thaw_unescape($value);
  895:         }
  896:         my @esc_order = split(/\&/,$orderitems);
  897:         foreach my $item (@esc_order) {
  898:             push(@order,&unescape($item));
  899:         }
  900:     } else {
  901:         &logthis("get_dom failed - no primary domain server for $udom");
  902:     }
  903:     return (\%returnhash,\@order);
  904: }
  905: 
  906: sub is_domainimage {
  907:     my ($url) = @_;
  908:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
  909:         if (&domain($1) ne '') {
  910:             return '1';
  911:         }
  912:     }
  913:     return;
  914: }
  915: 
  916: sub inst_directory_query {
  917:     my ($srch) = @_;
  918:     my $udom = $srch->{'srchdomain'};
  919:     my %results;
  920:     my $homeserver = &domain($udom,'primary');
  921:     my $outcome;
  922:     if ($homeserver ne '') {
  923: 	my $queryid=&reply("querysend:instdirsearch:".
  924: 			   &escape($srch->{'srchby'}).':'.
  925: 			   &escape($srch->{'srchterm'}).':'.
  926: 			   &escape($srch->{'srchtype'}),$homeserver);
  927: 	my $host=&hostname($homeserver);
  928: 	if ($queryid !~/^\Q$host\E\_/) {
  929: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
  930: 	    return;
  931: 	}
  932: 	my $response = &get_query_reply($queryid);
  933: 	my $maxtries = 5;
  934: 	my $tries = 1;
  935: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
  936: 	    $response = &get_query_reply($queryid);
  937: 	    $tries ++;
  938: 	}
  939: 
  940:         if (!&error($response) && $response ne 'refused') {
  941:             if ($response eq 'unavailable') {
  942:                 $outcome = $response;
  943:             } else {
  944:                 $outcome = 'ok';
  945:                 my @matches = split(/\n/,$response);
  946:                 foreach my $match (@matches) {
  947:                     my ($key,$value) = split(/=/,$match);
  948:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
  949:                 }
  950:             }
  951:         }
  952:     }
  953:     return ($outcome,%results);
  954: }
  955: 
  956: sub usersearch {
  957:     my ($srch) = @_;
  958:     my $dom = $srch->{'srchdomain'};
  959:     my %results;
  960:     my %libserv = &all_library();
  961:     my $query = 'usersearch';
  962:     foreach my $tryserver (keys(%libserv)) {
  963:         if (&host_domain($tryserver) eq $dom) {
  964:             my $host=&hostname($tryserver);
  965:             my $queryid=
  966:                 &reply("querysend:".&escape($query).':'.
  967:                        &escape($srch->{'srchby'}).':'.
  968:                        &escape($srch->{'srchtype'}).':'.
  969:                        &escape($srch->{'srchterm'}),$tryserver);
  970:             if ($queryid !~/^\Q$host\E\_/) {
  971:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
  972:                 next;
  973:             }
  974:             my $reply = &get_query_reply($queryid);
  975:             my $maxtries = 1;
  976:             my $tries = 1;
  977:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
  978:                 $reply = &get_query_reply($queryid);
  979:                 $tries ++;
  980:             }
  981:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
  982:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
  983:             } else {
  984:                 my @matches;
  985:                 if ($reply =~ /\n/) {
  986:                     @matches = split(/\n/,$reply);
  987:                 } else {
  988:                     @matches = split(/\&/,$reply);
  989:                 }
  990:                 foreach my $match (@matches) {
  991:                     my ($uname,$udom,%userhash);
  992:                     foreach my $entry (split(/:/,$match)) {
  993:                         my ($key,$value) =
  994:                             map {&unescape($_);} split(/=/,$entry);
  995:                         $userhash{$key} = $value;
  996:                         if ($key eq 'username') {
  997:                             $uname = $value;
  998:                         } elsif ($key eq 'domain') {
  999:                             $udom = $value;
 1000:                         }
 1001:                     }
 1002:                     $results{$uname.':'.$udom} = \%userhash;
 1003:                 }
 1004:             }
 1005:         }
 1006:     }
 1007:     return %results;
 1008: }
 1009: 
 1010: sub get_instuser {
 1011:     my ($udom,$uname,$id) = @_;
 1012:     my $homeserver = &domain($udom,'primary');
 1013:     my ($outcome,%results);
 1014:     if ($homeserver ne '') {
 1015:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1016:                            &escape($id).':'.&escape($udom),$homeserver);
 1017:         my $host=&hostname($homeserver);
 1018:         if ($queryid !~/^\Q$host\E\_/) {
 1019:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1020:             return;
 1021:         }
 1022:         my $response = &get_query_reply($queryid);
 1023:         my $maxtries = 5;
 1024:         my $tries = 1;
 1025:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1026:             $response = &get_query_reply($queryid);
 1027:             $tries ++;
 1028:         }
 1029:         if (!&error($response) && $response ne 'refused') {
 1030:             if ($response eq 'unavailable') {
 1031:                 $outcome = $response;
 1032:             } else {
 1033:                 $outcome = 'ok';
 1034:                 my @matches = split(/\n/,$response);
 1035:                 foreach my $match (@matches) {
 1036:                     my ($key,$value) = split(/=/,$match);
 1037:                     $results{&unescape($key)} = &thaw_unescape($value);
 1038:                 }
 1039:             }
 1040:         }
 1041:     }
 1042:     my %userinfo;
 1043:     if (ref($results{$uname}) eq 'HASH') {
 1044:         %userinfo = %{$results{$uname}};
 1045:     } 
 1046:     return ($outcome,%userinfo);
 1047: }
 1048: 
 1049: sub inst_rulecheck {
 1050:     my ($udom,$uname,$id,$item,$rules) = @_;
 1051:     my %returnhash;
 1052:     if ($udom ne '') {
 1053:         if (ref($rules) eq 'ARRAY') {
 1054:             @{$rules} = map {&escape($_);} (@{$rules});
 1055:             my $rulestr = join(':',@{$rules});
 1056:             my $homeserver=&domain($udom,'primary');
 1057:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1058:                 my $response;
 1059:                 if ($item eq 'username') {                
 1060:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1061:                                               ':'.&escape($uname).':'.$rulestr,
 1062:                                               $homeserver));
 1063:                 } elsif ($item eq 'id') {
 1064:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1065:                                               ':'.&escape($id).':'.$rulestr,
 1066:                                               $homeserver));
 1067:                 } elsif ($item eq 'selfcreate') {
 1068:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1069:                                                &escape($udom).':'.&escape($uname).
 1070:                                               ':'.$rulestr,$homeserver));
 1071:                 }
 1072:                 if ($response ne 'refused') {
 1073:                     my @pairs=split(/\&/,$response);
 1074:                     foreach my $item (@pairs) {
 1075:                         my ($key,$value)=split(/=/,$item,2);
 1076:                         $key = &unescape($key);
 1077:                         next if ($key =~ /^error: 2 /);
 1078:                         $returnhash{$key}=&thaw_unescape($value);
 1079:                     }
 1080:                 }
 1081:             }
 1082:         }
 1083:     }
 1084:     return %returnhash;
 1085: }
 1086: 
 1087: sub inst_userrules {
 1088:     my ($udom,$check) = @_;
 1089:     my (%ruleshash,@ruleorder);
 1090:     if ($udom ne '') {
 1091:         my $homeserver=&domain($udom,'primary');
 1092:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1093:             my $response;
 1094:             if ($check eq 'id') {
 1095:                 $response=&reply('instidrules:'.&escape($udom),
 1096:                                  $homeserver);
 1097:             } elsif ($check eq 'email') {
 1098:                 $response=&reply('instemailrules:'.&escape($udom),
 1099:                                  $homeserver);
 1100:             } else {
 1101:                 $response=&reply('instuserrules:'.&escape($udom),
 1102:                                  $homeserver);
 1103:             }
 1104:             if (($response ne 'refused') && ($response ne 'error') && 
 1105:                 ($response ne 'unknown_cmd') && 
 1106:                 ($response ne 'no_such_host')) {
 1107:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1108:                 my @pairs=split(/\&/,$hashitems);
 1109:                 foreach my $item (@pairs) {
 1110:                     my ($key,$value)=split(/=/,$item,2);
 1111:                     $key = &unescape($key);
 1112:                     next if ($key =~ /^error: 2 /);
 1113:                     $ruleshash{$key}=&thaw_unescape($value);
 1114:                 }
 1115:                 my @esc_order = split(/\&/,$orderitems);
 1116:                 foreach my $item (@esc_order) {
 1117:                     push(@ruleorder,&unescape($item));
 1118:                 }
 1119:             }
 1120:         }
 1121:     }
 1122:     return (\%ruleshash,\@ruleorder);
 1123: }
 1124: 
 1125: # ------------------------- Get Authentication and Language Defaults for Domain
 1126: 
 1127: sub get_domain_defaults {
 1128:     my ($domain) = @_;
 1129:     my $cachetime = 60*60*24;
 1130:     my ($defauthtype,$defautharg,$deflang);
 1131:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1132:     if (defined($cached)) {
 1133:         if (ref($result) eq 'HASH') {
 1134:             return %{$result};
 1135:         }
 1136:     }
 1137:     my %domdefaults;
 1138:     my %domconfig =
 1139:          &Apache::lonnet::get_dom('configuration',['defaults'],$domain);
 1140:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1141:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1142:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1143:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1144:     } else {
 1145:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1146:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1147:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1148:     }
 1149:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1150:                                   $cachetime);
 1151:     return %domdefaults;
 1152: }
 1153: 
 1154: # --------------------------------------------------- Assign a key to a student
 1155: 
 1156: sub assign_access_key {
 1157: #
 1158: # a valid key looks like uname:udom#comments
 1159: # comments are being appended
 1160: #
 1161:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1162:     $kdom=
 1163:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1164:     $knum=
 1165:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1166:     $cdom=
 1167:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1168:     $cnum=
 1169:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1170:     $udom=$env{'user.name'} unless (defined($udom));
 1171:     $uname=$env{'user.domain'} unless (defined($uname));
 1172:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1173:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1174:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1175:                                                   # assigned to this person
 1176:                                                   # - this should not happen,
 1177:                                                   # unless something went wrong
 1178:                                                   # the first time around
 1179: # ready to assign
 1180:         $logentry=$1.'; '.$logentry;
 1181:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1182:                                                  $kdom,$knum) eq 'ok') {
 1183: # key now belongs to user
 1184: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1185:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1186:                 &appenv('environment.'.$envkey => $ckey);
 1187:                 return 'ok';
 1188:             } else {
 1189:                 return 
 1190:   'error: Count not permanently assign key, will need to be re-entered later.';
 1191: 	    }
 1192:         } else {
 1193:             return 'error: Could not assign key, try again later.';
 1194:         }
 1195:     } elsif (!$existing{$ckey}) {
 1196: # the key does not exist
 1197: 	return 'error: The key does not exist';
 1198:     } else {
 1199: # the key is somebody else's
 1200: 	return 'error: The key is already in use';
 1201:     }
 1202: }
 1203: 
 1204: # ------------------------------------------ put an additional comment on a key
 1205: 
 1206: sub comment_access_key {
 1207: #
 1208: # a valid key looks like uname:udom#comments
 1209: # comments are being appended
 1210: #
 1211:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1212:     $cdom=
 1213:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1214:     $cnum=
 1215:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1216:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1217:     if ($existing{$ckey}) {
 1218:         $existing{$ckey}.='; '.$logentry;
 1219: # ready to assign
 1220:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1221:                                                  $cdom,$cnum) eq 'ok') {
 1222: 	    return 'ok';
 1223:         } else {
 1224: 	    return 'error: Count not store comment.';
 1225:         }
 1226:     } else {
 1227: # the key does not exist
 1228: 	return 'error: The key does not exist';
 1229:     }
 1230: }
 1231: 
 1232: # ------------------------------------------------------ Generate a set of keys
 1233: 
 1234: sub generate_access_keys {
 1235:     my ($number,$cdom,$cnum,$logentry)=@_;
 1236:     $cdom=
 1237:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1238:     $cnum=
 1239:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1240:     unless (&allowed('mky',$cdom)) { return 0; }
 1241:     unless (($cdom) && ($cnum)) { return 0; }
 1242:     if ($number>10000) { return 0; }
 1243:     sleep(2); # make sure don't get same seed twice
 1244:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1245:     my $total=0;
 1246:     for (my $i=1;$i<=$number;$i++) {
 1247:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1248:                   sprintf("%lx",int(100000*rand)).'-'.
 1249:                   sprintf("%lx",int(100000*rand));
 1250:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1251:        $newkey=~s/0/h/g; # and also 0 and O
 1252:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1253:        if ($existing{$newkey}) {
 1254:            $i--;
 1255:        } else {
 1256: 	  if (&put('accesskeys',
 1257:               { $newkey => '# generated '.localtime().
 1258:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1259:                            '; '.$logentry },
 1260: 		   $cdom,$cnum) eq 'ok') {
 1261:               $total++;
 1262: 	  }
 1263:        }
 1264:     }
 1265:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1266:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1267:     return $total;
 1268: }
 1269: 
 1270: # ------------------------------------------------------- Validate an accesskey
 1271: 
 1272: sub validate_access_key {
 1273:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1274:     $cdom=
 1275:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1276:     $cnum=
 1277:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1278:     $udom=$env{'user.domain'} unless (defined($udom));
 1279:     $uname=$env{'user.name'} unless (defined($uname));
 1280:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1281:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1282: }
 1283: 
 1284: # ------------------------------------- Find the section of student in a course
 1285: sub devalidate_getsection_cache {
 1286:     my ($udom,$unam,$courseid)=@_;
 1287:     my $hashid="$udom:$unam:$courseid";
 1288:     &devalidate_cache_new('getsection',$hashid);
 1289: }
 1290: 
 1291: sub courseid_to_courseurl {
 1292:     my ($courseid) = @_;
 1293:     #already url style courseid
 1294:     return $courseid if ($courseid =~ m{^/});
 1295: 
 1296:     if (exists($env{'course.'.$courseid.'.num'})) {
 1297: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1298: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1299: 	return "/$cdom/$cnum";
 1300:     }
 1301: 
 1302:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1303:     if (exists($courseinfo{'num'})) {
 1304: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1305:     }
 1306: 
 1307:     return undef;
 1308: }
 1309: 
 1310: sub getsection {
 1311:     my ($udom,$unam,$courseid)=@_;
 1312:     my $cachetime=1800;
 1313: 
 1314:     my $hashid="$udom:$unam:$courseid";
 1315:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1316:     if (defined($cached)) { return $result; }
 1317: 
 1318:     my %Pending; 
 1319:     my %Expired;
 1320:     #
 1321:     # Each role can either have not started yet (pending), be active, 
 1322:     #    or have expired.
 1323:     #
 1324:     # If there is an active role, we are done.
 1325:     #
 1326:     # If there is more than one role which has not started yet, 
 1327:     #     choose the one which will start sooner
 1328:     # If there is one role which has not started yet, return it.
 1329:     #
 1330:     # If there is more than one expired role, choose the one which ended last.
 1331:     # If there is a role which has expired, return it.
 1332:     #
 1333:     $courseid = &courseid_to_courseurl($courseid);
 1334:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1335:     foreach my $key (keys(%roleshash)) {
 1336:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1337:         my $section=$1;
 1338:         if ($key eq $courseid.'_st') { $section=''; }
 1339:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1340:         my $now=time;
 1341:         if (defined($end) && $end && ($now > $end)) {
 1342:             $Expired{$end}=$section;
 1343:             next;
 1344:         }
 1345:         if (defined($start) && $start && ($now < $start)) {
 1346:             $Pending{$start}=$section;
 1347:             next;
 1348:         }
 1349:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1350:     }
 1351:     #
 1352:     # Presumedly there will be few matching roles from the above
 1353:     # loop and the sorting time will be negligible.
 1354:     if (scalar(keys(%Pending))) {
 1355:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1356:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1357:     } 
 1358:     if (scalar(keys(%Expired))) {
 1359:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1360:         my $time = pop(@sorted);
 1361:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1362:     }
 1363:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1364: }
 1365: 
 1366: sub save_cache {
 1367:     &purge_remembered();
 1368:     #&Apache::loncommon::validate_page();
 1369:     undef(%env);
 1370:     undef($env_loaded);
 1371: }
 1372: 
 1373: my $to_remember=-1;
 1374: my %remembered;
 1375: my %accessed;
 1376: my $kicks=0;
 1377: my $hits=0;
 1378: sub make_key {
 1379:     my ($name,$id) = @_;
 1380:     if (length($id) > 65 
 1381: 	&& length(&escape($id)) > 200) {
 1382: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1383:     }
 1384:     return &escape($name.':'.$id);
 1385: }
 1386: 
 1387: sub devalidate_cache_new {
 1388:     my ($name,$id,$debug) = @_;
 1389:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1390:     $id=&make_key($name,$id);
 1391:     $memcache->delete($id);
 1392:     delete($remembered{$id});
 1393:     delete($accessed{$id});
 1394: }
 1395: 
 1396: sub is_cached_new {
 1397:     my ($name,$id,$debug) = @_;
 1398:     $id=&make_key($name,$id);
 1399:     if (exists($remembered{$id})) {
 1400: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1401: 	$accessed{$id}=[&gettimeofday()];
 1402: 	$hits++;
 1403: 	return ($remembered{$id},1);
 1404:     }
 1405:     my $value = $memcache->get($id);
 1406:     if (!(defined($value))) {
 1407: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1408: 	return (undef,undef);
 1409:     }
 1410:     if ($value eq '__undef__') {
 1411: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1412: 	$value=undef;
 1413:     }
 1414:     &make_room($id,$value,$debug);
 1415:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1416:     return ($value,1);
 1417: }
 1418: 
 1419: sub do_cache_new {
 1420:     my ($name,$id,$value,$time,$debug) = @_;
 1421:     $id=&make_key($name,$id);
 1422:     my $setvalue=$value;
 1423:     if (!defined($setvalue)) {
 1424: 	$setvalue='__undef__';
 1425:     }
 1426:     if (!defined($time) ) {
 1427: 	$time=600;
 1428:     }
 1429:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1430:     my $result = $memcache->set($id,$setvalue,$time);
 1431:     if (! $result) {
 1432: 	&logthis("caching of id -> $id  failed");
 1433: 	$memcache->disconnect_all();
 1434:     }
 1435:     # need to make a copy of $value
 1436:     &make_room($id,$value,$debug);
 1437:     return $value;
 1438: }
 1439: 
 1440: sub make_room {
 1441:     my ($id,$value,$debug)=@_;
 1442: 
 1443:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1444:                                     : $value;
 1445:     if ($to_remember<0) { return; }
 1446:     $accessed{$id}=[&gettimeofday()];
 1447:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1448:     my $to_kick;
 1449:     my $max_time=0;
 1450:     foreach my $other (keys(%accessed)) {
 1451: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1452: 	    $to_kick=$other;
 1453: 	    $max_time=&tv_interval($accessed{$other});
 1454: 	}
 1455:     }
 1456:     delete($remembered{$to_kick});
 1457:     delete($accessed{$to_kick});
 1458:     $kicks++;
 1459:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1460:     return;
 1461: }
 1462: 
 1463: sub purge_remembered {
 1464:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1465:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1466:     undef(%remembered);
 1467:     undef(%accessed);
 1468: }
 1469: # ------------------------------------- Read an entry from a user's environment
 1470: 
 1471: sub userenvironment {
 1472:     my ($udom,$unam,@what)=@_;
 1473:     my %returnhash=();
 1474:     my @answer=split(/\&/,
 1475:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1476:                       &homeserver($unam,$udom)));
 1477:     my $i;
 1478:     for ($i=0;$i<=$#what;$i++) {
 1479: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1480:     }
 1481:     return %returnhash;
 1482: }
 1483: 
 1484: # ---------------------------------------------------------- Get a studentphoto
 1485: sub studentphoto {
 1486:     my ($udom,$unam,$ext) = @_;
 1487:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1488:     if (defined($env{'request.course.id'})) {
 1489:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1490:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1491:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1492:             } else {
 1493:                 my ($result,$perm_reqd)=
 1494: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1495:                 if ($result eq 'ok') {
 1496:                     if (!($perm_reqd eq 'yes')) {
 1497:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1498:                     }
 1499:                 }
 1500:             }
 1501:         }
 1502:     } else {
 1503:         my ($result,$perm_reqd) = 
 1504: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1505:         if ($result eq 'ok') {
 1506:             if (!($perm_reqd eq 'yes')) {
 1507:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1508:             }
 1509:         }
 1510:     }
 1511:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1512: }
 1513: 
 1514: sub retrievestudentphoto {
 1515:     my ($udom,$unam,$ext,$type) = @_;
 1516:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1517:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1518:     if ($ret eq 'ok') {
 1519:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1520:         if ($type eq 'thumbnail') {
 1521:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1522:         }
 1523:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1524:         return $tokenurl;
 1525:     } else {
 1526:         if ($type eq 'thumbnail') {
 1527:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1528:         } else { 
 1529:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1530:         }
 1531:     }
 1532: }
 1533: 
 1534: # -------------------------------------------------------------------- New chat
 1535: 
 1536: sub chatsend {
 1537:     my ($newentry,$anon,$group)=@_;
 1538:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1539:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1540:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1541:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1542: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1543: 		   &escape($newentry)).':'.$group,$chome);
 1544: }
 1545: 
 1546: # ------------------------------------------ Find current version of a resource
 1547: 
 1548: sub getversion {
 1549:     my $fname=&clutter(shift);
 1550:     unless ($fname=~/^\/res\//) { return -1; }
 1551:     return &currentversion(&filelocation('',$fname));
 1552: }
 1553: 
 1554: sub currentversion {
 1555:     my $fname=shift;
 1556:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1557:     if (defined($cached)) { return $result; }
 1558:     my $author=$fname;
 1559:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1560:     my ($udom,$uname)=split(/\//,$author);
 1561:     my $home=homeserver($uname,$udom);
 1562:     if ($home eq 'no_host') { 
 1563:         return -1; 
 1564:     }
 1565:     my $answer=reply("currentversion:$fname",$home);
 1566:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1567: 	return -1;
 1568:     }
 1569:     return &do_cache_new('resversion',$fname,$answer,600);
 1570: }
 1571: 
 1572: # ----------------------------- Subscribe to a resource, return URL if possible
 1573: 
 1574: sub subscribe {
 1575:     my $fname=shift;
 1576:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1577:     $fname=~s/[\n\r]//g;
 1578:     my $author=$fname;
 1579:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1580:     my ($udom,$uname)=split(/\//,$author);
 1581:     my $home=homeserver($uname,$udom);
 1582:     if ($home eq 'no_host') {
 1583:         return 'not_found';
 1584:     }
 1585:     my $answer=reply("sub:$fname",$home);
 1586:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1587: 	$answer.=' by '.$home;
 1588:     }
 1589:     return $answer;
 1590: }
 1591:     
 1592: # -------------------------------------------------------------- Replicate file
 1593: 
 1594: sub repcopy {
 1595:     my $filename=shift;
 1596:     $filename=~s/\/+/\//g;
 1597:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1598:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1599:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1600: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1601: 	return &repcopy_userfile($filename);
 1602:     }
 1603:     $filename=~s/[\n\r]//g;
 1604:     my $transname="$filename.in.transfer";
 1605: # FIXME: this should flock
 1606:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1607:     my $remoteurl=subscribe($filename);
 1608:     if ($remoteurl =~ /^con_lost by/) {
 1609: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1610:            return 'unavailable';
 1611:     } elsif ($remoteurl eq 'not_found') {
 1612: 	   #&logthis("Subscribe returned not_found: $filename");
 1613: 	   return 'not_found';
 1614:     } elsif ($remoteurl =~ /^rejected by/) {
 1615: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1616:            return 'forbidden';
 1617:     } elsif ($remoteurl eq 'directory') {
 1618:            return 'ok';
 1619:     } else {
 1620:         my $author=$filename;
 1621:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1622:         my ($udom,$uname)=split(/\//,$author);
 1623:         my $home=homeserver($uname,$udom);
 1624:         unless ($home eq $perlvar{'lonHostID'}) {
 1625:            my @parts=split(/\//,$filename);
 1626:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1627:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1628:                &logthis("Malconfiguration for replication: $filename");
 1629: 	       return 'bad_request';
 1630:            }
 1631:            my $count;
 1632:            for ($count=5;$count<$#parts;$count++) {
 1633:                $path.="/$parts[$count]";
 1634:                if ((-e $path)!=1) {
 1635: 		   mkdir($path,0777);
 1636:                }
 1637:            }
 1638:            my $ua=new LWP::UserAgent;
 1639:            my $request=new HTTP::Request('GET',"$remoteurl");
 1640:            my $response=$ua->request($request,$transname);
 1641:            if ($response->is_error()) {
 1642: 	       unlink($transname);
 1643:                my $message=$response->status_line;
 1644:                &logthis("<font color=\"blue\">WARNING:"
 1645:                        ." LWP get: $message: $filename</font>");
 1646:                return 'unavailable';
 1647:            } else {
 1648: 	       if ($remoteurl!~/\.meta$/) {
 1649:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1650:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1651:                   if ($mresponse->is_error()) {
 1652: 		      unlink($filename.'.meta');
 1653:                       &logthis(
 1654:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1655:                   }
 1656: 	       }
 1657:                rename($transname,$filename);
 1658:                return 'ok';
 1659:            }
 1660:        }
 1661:     }
 1662: }
 1663: 
 1664: # ------------------------------------------------ Get server side include body
 1665: sub ssi_body {
 1666:     my ($filelink,%form)=@_;
 1667:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1668:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1669:     }
 1670:     my $output=($filelink=~/^http\:/?&externalssi($filelink):
 1671:                                      &ssi($filelink,%form));
 1672:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1673:     $output=~s/^.*?\<body[^\>]*\>//si;
 1674:     $output=~s/\<\/body\s*\>.*?$//si;
 1675:     return $output;
 1676: }
 1677: 
 1678: # --------------------------------------------------------- Server Side Include
 1679: 
 1680: sub absolute_url {
 1681:     my ($host_name) = @_;
 1682:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1683:     if ($host_name eq '') {
 1684: 	$host_name = $ENV{'SERVER_NAME'};
 1685:     }
 1686:     return $protocol.$host_name;
 1687: }
 1688: 
 1689: #
 1690: #   Server side include.
 1691: # Parameters:
 1692: #  fn     Possibly encrypted resource name/id.
 1693: #  form   Hash that describes how the rendering should be done
 1694: #         and other things.
 1695: # Returns:
 1696: #   Scalar context: The content of the reply.
 1697: #   Array context:  2 element list of the content and the full response variable.
 1698: #     
 1699: # Returns:
 1700: #    The content of the response.
 1701: sub ssi {
 1702: 
 1703:     my ($fn,%form)=@_;
 1704:     my $count = scalar(@_);
 1705:     
 1706: 
 1707:     my $ua=new LWP::UserAgent;
 1708:     
 1709:     my $request;
 1710: 
 1711:     $form{'no_update_last_known'}=1;
 1712:     &Apache::lonenc::check_encrypt(\$fn);
 1713:     if (%form) {
 1714:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1715:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1716:     } else {
 1717:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1718:     }
 1719: 
 1720:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1721:     my $response=$ua->request($request);
 1722:     my $status = $response->code;
 1723: 
 1724:     if (wantarray) {
 1725: 	return ($response->content, $response);
 1726:     } else {
 1727: 	return $response->content;
 1728:     }
 1729: }
 1730: 
 1731: sub externalssi {
 1732:     my ($url)=@_;
 1733:     my $ua=new LWP::UserAgent;
 1734:     my $request=new HTTP::Request('GET',$url);
 1735:     my $response=$ua->request($request);
 1736:     return $response->content;
 1737: }
 1738: 
 1739: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1740: 
 1741: sub allowuploaded {
 1742:     my ($srcurl,$url)=@_;
 1743:     $url=&clutter(&declutter($url));
 1744:     my $dir=$url;
 1745:     $dir=~s/\/[^\/]+$//;
 1746:     my %httpref=();
 1747:     my $httpurl=&hreflocation('',$url);
 1748:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1749:     &Apache::lonnet::appenv(%httpref);
 1750: }
 1751: 
 1752: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1753: # input: action, courseID, current domain, intended
 1754: #        path to file, source of file, instruction to parse file for objects,
 1755: #        ref to hash for embedded objects,
 1756: #        ref to hash for codebase of java objects.
 1757: #
 1758: # output: url to file (if action was uploaddoc), 
 1759: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1760: #
 1761: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1762: # course.
 1763: #
 1764: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1765: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1766: #          course's home server.
 1767: #
 1768: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1769: #          be copied from $source (current location) to 
 1770: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1771: #         and will then be copied to
 1772: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1773: #         course's home server.
 1774: #
 1775: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1776: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1777: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1778: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1779: #         in course's home server.
 1780: #
 1781: 
 1782: sub process_coursefile {
 1783:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1784:     my $fetchresult;
 1785:     my $home=&homeserver($docuname,$docudom);
 1786:     if ($action eq 'propagate') {
 1787:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1788: 			     $home);
 1789:     } else {
 1790:         my $fpath = '';
 1791:         my $fname = $file;
 1792:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1793:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1794:         my $filepath = &build_filepath($fpath);
 1795:         if ($action eq 'copy') {
 1796:             if ($source eq '') {
 1797:                 $fetchresult = 'no source file';
 1798:                 return $fetchresult;
 1799:             } else {
 1800:                 my $destination = $filepath.'/'.$fname;
 1801:                 rename($source,$destination);
 1802:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1803:                                  $home);
 1804:             }
 1805:         } elsif ($action eq 'uploaddoc') {
 1806:             open(my $fh,'>'.$filepath.'/'.$fname);
 1807:             print $fh $env{'form.'.$source};
 1808:             close($fh);
 1809:             if ($parser eq 'parse') {
 1810:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1811:                 unless ($parse_result eq 'ok') {
 1812:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1813:                 }
 1814:             }
 1815:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1816:                                  $home);
 1817:             if ($fetchresult eq 'ok') {
 1818:                 return '/uploaded/'.$fpath.'/'.$fname;
 1819:             } else {
 1820:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1821:                         ' to host '.$home.': '.$fetchresult);
 1822:                 return '/adm/notfound.html';
 1823:             }
 1824:         }
 1825:     }
 1826:     unless ( $fetchresult eq 'ok') {
 1827:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1828:              ' to host '.$home.': '.$fetchresult);
 1829:     }
 1830:     return $fetchresult;
 1831: }
 1832: 
 1833: sub build_filepath {
 1834:     my ($fpath) = @_;
 1835:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1836:     unless ($fpath eq '') {
 1837:         my @parts=split('/',$fpath);
 1838:         foreach my $part (@parts) {
 1839:             $filepath.= '/'.$part;
 1840:             if ((-e $filepath)!=1) {
 1841:                 mkdir($filepath,0777);
 1842:             }
 1843:         }
 1844:     }
 1845:     return $filepath;
 1846: }
 1847: 
 1848: sub store_edited_file {
 1849:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1850:     my $file = $primary_url;
 1851:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1852:     my $fpath = '';
 1853:     my $fname = $file;
 1854:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1855:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1856:     my $filepath = &build_filepath($fpath);
 1857:     open(my $fh,'>'.$filepath.'/'.$fname);
 1858:     print $fh $content;
 1859:     close($fh);
 1860:     my $home=&homeserver($docuname,$docudom);
 1861:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1862: 			  $home);
 1863:     if ($$fetchresult eq 'ok') {
 1864:         return '/uploaded/'.$fpath.'/'.$fname;
 1865:     } else {
 1866:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1867: 		 ' to host '.$home.': '.$$fetchresult);
 1868:         return '/adm/notfound.html';
 1869:     }
 1870: }
 1871: 
 1872: sub clean_filename {
 1873:     my ($fname,$args)=@_;
 1874: # Replace Windows backslashes by forward slashes
 1875:     $fname=~s/\\/\//g;
 1876:     if (!$args->{'keep_path'}) {
 1877:         # Get rid of everything but the actual filename
 1878: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1879:     }
 1880: # Replace spaces by underscores
 1881:     $fname=~s/\s+/\_/g;
 1882: # Replace all other weird characters by nothing
 1883:     $fname=~s{[^/\w\.\-]}{}g;
 1884: # Replace all .\d. sequences with _\d. so they no longer look like version
 1885: # numbers
 1886:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1887:     return $fname;
 1888: }
 1889: 
 1890: # --------------- Take an uploaded file and put it into the userfiles directory
 1891: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1892: #                    the desired filenam is in $env{"form.$formname.filename"}
 1893: #        $coursedoc - if true up to the current course
 1894: #                     if false
 1895: #        $subdir - directory in userfile to store the file into
 1896: #        $parser - instruction to parse file for objects ($parser = parse)    
 1897: #        $allfiles - reference to hash for embedded objects
 1898: #        $codebase - reference to hash for codebase of java objects
 1899: #        $desuname - username for permanent storage of uploaded file
 1900: #        $dsetudom - domain for permanaent storage of uploaded file
 1901: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1902: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1903: # 
 1904: # output: url of file in userspace, or error: <message> 
 1905: #             or /adm/notfound.html if failure to upload occurse
 1906: 
 1907: 
 1908: sub userfileupload {
 1909:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1910:         $destudom,$thumbwidth,$thumbheight)=@_;
 1911:     if (!defined($subdir)) { $subdir='unknown'; }
 1912:     my $fname=$env{'form.'.$formname.'.filename'};
 1913:     $fname=&clean_filename($fname);
 1914: # See if there is anything left
 1915:     unless ($fname) { return 'error: no uploaded file'; }
 1916:     chop($env{'form.'.$formname});
 1917:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1918:         my $now = time;
 1919:         my $filepath = 'tmp/helprequests/'.$now;
 1920:         my @parts=split(/\//,$filepath);
 1921:         my $fullpath = $perlvar{'lonDaemons'};
 1922:         for (my $i=0;$i<@parts;$i++) {
 1923:             $fullpath .= '/'.$parts[$i];
 1924:             if ((-e $fullpath)!=1) {
 1925:                 mkdir($fullpath,0777);
 1926:             }
 1927:         }
 1928:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1929:         print $fh $env{'form.'.$formname};
 1930:         close($fh);
 1931:         return $fullpath.'/'.$fname;
 1932:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1933:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1934:                        '_'.$env{'user.domain'}.'/pending';
 1935:         my @parts=split(/\//,$filepath);
 1936:         my $fullpath = $perlvar{'lonDaemons'};
 1937:         for (my $i=0;$i<@parts;$i++) {
 1938:             $fullpath .= '/'.$parts[$i];
 1939:             if ((-e $fullpath)!=1) {
 1940:                 mkdir($fullpath,0777);
 1941:             }
 1942:         }
 1943:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1944:         print $fh $env{'form.'.$formname};
 1945:         close($fh);
 1946:         return $fullpath.'/'.$fname;
 1947:     }
 1948:     
 1949: # Create the directory if not present
 1950:     $fname="$subdir/$fname";
 1951:     if ($coursedoc) {
 1952: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1953: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1954:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1955:             return &finishuserfileupload($docuname,$docudom,
 1956: 					 $formname,$fname,$parser,$allfiles,
 1957: 					 $codebase,$thumbwidth,$thumbheight);
 1958:         } else {
 1959:             $fname=$env{'form.folder'}.'/'.$fname;
 1960:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1961: 				       $fname,$formname,$parser,
 1962: 				       $allfiles,$codebase);
 1963:         }
 1964:     } elsif (defined($destuname)) {
 1965:         my $docuname=$destuname;
 1966:         my $docudom=$destudom;
 1967: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1968: 				     $parser,$allfiles,$codebase,
 1969:                                      $thumbwidth,$thumbheight);
 1970:         
 1971:     } else {
 1972:         my $docuname=$env{'user.name'};
 1973:         my $docudom=$env{'user.domain'};
 1974:         if (exists($env{'form.group'})) {
 1975:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1976:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1977:         }
 1978: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1979: 				     $parser,$allfiles,$codebase,
 1980:                                      $thumbwidth,$thumbheight);
 1981:     }
 1982: }
 1983: 
 1984: sub finishuserfileupload {
 1985:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1986:         $thumbwidth,$thumbheight) = @_;
 1987:     my $path=$docudom.'/'.$docuname.'/';
 1988:     my $filepath=$perlvar{'lonDocRoot'};
 1989:     my ($fnamepath,$file,$fetchthumb);
 1990:     $file=$fname;
 1991:     if ($fname=~m|/|) {
 1992:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1993: 	$path.=$fnamepath.'/';
 1994:     }
 1995:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1996:     my $count;
 1997:     for ($count=4;$count<=$#parts;$count++) {
 1998:         $filepath.="/$parts[$count]";
 1999:         if ((-e $filepath)!=1) {
 2000: 	    mkdir($filepath,0777);
 2001:         }
 2002:     }
 2003: # Save the file
 2004:     {
 2005: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2006: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2007: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2008: 	    return '/adm/notfound.html';
 2009: 	}
 2010: 	if (!print FH ($env{'form.'.$formname})) {
 2011: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2012: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2013: 	    return '/adm/notfound.html';
 2014: 	}
 2015: 	close(FH);
 2016:     }
 2017:     if ($parser eq 'parse') {
 2018:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 2019: 						   $codebase);
 2020:         unless ($parse_result eq 'ok') {
 2021:             &logthis('Failed to parse '.$filepath.$file.
 2022: 		     ' for embedded media: '.$parse_result); 
 2023:         }
 2024:     }
 2025:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2026:         my $input = $filepath.'/'.$file;
 2027:         my $output = $filepath.'/'.'tn-'.$file;
 2028:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2029:         system("convert -sample $thumbsize $input $output");
 2030:         if (-e $filepath.'/'.'tn-'.$file) {
 2031:             $fetchthumb  = 1; 
 2032:         }
 2033:     }
 2034:  
 2035: # Notify homeserver to grep it
 2036: #
 2037:     my $docuhome=&homeserver($docuname,$docudom);
 2038:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2039:     if ($fetchresult eq 'ok') {
 2040:         if ($fetchthumb) {
 2041:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2042:             if ($thumbresult ne 'ok') {
 2043:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2044:                          $docuhome.': '.$thumbresult);
 2045:             }
 2046:         }
 2047: #
 2048: # Return the URL to it
 2049:         return '/uploaded/'.$path.$file;
 2050:     } else {
 2051:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2052: 		 ': '.$fetchresult);
 2053:         return '/adm/notfound.html';
 2054:     }
 2055: }
 2056: 
 2057: sub extract_embedded_items {
 2058:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 2059:     my @state = ();
 2060:     my %javafiles = (
 2061:                       codebase => '',
 2062:                       code => '',
 2063:                       archive => ''
 2064:                     );
 2065:     my %mediafiles = (
 2066:                       src => '',
 2067:                       movie => '',
 2068:                      );
 2069:     my $p;
 2070:     if ($content) {
 2071:         $p = HTML::LCParser->new($content);
 2072:     } else {
 2073:         $p = HTML::LCParser->new($filepath.'/'.$file);
 2074:     }
 2075:     while (my $t=$p->get_token()) {
 2076: 	if ($t->[0] eq 'S') {
 2077: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2078: 	    push(@state, $tagname);
 2079:             if (lc($tagname) eq 'allow') {
 2080:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2081:             }
 2082: 	    if (lc($tagname) eq 'img') {
 2083: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2084: 	    }
 2085: 	    if (lc($tagname) eq 'a') {
 2086: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2087: 	    }
 2088:             if (lc($tagname) eq 'script') {
 2089:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2090:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2091:                 } else {
 2092:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2093:                 }
 2094:             }
 2095:             if (lc($tagname) eq 'link') {
 2096:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2097:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2098:                 }
 2099:             }
 2100: 	    if (lc($tagname) eq 'object' ||
 2101: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2102: 		foreach my $item (keys(%javafiles)) {
 2103: 		    $javafiles{$item} = '';
 2104: 		}
 2105: 	    }
 2106: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2107: 		my $name = lc($attr->{'name'});
 2108: 		foreach my $item (keys(%javafiles)) {
 2109: 		    if ($name eq $item) {
 2110: 			$javafiles{$item} = $attr->{'value'};
 2111: 			last;
 2112: 		    }
 2113: 		}
 2114: 		foreach my $item (keys(%mediafiles)) {
 2115: 		    if ($name eq $item) {
 2116: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2117: 			last;
 2118: 		    }
 2119: 		}
 2120: 	    }
 2121: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2122: 		foreach my $item (keys(%javafiles)) {
 2123: 		    if ($attr->{$item}) {
 2124: 			$javafiles{$item} = $attr->{$item};
 2125: 			last;
 2126: 		    }
 2127: 		}
 2128: 		foreach my $item (keys(%mediafiles)) {
 2129: 		    if ($attr->{$item}) {
 2130: 			&add_filetype($allfiles,$attr->{$item},$item);
 2131: 			last;
 2132: 		    }
 2133: 		}
 2134: 	    }
 2135: 	} elsif ($t->[0] eq 'E') {
 2136: 	    my ($tagname) = ($t->[1]);
 2137: 	    if ($javafiles{'codebase'} ne '') {
 2138: 		$javafiles{'codebase'} .= '/';
 2139: 	    }  
 2140: 	    if (lc($tagname) eq 'applet' ||
 2141: 		lc($tagname) eq 'object' ||
 2142: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2143: 		) {
 2144: 		foreach my $item (keys(%javafiles)) {
 2145: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2146: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2147: 			&add_filetype($allfiles,$file,$item);
 2148: 		    }
 2149: 		}
 2150: 	    } 
 2151: 	    pop @state;
 2152: 	}
 2153:     }
 2154:     return 'ok';
 2155: }
 2156: 
 2157: sub add_filetype {
 2158:     my ($allfiles,$file,$type)=@_;
 2159:     if (exists($allfiles->{$file})) {
 2160: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2161: 	    push(@{$allfiles->{$file}}, &escape($type));
 2162: 	}
 2163:     } else {
 2164: 	@{$allfiles->{$file}} = (&escape($type));
 2165:     }
 2166: }
 2167: 
 2168: sub removeuploadedurl {
 2169:     my ($url)=@_;
 2170:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2171:     return &removeuserfile($uname,$udom,$fname);
 2172: }
 2173: 
 2174: sub removeuserfile {
 2175:     my ($docuname,$docudom,$fname)=@_;
 2176:     my $home=&homeserver($docuname,$docudom);
 2177:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2178:     if ($result eq 'ok') {
 2179:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2180:             my $metafile = $fname.'.meta';
 2181:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2182: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2183:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2184:             my $sqlresult = 
 2185:                 &update_portfolio_table($docuname,$docudom,$file,
 2186:                                         'portfolio_metadata',$group,
 2187:                                         'delete');
 2188:         }
 2189:     }
 2190:     return $result;
 2191: }
 2192: 
 2193: sub mkdiruserfile {
 2194:     my ($docuname,$docudom,$dir)=@_;
 2195:     my $home=&homeserver($docuname,$docudom);
 2196:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2197: }
 2198: 
 2199: sub renameuserfile {
 2200:     my ($docuname,$docudom,$old,$new)=@_;
 2201:     my $home=&homeserver($docuname,$docudom);
 2202:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2203:                         &escape("$old").':'.&escape("$new"),$home);
 2204:     if ($result eq 'ok') {
 2205:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2206:             my $oldmeta = $old.'.meta';
 2207:             my $newmeta = $new.'.meta';
 2208:             my $metaresult = 
 2209:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2210: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2211:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2212:             my $sqlresult = 
 2213:                 &update_portfolio_table($docuname,$docudom,$file,
 2214:                                         'portfolio_metadata',$group,
 2215:                                         'delete');
 2216:         }
 2217:     }
 2218:     return $result;
 2219: }
 2220: 
 2221: # ------------------------------------------------------------------------- Log
 2222: 
 2223: sub log {
 2224:     my ($dom,$nam,$hom,$what)=@_;
 2225:     return critical("log:$dom:$nam:$what",$hom);
 2226: }
 2227: 
 2228: # ------------------------------------------------------------------ Course Log
 2229: #
 2230: # This routine flushes several buffers of non-mission-critical nature
 2231: #
 2232: 
 2233: sub flushcourselogs {
 2234:     &logthis('Flushing log buffers');
 2235: #
 2236: # course logs
 2237: # This is a log of all transactions in a course, which can be used
 2238: # for data mining purposes
 2239: #
 2240: # It also collects the courseid database, which lists last transaction
 2241: # times and course titles for all courseids
 2242: #
 2243:     my %courseidbuffer=();
 2244:     foreach my $crsid (keys(%courselogs)) {
 2245:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2246: 		          &escape($courselogs{$crsid}),
 2247: 		          $coursehombuf{$crsid}) eq 'ok') {
 2248: 	    delete $courselogs{$crsid};
 2249:         } else {
 2250:             &logthis('Failed to flush log buffer for '.$crsid);
 2251:             if (length($courselogs{$crsid})>40000) {
 2252:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2253:                         " exceeded maximum size, deleting.</font>");
 2254:                delete $courselogs{$crsid};
 2255:             }
 2256:         }
 2257:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2258:             'description' => $coursedescrbuf{$crsid},
 2259:             'inst_code'    => $courseinstcodebuf{$crsid},
 2260:             'type'        => $coursetypebuf{$crsid},
 2261:             'owner'       => $courseownerbuf{$crsid},
 2262:         };
 2263:     }
 2264: #
 2265: # Write course id database (reverse lookup) to homeserver of courses 
 2266: # Is used in pickcourse
 2267: #
 2268:     foreach my $crs_home (keys(%courseidbuffer)) {
 2269:         my $response = &courseidput(&host_domain($crs_home),
 2270:                                     $courseidbuffer{$crs_home},
 2271:                                     $crs_home,'timeonly');
 2272:     }
 2273: #
 2274: # File accesses
 2275: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2276: #
 2277:     foreach my $entry (keys(%accesshash)) {
 2278:         if ($entry =~ /___count$/) {
 2279:             my ($dom,$name);
 2280:             ($dom,$name,undef)=
 2281: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2282:             if (! defined($dom) || $dom eq '' || 
 2283:                 ! defined($name) || $name eq '') {
 2284:                 my $cid = $env{'request.course.id'};
 2285:                 $dom  = $env{'request.'.$cid.'.domain'};
 2286:                 $name = $env{'request.'.$cid.'.num'};
 2287:             }
 2288:             my $value = $accesshash{$entry};
 2289:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2290:             my %temphash=($url => $value);
 2291:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2292:             if ($result eq 'ok') {
 2293:                 delete $accesshash{$entry};
 2294:             } elsif ($result eq 'unknown_cmd') {
 2295:                 # Target server has old code running on it.
 2296:                 my %temphash=($entry => $value);
 2297:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2298:                     delete $accesshash{$entry};
 2299:                 }
 2300:             }
 2301:         } else {
 2302:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2303:             my %temphash=($entry => $accesshash{$entry});
 2304:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2305:                 delete $accesshash{$entry};
 2306:             }
 2307:         }
 2308:     }
 2309: #
 2310: # Roles
 2311: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2312: #
 2313:     foreach my $entry (keys(%userrolehash)) {
 2314:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2315: 	    split(/\:/,$entry);
 2316:         if (&Apache::lonnet::put('nohist_userroles',
 2317:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2318:                 $rudom,$runame) eq 'ok') {
 2319: 	    delete $userrolehash{$entry};
 2320:         }
 2321:     }
 2322: #
 2323: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2324: #
 2325:     my %domrolebuffer = ();
 2326:     foreach my $entry (keys %domainrolehash) {
 2327:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2328:         if ($domrolebuffer{$rudom}) {
 2329:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2330:                       '='.&escape($domainrolehash{$entry});
 2331:         } else {
 2332:             $domrolebuffer{$rudom}.=&escape($entry).
 2333:                       '='.&escape($domainrolehash{$entry});
 2334:         }
 2335:         delete $domainrolehash{$entry};
 2336:     }
 2337:     foreach my $dom (keys(%domrolebuffer)) {
 2338: 	my %servers = &get_servers($dom,'library');
 2339: 	foreach my $tryserver (keys(%servers)) {
 2340: 	    unless (&reply('domroleput:'.$dom.':'.
 2341: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2342: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2343: 	    }
 2344:         }
 2345:     }
 2346:     $dumpcount++;
 2347: }
 2348: 
 2349: sub courselog {
 2350:     my $what=shift;
 2351:     $what=time.':'.$what;
 2352:     unless ($env{'request.course.id'}) { return ''; }
 2353:     $coursedombuf{$env{'request.course.id'}}=
 2354:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2355:     $coursenumbuf{$env{'request.course.id'}}=
 2356:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2357:     $coursehombuf{$env{'request.course.id'}}=
 2358:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2359:     $coursedescrbuf{$env{'request.course.id'}}=
 2360:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2361:     $courseinstcodebuf{$env{'request.course.id'}}=
 2362:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2363:     $courseownerbuf{$env{'request.course.id'}}=
 2364:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2365:     $coursetypebuf{$env{'request.course.id'}}=
 2366:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2367:     if (defined $courselogs{$env{'request.course.id'}}) {
 2368: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2369:     } else {
 2370: 	$courselogs{$env{'request.course.id'}}.=$what;
 2371:     }
 2372:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2373: 	&flushcourselogs();
 2374:     }
 2375: }
 2376: 
 2377: sub courseacclog {
 2378:     my $fnsymb=shift;
 2379:     unless ($env{'request.course.id'}) { return ''; }
 2380:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2381:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2382:         $what.=':POST';
 2383:         # FIXME: Probably ought to escape things....
 2384: 	foreach my $key (keys(%env)) {
 2385:             if ($key=~/^form\.(.*)/) {
 2386: 		$what.=':'.$1.'='.$env{$key};
 2387:             }
 2388:         }
 2389:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2390:         # FIXME: We should not be depending on a form parameter that someone
 2391:         # editing lonsearchcat.pm might change in the future.
 2392:         if ($env{'form.phase'} eq 'course_search') {
 2393:             $what.= ':POST';
 2394:             # FIXME: Probably ought to escape things....
 2395:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2396:                                  'crsdiscuss') {
 2397:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2398:             }
 2399:         }
 2400:     }
 2401:     &courselog($what);
 2402: }
 2403: 
 2404: sub countacc {
 2405:     my $url=&declutter(shift);
 2406:     return if (! defined($url) || $url eq '');
 2407:     unless ($env{'request.course.id'}) { return ''; }
 2408:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2409:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2410:     $accesshash{$key}++;
 2411: }
 2412: 
 2413: sub linklog {
 2414:     my ($from,$to)=@_;
 2415:     $from=&declutter($from);
 2416:     $to=&declutter($to);
 2417:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2418:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2419: }
 2420:   
 2421: sub userrolelog {
 2422:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2423:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2424:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2425:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2426:         ($trole=~/^ta/)) {
 2427:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2428:        $userrolehash
 2429:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2430:                     =$tend.':'.$tstart;
 2431:     }
 2432:     if (($env{'request.role'} =~ /dc\./) &&
 2433: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2434: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2435: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2436:        $userrolehash
 2437:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2438:                     =$tend.':'.$tstart;
 2439:     }
 2440:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2441:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2442:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2443:         ($trole=~/^sc/)) {
 2444:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2445:        $domainrolehash
 2446:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2447:                     = $tend.':'.$tstart;
 2448:     }
 2449: }
 2450: 
 2451: sub get_course_adv_roles {
 2452:     my $cid=shift;
 2453:     $cid=$env{'request.course.id'} unless (defined($cid));
 2454:     my %coursehash=&coursedescription($cid);
 2455:     my %nothide=();
 2456:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2457:         if ($user !~ /:/) {
 2458: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2459:         } else {
 2460:             $nothide{$user}=1;
 2461:         }
 2462:     }
 2463:     my %returnhash=();
 2464:     my %dumphash=
 2465:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2466:     my $now=time;
 2467:     foreach my $entry (keys %dumphash) {
 2468: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2469:         if (($tstart) && ($tstart<0)) { next; }
 2470:         if (($tend) && ($tend<$now)) { next; }
 2471:         if (($tstart) && ($now<$tstart)) { next; }
 2472:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2473: 	if ($username eq '' || $domain eq '') { next; }
 2474: 	if ((&privileged($username,$domain)) && 
 2475: 	    (!$nothide{$username.':'.$domain})) { next; }
 2476: 	if ($role eq 'cr') { next; }
 2477:         my $key=&plaintext($role);
 2478:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2479:         if ($returnhash{$key}) {
 2480: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2481:         } else {
 2482:             $returnhash{$key}=$username.':'.$domain;
 2483:         }
 2484:      }
 2485:     return %returnhash;
 2486: }
 2487: 
 2488: sub get_my_roles {
 2489:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2490:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2491:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2492:     my (%dumphash,%nothide);
 2493:     if ($context eq 'userroles') { 
 2494:         %dumphash = &dump('roles',$udom,$uname);
 2495:     } else {
 2496:         %dumphash=
 2497:             &dump('nohist_userroles',$udom,$uname);
 2498:         if ($hidepriv) {
 2499:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2500:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2501:                 if ($user !~ /:/) {
 2502:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2503:                 } else {
 2504:                     $nothide{$user} = 1;
 2505:                 }
 2506:             }
 2507:         }
 2508:     }
 2509:     my %returnhash=();
 2510:     my $now=time;
 2511:     foreach my $entry (keys(%dumphash)) {
 2512:         my ($role,$tend,$tstart);
 2513:         if ($context eq 'userroles') {
 2514: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2515:         } else {
 2516:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2517:         }
 2518:         if (($tstart) && ($tstart<0)) { next; }
 2519:         my $status = 'active';
 2520:         if (($tend) && ($tend<=$now)) {
 2521:             $status = 'previous';
 2522:         } 
 2523:         if (($tstart) && ($now<$tstart)) {
 2524:             $status = 'future';
 2525:         }
 2526:         if (ref($types) eq 'ARRAY') {
 2527:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2528:                 next;
 2529:             } 
 2530:         } else {
 2531:             if ($status ne 'active') {
 2532:                 next;
 2533:             }
 2534:         }
 2535:         my ($rolecode,$username,$domain,$section,$area);
 2536:         if ($context eq 'userroles') {
 2537:             ($area,$rolecode) = split(/_/,$entry);
 2538:             (undef,$domain,$username,$section) = split(/\//,$area);
 2539:         } else {
 2540:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2541:         }
 2542:         if (ref($roledoms) eq 'ARRAY') {
 2543:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2544:                 next;
 2545:             }
 2546:         }
 2547:         if (ref($roles) eq 'ARRAY') {
 2548:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2549:                 if ($role =~ /^cr\//) {
 2550:                     if (!grep(/^cr$/,@{$roles})) {
 2551:                         next;
 2552:                     }
 2553:                 } else {
 2554:                     next;
 2555:                 }
 2556:             }
 2557:         }
 2558:         if ($hidepriv) {
 2559:             if ((&privileged($username,$domain)) &&
 2560:                 (!$nothide{$username.':'.$domain})) { 
 2561:                 next;
 2562:             }
 2563:         }
 2564:         if ($withsec) {
 2565:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2566:                 $tstart.':'.$tend;
 2567:         } else {
 2568:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2569:         }
 2570:     }
 2571:     return %returnhash;
 2572: }
 2573: 
 2574: # ----------------------------------------------------- Frontpage Announcements
 2575: #
 2576: #
 2577: 
 2578: sub postannounce {
 2579:     my ($server,$text)=@_;
 2580:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2581:     unless ($text=~/\w/) { $text=''; }
 2582:     return &reply('setannounce:'.&escape($text),$server);
 2583: }
 2584: 
 2585: sub getannounce {
 2586: 
 2587:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2588: 	my $announcement='';
 2589: 	while (my $line = <$fh>) { $announcement .= $line; }
 2590: 	close($fh);
 2591: 	if ($announcement=~/\w/) { 
 2592: 	    return 
 2593:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2594:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2595: 	} else {
 2596: 	    return '';
 2597: 	}
 2598:     } else {
 2599: 	return '';
 2600:     }
 2601: }
 2602: 
 2603: # ---------------------------------------------------------- Course ID routines
 2604: # Deal with domain's nohist_courseid.db files
 2605: #
 2606: 
 2607: sub courseidput {
 2608:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2609:     my $outcome;
 2610:     if ($caller eq 'timeonly') {
 2611:         my $cids = '';
 2612:         foreach my $item (keys(%$storehash)) {
 2613:             $cids.=&escape($item).'&';
 2614:         }
 2615:         $cids=~s/\&$//;
 2616:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2617:                           $coursehome);       
 2618:     } else {
 2619:         my $items = '';
 2620:         foreach my $item (keys(%$storehash)) {
 2621:             $items.= &escape($item).'='.
 2622:                      &freeze_escape($$storehash{$item}).'&';
 2623:         }
 2624:         $items=~s/\&$//;
 2625:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2626:                           $coursehome);
 2627:     }
 2628:     if ($outcome eq 'unknown_cmd') {
 2629:         my $what;
 2630:         foreach my $cid (keys(%$storehash)) {
 2631:             $what .= &escape($cid).'=';
 2632:             foreach my $item ('description','inst_code','owner','type') {
 2633:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2634:             }
 2635:             $what =~ s/\:$/&/;
 2636:         }
 2637:         $what =~ s/\&$//;  
 2638:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2639:     } else {
 2640:         return $outcome;
 2641:     }
 2642: }
 2643: 
 2644: sub courseiddump {
 2645:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2646:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2647:     my $as_hash = 1;
 2648:     my %returnhash;
 2649:     if (!$domfilter) { $domfilter=''; }
 2650:     my %libserv = &all_library();
 2651:     foreach my $tryserver (keys(%libserv)) {
 2652:         if ( (  $hostidflag == 1 
 2653: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2654: 	     || (!defined($hostidflag)) ) {
 2655: 
 2656: 	    if (($domfilter eq '') ||
 2657: 		(&host_domain($tryserver) eq $domfilter)) {
 2658:                 my $rep = 
 2659:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2660:                          $sincefilter.':'.&escape($descfilter).':'.
 2661:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2662:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2663:                          ':'.&escape($regexp_ok).':'.$as_hash,$tryserver);
 2664:                 my @pairs=split(/\&/,$rep);
 2665:                 foreach my $item (@pairs) {
 2666:                     my ($key,$value)=split(/\=/,$item,2);
 2667:                     $key = &unescape($key);
 2668:                     next if ($key =~ /^error: 2 /);
 2669:                     my $result = &thaw_unescape($value);
 2670:                     if (ref($result) eq 'HASH') {
 2671:                         $returnhash{$key}=$result;
 2672:                     } else {
 2673:                         my @responses = split(/:/,$value);
 2674:                         my @items = ('description','inst_code','owner','type');
 2675:                         for (my $i=0; $i<@responses; $i++) {
 2676:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2677:                         }
 2678:                     } 
 2679:                 }
 2680:             }
 2681:         }
 2682:     }
 2683:     return %returnhash;
 2684: }
 2685: 
 2686: # ---------------------------------------------------------- DC e-mail
 2687: 
 2688: sub dcmailput {
 2689:     my ($domain,$msgid,$message,$server)=@_;
 2690:     my $status = &Apache::lonnet::critical(
 2691:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2692:        &escape($message),$server);
 2693:     return $status;
 2694: }
 2695: 
 2696: sub dcmaildump {
 2697:     my ($dom,$startdate,$enddate,$senders) = @_;
 2698:     my %returnhash=();
 2699: 
 2700:     if (defined(&domain($dom,'primary'))) {
 2701:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2702:                                                          &escape($enddate).':';
 2703: 	my @esc_senders=map { &escape($_)} @$senders;
 2704: 	$cmd.=&escape(join('&',@esc_senders));
 2705: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2706:             my ($key,$value) = split(/\=/,$line,2);
 2707:             if (($key) && ($value)) {
 2708:                 $returnhash{&unescape($key)} = &unescape($value);
 2709:             }
 2710:         }
 2711:     }
 2712:     return %returnhash;
 2713: }
 2714: # ---------------------------------------------------------- Domain roles
 2715: 
 2716: sub get_domain_roles {
 2717:     my ($dom,$roles,$startdate,$enddate)=@_;
 2718:     if (undef($startdate) || $startdate eq '') {
 2719:         $startdate = '.';
 2720:     }
 2721:     if (undef($enddate) || $enddate eq '') {
 2722:         $enddate = '.';
 2723:     }
 2724:     my $rolelist;
 2725:     if (ref($roles) eq 'ARRAY') {
 2726:         $rolelist = join(':',@{$roles});
 2727:     }
 2728:     my %personnel = ();
 2729: 
 2730:     my %servers = &get_servers($dom,'library');
 2731:     foreach my $tryserver (keys(%servers)) {
 2732: 	%{$personnel{$tryserver}}=();
 2733: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2734: 					    &escape($startdate).':'.
 2735: 					    &escape($enddate).':'.
 2736: 					    &escape($rolelist), $tryserver))) {
 2737: 	    my ($key,$value) = split(/\=/,$line,2);
 2738: 	    if (($key) && ($value)) {
 2739: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2740: 	    }
 2741: 	}
 2742:     }
 2743:     return %personnel;
 2744: }
 2745: 
 2746: # ----------------------------------------------------------- Check out an item
 2747: 
 2748: sub get_first_access {
 2749:     my ($type,$argsymb)=@_;
 2750:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2751:     if ($argsymb) { $symb=$argsymb; }
 2752:     my ($map,$id,$res)=&decode_symb($symb);
 2753:     if ($type eq 'course') {
 2754: 	$res='course';
 2755:     } elsif ($type eq 'map') {
 2756: 	$res=&symbread($map);
 2757:     } else {
 2758: 	$res=$symb;
 2759:     }
 2760:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2761:     return $times{"$courseid\0$res"};
 2762: }
 2763: 
 2764: sub set_first_access {
 2765:     my ($type)=@_;
 2766:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2767:     my ($map,$id,$res)=&decode_symb($symb);
 2768:     if ($type eq 'course') {
 2769: 	$res='course';
 2770:     } elsif ($type eq 'map') {
 2771: 	$res=&symbread($map);
 2772:     } else {
 2773: 	$res=$symb;
 2774:     }
 2775:     my $firstaccess=&get_first_access($type,$symb);
 2776:     if (!$firstaccess) {
 2777: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2778:     }
 2779:     return 'already_set';
 2780: }
 2781: 
 2782: sub checkout {
 2783:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2784:     my $now=time;
 2785:     my $lonhost=$perlvar{'lonHostID'};
 2786:     my $infostr=&escape(
 2787:                  'CHECKOUTTOKEN&'.
 2788:                  $tuname.'&'.
 2789:                  $tudom.'&'.
 2790:                  $tcrsid.'&'.
 2791:                  $symb.'&'.
 2792: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2793:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2794:     if ($token=~/^error\:/) { 
 2795:         &logthis("<font color=\"blue\">WARNING: ".
 2796:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2797:                  "</font>");
 2798:         return ''; 
 2799:     }
 2800: 
 2801:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2802:     $token=~tr/a-z/A-Z/;
 2803: 
 2804:     my %infohash=('resource.0.outtoken' => $token,
 2805:                   'resource.0.checkouttime' => $now,
 2806:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2807: 
 2808:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2809:        return '';
 2810:     } else {
 2811:         &logthis("<font color=\"blue\">WARNING: ".
 2812:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2813:                  "</font>");
 2814:     }    
 2815: 
 2816:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2817:                          &escape('Checkout '.$infostr.' - '.
 2818:                                                  $token)) ne 'ok') {
 2819: 	return '';
 2820:     } else {
 2821:         &logthis("<font color=\"blue\">WARNING: ".
 2822:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2823:                  "</font>");
 2824:     }
 2825:     return $token;
 2826: }
 2827: 
 2828: # ------------------------------------------------------------ Check in an item
 2829: 
 2830: sub checkin {
 2831:     my $token=shift;
 2832:     my $now=time;
 2833:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2834:     $lonhost=~tr/A-Z/a-z/;
 2835:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2836:     $dtoken=~s/\W/\_/g;
 2837:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2838:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2839: 
 2840:     unless (($tuname) && ($tudom)) {
 2841:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2842:         return '';
 2843:     }
 2844:     
 2845:     unless (&allowed('mgr',$tcrsid)) {
 2846:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2847:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2848:         return '';
 2849:     }
 2850: 
 2851:     my %infohash=('resource.0.intoken' => $token,
 2852:                   'resource.0.checkintime' => $now,
 2853:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2854: 
 2855:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2856:        return '';
 2857:     }    
 2858: 
 2859:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2860:                          &escape('Checkin - '.$token)) ne 'ok') {
 2861: 	return '';
 2862:     }
 2863: 
 2864:     return ($symb,$tuname,$tudom,$tcrsid);    
 2865: }
 2866: 
 2867: # --------------------------------------------- Set Expire Date for Spreadsheet
 2868: 
 2869: sub expirespread {
 2870:     my ($uname,$udom,$stype,$usymb)=@_;
 2871:     my $cid=$env{'request.course.id'}; 
 2872:     if ($cid) {
 2873:        my $now=time;
 2874:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2875:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2876:                             $env{'course.'.$cid.'.num'}.
 2877: 	        	    ':nohist_expirationdates:'.
 2878:                             &escape($key).'='.$now,
 2879:                             $env{'course.'.$cid.'.home'})
 2880:     }
 2881:     return 'ok';
 2882: }
 2883: 
 2884: # ----------------------------------------------------- Devalidate Spreadsheets
 2885: 
 2886: sub devalidate {
 2887:     my ($symb,$uname,$udom)=@_;
 2888:     my $cid=$env{'request.course.id'}; 
 2889:     if ($cid) {
 2890:         # delete the stored spreadsheets for
 2891:         # - the student level sheet of this user in course's homespace
 2892:         # - the assessment level sheet for this resource 
 2893:         #   for this user in user's homespace
 2894: 	# - current conditional state info
 2895: 	my $key=$uname.':'.$udom.':';
 2896:         my $status=
 2897: 	    &del('nohist_calculatedsheets',
 2898: 		 [$key.'studentcalc:'],
 2899: 		 $env{'course.'.$cid.'.domain'},
 2900: 		 $env{'course.'.$cid.'.num'})
 2901: 		.' '.
 2902: 	    &del('nohist_calculatedsheets_'.$cid,
 2903: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2904:         unless ($status eq 'ok ok') {
 2905:            &logthis('Could not devalidate spreadsheet '.
 2906:                     $uname.' at '.$udom.' for '.
 2907: 		    $symb.': '.$status);
 2908:         }
 2909: 	&delenv('user.state.'.$cid);
 2910:     }
 2911: }
 2912: 
 2913: sub get_scalar {
 2914:     my ($string,$end) = @_;
 2915:     my $value;
 2916:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2917: 	$value = $1;
 2918:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2919: 	$value = $1;
 2920:     }
 2921:     return &unescape($value);
 2922: }
 2923: 
 2924: sub array2str {
 2925:   my (@array) = @_;
 2926:   my $result=&arrayref2str(\@array);
 2927:   $result=~s/^__ARRAY_REF__//;
 2928:   $result=~s/__END_ARRAY_REF__$//;
 2929:   return $result;
 2930: }
 2931: 
 2932: sub arrayref2str {
 2933:   my ($arrayref) = @_;
 2934:   my $result='__ARRAY_REF__';
 2935:   foreach my $elem (@$arrayref) {
 2936:     if(ref($elem) eq 'ARRAY') {
 2937:       $result.=&arrayref2str($elem).'&';
 2938:     } elsif(ref($elem) eq 'HASH') {
 2939:       $result.=&hashref2str($elem).'&';
 2940:     } elsif(ref($elem)) {
 2941:       #print("Got a ref of ".(ref($elem))." skipping.");
 2942:     } else {
 2943:       $result.=&escape($elem).'&';
 2944:     }
 2945:   }
 2946:   $result=~s/\&$//;
 2947:   $result .= '__END_ARRAY_REF__';
 2948:   return $result;
 2949: }
 2950: 
 2951: sub hash2str {
 2952:   my (%hash) = @_;
 2953:   my $result=&hashref2str(\%hash);
 2954:   $result=~s/^__HASH_REF__//;
 2955:   $result=~s/__END_HASH_REF__$//;
 2956:   return $result;
 2957: }
 2958: 
 2959: sub hashref2str {
 2960:   my ($hashref)=@_;
 2961:   my $result='__HASH_REF__';
 2962:   foreach my $key (sort(keys(%$hashref))) {
 2963:     if (ref($key) eq 'ARRAY') {
 2964:       $result.=&arrayref2str($key).'=';
 2965:     } elsif (ref($key) eq 'HASH') {
 2966:       $result.=&hashref2str($key).'=';
 2967:     } elsif (ref($key)) {
 2968:       $result.='=';
 2969:       #print("Got a ref of ".(ref($key))." skipping.");
 2970:     } else {
 2971: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2972:     }
 2973: 
 2974:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2975:       $result.=&arrayref2str($hashref->{$key}).'&';
 2976:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2977:       $result.=&hashref2str($hashref->{$key}).'&';
 2978:     } elsif(ref($hashref->{$key})) {
 2979:        $result.='&';
 2980:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2981:     } else {
 2982:       $result.=&escape($hashref->{$key}).'&';
 2983:     }
 2984:   }
 2985:   $result=~s/\&$//;
 2986:   $result .= '__END_HASH_REF__';
 2987:   return $result;
 2988: }
 2989: 
 2990: sub str2hash {
 2991:     my ($string)=@_;
 2992:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2993:     return %$hash;
 2994: }
 2995: 
 2996: sub str2hashref {
 2997:   my ($string) = @_;
 2998: 
 2999:   my %hash;
 3000: 
 3001:   if($string !~ /^__HASH_REF__/) {
 3002:       if (! ($string eq '' || !defined($string))) {
 3003: 	  $hash{'error'}='Not hash reference';
 3004:       }
 3005:       return (\%hash, $string);
 3006:   }
 3007: 
 3008:   $string =~ s/^__HASH_REF__//;
 3009: 
 3010:   while($string !~ /^__END_HASH_REF__/) {
 3011:       #key
 3012:       my $key='';
 3013:       if($string =~ /^__HASH_REF__/) {
 3014:           ($key, $string)=&str2hashref($string);
 3015:           if(defined($key->{'error'})) {
 3016:               $hash{'error'}='Bad data';
 3017:               return (\%hash, $string);
 3018:           }
 3019:       } elsif($string =~ /^__ARRAY_REF__/) {
 3020:           ($key, $string)=&str2arrayref($string);
 3021:           if($key->[0] eq 'Array reference error') {
 3022:               $hash{'error'}='Bad data';
 3023:               return (\%hash, $string);
 3024:           }
 3025:       } else {
 3026:           $string =~ s/^(.*?)=//;
 3027: 	  $key=&unescape($1);
 3028:       }
 3029:       $string =~ s/^=//;
 3030: 
 3031:       #value
 3032:       my $value='';
 3033:       if($string =~ /^__HASH_REF__/) {
 3034:           ($value, $string)=&str2hashref($string);
 3035:           if(defined($value->{'error'})) {
 3036:               $hash{'error'}='Bad data';
 3037:               return (\%hash, $string);
 3038:           }
 3039:       } elsif($string =~ /^__ARRAY_REF__/) {
 3040:           ($value, $string)=&str2arrayref($string);
 3041:           if($value->[0] eq 'Array reference error') {
 3042:               $hash{'error'}='Bad data';
 3043:               return (\%hash, $string);
 3044:           }
 3045:       } else {
 3046: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3047:       }
 3048:       $string =~ s/^&//;
 3049: 
 3050:       $hash{$key}=$value;
 3051:   }
 3052: 
 3053:   $string =~ s/^__END_HASH_REF__//;
 3054: 
 3055:   return (\%hash, $string);
 3056: }
 3057: 
 3058: sub str2array {
 3059:     my ($string)=@_;
 3060:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3061:     return @$array;
 3062: }
 3063: 
 3064: sub str2arrayref {
 3065:   my ($string) = @_;
 3066:   my @array;
 3067: 
 3068:   if($string !~ /^__ARRAY_REF__/) {
 3069:       if (! ($string eq '' || !defined($string))) {
 3070: 	  $array[0]='Array reference error';
 3071:       }
 3072:       return (\@array, $string);
 3073:   }
 3074: 
 3075:   $string =~ s/^__ARRAY_REF__//;
 3076: 
 3077:   while($string !~ /^__END_ARRAY_REF__/) {
 3078:       my $value='';
 3079:       if($string =~ /^__HASH_REF__/) {
 3080:           ($value, $string)=&str2hashref($string);
 3081:           if(defined($value->{'error'})) {
 3082:               $array[0] ='Array reference error';
 3083:               return (\@array, $string);
 3084:           }
 3085:       } elsif($string =~ /^__ARRAY_REF__/) {
 3086:           ($value, $string)=&str2arrayref($string);
 3087:           if($value->[0] eq 'Array reference error') {
 3088:               $array[0] ='Array reference error';
 3089:               return (\@array, $string);
 3090:           }
 3091:       } else {
 3092: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3093:       }
 3094:       $string =~ s/^&//;
 3095: 
 3096:       push(@array, $value);
 3097:   }
 3098: 
 3099:   $string =~ s/^__END_ARRAY_REF__//;
 3100: 
 3101:   return (\@array, $string);
 3102: }
 3103: 
 3104: # -------------------------------------------------------------------Temp Store
 3105: 
 3106: sub tmpreset {
 3107:   my ($symb,$namespace,$domain,$stuname) = @_;
 3108:   if (!$symb) {
 3109:     $symb=&symbread();
 3110:     if (!$symb) { $symb= $env{'request.url'}; }
 3111:   }
 3112:   $symb=escape($symb);
 3113: 
 3114:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3115:   $namespace=~s/\//\_/g;
 3116:   $namespace=~s/\W//g;
 3117: 
 3118:   if (!$domain) { $domain=$env{'user.domain'}; }
 3119:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3120:   if ($domain eq 'public' && $stuname eq 'public') {
 3121:       $stuname=$ENV{'REMOTE_ADDR'};
 3122:   }
 3123:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3124:   my %hash;
 3125:   if (tie(%hash,'GDBM_File',
 3126: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3127: 	  &GDBM_WRCREAT(),0640)) {
 3128:     foreach my $key (keys %hash) {
 3129:       if ($key=~ /:$symb/) {
 3130: 	delete($hash{$key});
 3131:       }
 3132:     }
 3133:   }
 3134: }
 3135: 
 3136: sub tmpstore {
 3137:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3138: 
 3139:   if (!$symb) {
 3140:     $symb=&symbread();
 3141:     if (!$symb) { $symb= $env{'request.url'}; }
 3142:   }
 3143:   $symb=escape($symb);
 3144: 
 3145:   if (!$namespace) {
 3146:     # I don't think we would ever want to store this for a course.
 3147:     # it seems this will only be used if we don't have a course.
 3148:     #$namespace=$env{'request.course.id'};
 3149:     #if (!$namespace) {
 3150:       $namespace=$env{'request.state'};
 3151:     #}
 3152:   }
 3153:   $namespace=~s/\//\_/g;
 3154:   $namespace=~s/\W//g;
 3155:   if (!$domain) { $domain=$env{'user.domain'}; }
 3156:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3157:   if ($domain eq 'public' && $stuname eq 'public') {
 3158:       $stuname=$ENV{'REMOTE_ADDR'};
 3159:   }
 3160:   my $now=time;
 3161:   my %hash;
 3162:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3163:   if (tie(%hash,'GDBM_File',
 3164: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3165: 	  &GDBM_WRCREAT(),0640)) {
 3166:     $hash{"version:$symb"}++;
 3167:     my $version=$hash{"version:$symb"};
 3168:     my $allkeys=''; 
 3169:     foreach my $key (keys(%$storehash)) {
 3170:       $allkeys.=$key.':';
 3171:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3172:     }
 3173:     $hash{"$version:$symb:timestamp"}=$now;
 3174:     $allkeys.='timestamp';
 3175:     $hash{"$version:keys:$symb"}=$allkeys;
 3176:     if (untie(%hash)) {
 3177:       return 'ok';
 3178:     } else {
 3179:       return "error:$!";
 3180:     }
 3181:   } else {
 3182:     return "error:$!";
 3183:   }
 3184: }
 3185: 
 3186: # -----------------------------------------------------------------Temp Restore
 3187: 
 3188: sub tmprestore {
 3189:   my ($symb,$namespace,$domain,$stuname) = @_;
 3190: 
 3191:   if (!$symb) {
 3192:     $symb=&symbread();
 3193:     if (!$symb) { $symb= $env{'request.url'}; }
 3194:   }
 3195:   $symb=escape($symb);
 3196: 
 3197:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3198: 
 3199:   if (!$domain) { $domain=$env{'user.domain'}; }
 3200:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3201:   if ($domain eq 'public' && $stuname eq 'public') {
 3202:       $stuname=$ENV{'REMOTE_ADDR'};
 3203:   }
 3204:   my %returnhash;
 3205:   $namespace=~s/\//\_/g;
 3206:   $namespace=~s/\W//g;
 3207:   my %hash;
 3208:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3209:   if (tie(%hash,'GDBM_File',
 3210: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3211: 	  &GDBM_READER(),0640)) {
 3212:     my $version=$hash{"version:$symb"};
 3213:     $returnhash{'version'}=$version;
 3214:     my $scope;
 3215:     for ($scope=1;$scope<=$version;$scope++) {
 3216:       my $vkeys=$hash{"$scope:keys:$symb"};
 3217:       my @keys=split(/:/,$vkeys);
 3218:       my $key;
 3219:       $returnhash{"$scope:keys"}=$vkeys;
 3220:       foreach $key (@keys) {
 3221: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3222: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3223:       }
 3224:     }
 3225:     if (!(untie(%hash))) {
 3226:       return "error:$!";
 3227:     }
 3228:   } else {
 3229:     return "error:$!";
 3230:   }
 3231:   return %returnhash;
 3232: }
 3233: 
 3234: # ----------------------------------------------------------------------- Store
 3235: 
 3236: sub store {
 3237:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3238:     my $home='';
 3239: 
 3240:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3241: 
 3242:     $symb=&symbclean($symb);
 3243:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3244: 
 3245:     if (!$domain) { $domain=$env{'user.domain'}; }
 3246:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3247: 
 3248:     &devalidate($symb,$stuname,$domain);
 3249: 
 3250:     $symb=escape($symb);
 3251:     if (!$namespace) { 
 3252:        unless ($namespace=$env{'request.course.id'}) { 
 3253:           return ''; 
 3254:        } 
 3255:     }
 3256:     if (!$home) { $home=$env{'user.home'}; }
 3257: 
 3258:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3259:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3260: 
 3261:     my $namevalue='';
 3262:     foreach my $key (keys(%$storehash)) {
 3263:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3264:     }
 3265:     $namevalue=~s/\&$//;
 3266:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3267:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3268: }
 3269: 
 3270: # -------------------------------------------------------------- Critical Store
 3271: 
 3272: sub cstore {
 3273:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3274:     my $home='';
 3275: 
 3276:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3277: 
 3278:     $symb=&symbclean($symb);
 3279:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3280: 
 3281:     if (!$domain) { $domain=$env{'user.domain'}; }
 3282:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3283: 
 3284:     &devalidate($symb,$stuname,$domain);
 3285: 
 3286:     $symb=escape($symb);
 3287:     if (!$namespace) { 
 3288:        unless ($namespace=$env{'request.course.id'}) { 
 3289:           return ''; 
 3290:        } 
 3291:     }
 3292:     if (!$home) { $home=$env{'user.home'}; }
 3293: 
 3294:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3295:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3296: 
 3297:     my $namevalue='';
 3298:     foreach my $key (keys(%$storehash)) {
 3299:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3300:     }
 3301:     $namevalue=~s/\&$//;
 3302:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3303:     return critical
 3304:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3305: }
 3306: 
 3307: # --------------------------------------------------------------------- Restore
 3308: 
 3309: sub restore {
 3310:     my ($symb,$namespace,$domain,$stuname) = @_;
 3311:     my $home='';
 3312: 
 3313:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3314: 
 3315:     if (!$symb) {
 3316:       unless ($symb=escape(&symbread())) { return ''; }
 3317:     } else {
 3318:       $symb=&escape(&symbclean($symb));
 3319:     }
 3320:     if (!$namespace) { 
 3321:        unless ($namespace=$env{'request.course.id'}) { 
 3322:           return ''; 
 3323:        } 
 3324:     }
 3325:     if (!$domain) { $domain=$env{'user.domain'}; }
 3326:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3327:     if (!$home) { $home=$env{'user.home'}; }
 3328:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3329: 
 3330:     my %returnhash=();
 3331:     foreach my $line (split(/\&/,$answer)) {
 3332: 	my ($name,$value)=split(/\=/,$line);
 3333:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3334:     }
 3335:     my $version;
 3336:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3337:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3338:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3339:        }
 3340:     }
 3341:     return %returnhash;
 3342: }
 3343: 
 3344: # ---------------------------------------------------------- Course Description
 3345: 
 3346: sub coursedescription {
 3347:     my ($courseid,$args)=@_;
 3348:     $courseid=~s/^\///;
 3349:     $courseid=~s/\_/\//g;
 3350:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3351:     my $chome=&homeserver($cnum,$cdomain);
 3352:     my $normalid=$cdomain.'_'.$cnum;
 3353:     # need to always cache even if we get errors otherwise we keep 
 3354:     # trying and trying and trying to get the course description.
 3355:     my %envhash=();
 3356:     my %returnhash=();
 3357:     
 3358:     my $expiretime=600;
 3359:     if ($env{'request.course.id'} eq $normalid) {
 3360: 	$expiretime=120;
 3361:     }
 3362: 
 3363:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3364:     if (!$args->{'freshen_cache'}
 3365: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3366: 	foreach my $key (keys(%env)) {
 3367: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3368: 	    my ($setting) = $1;
 3369: 	    $returnhash{$setting} = $env{$key};
 3370: 	}
 3371: 	return %returnhash;
 3372:     }
 3373: 
 3374:     # get the data agin
 3375:     if (!$args->{'one_time'}) {
 3376: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3377:     }
 3378: 
 3379:     if ($chome ne 'no_host') {
 3380:        %returnhash=&dump('environment',$cdomain,$cnum);
 3381:        if (!exists($returnhash{'con_lost'})) {
 3382:            $returnhash{'home'}= $chome;
 3383: 	   $returnhash{'domain'} = $cdomain;
 3384: 	   $returnhash{'num'} = $cnum;
 3385:            if (!defined($returnhash{'type'})) {
 3386:                $returnhash{'type'} = 'Course';
 3387:            }
 3388:            while (my ($name,$value) = each %returnhash) {
 3389:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3390:            }
 3391:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3392:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3393: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3394:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3395:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3396:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3397:        }
 3398:     }
 3399:     if (!$args->{'one_time'}) {
 3400: 	&appenv(%envhash);
 3401:     }
 3402:     return %returnhash;
 3403: }
 3404: 
 3405: # -------------------------------------------------See if a user is privileged
 3406: 
 3407: sub privileged {
 3408:     my ($username,$domain)=@_;
 3409:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3410: 			&homeserver($username,$domain));
 3411:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3412:     my $now=time;
 3413:     if ($rolesdump ne '') {
 3414:         foreach my $entry (split(/&/,$rolesdump)) {
 3415: 	    if ($entry!~/^rolesdef_/) {
 3416: 		my ($area,$role)=split(/=/,$entry);
 3417: 		$area=~s/\_\w\w$//;
 3418: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3419: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3420: 		    my $active=1;
 3421: 		    if ($tend) {
 3422: 			if ($tend<$now) { $active=0; }
 3423: 		    }
 3424: 		    if ($tstart) {
 3425: 			if ($tstart>$now) { $active=0; }
 3426: 		    }
 3427: 		    if ($active) { return 1; }
 3428: 		}
 3429: 	    }
 3430: 	}
 3431:     }
 3432:     return 0;
 3433: }
 3434: 
 3435: # -------------------------------------------------------- Get user privileges
 3436: 
 3437: sub rolesinit {
 3438:     my ($domain,$username,$authhost)=@_;
 3439:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3440:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3441:     my %allroles=();
 3442:     my %allgroups=();   
 3443:     my $now=time;
 3444:     my %userroles = ('user.login.time' => $now);
 3445:     my $group_privs;
 3446: 
 3447:     if ($rolesdump ne '') {
 3448:         foreach my $entry (split(/&/,$rolesdump)) {
 3449: 	  if ($entry!~/^rolesdef_/) {
 3450:             my ($area,$role)=split(/=/,$entry);
 3451: 	    $area=~s/\_\w\w$//;
 3452:             my ($trole,$tend,$tstart,$group_privs);
 3453: 	    if ($role=~/^cr/) { 
 3454: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3455: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3456: 		    ($tend,$tstart)=split('_',$trest);
 3457: 		} else {
 3458: 		    $trole=$role;
 3459: 		}
 3460:             } elsif ($role =~ m|^gr/|) {
 3461:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3462:                 ($trole,$group_privs) = split(/\//,$trole);
 3463:                 $group_privs = &unescape($group_privs);
 3464: 	    } else {
 3465: 		($trole,$tend,$tstart)=split(/_/,$role);
 3466: 	    }
 3467: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3468: 					 $username);
 3469: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3470:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3471:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3472:             if (($area ne '') && ($trole ne '')) {
 3473: 		my $spec=$trole.'.'.$area;
 3474: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3475: 		if ($trole =~ /^cr\//) {
 3476:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3477:                 } elsif ($trole eq 'gr') {
 3478:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3479: 		} else {
 3480:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3481: 		}
 3482:             }
 3483:           }
 3484:         }
 3485:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3486:         $userroles{'user.adv'}    = $adv;
 3487: 	$userroles{'user.author'} = $author;
 3488:         $env{'user.adv'}=$adv;
 3489:     }
 3490:     return \%userroles;  
 3491: }
 3492: 
 3493: sub set_arearole {
 3494:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3495: # log the associated role with the area
 3496:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3497:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3498: }
 3499: 
 3500: sub custom_roleprivs {
 3501:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3502:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3503:     my $homsvr=homeserver($rauthor,$rdomain);
 3504:     if (&hostname($homsvr) ne '') {
 3505:         my ($rdummy,$roledef)=
 3506:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3507:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3508:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3509:             if (defined($syspriv)) {
 3510:                 $$allroles{'cm./'}.=':'.$syspriv;
 3511:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3512:             }
 3513:             if ($tdomain ne '') {
 3514:                 if (defined($dompriv)) {
 3515:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3516:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3517:                 }
 3518:                 if (($trest ne '') && (defined($coursepriv))) {
 3519:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3520:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3521:                 }
 3522:             }
 3523:         }
 3524:     }
 3525: }
 3526: 
 3527: sub group_roleprivs {
 3528:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3529:     my $access = 1;
 3530:     my $now = time;
 3531:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3532:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3533:     if ($access) {
 3534:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3535:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3536:     }
 3537: }
 3538: 
 3539: sub standard_roleprivs {
 3540:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3541:     if (defined($pr{$trole.':s'})) {
 3542:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3543:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3544:     }
 3545:     if ($tdomain ne '') {
 3546:         if (defined($pr{$trole.':d'})) {
 3547:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3548:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3549:         }
 3550:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3551:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3552:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3553:         }
 3554:     }
 3555: }
 3556: 
 3557: sub set_userprivs {
 3558:     my ($userroles,$allroles,$allgroups) = @_; 
 3559:     my $author=0;
 3560:     my $adv=0;
 3561:     my %grouproles = ();
 3562:     if (keys(%{$allgroups}) > 0) {
 3563:         foreach my $role (keys %{$allroles}) {
 3564:             my ($trole,$area,$sec,$extendedarea);
 3565:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3566:                 $trole = $1;
 3567:                 $area = $2;
 3568:                 $sec = $3;
 3569:                 $extendedarea = $area.$sec;
 3570:                 if (exists($$allgroups{$area})) {
 3571:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3572:                         my $spec = $trole.'.'.$extendedarea;
 3573:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3574:                                                 $$allgroups{$area}{$group};
 3575:                     }
 3576:                 }
 3577:             }
 3578:         }
 3579:     }
 3580:     foreach my $group (keys(%grouproles)) {
 3581:         $$allroles{$group} = $grouproles{$group};
 3582:     }
 3583:     foreach my $role (keys(%{$allroles})) {
 3584:         my %thesepriv;
 3585:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3586:         foreach my $item (split(/:/,$$allroles{$role})) {
 3587:             if ($item ne '') {
 3588:                 my ($privilege,$restrictions)=split(/&/,$item);
 3589:                 if ($restrictions eq '') {
 3590:                     $thesepriv{$privilege}='F';
 3591:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3592:                     $thesepriv{$privilege}.=$restrictions;
 3593:                 }
 3594:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3595:             }
 3596:         }
 3597:         my $thesestr='';
 3598:         foreach my $priv (keys(%thesepriv)) {
 3599: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3600: 	}
 3601:         $userroles->{'user.priv.'.$role} = $thesestr;
 3602:     }
 3603:     return ($author,$adv);
 3604: }
 3605: 
 3606: # --------------------------------------------------------------- get interface
 3607: 
 3608: sub get {
 3609:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3610:    my $items='';
 3611:    foreach my $item (@$storearr) {
 3612:        $items.=&escape($item).'&';
 3613:    }
 3614:    $items=~s/\&$//;
 3615:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3616:    if (!$uname) { $uname=$env{'user.name'}; }
 3617:    my $uhome=&homeserver($uname,$udomain);
 3618: 
 3619:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3620:    my @pairs=split(/\&/,$rep);
 3621:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3622:      return @pairs;
 3623:    }
 3624:    my %returnhash=();
 3625:    my $i=0;
 3626:    foreach my $item (@$storearr) {
 3627:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3628:       $i++;
 3629:    }
 3630:    return %returnhash;
 3631: }
 3632: 
 3633: # --------------------------------------------------------------- del interface
 3634: 
 3635: sub del {
 3636:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3637:    my $items='';
 3638:    foreach my $item (@$storearr) {
 3639:        $items.=&escape($item).'&';
 3640:    }
 3641:    $items=~s/\&$//;
 3642:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3643:    if (!$uname) { $uname=$env{'user.name'}; }
 3644:    my $uhome=&homeserver($uname,$udomain);
 3645: 
 3646:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3647: }
 3648: 
 3649: # -------------------------------------------------------------- dump interface
 3650: 
 3651: sub dump {
 3652:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3653:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3654:     if (!$uname) { $uname=$env{'user.name'}; }
 3655:     my $uhome=&homeserver($uname,$udomain);
 3656:     if ($regexp) {
 3657: 	$regexp=&escape($regexp);
 3658:     } else {
 3659: 	$regexp='.';
 3660:     }
 3661:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3662:     my @pairs=split(/\&/,$rep);
 3663:     my %returnhash=();
 3664:     foreach my $item (@pairs) {
 3665: 	my ($key,$value)=split(/=/,$item,2);
 3666: 	$key = &unescape($key);
 3667: 	next if ($key =~ /^error: 2 /);
 3668: 	$returnhash{$key}=&thaw_unescape($value);
 3669:     }
 3670:     return %returnhash;
 3671: }
 3672: 
 3673: # --------------------------------------------------------- dumpstore interface
 3674: 
 3675: sub dumpstore {
 3676:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3677:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3678:    if (!$uname) { $uname=$env{'user.name'}; }
 3679:    my $uhome=&homeserver($uname,$udomain);
 3680:    if ($regexp) {
 3681:        $regexp=&escape($regexp);
 3682:    } else {
 3683:        $regexp='.';
 3684:    }
 3685:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3686:    my @pairs=split(/\&/,$rep);
 3687:    my %returnhash=();
 3688:    foreach my $item (@pairs) {
 3689:        my ($key,$value)=split(/=/,$item,2);
 3690:        next if ($key =~ /^error: 2 /);
 3691:        $returnhash{$key}=&thaw_unescape($value);
 3692:    }
 3693:    return %returnhash;
 3694: }
 3695: 
 3696: # -------------------------------------------------------------- keys interface
 3697: 
 3698: sub getkeys {
 3699:    my ($namespace,$udomain,$uname)=@_;
 3700:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3701:    if (!$uname) { $uname=$env{'user.name'}; }
 3702:    my $uhome=&homeserver($uname,$udomain);
 3703:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3704:    my @keyarray=();
 3705:    foreach my $key (split(/\&/,$rep)) {
 3706:       next if ($key =~ /^error: 2 /);
 3707:       push(@keyarray,&unescape($key));
 3708:    }
 3709:    return @keyarray;
 3710: }
 3711: 
 3712: # --------------------------------------------------------------- currentdump
 3713: sub currentdump {
 3714:    my ($courseid,$sdom,$sname)=@_;
 3715:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3716:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3717:    $sname    = $env{'user.name'}         if (! defined($sname));
 3718:    my $uhome = &homeserver($sname,$sdom);
 3719:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3720:    return if ($rep =~ /^(error:|no_such_host)/);
 3721:    #
 3722:    my %returnhash=();
 3723:    #
 3724:    if ($rep eq "unknown_cmd") { 
 3725:        # an old lond will not know currentdump
 3726:        # Do a dump and make it look like a currentdump
 3727:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3728:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3729:        my %hash = @tmp;
 3730:        @tmp=();
 3731:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3732:    } else {
 3733:        my @pairs=split(/\&/,$rep);
 3734:        foreach my $pair (@pairs) {
 3735:            my ($key,$value)=split(/=/,$pair,2);
 3736:            my ($symb,$param) = split(/:/,$key);
 3737:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3738:                                                         &thaw_unescape($value);
 3739:        }
 3740:    }
 3741:    return %returnhash;
 3742: }
 3743: 
 3744: sub convert_dump_to_currentdump{
 3745:     my %hash = %{shift()};
 3746:     my %returnhash;
 3747:     # Code ripped from lond, essentially.  The only difference
 3748:     # here is the unescaping done by lonnet::dump().  Conceivably
 3749:     # we might run in to problems with parameter names =~ /^v\./
 3750:     while (my ($key,$value) = each(%hash)) {
 3751:         my ($v,$symb,$param) = split(/:/,$key);
 3752: 	$symb  = &unescape($symb);
 3753: 	$param = &unescape($param);
 3754:         next if ($v eq 'version' || $symb eq 'keys');
 3755:         next if (exists($returnhash{$symb}) &&
 3756:                  exists($returnhash{$symb}->{$param}) &&
 3757:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3758:         $returnhash{$symb}->{$param}=$value;
 3759:         $returnhash{$symb}->{'v.'.$param}=$v;
 3760:     }
 3761:     #
 3762:     # Remove all of the keys in the hashes which keep track of
 3763:     # the version of the parameter.
 3764:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3765:         # use a foreach because we are going to delete from the hash.
 3766:         foreach my $key (keys(%$param_hash)) {
 3767:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3768:         }
 3769:     }
 3770:     return \%returnhash;
 3771: }
 3772: 
 3773: # ------------------------------------------------------ critical inc interface
 3774: 
 3775: sub cinc {
 3776:     return &inc(@_,'critical');
 3777: }
 3778: 
 3779: # --------------------------------------------------------------- inc interface
 3780: 
 3781: sub inc {
 3782:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3783:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3784:     if (!$uname) { $uname=$env{'user.name'}; }
 3785:     my $uhome=&homeserver($uname,$udomain);
 3786:     my $items='';
 3787:     if (! ref($store)) {
 3788:         # got a single value, so use that instead
 3789:         $items = &escape($store).'=&';
 3790:     } elsif (ref($store) eq 'SCALAR') {
 3791:         $items = &escape($$store).'=&';        
 3792:     } elsif (ref($store) eq 'ARRAY') {
 3793:         $items = join('=&',map {&escape($_);} @{$store});
 3794:     } elsif (ref($store) eq 'HASH') {
 3795:         while (my($key,$value) = each(%{$store})) {
 3796:             $items.= &escape($key).'='.&escape($value).'&';
 3797:         }
 3798:     }
 3799:     $items=~s/\&$//;
 3800:     if ($critical) {
 3801: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3802:     } else {
 3803: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3804:     }
 3805: }
 3806: 
 3807: # --------------------------------------------------------------- put interface
 3808: 
 3809: sub put {
 3810:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3811:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3812:    if (!$uname) { $uname=$env{'user.name'}; }
 3813:    my $uhome=&homeserver($uname,$udomain);
 3814:    my $items='';
 3815:    foreach my $item (keys(%$storehash)) {
 3816:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3817:    }
 3818:    $items=~s/\&$//;
 3819:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3820: }
 3821: 
 3822: # ------------------------------------------------------------ newput interface
 3823: 
 3824: sub newput {
 3825:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3826:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3827:    if (!$uname) { $uname=$env{'user.name'}; }
 3828:    my $uhome=&homeserver($uname,$udomain);
 3829:    my $items='';
 3830:    foreach my $key (keys(%$storehash)) {
 3831:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3832:    }
 3833:    $items=~s/\&$//;
 3834:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3835: }
 3836: 
 3837: # ---------------------------------------------------------  putstore interface
 3838: 
 3839: sub putstore {
 3840:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3841:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3842:    if (!$uname) { $uname=$env{'user.name'}; }
 3843:    my $uhome=&homeserver($uname,$udomain);
 3844:    my $items='';
 3845:    foreach my $key (keys(%$storehash)) {
 3846:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3847:    }
 3848:    $items=~s/\&$//;
 3849:    my $esc_symb=&escape($symb);
 3850:    my $esc_v=&escape($version);
 3851:    my $reply =
 3852:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3853: 	      $uhome);
 3854:    if ($reply eq 'unknown_cmd') {
 3855:        # gfall back to way things use to be done
 3856:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3857: 			    $uname);
 3858:    }
 3859:    return $reply;
 3860: }
 3861: 
 3862: sub old_putstore {
 3863:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3864:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3865:     if (!$uname) { $uname=$env{'user.name'}; }
 3866:     my $uhome=&homeserver($uname,$udomain);
 3867:     my %newstorehash;
 3868:     foreach my $item (keys(%$storehash)) {
 3869: 	my $key = $version.':'.&escape($symb).':'.$item;
 3870: 	$newstorehash{$key} = $storehash->{$item};
 3871:     }
 3872:     my $items='';
 3873:     my %allitems = ();
 3874:     foreach my $item (keys(%newstorehash)) {
 3875: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3876: 	    my $key = $1.':keys:'.$2;
 3877: 	    $allitems{$key} .= $3.':';
 3878: 	}
 3879: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3880:     }
 3881:     foreach my $item (keys(%allitems)) {
 3882: 	$allitems{$item} =~ s/\:$//;
 3883: 	$items.= $item.'='.$allitems{$item}.'&';
 3884:     }
 3885:     $items=~s/\&$//;
 3886:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3887: }
 3888: 
 3889: # ------------------------------------------------------ critical put interface
 3890: 
 3891: sub cput {
 3892:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3893:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3894:    if (!$uname) { $uname=$env{'user.name'}; }
 3895:    my $uhome=&homeserver($uname,$udomain);
 3896:    my $items='';
 3897:    foreach my $item (keys(%$storehash)) {
 3898:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3899:    }
 3900:    $items=~s/\&$//;
 3901:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3902: }
 3903: 
 3904: # -------------------------------------------------------------- eget interface
 3905: 
 3906: sub eget {
 3907:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3908:    my $items='';
 3909:    foreach my $item (@$storearr) {
 3910:        $items.=&escape($item).'&';
 3911:    }
 3912:    $items=~s/\&$//;
 3913:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3914:    if (!$uname) { $uname=$env{'user.name'}; }
 3915:    my $uhome=&homeserver($uname,$udomain);
 3916:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3917:    my @pairs=split(/\&/,$rep);
 3918:    my %returnhash=();
 3919:    my $i=0;
 3920:    foreach my $item (@$storearr) {
 3921:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3922:       $i++;
 3923:    }
 3924:    return %returnhash;
 3925: }
 3926: 
 3927: # ------------------------------------------------------------ tmpput interface
 3928: sub tmpput {
 3929:     my ($storehash,$server,$context)=@_;
 3930:     my $items='';
 3931:     foreach my $item (keys(%$storehash)) {
 3932: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3933:     }
 3934:     $items=~s/\&$//;
 3935:     if (defined($context)) {
 3936:         $items .= ':'.&escape($context);
 3937:     }
 3938:     return &reply("tmpput:$items",$server);
 3939: }
 3940: 
 3941: # ------------------------------------------------------------ tmpget interface
 3942: sub tmpget {
 3943:     my ($token,$server)=@_;
 3944:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3945:     my $rep=&reply("tmpget:$token",$server);
 3946:     my %returnhash;
 3947:     foreach my $item (split(/\&/,$rep)) {
 3948: 	my ($key,$value)=split(/=/,$item);
 3949: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3950:     }
 3951:     return %returnhash;
 3952: }
 3953: 
 3954: # ------------------------------------------------------------ tmpget interface
 3955: sub tmpdel {
 3956:     my ($token,$server)=@_;
 3957:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3958:     return &reply("tmpdel:$token",$server);
 3959: }
 3960: 
 3961: # -------------------------------------------------- portfolio access checking
 3962: 
 3963: sub portfolio_access {
 3964:     my ($requrl) = @_;
 3965:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3966:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3967:     if ($result) {
 3968:         my %setters;
 3969:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3970:             my ($startblock,$endblock) =
 3971:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3972:             if ($startblock && $endblock) {
 3973:                 return 'B';
 3974:             }
 3975:         } else {
 3976:             my ($startblock,$endblock) =
 3977:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3978:             if ($startblock && $endblock) {
 3979:                 return 'B';
 3980:             }
 3981:         }
 3982:     }
 3983:     if ($result eq 'ok') {
 3984:        return 'F';
 3985:     } elsif ($result =~ /^[^:]+:guest_/) {
 3986:        return 'A';
 3987:     }
 3988:     return '';
 3989: }
 3990: 
 3991: sub get_portfolio_access {
 3992:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3993: 
 3994:     if (!ref($access_hash)) {
 3995: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3996: 	my %access_controls = &get_access_controls($current_perms,$group,
 3997: 						   $file_name);
 3998: 	$access_hash = $access_controls{$file_name};
 3999:     }
 4000: 
 4001:     my ($public,$guest,@domains,@users,@courses,@groups);
 4002:     my $now = time;
 4003:     if (ref($access_hash) eq 'HASH') {
 4004:         foreach my $key (keys(%{$access_hash})) {
 4005:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4006:             if ($start > $now) {
 4007:                 next;
 4008:             }
 4009:             if ($end && $end<$now) {
 4010:                 next;
 4011:             }
 4012:             if ($scope eq 'public') {
 4013:                 $public = $key;
 4014:                 last;
 4015:             } elsif ($scope eq 'guest') {
 4016:                 $guest = $key;
 4017:             } elsif ($scope eq 'domains') {
 4018:                 push(@domains,$key);
 4019:             } elsif ($scope eq 'users') {
 4020:                 push(@users,$key);
 4021:             } elsif ($scope eq 'course') {
 4022:                 push(@courses,$key);
 4023:             } elsif ($scope eq 'group') {
 4024:                 push(@groups,$key);
 4025:             }
 4026:         }
 4027:         if ($public) {
 4028:             return 'ok';
 4029:         }
 4030:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4031:             if ($guest) {
 4032:                 return $guest;
 4033:             }
 4034:         } else {
 4035:             if (@domains > 0) {
 4036:                 foreach my $domkey (@domains) {
 4037:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4038:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4039:                             return 'ok';
 4040:                         }
 4041:                     }
 4042:                 }
 4043:             }
 4044:             if (@users > 0) {
 4045:                 foreach my $userkey (@users) {
 4046:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4047:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4048:                             if (ref($item) eq 'HASH') {
 4049:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4050:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4051:                                     return 'ok';
 4052:                                 }
 4053:                             }
 4054:                         }
 4055:                     } 
 4056:                 }
 4057:             }
 4058:             my %roleshash;
 4059:             my @courses_and_groups = @courses;
 4060:             push(@courses_and_groups,@groups); 
 4061:             if (@courses_and_groups > 0) {
 4062:                 my (%allgroups,%allroles); 
 4063:                 my ($start,$end,$role,$sec,$group);
 4064:                 foreach my $envkey (%env) {
 4065:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4066:                         my $cid = $2.'_'.$3; 
 4067:                         if ($1 eq 'gr') {
 4068:                             $group = $4;
 4069:                             $allgroups{$cid}{$group} = $env{$envkey};
 4070:                         } else {
 4071:                             if ($4 eq '') {
 4072:                                 $sec = 'none';
 4073:                             } else {
 4074:                                 $sec = $4;
 4075:                             }
 4076:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4077:                         }
 4078:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4079:                         my $cid = $2.'_'.$3;
 4080:                         if ($4 eq '') {
 4081:                             $sec = 'none';
 4082:                         } else {
 4083:                             $sec = $4;
 4084:                         }
 4085:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4086:                     }
 4087:                 }
 4088:                 if (keys(%allroles) == 0) {
 4089:                     return;
 4090:                 }
 4091:                 foreach my $key (@courses_and_groups) {
 4092:                     my %content = %{$$access_hash{$key}};
 4093:                     my $cnum = $content{'number'};
 4094:                     my $cdom = $content{'domain'};
 4095:                     my $cid = $cdom.'_'.$cnum;
 4096:                     if (!exists($allroles{$cid})) {
 4097:                         next;
 4098:                     }    
 4099:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4100:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4101:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4102:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4103:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4104:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4105:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4106:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4107:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4108:                                         if (grep/^all$/,@sections) {
 4109:                                             return 'ok';
 4110:                                         } else {
 4111:                                             if (grep/^$sec$/,@sections) {
 4112:                                                 return 'ok';
 4113:                                             }
 4114:                                         }
 4115:                                     }
 4116:                                 }
 4117:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4118:                                     if (grep/^none$/,@groups) {
 4119:                                         return 'ok';
 4120:                                     }
 4121:                                 } else {
 4122:                                     if (grep/^all$/,@groups) {
 4123:                                         return 'ok';
 4124:                                     } 
 4125:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4126:                                         if (grep/^$group$/,@groups) {
 4127:                                             return 'ok';
 4128:                                         }
 4129:                                     }
 4130:                                 } 
 4131:                             }
 4132:                         }
 4133:                     }
 4134:                 }
 4135:             }
 4136:             if ($guest) {
 4137:                 return $guest;
 4138:             }
 4139:         }
 4140:     }
 4141:     return;
 4142: }
 4143: 
 4144: sub course_group_datechecker {
 4145:     my ($dates,$now,$status) = @_;
 4146:     my ($start,$end) = split(/\./,$dates);
 4147:     if (!$start && !$end) {
 4148:         return 'ok';
 4149:     }
 4150:     if (grep/^active$/,@{$status}) {
 4151:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4152:             return 'ok';
 4153:         }
 4154:     }
 4155:     if (grep/^previous$/,@{$status}) {
 4156:         if ($end > $now ) {
 4157:             return 'ok';
 4158:         }
 4159:     }
 4160:     if (grep/^future$/,@{$status}) {
 4161:         if ($start > $now) {
 4162:             return 'ok';
 4163:         }
 4164:     }
 4165:     return; 
 4166: }
 4167: 
 4168: sub parse_portfolio_url {
 4169:     my ($url) = @_;
 4170: 
 4171:     my ($type,$udom,$unum,$group,$file_name);
 4172:     
 4173:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4174: 	$type = 1;
 4175:         $udom = $1;
 4176:         $unum = $2;
 4177:         $file_name = $3;
 4178:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4179: 	$type = 2;
 4180:         $udom = $1;
 4181:         $unum = $2;
 4182:         $group = $3;
 4183:         $file_name = $3.'/'.$4;
 4184:     }
 4185:     if (wantarray) {
 4186: 	return ($type,$udom,$unum,$file_name,$group);
 4187:     }
 4188:     return $type;
 4189: }
 4190: 
 4191: sub is_portfolio_url {
 4192:     my ($url) = @_;
 4193:     return scalar(&parse_portfolio_url($url));
 4194: }
 4195: 
 4196: sub is_portfolio_file {
 4197:     my ($file) = @_;
 4198:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4199:         return 1;
 4200:     }
 4201:     return;
 4202: }
 4203: 
 4204: 
 4205: # ---------------------------------------------- Custom access rule evaluation
 4206: 
 4207: sub customaccess {
 4208:     my ($priv,$uri)=@_;
 4209:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4210:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4211:     $udom = &LONCAPA::clean_domain($udom);
 4212:     $ucrs = &LONCAPA::clean_username($ucrs);
 4213:     my $access=0;
 4214:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4215: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4216: 	if ($type eq 'user') {
 4217: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4218: 		my ($tdom,$tuname)=split(m{/},$scope);
 4219: 		if ($tdom) {
 4220: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4221: 		}
 4222: 		if ($tuname) {
 4223: 		    if ($tuname ne $env{'user.name'}) { next; }
 4224: 		}
 4225: 		$access=($effect eq 'allow');
 4226: 		last;
 4227: 	    }
 4228: 	} else {
 4229: 	    if ($role) {
 4230: 		if ($role ne $urole) { next; }
 4231: 	    }
 4232: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4233: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4234: 		if ($tdom) {
 4235: 		    if ($tdom ne $udom) { next; }
 4236: 		}
 4237: 		if ($tcrs) {
 4238: 		    if ($tcrs ne $ucrs) { next; }
 4239: 		}
 4240: 		if ($tsec) {
 4241: 		    if ($tsec ne $usec) { next; }
 4242: 		}
 4243: 		$access=($effect eq 'allow');
 4244: 		last;
 4245: 	    }
 4246: 	    if ($realm eq '' && $role eq '') {
 4247: 		$access=($effect eq 'allow');
 4248: 	    }
 4249: 	}
 4250:     }
 4251:     return $access;
 4252: }
 4253: 
 4254: # ------------------------------------------------- Check for a user privilege
 4255: 
 4256: sub allowed {
 4257:     my ($priv,$uri,$symb,$role)=@_;
 4258:     my $ver_orguri=$uri;
 4259:     $uri=&deversion($uri);
 4260:     my $orguri=$uri;
 4261:     $uri=&declutter($uri);
 4262: 
 4263:     if ($priv eq 'evb') {
 4264: # Evade communication block restrictions for specified role in a course
 4265:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4266:             return $1;
 4267:         } else {
 4268:             return;
 4269:         }
 4270:     }
 4271: 
 4272:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4273: # Free bre access to adm and meta resources
 4274:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4275: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4276: 	&& ($priv eq 'bre')) {
 4277: 	return 'F';
 4278:     }
 4279: 
 4280: # Free bre access to user's own portfolio contents
 4281:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4282:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4283: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4284:         my %setters;
 4285:         my ($startblock,$endblock) = 
 4286:             &Apache::loncommon::blockcheck(\%setters,'port');
 4287:         if ($startblock && $endblock) {
 4288:             return 'B';
 4289:         } else {
 4290:             return 'F';
 4291:         }
 4292:     }
 4293: 
 4294: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4295:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4296:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4297:         if (exists($env{'request.course.id'})) {
 4298:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4299:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4300:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4301:                 my $courseprivid=$env{'request.course.id'};
 4302:                 $courseprivid=~s/\_/\//;
 4303:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4304:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4305:                     return $1; 
 4306:                 } else {
 4307:                     if ($env{'request.course.sec'}) {
 4308:                         $courseprivid.='/'.$env{'request.course.sec'};
 4309:                     }
 4310:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4311:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4312:                         return $2;
 4313:                     }
 4314:                 }
 4315:             }
 4316:         }
 4317:     }
 4318: 
 4319: # Free bre to public access
 4320: 
 4321:     if ($priv eq 'bre') {
 4322:         my $copyright=&metadata($uri,'copyright');
 4323: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4324:            return 'F'; 
 4325:         }
 4326:         if ($copyright eq 'priv') {
 4327:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4328: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4329: 		return '';
 4330:             }
 4331:         }
 4332:         if ($copyright eq 'domain') {
 4333:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4334: 	    unless (($env{'user.domain'} eq $1) ||
 4335:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4336: 		return '';
 4337:             }
 4338:         }
 4339:         if ($env{'request.role'}=~ /li\.\//) {
 4340:             # Library role, so allow browsing of resources in this domain.
 4341:             return 'F';
 4342:         }
 4343:         if ($copyright eq 'custom') {
 4344: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4345:         }
 4346:     }
 4347:     # Domain coordinator is trying to create a course
 4348:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4349:         # uri is the requested domain in this case.
 4350:         # comparison to 'request.role.domain' shows if the user has selected
 4351:         # a role of dc for the domain in question.
 4352:         return 'F' if ($uri eq $env{'request.role.domain'});
 4353:     }
 4354: 
 4355:     my $thisallowed='';
 4356:     my $statecond=0;
 4357:     my $courseprivid='';
 4358: 
 4359: # Course
 4360: 
 4361:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4362:        $thisallowed.=$1;
 4363:     }
 4364: 
 4365: # Domain
 4366: 
 4367:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4368:        =~/\Q$priv\E\&([^\:]*)/) {
 4369:        $thisallowed.=$1;
 4370:     }
 4371: 
 4372: # Course: uri itself is a course
 4373:     my $courseuri=$uri;
 4374:     $courseuri=~s/\_(\d)/\/$1/;
 4375:     $courseuri=~s/^([^\/])/\/$1/;
 4376: 
 4377:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4378:        =~/\Q$priv\E\&([^\:]*)/) {
 4379:        $thisallowed.=$1;
 4380:     }
 4381: 
 4382: # URI is an uploaded document for this course, default permissions don't matter
 4383: # not allowing 'edit' access (editupload) to uploaded course docs
 4384:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4385: 	$thisallowed='';
 4386:         my ($match)=&is_on_map($uri);
 4387:         if ($match) {
 4388:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4389:                   =~/\Q$priv\E\&([^\:]*)/) {
 4390:                 $thisallowed.=$1;
 4391:             }
 4392:         } else {
 4393:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4394:             if ($refuri) {
 4395:                 if ($refuri =~ m|^/adm/|) {
 4396:                     $thisallowed='F';
 4397:                 } else {
 4398:                     $refuri=&declutter($refuri);
 4399:                     my ($match) = &is_on_map($refuri);
 4400:                     if ($match) {
 4401:                         $thisallowed='F';
 4402:                     }
 4403:                 }
 4404:             }
 4405:         }
 4406:     }
 4407: 
 4408:     if ($priv eq 'bre'
 4409: 	&& $thisallowed ne 'F' 
 4410: 	&& $thisallowed ne '2'
 4411: 	&& &is_portfolio_url($uri)) {
 4412: 	$thisallowed = &portfolio_access($uri);
 4413:     }
 4414:     
 4415: # Full access at system, domain or course-wide level? Exit.
 4416: 
 4417:     if ($thisallowed=~/F/) {
 4418: 	return 'F';
 4419:     }
 4420: 
 4421: # If this is generating or modifying users, exit with special codes
 4422: 
 4423:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4424: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4425: 	    my ($audom,$auname)=split('/',$uri);
 4426: # no author name given, so this just checks on the general right to make a co-author in this domain
 4427: 	    unless ($auname) { return $thisallowed; }
 4428: # an author name is given, so we are about to actually make a co-author for a certain account
 4429: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4430: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4431: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4432: 	}
 4433: 	return $thisallowed;
 4434:     }
 4435: #
 4436: # Gathered so far: system, domain and course wide privileges
 4437: #
 4438: # Course: See if uri or referer is an individual resource that is part of 
 4439: # the course
 4440: 
 4441:     if ($env{'request.course.id'}) {
 4442: 
 4443:        $courseprivid=$env{'request.course.id'};
 4444:        if ($env{'request.course.sec'}) {
 4445:           $courseprivid.='/'.$env{'request.course.sec'};
 4446:        }
 4447:        $courseprivid=~s/\_/\//;
 4448:        my $checkreferer=1;
 4449:        my ($match,$cond)=&is_on_map($uri);
 4450:        if ($match) {
 4451:            $statecond=$cond;
 4452:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4453:                =~/\Q$priv\E\&([^\:]*)/) {
 4454:                $thisallowed.=$1;
 4455:                $checkreferer=0;
 4456:            }
 4457:        }
 4458:        
 4459:        if ($checkreferer) {
 4460: 	  my $refuri=$env{'httpref.'.$orguri};
 4461:             unless ($refuri) {
 4462:                 foreach my $key (keys(%env)) {
 4463: 		    if ($key=~/^httpref\..*\*/) {
 4464: 			my $pattern=$key;
 4465:                         $pattern=~s/^httpref\.\/res\///;
 4466:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4467:                         $pattern=~s/\//\\\//g;
 4468:                         if ($orguri=~/$pattern/) {
 4469: 			    $refuri=$env{$key};
 4470:                         }
 4471:                     }
 4472:                 }
 4473:             }
 4474: 
 4475:          if ($refuri) { 
 4476: 	  $refuri=&declutter($refuri);
 4477:           my ($match,$cond)=&is_on_map($refuri);
 4478:             if ($match) {
 4479:               my $refstatecond=$cond;
 4480:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4481:                   =~/\Q$priv\E\&([^\:]*)/) {
 4482:                   $thisallowed.=$1;
 4483:                   $uri=$refuri;
 4484:                   $statecond=$refstatecond;
 4485:               }
 4486:           }
 4487:         }
 4488:        }
 4489:    }
 4490: 
 4491: #
 4492: # Gathered now: all privileges that could apply, and condition number
 4493: # 
 4494: #
 4495: # Full or no access?
 4496: #
 4497: 
 4498:     if ($thisallowed=~/F/) {
 4499: 	return 'F';
 4500:     }
 4501: 
 4502:     unless ($thisallowed) {
 4503:         return '';
 4504:     }
 4505: 
 4506: # Restrictions exist, deal with them
 4507: #
 4508: #   C:according to course preferences
 4509: #   R:according to resource settings
 4510: #   L:unless locked
 4511: #   X:according to user session state
 4512: #
 4513: 
 4514: # Possibly locked functionality, check all courses
 4515: # Locks might take effect only after 10 minutes cache expiration for other
 4516: # courses, and 2 minutes for current course
 4517: 
 4518:     my $envkey;
 4519:     if ($thisallowed=~/L/) {
 4520:         foreach $envkey (keys %env) {
 4521:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4522:                my $courseid=$2;
 4523:                my $roleid=$1.'.'.$2;
 4524:                $courseid=~s/^\///;
 4525:                my $expiretime=600;
 4526:                if ($env{'request.role'} eq $roleid) {
 4527: 		  $expiretime=120;
 4528:                }
 4529: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4530:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4531:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4532: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4533:                }
 4534:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4535:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4536: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4537:                        &log($env{'user.domain'},$env{'user.name'},
 4538:                             $env{'user.home'},
 4539:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4540:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4541:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4542: 		       return '';
 4543:                    }
 4544:                }
 4545:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4546:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4547: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4548:                        &log($env{'user.domain'},$env{'user.name'},
 4549:                             $env{'user.home'},
 4550:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4551:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4552:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4553: 		       return '';
 4554:                    }
 4555:                }
 4556: 	   }
 4557:        }
 4558:     }
 4559:    
 4560: #
 4561: # Rest of the restrictions depend on selected course
 4562: #
 4563: 
 4564:     unless ($env{'request.course.id'}) {
 4565: 	if ($thisallowed eq 'A') {
 4566: 	    return 'A';
 4567:         } elsif ($thisallowed eq 'B') {
 4568:             return 'B';
 4569: 	} else {
 4570: 	    return '1';
 4571: 	}
 4572:     }
 4573: 
 4574: #
 4575: # Now user is definitely in a course
 4576: #
 4577: 
 4578: 
 4579: # Course preferences
 4580: 
 4581:    if ($thisallowed=~/C/) {
 4582:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4583:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4584:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4585: 	   =~/\Q$rolecode\E/) {
 4586: 	   if ($priv ne 'pch') { 
 4587: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4588: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4589: 			$env{'request.course.id'});
 4590: 	   }
 4591:            return '';
 4592:        }
 4593: 
 4594:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4595: 	   =~/\Q$unamedom\E/) {
 4596: 	   if ($priv ne 'pch') { 
 4597: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4598: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4599: 			$env{'request.course.id'});
 4600: 	   }
 4601:            return '';
 4602:        }
 4603:    }
 4604: 
 4605: # Resource preferences
 4606: 
 4607:    if ($thisallowed=~/R/) {
 4608:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4609:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4610: 	   if ($priv ne 'pch') { 
 4611: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4612: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4613: 	   }
 4614: 	   return '';
 4615:        }
 4616:    }
 4617: 
 4618: # Restricted by state or randomout?
 4619: 
 4620:    if ($thisallowed=~/X/) {
 4621:       if ($env{'acc.randomout'}) {
 4622: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4623:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4624:             return ''; 
 4625:          }
 4626:       }
 4627:       if (&condval($statecond)) {
 4628: 	 return '2';
 4629:       } else {
 4630:          return '';
 4631:       }
 4632:    }
 4633: 
 4634:     if ($thisallowed eq 'A') {
 4635: 	return 'A';
 4636:     } elsif ($thisallowed eq 'B') {
 4637:         return 'B';
 4638:     }
 4639:    return 'F';
 4640: }
 4641: 
 4642: sub split_uri_for_cond {
 4643:     my $uri=&deversion(&declutter(shift));
 4644:     my @uriparts=split(/\//,$uri);
 4645:     my $filename=pop(@uriparts);
 4646:     my $pathname=join('/',@uriparts);
 4647:     return ($pathname,$filename);
 4648: }
 4649: # --------------------------------------------------- Is a resource on the map?
 4650: 
 4651: sub is_on_map {
 4652:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4653:     #Trying to find the conditional for the file
 4654:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4655: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4656:     if ($match) {
 4657: 	return (1,$1);
 4658:     } else {
 4659: 	return (0,0);
 4660:     }
 4661: }
 4662: 
 4663: # --------------------------------------------------------- Get symb from alias
 4664: 
 4665: sub get_symb_from_alias {
 4666:     my $symb=shift;
 4667:     my ($map,$resid,$url)=&decode_symb($symb);
 4668: # Already is a symb
 4669:     if ($url) { return $symb; }
 4670: # Must be an alias
 4671:     my $aliassymb='';
 4672:     my %bighash;
 4673:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4674:                             &GDBM_READER(),0640)) {
 4675:         my $rid=$bighash{'mapalias_'.$symb};
 4676: 	if ($rid) {
 4677: 	    my ($mapid,$resid)=split(/\./,$rid);
 4678: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4679: 				    $resid,$bighash{'src_'.$rid});
 4680: 	}
 4681:         untie %bighash;
 4682:     }
 4683:     return $aliassymb;
 4684: }
 4685: 
 4686: # ----------------------------------------------------------------- Define Role
 4687: 
 4688: sub definerole {
 4689:   if (allowed('mcr','/')) {
 4690:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4691:     foreach my $role (split(':',$sysrole)) {
 4692: 	my ($crole,$cqual)=split(/\&/,$role);
 4693:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4694:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4695: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4696:                return "refused:s:$crole&$cqual"; 
 4697:             }
 4698:         }
 4699:     }
 4700:     foreach my $role (split(':',$domrole)) {
 4701: 	my ($crole,$cqual)=split(/\&/,$role);
 4702:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4703:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4704: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4705:                return "refused:d:$crole&$cqual"; 
 4706:             }
 4707:         }
 4708:     }
 4709:     foreach my $role (split(':',$courole)) {
 4710: 	my ($crole,$cqual)=split(/\&/,$role);
 4711:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4712:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4713: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4714:                return "refused:c:$crole&$cqual"; 
 4715:             }
 4716:         }
 4717:     }
 4718:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4719:                 "$env{'user.domain'}:$env{'user.name'}:".
 4720: 	        "rolesdef_$rolename=".
 4721:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4722:     return reply($command,$env{'user.home'});
 4723:   } else {
 4724:     return 'refused';
 4725:   }
 4726: }
 4727: 
 4728: # ---------------- Make a metadata query against the network of library servers
 4729: 
 4730: sub metadata_query {
 4731:     my ($query,$custom,$customshow,$server_array)=@_;
 4732:     my %rhash;
 4733:     my %libserv = &all_library();
 4734:     my @server_list = (defined($server_array) ? @$server_array
 4735:                                               : keys(%libserv) );
 4736:     for my $server (@server_list) {
 4737: 	unless ($custom or $customshow) {
 4738: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4739: 	    $rhash{$server}=$reply;
 4740: 	}
 4741: 	else {
 4742: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4743: 			     &escape($custom).':'.&escape($customshow),
 4744: 			     $server);
 4745: 	    $rhash{$server}=$reply;
 4746: 	}
 4747:     }
 4748:     return \%rhash;
 4749: }
 4750: 
 4751: # ----------------------------------------- Send log queries and wait for reply
 4752: 
 4753: sub log_query {
 4754:     my ($uname,$udom,$query,%filters)=@_;
 4755:     my $uhome=&homeserver($uname,$udom);
 4756:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4757:     my $uhost=&hostname($uhome);
 4758:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4759:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4760:                        $uhome);
 4761:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4762:     return get_query_reply($queryid);
 4763: }
 4764: 
 4765: # -------------------------- Update MySQL table for portfolio file
 4766: 
 4767: sub update_portfolio_table {
 4768:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4769:     my $homeserver = &homeserver($uname,$udom);
 4770:     my $queryid=
 4771:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4772:                ':'.&escape($file_name).':'.$action,$homeserver);
 4773:     my $reply = &get_query_reply($queryid);
 4774:     return $reply;
 4775: }
 4776: 
 4777: # -------------------------- Update MySQL allusers table
 4778: 
 4779: sub update_allusers_table {
 4780:     my ($uname,$udom,$names) = @_;
 4781:     my $homeserver = &homeserver($uname,$udom);
 4782:     my $queryid=
 4783:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 4784:                'lastname='.&escape($names->{'lastname'}).'%%'.
 4785:                'firstname='.&escape($names->{'firstname'}).'%%'.
 4786:                'middlename='.&escape($names->{'middlename'}).'%%'.
 4787:                'generation='.&escape($names->{'generation'}).'%%'.
 4788:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 4789:                'id='.&escape($names->{'id'}),$homeserver);
 4790:     my $reply = &get_query_reply($queryid);
 4791:     return $reply;
 4792: }
 4793: 
 4794: # ------- Request retrieval of institutional classlists for course(s)
 4795: 
 4796: sub fetch_enrollment_query {
 4797:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4798:     my $homeserver;
 4799:     my $maxtries = 1;
 4800:     if ($context eq 'automated') {
 4801:         $homeserver = $perlvar{'lonHostID'};
 4802:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4803:     } else {
 4804:         $homeserver = &homeserver($cnum,$dom);
 4805:     }
 4806:     my $host=&hostname($homeserver);
 4807:     my $cmd = '';
 4808:     foreach my $affiliate (keys %{$affiliatesref}) {
 4809:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4810:     }
 4811:     $cmd =~ s/%%$//;
 4812:     $cmd = &escape($cmd);
 4813:     my $query = 'fetchenrollment';
 4814:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4815:     unless ($queryid=~/^\Q$host\E\_/) { 
 4816:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4817:         return 'error: '.$queryid;
 4818:     }
 4819:     my $reply = &get_query_reply($queryid);
 4820:     my $tries = 1;
 4821:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4822:         $reply = &get_query_reply($queryid);
 4823:         $tries ++;
 4824:     }
 4825:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4826:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4827:     } else {
 4828:         my @responses = split(/:/,$reply);
 4829:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4830:             foreach my $line (@responses) {
 4831:                 my ($key,$value) = split(/=/,$line,2);
 4832:                 $$replyref{$key} = $value;
 4833:             }
 4834:         } else {
 4835:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4836:             foreach my $line (@responses) {
 4837:                 my ($key,$value) = split(/=/,$line);
 4838:                 $$replyref{$key} = $value;
 4839:                 if ($value > 0) {
 4840:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4841:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4842:                         my $destname = $pathname.'/'.$filename;
 4843:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4844:                         if ($xml_classlist =~ /^error/) {
 4845:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4846:                         } else {
 4847:                             if ( open(FILE,">$destname") ) {
 4848:                                 print FILE &unescape($xml_classlist);
 4849:                                 close(FILE);
 4850:                             } else {
 4851:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4852:                             }
 4853:                         }
 4854:                     }
 4855:                 }
 4856:             }
 4857:         }
 4858:         return 'ok';
 4859:     }
 4860:     return 'error';
 4861: }
 4862: 
 4863: sub get_query_reply {
 4864:     my $queryid=shift;
 4865:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4866:     my $reply='';
 4867:     for (1..100) {
 4868: 	sleep 2;
 4869:         if (-e $replyfile.'.end') {
 4870: 	    if (open(my $fh,$replyfile)) {
 4871: 		$reply = join('',<$fh>);
 4872: 		close($fh);
 4873: 	   } else { return 'error: reply_file_error'; }
 4874:            return &unescape($reply);
 4875: 	}
 4876:     }
 4877:     return 'timeout:'.$queryid;
 4878: }
 4879: 
 4880: sub courselog_query {
 4881: #
 4882: # possible filters:
 4883: # url: url or symb
 4884: # username
 4885: # domain
 4886: # action: view, submit, grade
 4887: # start: timestamp
 4888: # end: timestamp
 4889: #
 4890:     my (%filters)=@_;
 4891:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4892:     if ($filters{'url'}) {
 4893: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4894:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4895:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4896:     }
 4897:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4898:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4899:     return &log_query($cname,$cdom,'courselog',%filters);
 4900: }
 4901: 
 4902: sub userlog_query {
 4903: #
 4904: # possible filters:
 4905: # action: log check role
 4906: # start: timestamp
 4907: # end: timestamp
 4908: #
 4909:     my ($uname,$udom,%filters)=@_;
 4910:     return &log_query($uname,$udom,'userlog',%filters);
 4911: }
 4912: 
 4913: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4914: 
 4915: sub auto_run {
 4916:     my ($cnum,$cdom) = @_;
 4917:     my $response = 0;
 4918:     my $settings;
 4919:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 4920:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4921:         $settings = $domconfig{'autoenroll'};
 4922:         if ($settings->{'run'} eq '1') {
 4923:             $response = 1;
 4924:         }
 4925:     } else {
 4926:         my $homeserver;
 4927:         if (&is_course($cdom,$cnum)) {
 4928:             $homeserver = &homeserver($cnum,$cdom);
 4929:         } else {
 4930:             $homeserver = &domain($cdom,'primary');
 4931:         }
 4932:         if ($homeserver ne 'no_host') {
 4933:             $response = &reply('autorun:'.$cdom,$homeserver);
 4934:         }
 4935:     }
 4936:     return $response;
 4937: }
 4938: 
 4939: sub auto_get_sections {
 4940:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4941:     my $homeserver = &homeserver($cnum,$cdom);
 4942:     my @secs = ();
 4943:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4944:     unless ($response eq 'refused') {
 4945:         @secs = split(/:/,$response);
 4946:     }
 4947:     return @secs;
 4948: }
 4949: 
 4950: sub auto_new_course {
 4951:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4952:     my $homeserver = &homeserver($cnum,$cdom);
 4953:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4954:     return $response;
 4955: }
 4956: 
 4957: sub auto_validate_courseID {
 4958:     my ($cnum,$cdom,$inst_course_id) = @_;
 4959:     my $homeserver = &homeserver($cnum,$cdom);
 4960:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4961:     return $response;
 4962: }
 4963: 
 4964: sub auto_create_password {
 4965:     my ($cnum,$cdom,$authparam,$udom) = @_;
 4966:     my ($homeserver,$response);
 4967:     my $create_passwd = 0;
 4968:     my $authchk = '';
 4969:     if ($udom =~ /^$match_domain$/) {
 4970:         $homeserver = &domain($udom,'primary');
 4971:     }
 4972:     if ($homeserver eq '') {
 4973:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 4974:             $homeserver = &homeserver($cnum,$cdom);
 4975:         }
 4976:     }
 4977:     if ($homeserver eq '') {
 4978:         $authchk = 'nodomain';
 4979:     } else {
 4980:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4981:         if ($response eq 'refused') {
 4982:             $authchk = 'refused';
 4983:         } else {
 4984:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 4985:         }
 4986:     }
 4987:     return ($authparam,$create_passwd,$authchk);
 4988: }
 4989: 
 4990: sub auto_photo_permission {
 4991:     my ($cnum,$cdom,$students) = @_;
 4992:     my $homeserver = &homeserver($cnum,$cdom);
 4993:     my ($outcome,$perm_reqd,$conditions) = 
 4994: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4995:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4996: 	return (undef,undef);
 4997:     }
 4998:     return ($outcome,$perm_reqd,$conditions);
 4999: }
 5000: 
 5001: sub auto_checkphotos {
 5002:     my ($uname,$udom,$pid) = @_;
 5003:     my $homeserver = &homeserver($uname,$udom);
 5004:     my ($result,$resulttype);
 5005:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5006: 				   &escape($uname).':'.&escape($pid),
 5007: 				   $homeserver));
 5008:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5009: 	return (undef,undef);
 5010:     }
 5011:     if ($outcome) {
 5012:         ($result,$resulttype) = split(/:/,$outcome);
 5013:     } 
 5014:     return ($result,$resulttype);
 5015: }
 5016: 
 5017: sub auto_photochoice {
 5018:     my ($cnum,$cdom) = @_;
 5019:     my $homeserver = &homeserver($cnum,$cdom);
 5020:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5021: 						       &escape($cdom),
 5022: 						       $homeserver)));
 5023:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5024: 	return (undef,undef);
 5025:     }
 5026:     return ($update,$comment);
 5027: }
 5028: 
 5029: sub auto_photoupdate {
 5030:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5031:     my $homeserver = &homeserver($cnum,$dom);
 5032:     my $host=&hostname($homeserver);
 5033:     my $cmd = '';
 5034:     my $maxtries = 1;
 5035:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5036:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5037:     }
 5038:     $cmd =~ s/%%$//;
 5039:     $cmd = &escape($cmd);
 5040:     my $query = 'institutionalphotos';
 5041:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5042:     unless ($queryid=~/^\Q$host\E\_/) {
 5043:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5044:         return 'error: '.$queryid;
 5045:     }
 5046:     my $reply = &get_query_reply($queryid);
 5047:     my $tries = 1;
 5048:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5049:         $reply = &get_query_reply($queryid);
 5050:         $tries ++;
 5051:     }
 5052:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5053:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5054:     } else {
 5055:         my @responses = split(/:/,$reply);
 5056:         my $outcome = shift(@responses); 
 5057:         foreach my $item (@responses) {
 5058:             my ($key,$value) = split(/=/,$item);
 5059:             $$photo{$key} = $value;
 5060:         }
 5061:         return $outcome;
 5062:     }
 5063:     return 'error';
 5064: }
 5065: 
 5066: sub auto_instcode_format {
 5067:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5068: 	$cat_order) = @_;
 5069:     my $courses = '';
 5070:     my @homeservers;
 5071:     if ($caller eq 'global') {
 5072: 	my %servers = &get_servers($codedom,'library');
 5073: 	foreach my $tryserver (keys(%servers)) {
 5074: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5075: 		push(@homeservers,$tryserver);
 5076: 	    }
 5077:         }
 5078:     } else {
 5079:         push(@homeservers,&homeserver($caller,$codedom));
 5080:     }
 5081:     foreach my $code (keys(%{$instcodes})) {
 5082:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5083:     }
 5084:     chop($courses);
 5085:     my $ok_response = 0;
 5086:     my $response;
 5087:     while (@homeservers > 0 && $ok_response == 0) {
 5088:         my $server = shift(@homeservers); 
 5089:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5090:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5091:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5092: 		split(/:/,$response);
 5093:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5094:             push(@{$codetitles},&str2array($codetitles_str));
 5095:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5096:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5097:             $ok_response = 1;
 5098:         }
 5099:     }
 5100:     if ($ok_response) {
 5101:         return 'ok';
 5102:     } else {
 5103:         return $response;
 5104:     }
 5105: }
 5106: 
 5107: sub auto_instcode_defaults {
 5108:     my ($domain,$returnhash,$code_order) = @_;
 5109:     my @homeservers;
 5110: 
 5111:     my %servers = &get_servers($domain,'library');
 5112:     foreach my $tryserver (keys(%servers)) {
 5113: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5114: 	    push(@homeservers,$tryserver);
 5115: 	}
 5116:     }
 5117: 
 5118:     my $response;
 5119:     foreach my $server (@homeservers) {
 5120:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5121:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5122: 	
 5123: 	foreach my $pair (split(/\&/,$response)) {
 5124: 	    my ($name,$value)=split(/\=/,$pair);
 5125: 	    if ($name eq 'code_order') {
 5126: 		@{$code_order} = split(/\&/,&unescape($value));
 5127: 	    } else {
 5128: 		$returnhash->{&unescape($name)}=&unescape($value);
 5129: 	    }
 5130: 	}
 5131: 	return 'ok';
 5132:     }
 5133: 
 5134:     return $response;
 5135: } 
 5136: 
 5137: sub auto_validate_class_sec {
 5138:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5139:     my $homeserver = &homeserver($cnum,$cdom);
 5140:     my $ownerlist;
 5141:     if (ref($owners) eq 'ARRAY') {
 5142:         $ownerlist = join(',',@{$owners});
 5143:     } else {
 5144:         $ownerlist = $owners;
 5145:     }
 5146:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5147:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5148:     return $response;
 5149: }
 5150: 
 5151: # ------------------------------------------------------- Course Group routines
 5152: 
 5153: sub get_coursegroups {
 5154:     my ($cdom,$cnum,$group,$namespace) = @_;
 5155:     return(&dump($namespace,$cdom,$cnum,$group));
 5156: }
 5157: 
 5158: sub modify_coursegroup {
 5159:     my ($cdom,$cnum,$groupsettings) = @_;
 5160:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5161: }
 5162: 
 5163: sub toggle_coursegroup_status {
 5164:     my ($cdom,$cnum,$group,$action) = @_;
 5165:     my ($from_namespace,$to_namespace);
 5166:     if ($action eq 'delete') {
 5167:         $from_namespace = 'coursegroups';
 5168:         $to_namespace = 'deleted_groups';
 5169:     } else {
 5170:         $from_namespace = 'deleted_groups';
 5171:         $to_namespace = 'coursegroups';
 5172:     }
 5173:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5174:     if (my $tmp = &error(%curr_group)) {
 5175:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5176:         return ('read error',$tmp);
 5177:     } else {
 5178:         my %savedsettings = %curr_group; 
 5179:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5180:         my $deloutcome;
 5181:         if ($result eq 'ok') {
 5182:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5183:         } else {
 5184:             return ('write error',$result);
 5185:         }
 5186:         if ($deloutcome eq 'ok') {
 5187:             return 'ok';
 5188:         } else {
 5189:             return ('delete error',$deloutcome);
 5190:         }
 5191:     }
 5192: }
 5193: 
 5194: sub modify_group_roles {
 5195:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 5196:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5197:     my $role = 'gr/'.&escape($userprivs);
 5198:     my ($uname,$udom) = split(/:/,$user);
 5199:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 5200:     if ($result eq 'ok') {
 5201:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5202:     }
 5203:     return $result;
 5204: }
 5205: 
 5206: sub modify_coursegroup_membership {
 5207:     my ($cdom,$cnum,$membership) = @_;
 5208:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5209:     return $result;
 5210: }
 5211: 
 5212: sub get_active_groups {
 5213:     my ($udom,$uname,$cdom,$cnum) = @_;
 5214:     my $now = time;
 5215:     my %groups = ();
 5216:     foreach my $key (keys(%env)) {
 5217:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5218:             my ($start,$end) = split(/\./,$env{$key});
 5219:             if (($end!=0) && ($end<$now)) { next; }
 5220:             if (($start!=0) && ($start>$now)) { next; }
 5221:             if ($1 eq $cdom && $2 eq $cnum) {
 5222:                 $groups{$3} = $env{$key} ;
 5223:             }
 5224:         }
 5225:     }
 5226:     return %groups;
 5227: }
 5228: 
 5229: sub get_group_membership {
 5230:     my ($cdom,$cnum,$group) = @_;
 5231:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5232: }
 5233: 
 5234: sub get_users_groups {
 5235:     my ($udom,$uname,$courseid) = @_;
 5236:     my @usersgroups;
 5237:     my $cachetime=1800;
 5238: 
 5239:     my $hashid="$udom:$uname:$courseid";
 5240:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5241:     if (defined($cached)) {
 5242:         @usersgroups = split(/:/,$grouplist);
 5243:     } else {  
 5244:         $grouplist = '';
 5245:         my $courseurl = &courseid_to_courseurl($courseid);
 5246:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5247:         my $access_end = $env{'course.'.$courseid.
 5248:                               '.default_enrollment_end_date'};
 5249:         my $now = time;
 5250:         foreach my $key (keys(%roleshash)) {
 5251:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5252:                 my $group = $1;
 5253:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5254:                     my $start = $2;
 5255:                     my $end = $1;
 5256:                     if ($start == -1) { next; } # deleted from group
 5257:                     if (($start!=0) && ($start>$now)) { next; }
 5258:                     if (($end!=0) && ($end<$now)) {
 5259:                         if ($access_end && $access_end < $now) {
 5260:                             if ($access_end - $end < 86400) {
 5261:                                 push(@usersgroups,$group);
 5262:                             }
 5263:                         }
 5264:                         next;
 5265:                     }
 5266:                     push(@usersgroups,$group);
 5267:                 }
 5268:             }
 5269:         }
 5270:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5271:         $grouplist = join(':',@usersgroups);
 5272:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5273:     }
 5274:     return @usersgroups;
 5275: }
 5276: 
 5277: sub devalidate_getgroups_cache {
 5278:     my ($udom,$uname,$cdom,$cnum)=@_;
 5279:     my $courseid = $cdom.'_'.$cnum;
 5280: 
 5281:     my $hashid="$udom:$uname:$courseid";
 5282:     &devalidate_cache_new('getgroups',$hashid);
 5283: }
 5284: 
 5285: # ------------------------------------------------------------------ Plain Text
 5286: 
 5287: sub plaintext {
 5288:     my ($short,$type,$cid) = @_;
 5289:     if ($short =~ /^cr/) {
 5290: 	return (split('/',$short))[-1];
 5291:     }
 5292:     if (!defined($cid)) {
 5293:         $cid = $env{'request.course.id'};
 5294:     }
 5295:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5296:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5297:                                           '.plaintext'});
 5298:     }
 5299:     my %rolenames = (
 5300:                       Course => 'std',
 5301:                       Group => 'alt1',
 5302:                     );
 5303:     if (defined($type) && 
 5304:          defined($rolenames{$type}) && 
 5305:          defined($prp{$short}{$rolenames{$type}})) {
 5306:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5307:     } else {
 5308:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5309:     }
 5310: }
 5311: 
 5312: # ----------------------------------------------------------------- Assign Role
 5313: 
 5314: sub assignrole {
 5315:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 5316:     my $mrole;
 5317:     if ($role =~ /^cr\//) {
 5318:         my $cwosec=$url;
 5319:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5320: 	unless (&allowed('ccr',$cwosec)) {
 5321:            &logthis('Refused custom assignrole: '.
 5322:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5323: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5324:            return 'refused'; 
 5325:         }
 5326:         $mrole='cr';
 5327:     } elsif ($role =~ /^gr\//) {
 5328:         my $cwogrp=$url;
 5329:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5330:         unless (&allowed('mdg',$cwogrp)) {
 5331:             &logthis('Refused group assignrole: '.
 5332:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5333:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5334:             return 'refused';
 5335:         }
 5336:         $mrole='gr';
 5337:     } else {
 5338:         my $cwosec=$url;
 5339:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5340:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5341:             my $refused;
 5342:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5343:                 if (!(&allowed('c'.$role,$url))) {
 5344:                     $refused = 1;
 5345:                 }
 5346:             } else {
 5347:                 $refused = 1;
 5348:             }
 5349:             if ($refused) { 
 5350:                 &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5351:                          ' '.$role.' '.$end.' '.$start.' by '.
 5352: 	  	         $env{'user.name'}.' at '.$env{'user.domain'});
 5353:                 return 'refused';
 5354:             }
 5355:         }
 5356:         $mrole=$role;
 5357:     }
 5358:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5359:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5360:     if ($end) { $command.='_'.$end; }
 5361:     if ($start) {
 5362: 	if ($end) { 
 5363:            $command.='_'.$start; 
 5364:         } else {
 5365:            $command.='_0_'.$start;
 5366:         }
 5367:     }
 5368:     my $origstart = $start;
 5369:     my $origend = $end;
 5370: # actually delete
 5371:     if ($deleteflag) {
 5372: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5373: # modify command to delete the role
 5374:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5375:                 "$udom:$uname:$url".'_'."$mrole";
 5376: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5377: # set start and finish to negative values for userrolelog
 5378:            $start=-1;
 5379:            $end=-1;
 5380:         }
 5381:     }
 5382: # send command
 5383:     my $answer=&reply($command,&homeserver($uname,$udom));
 5384: # log new user role if status is ok
 5385:     if ($answer eq 'ok') {
 5386: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5387: # for course roles, perform group memberships changes triggered by role change.
 5388:         unless ($role =~ /^gr/) {
 5389:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5390:                                              $origstart);
 5391:         }
 5392:     }
 5393:     return $answer;
 5394: }
 5395: 
 5396: # -------------------------------------------------- Modify user authentication
 5397: # Overrides without validation
 5398: 
 5399: sub modifyuserauth {
 5400:     my ($udom,$uname,$umode,$upass)=@_;
 5401:     my $uhome=&homeserver($uname,$udom);
 5402:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5403:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5404:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5405:              ' in domain '.$env{'request.role.domain'});  
 5406:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5407: 		     &escape($upass),$uhome);
 5408:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5409:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5410:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5411:     &log($udom,,$uname,$uhome,
 5412:         'Authentication changed by '.$env{'user.domain'}.', '.
 5413:                                      $env{'user.name'}.', '.$umode.
 5414:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5415:     unless ($reply eq 'ok') {
 5416:         &logthis('Authentication mode error: '.$reply);
 5417: 	return 'error: '.$reply;
 5418:     }   
 5419:     return 'ok';
 5420: }
 5421: 
 5422: # --------------------------------------------------------------- Modify a user
 5423: 
 5424: sub modifyuser {
 5425:     my ($udom,    $uname, $uid,
 5426:         $umode,   $upass, $first,
 5427:         $middle,  $last,  $gene,
 5428:         $forceid, $desiredhome, $email)=@_;
 5429:     $udom= &LONCAPA::clean_domain($udom);
 5430:     $uname=&LONCAPA::clean_username($uname);
 5431:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5432:              $umode.', '.$first.', '.$middle.', '.
 5433: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5434:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5435:                                      ' desiredhome not specified'). 
 5436:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5437:              ' in domain '.$env{'request.role.domain'});
 5438:     my $uhome=&homeserver($uname,$udom,'true');
 5439: # ----------------------------------------------------------------- Create User
 5440:     if (($uhome eq 'no_host') && 
 5441: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5442:         my $unhome='';
 5443:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5444:             $unhome = $desiredhome;
 5445: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5446: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5447:         } else { # load balancing routine for determining $unhome
 5448:             my $loadm=10000000;
 5449: 	    my %servers = &get_servers($udom,'library');
 5450: 	    foreach my $tryserver (keys(%servers)) {
 5451: 		my $answer=reply('load',$tryserver);
 5452: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5453: 		    $loadm=$answer;
 5454: 		    $unhome=$tryserver;
 5455: 		}
 5456: 	    }
 5457:         }
 5458:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5459: 	    return 'error: unable to find a home server for '.$uname.
 5460:                    ' in domain '.$udom;
 5461:         }
 5462:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5463:                          &escape($upass),$unhome);
 5464: 	unless ($reply eq 'ok') {
 5465:             return 'error: '.$reply;
 5466:         }   
 5467:         $uhome=&homeserver($uname,$udom,'true');
 5468:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5469: 	    return 'error: unable verify users home machine.';
 5470:         }
 5471:     }   # End of creation of new user
 5472: # ---------------------------------------------------------------------- Add ID
 5473:     if ($uid) {
 5474:        $uid=~tr/A-Z/a-z/;
 5475:        my %uidhash=&idrget($udom,$uname);
 5476:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5477:          && (!$forceid)) {
 5478: 	  unless ($uid eq $uidhash{$uname}) {
 5479: 	      return 'error: user id "'.$uid.'" does not match '.
 5480:                   'current user id "'.$uidhash{$uname}.'".';
 5481:           }
 5482:        } else {
 5483: 	  &idput($udom,($uname => $uid));
 5484:        }
 5485:     }
 5486: # -------------------------------------------------------------- Add names, etc
 5487:     my @tmp=&get('environment',
 5488: 		   ['firstname','middlename','lastname','generation','id',
 5489:                     'permanentemail'],
 5490: 		   $udom,$uname);
 5491:     my %names;
 5492:     if ($tmp[0] =~ m/^error:.*/) { 
 5493:         %names=(); 
 5494:     } else {
 5495:         %names = @tmp;
 5496:     }
 5497: #
 5498: # Make sure to not trash student environment if instructor does not bother
 5499: # to supply name and email information
 5500: #
 5501:     if ($first)  { $names{'firstname'}  = $first; }
 5502:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5503:     if ($last)   { $names{'lastname'}   = $last; }
 5504:     if (defined($gene))   { $names{'generation'} = $gene; }
 5505:     if ($email) {
 5506:        $email=~s/[^\w\@\.\-\,]//gs;
 5507:        if ($email=~/\@/) { $names{'notification'} = $email;
 5508: 			   $names{'critnotification'} = $email;
 5509: 			   $names{'permanentemail'} = $email; }
 5510:     }
 5511:     if ($uid) { $names{'id'}  = $uid; }
 5512:     my $reply = &put('environment', \%names, $udom,$uname);
 5513:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5514:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5515:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5516:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5517:              $umode.', '.$first.', '.$middle.', '.
 5518: 	     $last.', '.$gene.' by '.
 5519:              $env{'user.name'}.' at '.$env{'user.domain'});
 5520:     return 'ok';
 5521: }
 5522: 
 5523: # -------------------------------------------------------------- Modify student
 5524: 
 5525: sub modifystudent {
 5526:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5527:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5528:     if (!$cid) {
 5529: 	unless ($cid=$env{'request.course.id'}) {
 5530: 	    return 'not_in_class';
 5531: 	}
 5532:     }
 5533: # --------------------------------------------------------------- Make the user
 5534:     my $reply=&modifyuser
 5535: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5536:          $desiredhome,$email);
 5537:     unless ($reply eq 'ok') { return $reply; }
 5538:     # This will cause &modify_student_enrollment to get the uid from the
 5539:     # students environment
 5540:     $uid = undef if (!$forceid);
 5541:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5542: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5543:     return $reply;
 5544: }
 5545: 
 5546: sub modify_student_enrollment {
 5547:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 5548:     my ($cdom,$cnum,$chome);
 5549:     if (!$cid) {
 5550: 	unless ($cid=$env{'request.course.id'}) {
 5551: 	    return 'not_in_class';
 5552: 	}
 5553: 	$cdom=$env{'course.'.$cid.'.domain'};
 5554: 	$cnum=$env{'course.'.$cid.'.num'};
 5555:     } else {
 5556: 	($cdom,$cnum)=split(/_/,$cid);
 5557:     }
 5558:     $chome=$env{'course.'.$cid.'.home'};
 5559:     if (!$chome) {
 5560: 	$chome=&homeserver($cnum,$cdom);
 5561:     }
 5562:     if (!$chome) { return 'unknown_course'; }
 5563:     # Make sure the user exists
 5564:     my $uhome=&homeserver($uname,$udom);
 5565:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5566: 	return 'error: no such user';
 5567:     }
 5568:     # Get student data if we were not given enough information
 5569:     if (!defined($first)  || $first  eq '' || 
 5570:         !defined($last)   || $last   eq '' || 
 5571:         !defined($uid)    || $uid    eq '' || 
 5572:         !defined($middle) || $middle eq '' || 
 5573:         !defined($gene)   || $gene   eq '') {
 5574:         # They did not supply us with enough data to enroll the student, so
 5575:         # we need to pick up more information.
 5576:         my %tmp = &get('environment',
 5577:                        ['firstname','middlename','lastname', 'generation','id']
 5578:                        ,$udom,$uname);
 5579: 
 5580:         #foreach my $key (keys(%tmp)) {
 5581:         #    &logthis("key $key = ".$tmp{$key});
 5582:         #}
 5583:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5584:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5585:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5586:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5587:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5588:     }
 5589:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5590:     my $reply=cput('classlist',
 5591: 		   {"$uname:$udom" => 
 5592: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5593: 		   $cdom,$cnum);
 5594:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5595: 	return 'error: '.$reply;
 5596:     } else {
 5597: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5598:     }
 5599:     # Add student role to user
 5600:     my $uurl='/'.$cid;
 5601:     $uurl=~s/\_/\//g;
 5602:     if ($usec) {
 5603: 	$uurl.='/'.$usec;
 5604:     }
 5605:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5606: }
 5607: 
 5608: sub format_name {
 5609:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5610:     my $name;
 5611:     if ($first ne 'lastname') {
 5612: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5613:     } else {
 5614: 	if ($lastname=~/\S/) {
 5615: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5616: 	    $name=~s/\s+,/,/;
 5617: 	} else {
 5618: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5619: 	}
 5620:     }
 5621:     $name=~s/^\s+//;
 5622:     $name=~s/\s+$//;
 5623:     $name=~s/\s+/ /g;
 5624:     return $name;
 5625: }
 5626: 
 5627: # ------------------------------------------------- Write to course preferences
 5628: 
 5629: sub writecoursepref {
 5630:     my ($courseid,%prefs)=@_;
 5631:     $courseid=~s/^\///;
 5632:     $courseid=~s/\_/\//g;
 5633:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5634:     my $chome=homeserver($cnum,$cdomain);
 5635:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5636: 	return 'error: no such course';
 5637:     }
 5638:     my $cstring='';
 5639:     foreach my $pref (keys(%prefs)) {
 5640: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5641:     }
 5642:     $cstring=~s/\&$//;
 5643:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5644: }
 5645: 
 5646: # ---------------------------------------------------------- Make/modify course
 5647: 
 5648: sub createcourse {
 5649:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5650:         $course_owner,$crstype)=@_;
 5651:     $url=&declutter($url);
 5652:     my $cid='';
 5653:     unless (&allowed('ccc',$udom)) {
 5654:         return 'refused';
 5655:     }
 5656: # ------------------------------------------------------------------- Create ID
 5657:    my $uname=int(1+rand(9)).
 5658:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5659:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5660:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5661: # ----------------------------------------------- Make sure that does not exist
 5662:    my $uhome=&homeserver($uname,$udom,'true');
 5663:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5664:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5665:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5666:        $uhome=&homeserver($uname,$udom,'true');       
 5667:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5668:            return 'error: unable to generate unique course-ID';
 5669:        } 
 5670:    }
 5671: # ------------------------------------------------ Check supplied server name
 5672:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5673:     if (! &is_library($course_server)) {
 5674:         return 'error:bad server name '.$course_server;
 5675:     }
 5676: # ------------------------------------------------------------- Make the course
 5677:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5678:                       $course_server);
 5679:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5680:     $uhome=&homeserver($uname,$udom,'true');
 5681:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5682: 	return 'error: no such course';
 5683:     }
 5684: # ----------------------------------------------------------------- Course made
 5685: # log existence
 5686:     my $newcourse = {
 5687:                     $udom.'_'.$uname => {
 5688:                                      description => $description,
 5689:                                      inst_code   => $inst_code,
 5690:                                      owner       => $course_owner,
 5691:                                      type        => $crstype,
 5692:                                                 },
 5693:                     };
 5694:     &courseidput($udom,$newcourse,$uhome,'notime');
 5695: # set toplevel url
 5696:     my $topurl=$url;
 5697:     unless ($nonstandard) {
 5698: # ------------------------------------------ For standard courses, make top url
 5699:         my $mapurl=&clutter($url);
 5700:         if ($mapurl eq '/res/') { $mapurl=''; }
 5701:         $env{'form.initmap'}=(<<ENDINITMAP);
 5702: <map>
 5703: <resource id="1" type="start"></resource>
 5704: <resource id="2" src="$mapurl"></resource>
 5705: <resource id="3" type="finish"></resource>
 5706: <link index="1" from="1" to="2"></link>
 5707: <link index="2" from="2" to="3"></link>
 5708: </map>
 5709: ENDINITMAP
 5710:         $topurl=&declutter(
 5711:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5712:                           );
 5713:     }
 5714: # ----------------------------------------------------------- Write preferences
 5715:     &writecoursepref($udom.'_'.$uname,
 5716:                      ('description' => $description,
 5717:                       'url'         => $topurl));
 5718:     return '/'.$udom.'/'.$uname;
 5719: }
 5720: 
 5721: sub is_course {
 5722:     my ($cdom,$cnum) = @_;
 5723:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5724: 				undef,'.',undef,1);
 5725:     if (exists($courses{$cdom.'_'.$cnum})) {
 5726:         return 1;
 5727:     }
 5728:     return 0;
 5729: }
 5730: 
 5731: # ---------------------------------------------------------- Assign Custom Role
 5732: 
 5733: sub assigncustomrole {
 5734:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5735:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5736:                        $end,$start,$deleteflag);
 5737: }
 5738: 
 5739: # ----------------------------------------------------------------- Revoke Role
 5740: 
 5741: sub revokerole {
 5742:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5743:     my $now=time;
 5744:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5745: }
 5746: 
 5747: # ---------------------------------------------------------- Revoke Custom Role
 5748: 
 5749: sub revokecustomrole {
 5750:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5751:     my $now=time;
 5752:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5753:            $deleteflag);
 5754: }
 5755: 
 5756: # ------------------------------------------------------------ Disk usage
 5757: sub diskusage {
 5758:     my ($udom,$uname,$directoryRoot)=@_;
 5759:     $directoryRoot =~ s/\/$//;
 5760:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5761:     return $listing;
 5762: }
 5763: 
 5764: sub is_locked {
 5765:     my ($file_name, $domain, $user) = @_;
 5766:     my @check;
 5767:     my $is_locked;
 5768:     push @check, $file_name;
 5769:     my %locked = &get('file_permissions',\@check,
 5770: 		      $env{'user.domain'},$env{'user.name'});
 5771:     my ($tmp)=keys(%locked);
 5772:     if ($tmp=~/^error:/) { undef(%locked); }
 5773:     
 5774:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5775:         $is_locked = 'false';
 5776:         foreach my $entry (@{$locked{$file_name}}) {
 5777:            if (ref($entry) eq 'ARRAY') { 
 5778:                $is_locked = 'true';
 5779:                last;
 5780:            }
 5781:        }
 5782:     } else {
 5783:         $is_locked = 'false';
 5784:     }
 5785: }
 5786: 
 5787: sub declutter_portfile {
 5788:     my ($file) = @_;
 5789:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5790:     return $file;
 5791: }
 5792: 
 5793: # ------------------------------------------------------------- Mark as Read Only
 5794: 
 5795: sub mark_as_readonly {
 5796:     my ($domain,$user,$files,$what) = @_;
 5797:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5798:     my ($tmp)=keys(%current_permissions);
 5799:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5800:     foreach my $file (@{$files}) {
 5801: 	$file = &declutter_portfile($file);
 5802:         push(@{$current_permissions{$file}},$what);
 5803:     }
 5804:     &put('file_permissions',\%current_permissions,$domain,$user);
 5805:     return;
 5806: }
 5807: 
 5808: # ------------------------------------------------------------Save Selected Files
 5809: 
 5810: sub save_selected_files {
 5811:     my ($user, $path, @files) = @_;
 5812:     my $filename = $user."savedfiles";
 5813:     my @other_files = &files_not_in_path($user, $path);
 5814:     open (OUT, '>'.$tmpdir.$filename);
 5815:     foreach my $file (@files) {
 5816:         print (OUT $env{'form.currentpath'}.$file."\n");
 5817:     }
 5818:     foreach my $file (@other_files) {
 5819:         print (OUT $file."\n");
 5820:     }
 5821:     close (OUT);
 5822:     return 'ok';
 5823: }
 5824: 
 5825: sub clear_selected_files {
 5826:     my ($user) = @_;
 5827:     my $filename = $user."savedfiles";
 5828:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5829:     print (OUT undef);
 5830:     close (OUT);
 5831:     return ("ok");    
 5832: }
 5833: 
 5834: sub files_in_path {
 5835:     my ($user, $path) = @_;
 5836:     my $filename = $user."savedfiles";
 5837:     my %return_files;
 5838:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5839:     while (my $line_in = <IN>) {
 5840:         chomp ($line_in);
 5841:         my @paths_and_file = split (m!/!, $line_in);
 5842:         my $file_part = pop (@paths_and_file);
 5843:         my $path_part = join ('/', @paths_and_file);
 5844:         $path_part.='/';
 5845:         my $path_and_file = $path_part.$file_part;
 5846:         if ($path_part eq $path) {
 5847:             $return_files{$file_part}= 'selected';
 5848:         }
 5849:     }
 5850:     close (IN);
 5851:     return (\%return_files);
 5852: }
 5853: 
 5854: # called in portfolio select mode, to show files selected NOT in current directory
 5855: sub files_not_in_path {
 5856:     my ($user, $path) = @_;
 5857:     my $filename = $user."savedfiles";
 5858:     my @return_files;
 5859:     my $path_part;
 5860:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5861:     while (my $line = <IN>) {
 5862:         #ok, I know it's clunky, but I want it to work
 5863:         my @paths_and_file = split(m|/|, $line);
 5864:         my $file_part = pop(@paths_and_file);
 5865:         chomp($file_part);
 5866:         my $path_part = join('/', @paths_and_file);
 5867:         $path_part .= '/';
 5868:         my $path_and_file = $path_part.$file_part;
 5869:         if ($path_part ne $path) {
 5870:             push(@return_files, ($path_and_file));
 5871:         }
 5872:     }
 5873:     close(OUT);
 5874:     return (@return_files);
 5875: }
 5876: 
 5877: #----------------------------------------------Get portfolio file permissions
 5878: 
 5879: sub get_portfile_permissions {
 5880:     my ($domain,$user) = @_;
 5881:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5882:     my ($tmp)=keys(%current_permissions);
 5883:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5884:     return \%current_permissions;
 5885: }
 5886: 
 5887: #---------------------------------------------Get portfolio file access controls
 5888: 
 5889: sub get_access_controls {
 5890:     my ($current_permissions,$group,$file) = @_;
 5891:     my %access;
 5892:     my $real_file = $file;
 5893:     $file =~ s/\.meta$//;
 5894:     if (defined($file)) {
 5895:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5896:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5897:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5898:             }
 5899:         }
 5900:     } else {
 5901:         foreach my $key (keys(%{$current_permissions})) {
 5902:             if ($key =~ /\0accesscontrol$/) {
 5903:                 if (defined($group)) {
 5904:                     if ($key !~ m-^\Q$group\E/-) {
 5905:                         next;
 5906:                     }
 5907:                 }
 5908:                 my ($fullpath) = split(/\0/,$key);
 5909:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5910:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5911:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5912:                     }
 5913:                 }
 5914:             }
 5915:         }
 5916:     }
 5917:     return %access;
 5918: }
 5919: 
 5920: sub modify_access_controls {
 5921:     my ($file_name,$changes,$domain,$user)=@_;
 5922:     my ($outcome,$deloutcome);
 5923:     my %store_permissions;
 5924:     my %new_values;
 5925:     my %new_control;
 5926:     my %translation;
 5927:     my @deletions = ();
 5928:     my $now = time;
 5929:     if (exists($$changes{'activate'})) {
 5930:         if (ref($$changes{'activate'}) eq 'HASH') {
 5931:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5932:             my $numnew = scalar(@newitems);
 5933:             for (my $i=0; $i<$numnew; $i++) {
 5934:                 my $newkey = $newitems[$i];
 5935:                 my $newid = &Apache::loncommon::get_cgi_id();
 5936:                 if ($newkey =~ /^\d+:/) { 
 5937:                     $newkey =~ s/^(\d+)/$newid/;
 5938:                     $translation{$1} = $newid;
 5939:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5940:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5941:                     $translation{$1} = $newid;
 5942:                 }
 5943:                 $new_values{$file_name."\0".$newkey} = 
 5944:                                           $$changes{'activate'}{$newitems[$i]};
 5945:                 $new_control{$newkey} = $now;
 5946:             }
 5947:         }
 5948:     }
 5949:     my %todelete;
 5950:     my %changed_items;
 5951:     foreach my $action ('delete','update') {
 5952:         if (exists($$changes{$action})) {
 5953:             if (ref($$changes{$action}) eq 'HASH') {
 5954:                 foreach my $key (keys(%{$$changes{$action}})) {
 5955:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5956:                     if ($action eq 'delete') { 
 5957:                         $todelete{$itemnum} = 1;
 5958:                     } else {
 5959:                         $changed_items{$itemnum} = $key;
 5960:                     }
 5961:                 }
 5962:             }
 5963:         }
 5964:     }
 5965:     # get lock on access controls for file.
 5966:     my $lockhash = {
 5967:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5968:                                                        ':'.$env{'user.domain'},
 5969:                    }; 
 5970:     my $tries = 0;
 5971:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5972:    
 5973:     while (($gotlock ne 'ok') && $tries <3) {
 5974:         $tries ++;
 5975:         sleep 1;
 5976:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5977:     }
 5978:     if ($gotlock eq 'ok') {
 5979:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5980:         my ($tmp)=keys(%curr_permissions);
 5981:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5982:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5983:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5984:             if (ref($curr_controls) eq 'HASH') {
 5985:                 foreach my $control_item (keys(%{$curr_controls})) {
 5986:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5987:                     if (defined($todelete{$itemnum})) {
 5988:                         push(@deletions,$file_name."\0".$control_item);
 5989:                     } else {
 5990:                         if (defined($changed_items{$itemnum})) {
 5991:                             $new_control{$changed_items{$itemnum}} = $now;
 5992:                             push(@deletions,$file_name."\0".$control_item);
 5993:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5994:                         } else {
 5995:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5996:                         }
 5997:                     }
 5998:                 }
 5999:             }
 6000:         }
 6001:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6002:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6003:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6004:         #  remove lock
 6005:         my @del_lock = ($file_name."\0".'locked_access_records');
 6006:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6007:         my ($file,$group);
 6008:         if (&is_course($domain,$user)) {
 6009:             ($group,$file) = split(/\//,$file_name,2);
 6010:         } else {
 6011:             $file = $file_name;
 6012:         }
 6013:         my $sqlresult =
 6014:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 6015:                                     $group);
 6016:     } else {
 6017:         $outcome = "error: could not obtain lockfile\n";  
 6018:     }
 6019:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6020: }
 6021: 
 6022: sub make_public_indefinitely {
 6023:     my ($requrl) = @_;
 6024:     my $now = time;
 6025:     my $action = 'activate';
 6026:     my $aclnum = 0;
 6027:     if (&is_portfolio_url($requrl)) {
 6028:         my (undef,$udom,$unum,$file_name,$group) =
 6029:             &parse_portfolio_url($requrl);
 6030:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6031:         my %access_controls = &get_access_controls($current_perms,
 6032:                                                    $group,$file_name);
 6033:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6034:             my ($num,$scope,$end,$start) = 
 6035:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6036:             if ($scope eq 'public') {
 6037:                 if ($start <= $now && $end == 0) {
 6038:                     $action = 'none';
 6039:                 } else {
 6040:                     $action = 'update';
 6041:                     $aclnum = $num;
 6042:                 }
 6043:                 last;
 6044:             }
 6045:         }
 6046:         if ($action eq 'none') {
 6047:              return 'ok';
 6048:         } else {
 6049:             my %changes;
 6050:             my $newend = 0;
 6051:             my $newstart = $now;
 6052:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6053:             $changes{$action}{$newkey} = {
 6054:                 type => 'public',
 6055:                 time => {
 6056:                     start => $newstart,
 6057:                     end   => $newend,
 6058:                 },
 6059:             };
 6060:             my ($outcome,$deloutcome,$new_values,$translation) =
 6061:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6062:             return $outcome;
 6063:         }
 6064:     } else {
 6065:         return 'invalid';
 6066:     }
 6067: }
 6068: 
 6069: #------------------------------------------------------Get Marked as Read Only
 6070: 
 6071: sub get_marked_as_readonly {
 6072:     my ($domain,$user,$what,$group) = @_;
 6073:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6074:     my @readonly_files;
 6075:     my $cmp1=$what;
 6076:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6077:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6078:         if (defined($group)) {
 6079:             if ($file_name !~ m-^\Q$group\E/-) {
 6080:                 next;
 6081:             }
 6082:         }
 6083:         if (ref($value) eq "ARRAY"){
 6084:             foreach my $stored_what (@{$value}) {
 6085:                 my $cmp2=$stored_what;
 6086:                 if (ref($stored_what) eq 'ARRAY') {
 6087:                     $cmp2=join('',@{$stored_what});
 6088:                 }
 6089:                 if ($cmp1 eq $cmp2) {
 6090:                     push(@readonly_files, $file_name);
 6091:                     last;
 6092:                 } elsif (!defined($what)) {
 6093:                     push(@readonly_files, $file_name);
 6094:                     last;
 6095:                 }
 6096:             }
 6097:         }
 6098:     }
 6099:     return @readonly_files;
 6100: }
 6101: #-----------------------------------------------------------Get Marked as Read Only Hash
 6102: 
 6103: sub get_marked_as_readonly_hash {
 6104:     my ($current_permissions,$group,$what) = @_;
 6105:     my %readonly_files;
 6106:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6107:         if (defined($group)) {
 6108:             if ($file_name !~ m-^\Q$group\E/-) {
 6109:                 next;
 6110:             }
 6111:         }
 6112:         if (ref($value) eq "ARRAY"){
 6113:             foreach my $stored_what (@{$value}) {
 6114:                 if (ref($stored_what) eq 'ARRAY') {
 6115:                     foreach my $lock_descriptor(@{$stored_what}) {
 6116:                         if ($lock_descriptor eq 'graded') {
 6117:                             $readonly_files{$file_name} = 'graded';
 6118:                         } elsif ($lock_descriptor eq 'handback') {
 6119:                             $readonly_files{$file_name} = 'handback';
 6120:                         } else {
 6121:                             if (!exists($readonly_files{$file_name})) {
 6122:                                 $readonly_files{$file_name} = 'locked';
 6123:                             }
 6124:                         }
 6125:                     }
 6126:                 } 
 6127:             }
 6128:         } 
 6129:     }
 6130:     return %readonly_files;
 6131: }
 6132: # ------------------------------------------------------------ Unmark as Read Only
 6133: 
 6134: sub unmark_as_readonly {
 6135:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6136:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6137:     my ($domain,$user,$what,$file_name,$group) = @_;
 6138:     $file_name = &declutter_portfile($file_name);
 6139:     my $symb_crs = $what;
 6140:     if (ref($what)) { $symb_crs=join('',@$what); }
 6141:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6142:     my ($tmp)=keys(%current_permissions);
 6143:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6144:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6145:     foreach my $file (@readonly_files) {
 6146: 	my $clean_file = &declutter_portfile($file);
 6147: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6148: 	my $current_locks = $current_permissions{$file};
 6149:         my @new_locks;
 6150:         my @del_keys;
 6151:         if (ref($current_locks) eq "ARRAY"){
 6152:             foreach my $locker (@{$current_locks}) {
 6153:                 my $compare=$locker;
 6154:                 if (ref($locker) eq 'ARRAY') {
 6155:                     $compare=join('',@{$locker});
 6156:                     if ($compare ne $symb_crs) {
 6157:                         push(@new_locks, $locker);
 6158:                     }
 6159:                 }
 6160:             }
 6161:             if (scalar(@new_locks) > 0) {
 6162:                 $current_permissions{$file} = \@new_locks;
 6163:             } else {
 6164:                 push(@del_keys, $file);
 6165:                 &del('file_permissions',\@del_keys, $domain, $user);
 6166:                 delete($current_permissions{$file});
 6167:             }
 6168:         }
 6169:     }
 6170:     &put('file_permissions',\%current_permissions,$domain,$user);
 6171:     return;
 6172: }
 6173: 
 6174: # ------------------------------------------------------------ Directory lister
 6175: 
 6176: sub dirlist {
 6177:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 6178: 
 6179:     $uri=~s/^\///;
 6180:     $uri=~s/\/$//;
 6181:     my ($udom, $uname);
 6182:     (undef,$udom,$uname)=split(/\//,$uri);
 6183:     if(defined($userdomain)) {
 6184:         $udom = $userdomain;
 6185:     }
 6186:     if(defined($username)) {
 6187:         $uname = $username;
 6188:     }
 6189: 
 6190:     my $dirRoot = $perlvar{'lonDocRoot'};
 6191:     if(defined($alternateDirectoryRoot)) {
 6192:         $dirRoot = $alternateDirectoryRoot;
 6193:         $dirRoot =~ s/\/$//;
 6194:     }
 6195: 
 6196:     if($udom) {
 6197:         if($uname) {
 6198:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6199: 				 &homeserver($uname,$udom));
 6200:             my @listing_results;
 6201:             if ($listing eq 'unknown_cmd') {
 6202:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6203: 				  &homeserver($uname,$udom));
 6204:                 @listing_results = split(/:/,$listing);
 6205:             } else {
 6206:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6207:             }
 6208:             return @listing_results;
 6209:         } elsif(!defined($alternateDirectoryRoot)) {
 6210:             my %allusers;
 6211: 	    my %servers = &get_servers($udom,'library');
 6212: 	    foreach my $tryserver (keys(%servers)) {
 6213: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6214: 				     $udom, $tryserver);
 6215: 		my @listing_results;
 6216: 		if ($listing eq 'unknown_cmd') {
 6217: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6218: 				      $udom, $tryserver);
 6219: 		    @listing_results = split(/:/,$listing);
 6220: 		} else {
 6221: 		    @listing_results =
 6222: 			map { &unescape($_); } split(/:/,$listing);
 6223: 		}
 6224: 		if ($listing_results[0] ne 'no_such_dir' && 
 6225: 		    $listing_results[0] ne 'empty'       &&
 6226: 		    $listing_results[0] ne 'con_lost') {
 6227: 		    foreach my $line (@listing_results) {
 6228: 			my ($entry) = split(/&/,$line,2);
 6229: 			$allusers{$entry} = 1;
 6230: 		    }
 6231: 		}
 6232:             }
 6233:             my $alluserstr='';
 6234:             foreach my $user (sort(keys(%allusers))) {
 6235:                 $alluserstr.=$user.'&user:';
 6236:             }
 6237:             $alluserstr=~s/:$//;
 6238:             return split(/:/,$alluserstr);
 6239:         } else {
 6240:             return ('missing user name');
 6241:         }
 6242:     } elsif(!defined($alternateDirectoryRoot)) {
 6243:         my @all_domains = sort(&all_domains());
 6244:          foreach my $domain (@all_domains) {
 6245:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6246:          }
 6247:          return @all_domains;
 6248:      } else {
 6249:         return ('missing domain');
 6250:     }
 6251: }
 6252: 
 6253: # --------------------------------------------- GetFileTimestamp
 6254: # This function utilizes dirlist and returns the date stamp for
 6255: # when it was last modified.  It will also return an error of -1
 6256: # if an error occurs
 6257: 
 6258: ##
 6259: ## FIXME: This subroutine assumes its caller knows something about the
 6260: ## directory structure of the home server for the student ($root).
 6261: ## Not a good assumption to make.  Since this is for looking up files
 6262: ## in user directories, the full path should be constructed by lond, not
 6263: ## whatever machine we request data from.
 6264: ##
 6265: sub GetFileTimestamp {
 6266:     my ($studentDomain,$studentName,$filename,$root)=@_;
 6267:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6268:     $studentName   = &LONCAPA::clean_username($studentName);
 6269:     my $subdir=$studentName.'__';
 6270:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6271:     my $proname="$studentDomain/$subdir/$studentName";
 6272:     $proname .= '/'.$filename;
 6273:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 6274:                                               $studentName, $root);
 6275:     my @stats = split('&', $fileStat);
 6276:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6277:         # @stats contains first the filename, then the stat output
 6278:         return $stats[10]; # so this is 10 instead of 9.
 6279:     } else {
 6280:         return -1;
 6281:     }
 6282: }
 6283: 
 6284: sub stat_file {
 6285:     my ($uri) = @_;
 6286:     $uri = &clutter_with_no_wrapper($uri);
 6287: 
 6288:     my ($udom,$uname,$file,$dir);
 6289:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6290: 	($udom,$uname,$file) =
 6291: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6292: 	$file = 'userfiles/'.$file;
 6293: 	$dir = &propath($udom,$uname);
 6294:     }
 6295:     if ($uri =~ m-^/res/-) {
 6296: 	($udom,$uname) = 
 6297: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6298: 	$file = $uri;
 6299:     }
 6300: 
 6301:     if (!$udom || !$uname || !$file) {
 6302: 	# unable to handle the uri
 6303: 	return ();
 6304:     }
 6305: 
 6306:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 6307:     my @stats = split('&', $result);
 6308:     
 6309:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6310: 	shift(@stats); #filename is first
 6311: 	return @stats;
 6312:     }
 6313:     return ();
 6314: }
 6315: 
 6316: # -------------------------------------------------------- Value of a Condition
 6317: 
 6318: # gets the value of a specific preevaluated condition
 6319: #    stored in the string  $env{user.state.<cid>}
 6320: # or looks up a condition reference in the bighash and if if hasn't
 6321: # already been evaluated recurses into docondval to get the value of
 6322: # the condition, then memoizing it to 
 6323: #   $env{user.state.<cid>.<condition>}
 6324: sub directcondval {
 6325:     my $number=shift;
 6326:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6327: 	&Apache::lonuserstate::evalstate();
 6328:     }
 6329:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6330: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6331:     } elsif ($number =~ /^_/) {
 6332: 	my $sub_condition;
 6333: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6334: 		&GDBM_READER(),0640)) {
 6335: 	    $sub_condition=$bighash{'conditions'.$number};
 6336: 	    untie(%bighash);
 6337: 	}
 6338: 	my $value = &docondval($sub_condition);
 6339: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 6340: 	return $value;
 6341:     }
 6342:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6343:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6344:     } else {
 6345:        return 2;
 6346:     }
 6347: }
 6348: 
 6349: # get the collection of conditions for this resource
 6350: sub condval {
 6351:     my $condidx=shift;
 6352:     my $allpathcond='';
 6353:     foreach my $cond (split(/\|/,$condidx)) {
 6354: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6355: 	    $allpathcond.=
 6356: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6357: 	}
 6358:     }
 6359:     $allpathcond=~s/\|$//;
 6360:     return &docondval($allpathcond);
 6361: }
 6362: 
 6363: #evaluates an expression of conditions
 6364: sub docondval {
 6365:     my ($allpathcond) = @_;
 6366:     my $result=0;
 6367:     if ($env{'request.course.id'}
 6368: 	&& defined($allpathcond)) {
 6369: 	my $operand='|';
 6370: 	my @stack;
 6371: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6372: 	    if ($chunk eq '(') {
 6373: 		push @stack,($operand,$result);
 6374: 	    } elsif ($chunk eq ')') {
 6375: 		my $before=pop @stack;
 6376: 		if (pop @stack eq '&') {
 6377: 		    $result=$result>$before?$before:$result;
 6378: 		} else {
 6379: 		    $result=$result>$before?$result:$before;
 6380: 		}
 6381: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6382: 		$operand=$chunk;
 6383: 	    } else {
 6384: 		my $new=directcondval($chunk);
 6385: 		if ($operand eq '&') {
 6386: 		    $result=$result>$new?$new:$result;
 6387: 		} else {
 6388: 		    $result=$result>$new?$result:$new;
 6389: 		}
 6390: 	    }
 6391: 	}
 6392:     }
 6393:     return $result;
 6394: }
 6395: 
 6396: # ---------------------------------------------------- Devalidate courseresdata
 6397: 
 6398: sub devalidatecourseresdata {
 6399:     my ($coursenum,$coursedomain)=@_;
 6400:     my $hashid=$coursenum.':'.$coursedomain;
 6401:     &devalidate_cache_new('courseres',$hashid);
 6402: }
 6403: 
 6404: 
 6405: # --------------------------------------------------- Course Resourcedata Query
 6406: #
 6407: #  Parameters:
 6408: #      $coursenum    - Number of the course.
 6409: #      $coursedomain - Domain at which the course was created.
 6410: #  Returns:
 6411: #     A hash of the course parameters along (I think) with timestamps
 6412: #     and version info.
 6413: 
 6414: sub get_courseresdata {
 6415:     my ($coursenum,$coursedomain)=@_;
 6416:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6417:     my $hashid=$coursenum.':'.$coursedomain;
 6418:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6419:     my %dumpreply;
 6420:     unless (defined($cached)) {
 6421: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6422: 	$result=\%dumpreply;
 6423: 	my ($tmp) = keys(%dumpreply);
 6424: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6425: 	    &do_cache_new('courseres',$hashid,$result,600);
 6426: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6427: 	    return $tmp;
 6428: 	} elsif ($tmp =~ /^(error)/) {
 6429: 	    $result=undef;
 6430: 	    &do_cache_new('courseres',$hashid,$result,600);
 6431: 	}
 6432:     }
 6433:     return $result;
 6434: }
 6435: 
 6436: sub devalidateuserresdata {
 6437:     my ($uname,$udom)=@_;
 6438:     my $hashid="$udom:$uname";
 6439:     &devalidate_cache_new('userres',$hashid);
 6440: }
 6441: 
 6442: sub get_userresdata {
 6443:     my ($uname,$udom)=@_;
 6444:     #most student don\'t have any data set, check if there is some data
 6445:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6446: 
 6447:     my $hashid="$udom:$uname";
 6448:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6449:     if (!defined($cached)) {
 6450: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6451: 	$result=\%resourcedata;
 6452: 	&do_cache_new('userres',$hashid,$result,600);
 6453:     }
 6454:     my ($tmp)=keys(%$result);
 6455:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6456: 	return $result;
 6457:     }
 6458:     #error 2 occurs when the .db doesn't exist
 6459:     if ($tmp!~/error: 2 /) {
 6460: 	&logthis("<font color=\"blue\">WARNING:".
 6461: 		 " Trying to get resource data for ".
 6462: 		 $uname." at ".$udom.": ".
 6463: 		 $tmp."</font>");
 6464:     } elsif ($tmp=~/error: 2 /) {
 6465: 	#&EXT_cache_set($udom,$uname);
 6466: 	&do_cache_new('userres',$hashid,undef,600);
 6467: 	undef($tmp); # not really an error so don't send it back
 6468:     }
 6469:     return $tmp;
 6470: }
 6471: #----------------------------------------------- resdata - return resource data
 6472: #  Purpose:
 6473: #    Return resource data for either users or for a course.
 6474: #  Parameters:
 6475: #     $name      - Course/user name.
 6476: #     $domain    - Name of the domain the user/course is registered on.
 6477: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6478: #     @which     - Array of names of resources desired.
 6479: #  Returns:
 6480: #     The value of the first reasource in @which that is found in the
 6481: #     resource hash.
 6482: #  Exceptional Conditions:
 6483: #     If the $type passed in is not valid (not the string 'course' or 
 6484: #     'user', an undefined  reference is returned.
 6485: #     If none of the resources are found, an undef is returned
 6486: sub resdata {
 6487:     my ($name,$domain,$type,@which)=@_;
 6488:     my $result;
 6489:     if ($type eq 'course') {
 6490: 	$result=&get_courseresdata($name,$domain);
 6491:     } elsif ($type eq 'user') {
 6492: 	$result=&get_userresdata($name,$domain);
 6493:     }
 6494:     if (!ref($result)) { return $result; }    
 6495:     foreach my $item (@which) {
 6496: 	if (defined($result->{$item->[0]})) {
 6497: 	    return [$result->{$item->[0]},$item->[1]];
 6498: 	}
 6499:     }
 6500:     return undef;
 6501: }
 6502: 
 6503: #
 6504: # EXT resource caching routines
 6505: #
 6506: 
 6507: sub clear_EXT_cache_status {
 6508:     &delenv('cache.EXT.');
 6509: }
 6510: 
 6511: sub EXT_cache_status {
 6512:     my ($target_domain,$target_user) = @_;
 6513:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6514:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6515:         # We know already the user has no data
 6516:         return 1;
 6517:     } else {
 6518:         return 0;
 6519:     }
 6520: }
 6521: 
 6522: sub EXT_cache_set {
 6523:     my ($target_domain,$target_user) = @_;
 6524:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6525:     #&appenv($cachename => time);
 6526: }
 6527: 
 6528: # --------------------------------------------------------- Value of a Variable
 6529: sub EXT {
 6530: 
 6531:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6532:     unless ($varname) { return ''; }
 6533:     #get real user name/domain, courseid and symb
 6534:     my $courseid;
 6535:     my $publicuser;
 6536:     if ($symbparm) {
 6537: 	$symbparm=&get_symb_from_alias($symbparm);
 6538:     }
 6539:     if (!($uname && $udom)) {
 6540:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6541:       if (!$symbparm) {	$symbparm=$cursymb; }
 6542:     } else {
 6543: 	$courseid=$env{'request.course.id'};
 6544:     }
 6545:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6546:     my $rest;
 6547:     if (defined($therest[0])) {
 6548:        $rest=join('.',@therest);
 6549:     } else {
 6550:        $rest='';
 6551:     }
 6552: 
 6553:     my $qualifierrest=$qualifier;
 6554:     if ($rest) { $qualifierrest.='.'.$rest; }
 6555:     my $spacequalifierrest=$space;
 6556:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6557:     if ($realm eq 'user') {
 6558: # --------------------------------------------------------------- user.resource
 6559: 	if ($space eq 'resource') {
 6560: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6561: 		  || defined($Apache::lonhomework::parsing_a_task))
 6562: 		 &&
 6563: 		 ($symbparm eq &symbread()) ) {	
 6564: 		# if we are in the middle of processing the resource the
 6565: 		# get the value we are planning on committing
 6566:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6567:                     return $Apache::lonhomework::results{$qualifierrest};
 6568:                 } else {
 6569:                     return $Apache::lonhomework::history{$qualifierrest};
 6570:                 }
 6571: 	    } else {
 6572: 		my %restored;
 6573: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6574: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6575: 		} else {
 6576: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6577: 		}
 6578: 		return $restored{$qualifierrest};
 6579: 	    }
 6580: # ----------------------------------------------------------------- user.access
 6581:         } elsif ($space eq 'access') {
 6582: 	    # FIXME - not supporting calls for a specific user
 6583:             return &allowed($qualifier,$rest);
 6584: # ------------------------------------------ user.preferences, user.environment
 6585:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6586: 	    if (($uname eq $env{'user.name'}) &&
 6587: 		($udom eq $env{'user.domain'})) {
 6588: 		return $env{join('.',('environment',$qualifierrest))};
 6589: 	    } else {
 6590: 		my %returnhash;
 6591: 		if (!$publicuser) {
 6592: 		    %returnhash=&userenvironment($udom,$uname,
 6593: 						 $qualifierrest);
 6594: 		}
 6595: 		return $returnhash{$qualifierrest};
 6596: 	    }
 6597: # ----------------------------------------------------------------- user.course
 6598:         } elsif ($space eq 'course') {
 6599: 	    # FIXME - not supporting calls for a specific user
 6600:             return $env{join('.',('request.course',$qualifier))};
 6601: # ------------------------------------------------------------------- user.role
 6602:         } elsif ($space eq 'role') {
 6603: 	    # FIXME - not supporting calls for a specific user
 6604:             my ($role,$where)=split(/\./,$env{'request.role'});
 6605:             if ($qualifier eq 'value') {
 6606: 		return $role;
 6607:             } elsif ($qualifier eq 'extent') {
 6608:                 return $where;
 6609:             }
 6610: # ----------------------------------------------------------------- user.domain
 6611:         } elsif ($space eq 'domain') {
 6612:             return $udom;
 6613: # ------------------------------------------------------------------- user.name
 6614:         } elsif ($space eq 'name') {
 6615:             return $uname;
 6616: # ---------------------------------------------------- Any other user namespace
 6617:         } else {
 6618: 	    my %reply;
 6619: 	    if (!$publicuser) {
 6620: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6621: 	    }
 6622: 	    return $reply{$qualifierrest};
 6623:         }
 6624:     } elsif ($realm eq 'query') {
 6625: # ---------------------------------------------- pull stuff out of query string
 6626:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6627: 						[$spacequalifierrest]);
 6628: 	return $env{'form.'.$spacequalifierrest}; 
 6629:    } elsif ($realm eq 'request') {
 6630: # ------------------------------------------------------------- request.browser
 6631:         if ($space eq 'browser') {
 6632: 	    if ($qualifier eq 'textremote') {
 6633: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6634: 		    return 1;
 6635: 		} else {
 6636: 		    return 0;
 6637: 		}
 6638: 	    } else {
 6639: 		return $env{'browser.'.$qualifier};
 6640: 	    }
 6641: # ------------------------------------------------------------ request.filename
 6642:         } else {
 6643:             return $env{'request.'.$spacequalifierrest};
 6644:         }
 6645:     } elsif ($realm eq 'course') {
 6646: # ---------------------------------------------------------- course.description
 6647:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6648:     } elsif ($realm eq 'resource') {
 6649: 
 6650: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6651: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6652: 	}
 6653: 
 6654: 	if ($space eq 'title') {
 6655: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6656: 	    return &gettitle($symbparm);
 6657: 	}
 6658: 	
 6659: 	if ($space eq 'map') {
 6660: 	    my ($map) = &decode_symb($symbparm);
 6661: 	    return &symbread($map);
 6662: 	}
 6663: 	if ($space eq 'filename') {
 6664: 	    if ($symbparm) {
 6665: 		return &clutter((&decode_symb($symbparm))[2]);
 6666: 	    }
 6667: 	    return &hreflocation('',$env{'request.filename'});
 6668: 	}
 6669: 
 6670: 	my ($section, $group, @groups);
 6671: 	my ($courselevelm,$courselevel);
 6672: 	if ($symbparm && defined($courseid) && 
 6673: 	    $courseid eq $env{'request.course.id'}) {
 6674: 
 6675: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6676: 
 6677: # ----------------------------------------------------- Cascading lookup scheme
 6678: 	    my $symbp=$symbparm;
 6679: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6680: 
 6681: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6682: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6683: 
 6684: 	    if (($env{'user.name'} eq $uname) &&
 6685: 		($env{'user.domain'} eq $udom)) {
 6686: 		$section=$env{'request.course.sec'};
 6687:                 @groups = split(/:/,$env{'request.course.groups'});  
 6688:                 @groups=&sort_course_groups($courseid,@groups); 
 6689: 	    } else {
 6690: 		if (! defined($usection)) {
 6691: 		    $section=&getsection($udom,$uname,$courseid);
 6692: 		} else {
 6693: 		    $section = $usection;
 6694: 		}
 6695:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6696: 	    }
 6697: 
 6698: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6699: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6700: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6701: 
 6702: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6703: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6704: 	    $courselevelm=$courseid.'.'.$mapparm;
 6705: 
 6706: # ----------------------------------------------------------- first, check user
 6707: 
 6708: 	    my $userreply=&resdata($uname,$udom,'user',
 6709: 				       ([$courselevelr,'resource'],
 6710: 					[$courselevelm,'map'     ],
 6711: 					[$courselevel, 'course'  ]));
 6712: 	    if (defined($userreply)) { return &get_reply($userreply); }
 6713: 
 6714: # ------------------------------------------------ second, check some of course
 6715:             my $coursereply;
 6716:             if (@groups > 0) {
 6717:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6718:                                        $mapparm,$spacequalifierrest);
 6719:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 6720:             }
 6721: 
 6722: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6723: 				  $env{'course.'.$courseid.'.domain'},
 6724: 				  'course',
 6725: 				  ([$seclevelr,   'resource'],
 6726: 				   [$seclevelm,   'map'     ],
 6727: 				   [$seclevel,    'course'  ],
 6728: 				   [$courselevelr,'resource']));
 6729: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6730: 
 6731: # ------------------------------------------------------ third, check map parms
 6732: 	    my %parmhash=();
 6733: 	    my $thisparm='';
 6734: 	    if (tie(%parmhash,'GDBM_File',
 6735: 		    $env{'request.course.fn'}.'_parms.db',
 6736: 		    &GDBM_READER(),0640)) {
 6737: 		$thisparm=$parmhash{$symbparm};
 6738: 		untie(%parmhash);
 6739: 	    }
 6740: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 6741: 	}
 6742: # ------------------------------------------ fourth, look in resource metadata
 6743: 
 6744: 	$spacequalifierrest=~s/\./\_/;
 6745: 	my $filename;
 6746: 	if (!$symbparm) { $symbparm=&symbread(); }
 6747: 	if ($symbparm) {
 6748: 	    $filename=(&decode_symb($symbparm))[2];
 6749: 	} else {
 6750: 	    $filename=$env{'request.filename'};
 6751: 	}
 6752: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6753: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6754: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6755: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6756: 
 6757: # ---------------------------------------------- fourth, look in rest of course
 6758: 	if ($symbparm && defined($courseid) && 
 6759: 	    $courseid eq $env{'request.course.id'}) {
 6760: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6761: 				     $env{'course.'.$courseid.'.domain'},
 6762: 				     'course',
 6763: 				     ([$courselevelm,'map'   ],
 6764: 				      [$courselevel, 'course']));
 6765: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6766: 	}
 6767: # ------------------------------------------------------------------ Cascade up
 6768: 	unless ($space eq '0') {
 6769: 	    my @parts=split(/_/,$space);
 6770: 	    my $id=pop(@parts);
 6771: 	    my $part=join('_',@parts);
 6772: 	    if ($part eq '') { $part='0'; }
 6773: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6774: 				 $symbparm,$udom,$uname,$section,1);
 6775: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 6776: 	}
 6777: 	if ($recurse) { return undef; }
 6778: 	my $pack_def=&packages_tab_default($filename,$varname);
 6779: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 6780: # ---------------------------------------------------- Any other user namespace
 6781:     } elsif ($realm eq 'environment') {
 6782: # ----------------------------------------------------------------- environment
 6783: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6784: 	    return $env{'environment.'.$spacequalifierrest};
 6785: 	} else {
 6786: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6787: 		return '';
 6788: 	    }
 6789: 	    my %returnhash=&userenvironment($udom,$uname,
 6790: 					    $spacequalifierrest);
 6791: 	    return $returnhash{$spacequalifierrest};
 6792: 	}
 6793:     } elsif ($realm eq 'system') {
 6794: # ----------------------------------------------------------------- system.time
 6795: 	if ($space eq 'time') {
 6796: 	    return time;
 6797:         }
 6798:     } elsif ($realm eq 'server') {
 6799: # ----------------------------------------------------------------- system.time
 6800: 	if ($space eq 'name') {
 6801: 	    return $ENV{'SERVER_NAME'};
 6802:         }
 6803:     }
 6804:     return '';
 6805: }
 6806: 
 6807: sub get_reply {
 6808:     my ($reply_value) = @_;
 6809:     if (ref($reply_value) eq 'ARRAY') {
 6810:         if (wantarray) {
 6811: 	    return @$reply_value;
 6812:         }
 6813:         return $reply_value->[0];
 6814:     } else {
 6815:         return $reply_value;
 6816:     }
 6817: }
 6818: 
 6819: sub check_group_parms {
 6820:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6821:     my @groupitems = ();
 6822:     my $resultitem;
 6823:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 6824:     foreach my $group (@{$groups}) {
 6825:         foreach my $level (@levels) {
 6826:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 6827:              push(@groupitems,[$item,$level->[1]]);
 6828:         }
 6829:     }
 6830:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6831:                             $env{'course.'.$courseid.'.domain'},
 6832:                                      'course',@groupitems);
 6833:     return $coursereply;
 6834: }
 6835: 
 6836: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6837:     my ($courseid,@groups) = @_;
 6838:     @groups = sort(@groups);
 6839:     return @groups;
 6840: }
 6841: 
 6842: sub packages_tab_default {
 6843:     my ($uri,$varname)=@_;
 6844:     my (undef,$part,$name)=split(/\./,$varname);
 6845: 
 6846:     my (@extension,@specifics,$do_default);
 6847:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6848: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6849: 	if ($pack_type eq 'default') {
 6850: 	    $do_default=1;
 6851: 	} elsif ($pack_type eq 'extension') {
 6852: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6853: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 6854: 	    # only look at packages defaults for packages that this id is
 6855: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6856: 	}
 6857:     }
 6858:     # first look for a package that matches the requested part id
 6859:     foreach my $package (@specifics) {
 6860: 	my (undef,$pack_type,$pack_part)=@{$package};
 6861: 	next if ($pack_part ne $part);
 6862: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6863: 	    return $packagetab{"$pack_type&$name&default"};
 6864: 	}
 6865:     }
 6866:     # look for any possible matching non extension_ package
 6867:     foreach my $package (@specifics) {
 6868: 	my (undef,$pack_type,$pack_part)=@{$package};
 6869: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6870: 	    return $packagetab{"$pack_type&$name&default"};
 6871: 	}
 6872: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6873: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6874: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6875: 	}
 6876:     }
 6877:     # look for any posible extension_ match
 6878:     foreach my $package (@extension) {
 6879: 	my ($package,$pack_type)=@{$package};
 6880: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6881: 	    return $packagetab{"$pack_type&$name&default"};
 6882: 	}
 6883: 	if (defined($packagetab{$package."&$name&default"})) {
 6884: 	    return $packagetab{$package."&$name&default"};
 6885: 	}
 6886:     }
 6887:     # look for a global default setting
 6888:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6889: 	return $packagetab{"default&$name&default"};
 6890:     }
 6891:     return undef;
 6892: }
 6893: 
 6894: sub add_prefix_and_part {
 6895:     my ($prefix,$part)=@_;
 6896:     my $keyroot;
 6897:     if (defined($prefix) && $prefix !~ /^__/) {
 6898: 	# prefix that has a part already
 6899: 	$keyroot=$prefix;
 6900:     } elsif (defined($prefix)) {
 6901: 	# prefix that is missing a part
 6902: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6903:     } else {
 6904: 	# no prefix at all
 6905: 	if (defined($part)) { $keyroot='_'.$part; }
 6906:     }
 6907:     return $keyroot;
 6908: }
 6909: 
 6910: # ---------------------------------------------------------------- Get metadata
 6911: 
 6912: my %metaentry;
 6913: sub metadata {
 6914:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6915:     $uri=&declutter($uri);
 6916:     # if it is a non metadata possible uri return quickly
 6917:     if (($uri eq '') || 
 6918: 	(($uri =~ m|^/*adm/|) && 
 6919: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6920:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 6921: 	return undef;
 6922:     }
 6923:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 6924: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 6925: 	return undef;
 6926:     }
 6927:     my $filename=$uri;
 6928:     $uri=~s/\.meta$//;
 6929: #
 6930: # Is the metadata already cached?
 6931: # Look at timestamp of caching
 6932: # Everything is cached by the main uri, libraries are never directly cached
 6933: #
 6934:     if (!defined($liburi)) {
 6935: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6936: 	if (defined($cached)) { return $result->{':'.$what}; }
 6937:     }
 6938:     {
 6939: #
 6940: # Is this a recursive call for a library?
 6941: #
 6942: #	if (! exists($metacache{$uri})) {
 6943: #	    $metacache{$uri}={};
 6944: #	}
 6945: 	my $cachetime = 60*60;
 6946:         if ($liburi) {
 6947: 	    $liburi=&declutter($liburi);
 6948:             $filename=$liburi;
 6949:         } else {
 6950: 	    &devalidate_cache_new('meta',$uri);
 6951: 	    undef(%metaentry);
 6952: 	}
 6953:         my %metathesekeys=();
 6954:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6955: 	my $metastring;
 6956: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 6957: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 6958: 	    $metastring = 
 6959: 		&Apache::lonnet::ssi_body($which,
 6960: 					  ('grade_target' => 'meta'));
 6961: 	    $cachetime = 1; # only want this cached in the child not long term
 6962: 	} elsif ($uri !~ m -^(editupload)/-) {
 6963: 	    my $file=&filelocation('',&clutter($filename));
 6964: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6965: 	    $metastring=&getfile($file);
 6966: 	}
 6967:         my $parser=HTML::LCParser->new(\$metastring);
 6968:         my $token;
 6969:         undef %metathesekeys;
 6970:         while ($token=$parser->get_token) {
 6971: 	    if ($token->[0] eq 'S') {
 6972: 		if (defined($token->[2]->{'package'})) {
 6973: #
 6974: # This is a package - get package info
 6975: #
 6976: 		    my $package=$token->[2]->{'package'};
 6977: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6978: 		    if (defined($token->[2]->{'id'})) { 
 6979: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6980: 		    }
 6981: 		    if ($metaentry{':packages'}) {
 6982: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6983: 		    } else {
 6984: 			$metaentry{':packages'}=$package.$keyroot;
 6985: 		    }
 6986: 		    foreach my $pack_entry (keys(%packagetab)) {
 6987: 			my $part=$keyroot;
 6988: 			$part=~s/^\_//;
 6989: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6990: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6991: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6992: 			    # ignore package.tab specified default values
 6993:                             # here &package_tab_default() will fetch those
 6994: 			    if ($subp eq 'default') { next; }
 6995: 			    my $value=$packagetab{$pack_entry};
 6996: 			    my $unikey;
 6997: 			    if ($pack =~ /_0$/) {
 6998: 				$unikey='parameter_0_'.$name;
 6999: 				$part=0;
 7000: 			    } else {
 7001: 				$unikey='parameter'.$keyroot.'_'.$name;
 7002: 			    }
 7003: 			    if ($subp eq 'display') {
 7004: 				$value.=' [Part: '.$part.']';
 7005: 			    }
 7006: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7007: 			    $metathesekeys{$unikey}=1;
 7008: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7009: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7010: 			    }
 7011: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7012: 				$metaentry{':'.$unikey}=
 7013: 				    $metaentry{':'.$unikey.'.default'};
 7014: 			    }
 7015: 			}
 7016: 		    }
 7017: 		} else {
 7018: #
 7019: # This is not a package - some other kind of start tag
 7020: #
 7021: 		    my $entry=$token->[1];
 7022: 		    my $unikey;
 7023: 		    if ($entry eq 'import') {
 7024: 			$unikey='';
 7025: 		    } else {
 7026: 			$unikey=$entry;
 7027: 		    }
 7028: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7029: 
 7030: 		    if (defined($token->[2]->{'id'})) { 
 7031: 			$unikey.='_'.$token->[2]->{'id'}; 
 7032: 		    }
 7033: 
 7034: 		    if ($entry eq 'import') {
 7035: #
 7036: # Importing a library here
 7037: #
 7038: 			if ($depthcount<20) {
 7039: 			    my $location=$parser->get_text('/import');
 7040: 			    my $dir=$filename;
 7041: 			    $dir=~s|[^/]*$||;
 7042: 			    $location=&filelocation($dir,$location);
 7043: 			    my $metadata = 
 7044: 				&metadata($uri,'keys', $location,$unikey,
 7045: 					  $depthcount+1);
 7046: 			    foreach my $meta (split(',',$metadata)) {
 7047: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7048: 				$metathesekeys{$meta}=1;
 7049: 			    }
 7050: 			}
 7051: 		    } else { 
 7052: 			
 7053: 			if (defined($token->[2]->{'name'})) { 
 7054: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7055: 			}
 7056: 			$metathesekeys{$unikey}=1;
 7057: 			foreach my $param (@{$token->[3]}) {
 7058: 			    $metaentry{':'.$unikey.'.'.$param} =
 7059: 				$token->[2]->{$param};
 7060: 			}
 7061: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7062: 			my $default=$metaentry{':'.$unikey.'.default'};
 7063: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7064: 		 # only ws inside the tag, and not in default, so use default
 7065: 		 # as value
 7066: 			    $metaentry{':'.$unikey}=$default;
 7067: 			} elsif ( $internaltext =~ /\S/ ) {
 7068: 		  # something interesting inside the tag
 7069: 			    $metaentry{':'.$unikey}=$internaltext;
 7070: 			} else {
 7071: 		  # no interesting values, don't set a default
 7072: 			}
 7073: # end of not-a-package not-a-library import
 7074: 		    }
 7075: # end of not-a-package start tag
 7076: 		}
 7077: # the next is the end of "start tag"
 7078: 	    }
 7079: 	}
 7080: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7081: 	$extension = lc($extension);
 7082: 	if ($extension eq 'htm') { $extension='html'; }
 7083: 
 7084: 	foreach my $key (keys(%packagetab)) {
 7085: 	    #no specific packages #how's our extension
 7086: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7087: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7088: 					 \%metathesekeys);
 7089: 	}
 7090: 
 7091: 	if (!exists($metaentry{':packages'})
 7092: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7093: 	    foreach my $key (keys(%packagetab)) {
 7094: 		#no specific packages well let's get default then
 7095: 		if ($key!~/^default&/) { next; }
 7096: 		&metadata_create_package_def($uri,$key,'default',
 7097: 					     \%metathesekeys);
 7098: 	    }
 7099: 	}
 7100: # are there custom rights to evaluate
 7101: 	if ($metaentry{':copyright'} eq 'custom') {
 7102: 
 7103:     #
 7104:     # Importing a rights file here
 7105:     #
 7106: 	    unless ($depthcount) {
 7107: 		my $location=$metaentry{':customdistributionfile'};
 7108: 		my $dir=$filename;
 7109: 		$dir=~s|[^/]*$||;
 7110: 		$location=&filelocation($dir,$location);
 7111: 		my $rights_metadata =
 7112: 		    &metadata($uri,'keys',$location,'_rights',
 7113: 			      $depthcount+1);
 7114: 		foreach my $rights (split(',',$rights_metadata)) {
 7115: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7116: 		    $metathesekeys{$rights}=1;
 7117: 		}
 7118: 	    }
 7119: 	}
 7120: 	# uniqifiy package listing
 7121: 	my %seen;
 7122: 	my @uniq_packages =
 7123: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7124: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7125: 
 7126: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7127: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7128: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7129: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7130: # this is the end of "was not already recently cached
 7131:     }
 7132:     return $metaentry{':'.$what};
 7133: }
 7134: 
 7135: sub metadata_create_package_def {
 7136:     my ($uri,$key,$package,$metathesekeys)=@_;
 7137:     my ($pack,$name,$subp)=split(/\&/,$key);
 7138:     if ($subp eq 'default') { next; }
 7139:     
 7140:     if (defined($metaentry{':packages'})) {
 7141: 	$metaentry{':packages'}.=','.$package;
 7142:     } else {
 7143: 	$metaentry{':packages'}=$package;
 7144:     }
 7145:     my $value=$packagetab{$key};
 7146:     my $unikey;
 7147:     $unikey='parameter_0_'.$name;
 7148:     $metaentry{':'.$unikey.'.part'}=0;
 7149:     $$metathesekeys{$unikey}=1;
 7150:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7151: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7152:     }
 7153:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7154: 	$metaentry{':'.$unikey}=
 7155: 	    $metaentry{':'.$unikey.'.default'};
 7156:     }
 7157: }
 7158: 
 7159: sub metadata_generate_part0 {
 7160:     my ($metadata,$metacache,$uri) = @_;
 7161:     my %allnames;
 7162:     foreach my $metakey (keys(%$metadata)) {
 7163: 	if ($metakey=~/^parameter\_(.*)/) {
 7164: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7165: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7166: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7167: 	    $allnames{$name}=$part;
 7168: 	  }
 7169: 	}
 7170:     }
 7171:     foreach my $name (keys(%allnames)) {
 7172:       $$metadata{"parameter_0_$name"}=1;
 7173:       my $key=":parameter_0_$name";
 7174:       $$metacache{"$key.part"}='0';
 7175:       $$metacache{"$key.name"}=$name;
 7176:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7177: 					   $allnames{$name}.'_'.$name.
 7178: 					   '.type'};
 7179:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7180: 			     '.display'};
 7181:       my $expr='[Part: '.$allnames{$name}.']';
 7182:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7183:       $$metacache{"$key.display"}=$olddis;
 7184:     }
 7185: }
 7186: 
 7187: # ------------------------------------------------------ Devalidate title cache
 7188: 
 7189: sub devalidate_title_cache {
 7190:     my ($url)=@_;
 7191:     if (!$env{'request.course.id'}) { return; }
 7192:     my $symb=&symbread($url);
 7193:     if (!$symb) { return; }
 7194:     my $key=$env{'request.course.id'}."\0".$symb;
 7195:     &devalidate_cache_new('title',$key);
 7196: }
 7197: 
 7198: # ------------------------------------------------- Get the title of a resource
 7199: 
 7200: sub gettitle {
 7201:     my $urlsymb=shift;
 7202:     my $symb=&symbread($urlsymb);
 7203:     if ($symb) {
 7204: 	my $key=$env{'request.course.id'}."\0".$symb;
 7205: 	my ($result,$cached)=&is_cached_new('title',$key);
 7206: 	if (defined($cached)) { 
 7207: 	    return $result;
 7208: 	}
 7209: 	my ($map,$resid,$url)=&decode_symb($symb);
 7210: 	my $title='';
 7211: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7212: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7213: 	} else {
 7214: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7215: 		    &GDBM_READER(),0640)) {
 7216: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7217: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7218: 		untie(%bighash);
 7219: 	    }
 7220: 	}
 7221: 	$title=~s/\&colon\;/\:/gs;
 7222: 	if ($title) {
 7223: 	    return &do_cache_new('title',$key,$title,600);
 7224: 	}
 7225: 	$urlsymb=$url;
 7226:     }
 7227:     my $title=&metadata($urlsymb,'title');
 7228:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7229:     return $title;
 7230: }
 7231: 
 7232: sub get_slot {
 7233:     my ($which,$cnum,$cdom)=@_;
 7234:     if (!$cnum || !$cdom) {
 7235: 	(undef,my $courseid)=&whichuser();
 7236: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7237: 	$cnum=$env{'course.'.$courseid.'.num'};
 7238:     }
 7239:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7240:     my %slotinfo;
 7241:     if (exists($remembered{$key})) {
 7242: 	$slotinfo{$which} = $remembered{$key};
 7243:     } else {
 7244: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7245: 	&Apache::lonhomework::showhash(%slotinfo);
 7246: 	my ($tmp)=keys(%slotinfo);
 7247: 	if ($tmp=~/^error:/) { return (); }
 7248: 	$remembered{$key} = $slotinfo{$which};
 7249:     }
 7250:     if (ref($slotinfo{$which}) eq 'HASH') {
 7251: 	return %{$slotinfo{$which}};
 7252:     }
 7253:     return $slotinfo{$which};
 7254: }
 7255: # ------------------------------------------------- Update symbolic store links
 7256: 
 7257: sub symblist {
 7258:     my ($mapname,%newhash)=@_;
 7259:     $mapname=&deversion(&declutter($mapname));
 7260:     my %hash;
 7261:     if (($env{'request.course.fn'}) && (%newhash)) {
 7262:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7263:                       &GDBM_WRCREAT(),0640)) {
 7264: 	    foreach my $url (keys %newhash) {
 7265: 		next if ($url eq 'last_known'
 7266: 			 && $env{'form.no_update_last_known'});
 7267: 		$hash{declutter($url)}=&encode_symb($mapname,
 7268: 						    $newhash{$url}->[1],
 7269: 						    $newhash{$url}->[0]);
 7270:             }
 7271:             if (untie(%hash)) {
 7272: 		return 'ok';
 7273:             }
 7274:         }
 7275:     }
 7276:     return 'error';
 7277: }
 7278: 
 7279: # --------------------------------------------------------------- Verify a symb
 7280: 
 7281: sub symbverify {
 7282:     my ($symb,$thisurl)=@_;
 7283:     my $thisfn=$thisurl;
 7284:     $thisfn=&declutter($thisfn);
 7285: # direct jump to resource in page or to a sequence - will construct own symbs
 7286:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7287: # check URL part
 7288:     my ($map,$resid,$url)=&decode_symb($symb);
 7289: 
 7290:     unless ($url eq $thisfn) { return 0; }
 7291: 
 7292:     $symb=&symbclean($symb);
 7293:     $thisurl=&deversion($thisurl);
 7294:     $thisfn=&deversion($thisfn);
 7295: 
 7296:     my %bighash;
 7297:     my $okay=0;
 7298: 
 7299:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7300:                             &GDBM_READER(),0640)) {
 7301:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7302:         unless ($ids) { 
 7303:            $ids=$bighash{'ids_/'.$thisurl};
 7304:         }
 7305:         if ($ids) {
 7306: # ------------------------------------------------------------------- Has ID(s)
 7307: 	    foreach my $id (split(/\,/,$ids)) {
 7308: 	       my ($mapid,$resid)=split(/\./,$id);
 7309:                if (
 7310:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7311:    eq $symb) { 
 7312: 		   if (($env{'request.role.adv'}) ||
 7313: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7314: 		       $okay=1; 
 7315: 		   }
 7316: 	       }
 7317: 	   }
 7318:         }
 7319: 	untie(%bighash);
 7320:     }
 7321:     return $okay;
 7322: }
 7323: 
 7324: # --------------------------------------------------------------- Clean-up symb
 7325: 
 7326: sub symbclean {
 7327:     my $symb=shift;
 7328:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7329: # remove version from map
 7330:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7331: 
 7332: # remove version from URL
 7333:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7334: 
 7335: # remove wrapper
 7336: 
 7337:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7338:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7339:     return $symb;
 7340: }
 7341: 
 7342: # ---------------------------------------------- Split symb to find map and url
 7343: 
 7344: sub encode_symb {
 7345:     my ($map,$resid,$url)=@_;
 7346:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7347: }
 7348: 
 7349: sub decode_symb {
 7350:     my $symb=shift;
 7351:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7352:     my ($map,$resid,$url)=split(/___/,$symb);
 7353:     return (&fixversion($map),$resid,&fixversion($url));
 7354: }
 7355: 
 7356: sub fixversion {
 7357:     my $fn=shift;
 7358:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7359:     my %bighash;
 7360:     my $uri=&clutter($fn);
 7361:     my $key=$env{'request.course.id'}.'_'.$uri;
 7362: # is this cached?
 7363:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7364:     if (defined($cached)) { return $result; }
 7365: # unfortunately not cached, or expired
 7366:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7367: 	    &GDBM_READER(),0640)) {
 7368:  	if ($bighash{'version_'.$uri}) {
 7369:  	    my $version=$bighash{'version_'.$uri};
 7370:  	    unless (($version eq 'mostrecent') || 
 7371: 		    ($version==&getversion($uri))) {
 7372:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7373:  	    }
 7374:  	}
 7375:  	untie %bighash;
 7376:     }
 7377:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7378: }
 7379: 
 7380: sub deversion {
 7381:     my $url=shift;
 7382:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7383:     return $url;
 7384: }
 7385: 
 7386: # ------------------------------------------------------ Return symb list entry
 7387: 
 7388: sub symbread {
 7389:     my ($thisfn,$donotrecurse)=@_;
 7390:     my $cache_str='request.symbread.cached.'.$thisfn;
 7391:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7392: # no filename provided? try from environment
 7393:     unless ($thisfn) {
 7394:         if ($env{'request.symb'}) {
 7395: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7396: 	}
 7397: 	$thisfn=$env{'request.filename'};
 7398:     }
 7399:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7400: # is that filename actually a symb? Verify, clean, and return
 7401:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7402: 	if (&symbverify($thisfn,$1)) {
 7403: 	    return $env{$cache_str}=&symbclean($thisfn);
 7404: 	}
 7405:     }
 7406:     $thisfn=declutter($thisfn);
 7407:     my %hash;
 7408:     my %bighash;
 7409:     my $syval='';
 7410:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7411:         my $targetfn = $thisfn;
 7412:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7413:             $targetfn = 'adm/wrapper/'.$thisfn;
 7414:         }
 7415: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7416: 	    $targetfn=$1;
 7417: 	}
 7418:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7419:                       &GDBM_READER(),0640)) {
 7420: 	    $syval=$hash{$targetfn};
 7421:             untie(%hash);
 7422:         }
 7423: # ---------------------------------------------------------- There was an entry
 7424:         if ($syval) {
 7425: 	    #unless ($syval=~/\_\d+$/) {
 7426: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7427: 		    #&appenv('request.ambiguous' => $thisfn);
 7428: 		    #return $env{$cache_str}='';
 7429: 		#}    
 7430: 		#$syval.=$1;
 7431: 	    #}
 7432:         } else {
 7433: # ------------------------------------------------------- Was not in symb table
 7434:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7435:                             &GDBM_READER(),0640)) {
 7436: # ---------------------------------------------- Get ID(s) for current resource
 7437:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7438:               unless ($ids) { 
 7439:                  $ids=$bighash{'ids_/'.$thisfn};
 7440:               }
 7441:               unless ($ids) {
 7442: # alias?
 7443: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7444:               }
 7445:               if ($ids) {
 7446: # ------------------------------------------------------------------- Has ID(s)
 7447:                  my @possibilities=split(/\,/,$ids);
 7448:                  if ($#possibilities==0) {
 7449: # ----------------------------------------------- There is only one possibility
 7450: 		     my ($mapid,$resid)=split(/\./,$ids);
 7451: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7452: 						    $resid,$thisfn);
 7453:                  } elsif (!$donotrecurse) {
 7454: # ------------------------------------------ There is more than one possibility
 7455:                      my $realpossible=0;
 7456:                      foreach my $id (@possibilities) {
 7457: 			 my $file=$bighash{'src_'.$id};
 7458:                          if (&allowed('bre',$file)) {
 7459:          		    my ($mapid,$resid)=split(/\./,$id);
 7460:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7461: 				$realpossible++;
 7462:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7463: 						    $resid,$thisfn);
 7464:                             }
 7465: 			 }
 7466:                      }
 7467: 		     if ($realpossible!=1) { $syval=''; }
 7468:                  } else {
 7469:                      $syval='';
 7470:                  }
 7471: 	      }
 7472:               untie(%bighash)
 7473:            }
 7474:         }
 7475:         if ($syval) {
 7476: 	    return $env{$cache_str}=$syval;
 7477:         }
 7478:     }
 7479:     &appenv('request.ambiguous' => $thisfn);
 7480:     return $env{$cache_str}='';
 7481: }
 7482: 
 7483: # ---------------------------------------------------------- Return random seed
 7484: 
 7485: sub numval {
 7486:     my $txt=shift;
 7487:     $txt=~tr/A-J/0-9/;
 7488:     $txt=~tr/a-j/0-9/;
 7489:     $txt=~tr/K-T/0-9/;
 7490:     $txt=~tr/k-t/0-9/;
 7491:     $txt=~tr/U-Z/0-5/;
 7492:     $txt=~tr/u-z/0-5/;
 7493:     $txt=~s/\D//g;
 7494:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7495:     return int($txt);
 7496: }
 7497: 
 7498: sub numval2 {
 7499:     my $txt=shift;
 7500:     $txt=~tr/A-J/0-9/;
 7501:     $txt=~tr/a-j/0-9/;
 7502:     $txt=~tr/K-T/0-9/;
 7503:     $txt=~tr/k-t/0-9/;
 7504:     $txt=~tr/U-Z/0-5/;
 7505:     $txt=~tr/u-z/0-5/;
 7506:     $txt=~s/\D//g;
 7507:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7508:     my $total;
 7509:     foreach my $val (@txts) { $total+=$val; }
 7510:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7511:     return int($total);
 7512: }
 7513: 
 7514: sub numval3 {
 7515:     use integer;
 7516:     my $txt=shift;
 7517:     $txt=~tr/A-J/0-9/;
 7518:     $txt=~tr/a-j/0-9/;
 7519:     $txt=~tr/K-T/0-9/;
 7520:     $txt=~tr/k-t/0-9/;
 7521:     $txt=~tr/U-Z/0-5/;
 7522:     $txt=~tr/u-z/0-5/;
 7523:     $txt=~s/\D//g;
 7524:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7525:     my $total;
 7526:     foreach my $val (@txts) { $total+=$val; }
 7527:     if ($_64bit) { $total=(($total<<32)>>32); }
 7528:     return $total;
 7529: }
 7530: 
 7531: sub digest {
 7532:     my ($data)=@_;
 7533:     my $digest=&Digest::MD5::md5($data);
 7534:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7535:     my ($e,$f);
 7536:     {
 7537:         use integer;
 7538:         $e=($a+$b);
 7539:         $f=($c+$d);
 7540:         if ($_64bit) {
 7541:             $e=(($e<<32)>>32);
 7542:             $f=(($f<<32)>>32);
 7543:         }
 7544:     }
 7545:     if (wantarray) {
 7546: 	return ($e,$f);
 7547:     } else {
 7548: 	my $g;
 7549: 	{
 7550: 	    use integer;
 7551: 	    $g=($e+$f);
 7552: 	    if ($_64bit) {
 7553: 		$g=(($g<<32)>>32);
 7554: 	    }
 7555: 	}
 7556: 	return $g;
 7557:     }
 7558: }
 7559: 
 7560: sub latest_rnd_algorithm_id {
 7561:     return '64bit5';
 7562: }
 7563: 
 7564: sub get_rand_alg {
 7565:     my ($courseid)=@_;
 7566:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7567:     if ($courseid) {
 7568: 	return $env{"course.$courseid.rndseed"};
 7569:     }
 7570:     return &latest_rnd_algorithm_id();
 7571: }
 7572: 
 7573: sub validCODE {
 7574:     my ($CODE)=@_;
 7575:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7576:     return 0;
 7577: }
 7578: 
 7579: sub getCODE {
 7580:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7581:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7582: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7583: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7584: 	return $Apache::lonhomework::history{'resource.CODE'};
 7585:     }
 7586:     return undef;
 7587: }
 7588: 
 7589: sub rndseed {
 7590:     my ($symb,$courseid,$domain,$username)=@_;
 7591:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7592:     if (!defined($symb)) {
 7593: 	unless ($symb=$wsymb) { return time; }
 7594:     }
 7595:     if (!$courseid) { $courseid=$wcourseid; }
 7596:     if (!$domain) { $domain=$wdomain; }
 7597:     if (!$username) { $username=$wusername }
 7598:     my $which=&get_rand_alg();
 7599: 
 7600:     if (defined(&getCODE())) {
 7601: 	if ($which eq '64bit5') {
 7602: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7603: 	} elsif ($which eq '64bit4') {
 7604: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7605: 	} else {
 7606: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7607: 	}
 7608:     } elsif ($which eq '64bit5') {
 7609: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7610:     } elsif ($which eq '64bit4') {
 7611: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7612:     } elsif ($which eq '64bit3') {
 7613: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7614:     } elsif ($which eq '64bit2') {
 7615: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7616:     } elsif ($which eq '64bit') {
 7617: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7618:     }
 7619:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7620: }
 7621: 
 7622: sub rndseed_32bit {
 7623:     my ($symb,$courseid,$domain,$username)=@_;
 7624:     {
 7625: 	use integer;
 7626: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7627: 	my $symbseed=numval($symb) << 22;
 7628: 	my $namechck=unpack("%32C*",$username) << 17;
 7629: 	my $nameseed=numval($username) << 12;
 7630: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7631: 	my $courseseed=unpack("%32C*",$courseid);
 7632: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7633: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7634: 	#&logthis("rndseed :$num:$symb");
 7635: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7636: 	return $num;
 7637:     }
 7638: }
 7639: 
 7640: sub rndseed_64bit {
 7641:     my ($symb,$courseid,$domain,$username)=@_;
 7642:     {
 7643: 	use integer;
 7644: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7645: 	my $symbseed=numval($symb) << 10;
 7646: 	my $namechck=unpack("%32S*",$username);
 7647: 	
 7648: 	my $nameseed=numval($username) << 21;
 7649: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7650: 	my $courseseed=unpack("%32S*",$courseid);
 7651: 	
 7652: 	my $num1=$symbchck+$symbseed+$namechck;
 7653: 	my $num2=$nameseed+$domainseed+$courseseed;
 7654: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7655: 	#&logthis("rndseed :$num:$symb");
 7656: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7657: 	return "$num1,$num2";
 7658:     }
 7659: }
 7660: 
 7661: sub rndseed_64bit2 {
 7662:     my ($symb,$courseid,$domain,$username)=@_;
 7663:     {
 7664: 	use integer;
 7665: 	# strings need to be an even # of cahracters long, it it is odd the
 7666:         # last characters gets thrown away
 7667: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7668: 	my $symbseed=numval($symb) << 10;
 7669: 	my $namechck=unpack("%32S*",$username.' ');
 7670: 	
 7671: 	my $nameseed=numval($username) << 21;
 7672: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7673: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7674: 	
 7675: 	my $num1=$symbchck+$symbseed+$namechck;
 7676: 	my $num2=$nameseed+$domainseed+$courseseed;
 7677: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7678: 	#&logthis("rndseed :$num:$symb");
 7679: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7680: 	return "$num1,$num2";
 7681:     }
 7682: }
 7683: 
 7684: sub rndseed_64bit3 {
 7685:     my ($symb,$courseid,$domain,$username)=@_;
 7686:     {
 7687: 	use integer;
 7688: 	# strings need to be an even # of cahracters long, it it is odd the
 7689:         # last characters gets thrown away
 7690: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7691: 	my $symbseed=numval2($symb) << 10;
 7692: 	my $namechck=unpack("%32S*",$username.' ');
 7693: 	
 7694: 	my $nameseed=numval2($username) << 21;
 7695: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7696: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7697: 	
 7698: 	my $num1=$symbchck+$symbseed+$namechck;
 7699: 	my $num2=$nameseed+$domainseed+$courseseed;
 7700: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7701: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7702: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7703: 	
 7704: 	return "$num1:$num2";
 7705:     }
 7706: }
 7707: 
 7708: sub rndseed_64bit4 {
 7709:     my ($symb,$courseid,$domain,$username)=@_;
 7710:     {
 7711: 	use integer;
 7712: 	# strings need to be an even # of cahracters long, it it is odd the
 7713:         # last characters gets thrown away
 7714: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7715: 	my $symbseed=numval3($symb) << 10;
 7716: 	my $namechck=unpack("%32S*",$username.' ');
 7717: 	
 7718: 	my $nameseed=numval3($username) << 21;
 7719: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7720: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7721: 	
 7722: 	my $num1=$symbchck+$symbseed+$namechck;
 7723: 	my $num2=$nameseed+$domainseed+$courseseed;
 7724: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7725: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7726: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7727: 	
 7728: 	return "$num1:$num2";
 7729:     }
 7730: }
 7731: 
 7732: sub rndseed_64bit5 {
 7733:     my ($symb,$courseid,$domain,$username)=@_;
 7734:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7735:     return "$num1:$num2";
 7736: }
 7737: 
 7738: sub rndseed_CODE_64bit {
 7739:     my ($symb,$courseid,$domain,$username)=@_;
 7740:     {
 7741: 	use integer;
 7742: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7743: 	my $symbseed=numval2($symb);
 7744: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7745: 	my $CODEseed=numval(&getCODE());
 7746: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7747: 	my $num1=$symbseed+$CODEchck;
 7748: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7749: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7750: 	#&logthis("rndseed :$num1:$num2:$symb");
 7751: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7752: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7753: 	return "$num1:$num2";
 7754:     }
 7755: }
 7756: 
 7757: sub rndseed_CODE_64bit4 {
 7758:     my ($symb,$courseid,$domain,$username)=@_;
 7759:     {
 7760: 	use integer;
 7761: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7762: 	my $symbseed=numval3($symb);
 7763: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7764: 	my $CODEseed=numval3(&getCODE());
 7765: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7766: 	my $num1=$symbseed+$CODEchck;
 7767: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7768: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7769: 	#&logthis("rndseed :$num1:$num2:$symb");
 7770: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7771: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7772: 	return "$num1:$num2";
 7773:     }
 7774: }
 7775: 
 7776: sub rndseed_CODE_64bit5 {
 7777:     my ($symb,$courseid,$domain,$username)=@_;
 7778:     my $code = &getCODE();
 7779:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7780:     return "$num1:$num2";
 7781: }
 7782: 
 7783: sub setup_random_from_rndseed {
 7784:     my ($rndseed)=@_;
 7785:     if ($rndseed =~/([,:])/) {
 7786: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7787: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7788:     } else {
 7789: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7790:     }
 7791: }
 7792: 
 7793: sub latest_receipt_algorithm_id {
 7794:     return 'receipt3';
 7795: }
 7796: 
 7797: sub recunique {
 7798:     my $fucourseid=shift;
 7799:     my $unique;
 7800:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7801: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7802: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7803:     } else {
 7804: 	$unique=$perlvar{'lonReceipt'};
 7805:     }
 7806:     return unpack("%32C*",$unique);
 7807: }
 7808: 
 7809: sub recprefix {
 7810:     my $fucourseid=shift;
 7811:     my $prefix;
 7812:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7813: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7814: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7815:     } else {
 7816: 	$prefix=$perlvar{'lonHostID'};
 7817:     }
 7818:     return unpack("%32C*",$prefix);
 7819: }
 7820: 
 7821: sub ireceipt {
 7822:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7823: 
 7824:     my $return =&recprefix($fucourseid).'-';
 7825: 
 7826:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7827: 	$env{'request.state'} eq 'construct') {
 7828: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7829: 	return $return;
 7830:     }
 7831: 
 7832:     my $cuname=unpack("%32C*",$funame);
 7833:     my $cudom=unpack("%32C*",$fudom);
 7834:     my $cucourseid=unpack("%32C*",$fucourseid);
 7835:     my $cusymb=unpack("%32C*",$fusymb);
 7836:     my $cunique=&recunique($fucourseid);
 7837:     my $cpart=unpack("%32S*",$part);
 7838:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7839: 
 7840: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7841: 			       
 7842: 	$return.= ($cunique%$cuname+
 7843: 		   $cunique%$cudom+
 7844: 		   $cusymb%$cuname+
 7845: 		   $cusymb%$cudom+
 7846: 		   $cucourseid%$cuname+
 7847: 		   $cucourseid%$cudom+
 7848: 		   $cpart%$cuname+
 7849: 		   $cpart%$cudom);
 7850:     } else {
 7851: 	$return.= ($cunique%$cuname+
 7852: 		   $cunique%$cudom+
 7853: 		   $cusymb%$cuname+
 7854: 		   $cusymb%$cudom+
 7855: 		   $cucourseid%$cuname+
 7856: 		   $cucourseid%$cudom);
 7857:     }
 7858:     return $return;
 7859: }
 7860: 
 7861: sub receipt {
 7862:     my ($part)=@_;
 7863:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7864:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7865: }
 7866: 
 7867: sub whichuser {
 7868:     my ($passedsymb)=@_;
 7869:     my ($symb,$courseid,$domain,$name,$publicuser);
 7870:     if (defined($env{'form.grade_symb'})) {
 7871: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7872: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7873: 	if (!$allowed &&
 7874: 	    exists($env{'request.course.sec'}) &&
 7875: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7876: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7877: 			      '/'.$env{'request.course.sec'});
 7878: 	}
 7879: 	if ($allowed) {
 7880: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7881: 	    $courseid=$tmp_courseid;
 7882: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7883: 	    ($name)=&get_env_multiple('form.grade_username');
 7884: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7885: 	}
 7886:     }
 7887:     if (!$passedsymb) {
 7888: 	$symb=&symbread();
 7889:     } else {
 7890: 	$symb=$passedsymb;
 7891:     }
 7892:     $courseid=$env{'request.course.id'};
 7893:     $domain=$env{'user.domain'};
 7894:     $name=$env{'user.name'};
 7895:     if ($name eq 'public' && $domain eq 'public') {
 7896: 	if (!defined($env{'form.username'})) {
 7897: 	    $env{'form.username'}.=time.rand(10000000);
 7898: 	}
 7899: 	$name.=$env{'form.username'};
 7900:     }
 7901:     return ($symb,$courseid,$domain,$name,$publicuser);
 7902: 
 7903: }
 7904: 
 7905: # ------------------------------------------------------------ Serves up a file
 7906: # returns either the contents of the file or 
 7907: # -1 if the file doesn't exist
 7908: #
 7909: # if the target is a file that was uploaded via DOCS, 
 7910: # a check will be made to see if a current copy exists on the local server,
 7911: # if it does this will be served, otherwise a copy will be retrieved from
 7912: # the home server for the course and stored in /home/httpd/html/userfiles on
 7913: # the local server.   
 7914: 
 7915: sub getfile {
 7916:     my ($file) = @_;
 7917:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7918:     &repcopy($file);
 7919:     return &readfile($file);
 7920: }
 7921: 
 7922: sub repcopy_userfile {
 7923:     my ($file)=@_;
 7924:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7925:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7926:     my ($cdom,$cnum,$filename) = 
 7927: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7928:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7929:     if (-e "$file") {
 7930: # we already have a local copy, check it out
 7931: 	my @fileinfo = stat($file);
 7932: 	my $rtncode;
 7933: 	my $info;
 7934: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7935: 	if ($lwpresp ne 'ok') {
 7936: # there is no such file anymore, even though we had a local copy
 7937: 	    if ($rtncode eq '404') {
 7938: 		unlink($file);
 7939: 	    }
 7940: 	    return -1;
 7941: 	}
 7942: 	if ($info < $fileinfo[9]) {
 7943: # nice, the file we have is up-to-date, just say okay
 7944: 	    return 'ok';
 7945: 	} else {
 7946: # the file is outdated, get rid of it
 7947: 	    unlink($file);
 7948: 	}
 7949:     }
 7950: # one way or the other, at this point, we don't have the file
 7951: # construct the correct path for the file
 7952:     my @parts = ($cdom,$cnum); 
 7953:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7954: 	push @parts, split(/\//,$1);
 7955:     }
 7956:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7957:     foreach my $part (@parts) {
 7958: 	$path .= '/'.$part;
 7959: 	if (!-e $path) {
 7960: 	    mkdir($path,0770);
 7961: 	}
 7962:     }
 7963: # now the path exists for sure
 7964: # get a user agent
 7965:     my $ua=new LWP::UserAgent;
 7966:     my $transferfile=$file.'.in.transfer';
 7967: # FIXME: this should flock
 7968:     if (-e $transferfile) { return 'ok'; }
 7969:     my $request;
 7970:     $uri=~s/^\///;
 7971:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7972:     my $response=$ua->request($request,$transferfile);
 7973: # did it work?
 7974:     if ($response->is_error()) {
 7975: 	unlink($transferfile);
 7976: 	&logthis("Userfile repcopy failed for $uri");
 7977: 	return -1;
 7978:     }
 7979: # worked, rename the transfer file
 7980:     rename($transferfile,$file);
 7981:     return 'ok';
 7982: }
 7983: 
 7984: sub tokenwrapper {
 7985:     my $uri=shift;
 7986:     $uri=~s|^http\://([^/]+)||;
 7987:     $uri=~s|^/||;
 7988:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7989:     my $token=$1;
 7990:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7991:     if ($udom && $uname && $file) {
 7992: 	$file=~s|(\?\.*)*$||;
 7993:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7994:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7995:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7996:                                '&tokenissued='.$perlvar{'lonHostID'};
 7997:     } else {
 7998:         return '/adm/notfound.html';
 7999:     }
 8000: }
 8001: 
 8002: # call with reqtype HEAD: get last modification time
 8003: # call with reqtype GET: get the file contents
 8004: # Do not call this with reqtype GET for large files! It loads everything into memory
 8005: #
 8006: sub getuploaded {
 8007:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8008:     $uri=~s/^\///;
 8009:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 8010:     my $ua=new LWP::UserAgent;
 8011:     my $request=new HTTP::Request($reqtype,$uri);
 8012:     my $response=$ua->request($request);
 8013:     $$rtncode = $response->code;
 8014:     if (! $response->is_success()) {
 8015: 	return 'failed';
 8016:     }      
 8017:     if ($reqtype eq 'HEAD') {
 8018: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8019:     } elsif ($reqtype eq 'GET') {
 8020: 	$$info = $response->content;
 8021:     }
 8022:     return 'ok';
 8023: }
 8024: 
 8025: sub readfile {
 8026:     my $file = shift;
 8027:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8028:     my $fh;
 8029:     open($fh,"<$file");
 8030:     my $a='';
 8031:     while (my $line = <$fh>) { $a .= $line; }
 8032:     return $a;
 8033: }
 8034: 
 8035: sub filelocation {
 8036:     my ($dir,$file) = @_;
 8037:     my $location;
 8038:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8039: 
 8040:     if ($file =~ m-^/adm/-) {
 8041: 	$file=~s-^/adm/wrapper/-/-;
 8042: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8043:     }
 8044: 
 8045:     if ($file=~m:^/~:) { # is a contruction space reference
 8046:         $location = $file;
 8047:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8048:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8049: 	# is a correct contruction space reference
 8050:         $location = $file;
 8051:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8052:         my ($udom,$uname,$filename)=
 8053:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8054:         my $home=&homeserver($uname,$udom);
 8055:         my $is_me=0;
 8056:         my @ids=&current_machine_ids();
 8057:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8058:         if ($is_me) {
 8059:   	    $location=&propath($udom,$uname).
 8060:   	      '/userfiles/'.$filename;
 8061:         } else {
 8062:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8063:   	      $udom.'/'.$uname.'/'.$filename;
 8064:         }
 8065:     } elsif ($file =~ m-^/adm/-) {
 8066: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8067:     } else {
 8068:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8069:         $file=~s:^/res/:/:;
 8070:         if ( !( $file =~ m:^/:) ) {
 8071:             $location = $dir. '/'.$file;
 8072:         } else {
 8073:             $location = '/home/httpd/html/res'.$file;
 8074:         }
 8075:     }
 8076:     $location=~s://+:/:g; # remove duplicate /
 8077:     while ($location=~m{/\.\./}) {
 8078: 	if ($location =~ m{/[^/]+/\.\./}) {
 8079: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8080: 	} else {
 8081: 	    $location=~ s{/\.\./}{/}g;
 8082: 	}
 8083:     } #remove dir/..
 8084:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8085:     return $location;
 8086: }
 8087: 
 8088: sub hreflocation {
 8089:     my ($dir,$file)=@_;
 8090:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 8091: 	$file=filelocation($dir,$file);
 8092:     } elsif ($file=~m-^/adm/-) {
 8093: 	$file=~s-^/adm/wrapper/-/-;
 8094: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8095:     }
 8096:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8097: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8098:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8099: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8100:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8101: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8102: 	    -/uploaded/$1/$2/-x;
 8103:     }
 8104:     if ($file=~ m{^/userfiles/}) {
 8105: 	$file =~ s{^/userfiles/}{/uploaded/};
 8106:     }
 8107:     return $file;
 8108: }
 8109: 
 8110: sub current_machine_domains {
 8111:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8112: }
 8113: 
 8114: sub machine_domains {
 8115:     my ($hostname) = @_;
 8116:     my @domains;
 8117:     my %hostname = &all_hostnames();
 8118:     while( my($id, $name) = each(%hostname)) {
 8119: #	&logthis("-$id-$name-$hostname-");
 8120: 	if ($hostname eq $name) {
 8121: 	    push(@domains,&host_domain($id));
 8122: 	}
 8123:     }
 8124:     return @domains;
 8125: }
 8126: 
 8127: sub current_machine_ids {
 8128:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8129: }
 8130: 
 8131: sub machine_ids {
 8132:     my ($hostname) = @_;
 8133:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8134:     my @ids;
 8135:     my %name_to_host = &all_names();
 8136:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8137: 	return @{ $name_to_host{$hostname} };
 8138:     }
 8139:     return;
 8140: }
 8141: 
 8142: sub additional_machine_domains {
 8143:     my @domains;
 8144:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8145:     while( my $line = <$fh>) {
 8146:         $line =~ s/\s//g;
 8147:         push(@domains,$line);
 8148:     }
 8149:     return @domains;
 8150: }
 8151: 
 8152: sub default_login_domain {
 8153:     my $domain = $perlvar{'lonDefDomain'};
 8154:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8155:     foreach my $posdom (&current_machine_domains(),
 8156:                         &additional_machine_domains()) {
 8157:         if (lc($posdom) eq lc($testdomain)) {
 8158:             $domain=$posdom;
 8159:             last;
 8160:         }
 8161:     }
 8162:     return $domain;
 8163: }
 8164: 
 8165: # ------------------------------------------------------------- Declutters URLs
 8166: 
 8167: sub declutter {
 8168:     my $thisfn=shift;
 8169:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8170:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8171:     $thisfn=~s/^\///;
 8172:     $thisfn=~s|^adm/wrapper/||;
 8173:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8174:     $thisfn=~s/^res\///;
 8175:     $thisfn=~s/\?.+$//;
 8176:     return $thisfn;
 8177: }
 8178: 
 8179: # ------------------------------------------------------------- Clutter up URLs
 8180: 
 8181: sub clutter {
 8182:     my $thisfn='/'.&declutter(shift);
 8183:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8184: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8185:        $thisfn='/res'.$thisfn; 
 8186:     }
 8187:     if ($thisfn !~m|/adm|) {
 8188: 	if ($thisfn =~ m|/ext/|) {
 8189: 	    $thisfn='/adm/wrapper'.$thisfn;
 8190: 	} else {
 8191: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8192: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8193: 	    if ($embstyle eq 'ssi'
 8194: 		|| ($embstyle eq 'hdn')
 8195: 		|| ($embstyle eq 'rat')
 8196: 		|| ($embstyle eq 'prv')
 8197: 		|| ($embstyle eq 'ign')) {
 8198: 		#do nothing with these
 8199: 	    } elsif (($embstyle eq 'img') 
 8200: 		|| ($embstyle eq 'emb')
 8201: 		|| ($embstyle eq 'wrp')) {
 8202: 		$thisfn='/adm/wrapper'.$thisfn;
 8203: 	    } elsif ($embstyle eq 'unk'
 8204: 		     && $thisfn!~/\.(sequence|page)$/) {
 8205: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8206: 	    } else {
 8207: #		&logthis("Got a blank emb style");
 8208: 	    }
 8209: 	}
 8210:     }
 8211:     return $thisfn;
 8212: }
 8213: 
 8214: sub clutter_with_no_wrapper {
 8215:     my $uri = &clutter(shift);
 8216:     if ($uri =~ m-^/adm/-) {
 8217: 	$uri =~ s-^/adm/wrapper/-/-;
 8218: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8219:     }
 8220:     return $uri;
 8221: }
 8222: 
 8223: sub freeze_escape {
 8224:     my ($value)=@_;
 8225:     if (ref($value)) {
 8226: 	$value=&nfreeze($value);
 8227: 	return '__FROZEN__'.&escape($value);
 8228:     }
 8229:     return &escape($value);
 8230: }
 8231: 
 8232: 
 8233: sub thaw_unescape {
 8234:     my ($value)=@_;
 8235:     if ($value =~ /^__FROZEN__/) {
 8236: 	substr($value,0,10,undef);
 8237: 	$value=&unescape($value);
 8238: 	return &thaw($value);
 8239:     }
 8240:     return &unescape($value);
 8241: }
 8242: 
 8243: sub correct_line_ends {
 8244:     my ($result)=@_;
 8245:     $$result =~s/\r\n/\n/mg;
 8246:     $$result =~s/\r/\n/mg;
 8247: }
 8248: # ================================================================ Main Program
 8249: 
 8250: sub goodbye {
 8251:    &logthis("Starting Shut down");
 8252: #not converted to using infrastruture and probably shouldn't be
 8253:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8254: #converted
 8255: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8256:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8257: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8258: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8259: #1.1 only
 8260: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8261: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8262: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8263: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8264:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8265:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8266:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8267:    &flushcourselogs();
 8268:    &logthis("Shutting down");
 8269: }
 8270: 
 8271: sub get_dns {
 8272:     my ($url,$func,$ignore_cache) = @_;
 8273:     if (!$ignore_cache) {
 8274: 	my ($content,$cached)=
 8275: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8276: 	if ($cached) {
 8277: 	    &$func($content);
 8278: 	    return;
 8279: 	}
 8280:     }
 8281: 
 8282:     my %alldns;
 8283:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8284:     foreach my $dns (<$config>) {
 8285: 	next if ($dns !~ /^\^(\S*)/x);
 8286: 	$alldns{$1} = 1;
 8287:     }
 8288:     while (%alldns) {
 8289: 	my ($dns) = keys(%alldns);
 8290: 	delete($alldns{$dns});
 8291: 	my $ua=new LWP::UserAgent;
 8292: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 8293: 	my $response=$ua->request($request);
 8294: 	next if ($response->is_error());
 8295: 	my @content = split("\n",$response->content);
 8296: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8297: 	&$func(\@content);
 8298: 	return;
 8299:     }
 8300:     close($config);
 8301:     my $which = (split('/',$url))[3];
 8302:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8303:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8304:     my @content = <$config>;
 8305:     &$func(\@content);
 8306:     return;
 8307: }
 8308: # ------------------------------------------------------------ Read domain file
 8309: {
 8310:     my $loaded;
 8311:     my %domain;
 8312: 
 8313:     sub parse_domain_tab {
 8314: 	my ($lines) = @_;
 8315: 	foreach my $line (@$lines) {
 8316: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8317: 
 8318: 	    chomp($line);
 8319: 	    my ($name,@elements) = split(/:/,$line,9);
 8320: 	    my %this_domain;
 8321: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8322: 			       'lang_def', 'city', 'longi', 'lati',
 8323: 			       'primary') {
 8324: 		$this_domain{$field} = shift(@elements);
 8325: 	    }
 8326: 	    $domain{$name} = \%this_domain;
 8327: 	}
 8328:     }
 8329: 
 8330:     sub reset_domain_info {
 8331: 	undef($loaded);
 8332: 	undef(%domain);
 8333:     }
 8334: 
 8335:     sub load_domain_tab {
 8336: 	my ($ignore_cache) = @_;
 8337: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8338: 	my $fh;
 8339: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8340: 	    my @lines = <$fh>;
 8341: 	    &parse_domain_tab(\@lines);
 8342: 	}
 8343: 	close($fh);
 8344: 	$loaded = 1;
 8345:     }
 8346: 
 8347:     sub domain {
 8348: 	&load_domain_tab() if (!$loaded);
 8349: 
 8350: 	my ($name,$what) = @_;
 8351: 	return if ( !exists($domain{$name}) );
 8352: 
 8353: 	if (!$what) {
 8354: 	    return $domain{$name}{'description'};
 8355: 	}
 8356: 	return $domain{$name}{$what};
 8357:     }
 8358: }
 8359: 
 8360: 
 8361: # ------------------------------------------------------------- Read hosts file
 8362: {
 8363:     my %hostname;
 8364:     my %hostdom;
 8365:     my %libserv;
 8366:     my $loaded;
 8367:     my %name_to_host;
 8368: 
 8369:     sub parse_hosts_tab {
 8370: 	my ($file) = @_;
 8371: 	foreach my $configline (@$file) {
 8372: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8373: 	    next if ($configline =~ /^\^/);
 8374: 	    chomp($configline);
 8375: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 8376: 	    $name=~s/\s//g;
 8377: 	    if ($id && $domain && $role && $name) {
 8378: 		$hostname{$id}=$name;
 8379: 		push(@{$name_to_host{$name}}, $id);
 8380: 		$hostdom{$id}=$domain;
 8381: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8382: 	    }
 8383: 	}
 8384:     }
 8385:     
 8386:     sub reset_hosts_info {
 8387: 	&purge_remembered();
 8388: 	&reset_domain_info();
 8389: 	&reset_hosts_ip_info();
 8390: 	undef(%name_to_host);
 8391: 	undef(%hostname);
 8392: 	undef(%hostdom);
 8393: 	undef(%libserv);
 8394: 	undef($loaded);
 8395:     }
 8396: 
 8397:     sub load_hosts_tab {
 8398: 	my ($ignore_cache) = @_;
 8399: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8400: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8401: 	my @config = <$config>;
 8402: 	&parse_hosts_tab(\@config);
 8403: 	close($config);
 8404: 	$loaded=1;
 8405:     }
 8406: 
 8407:     sub hostname {
 8408: 	&load_hosts_tab() if (!$loaded);
 8409: 
 8410: 	my ($lonid) = @_;
 8411: 	return $hostname{$lonid};
 8412:     }
 8413: 
 8414:     sub all_hostnames {
 8415: 	&load_hosts_tab() if (!$loaded);
 8416: 
 8417: 	return %hostname;
 8418:     }
 8419: 
 8420:     sub all_names {
 8421: 	&load_hosts_tab() if (!$loaded);
 8422: 
 8423: 	return %name_to_host;
 8424:     }
 8425: 
 8426:     sub is_library {
 8427: 	&load_hosts_tab() if (!$loaded);
 8428: 
 8429: 	return exists($libserv{$_[0]});
 8430:     }
 8431: 
 8432:     sub all_library {
 8433: 	&load_hosts_tab() if (!$loaded);
 8434: 
 8435: 	return %libserv;
 8436:     }
 8437: 
 8438:     sub get_servers {
 8439: 	&load_hosts_tab() if (!$loaded);
 8440: 
 8441: 	my ($domain,$type) = @_;
 8442: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8443: 	                                          : %hostname;
 8444: 	my %result;
 8445: 	if (ref($domain) eq 'ARRAY') {
 8446: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8447: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8448: 		    $result{$host} = $hostname;
 8449: 		}
 8450: 	    }
 8451: 	} else {
 8452: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8453: 		if ($hostdom{$host} eq $domain) {
 8454: 		    $result{$host} = $hostname;
 8455: 		}
 8456: 	    }
 8457: 	}
 8458: 	return %result;
 8459:     }
 8460: 
 8461:     sub host_domain {
 8462: 	&load_hosts_tab() if (!$loaded);
 8463: 
 8464: 	my ($lonid) = @_;
 8465: 	return $hostdom{$lonid};
 8466:     }
 8467: 
 8468:     sub all_domains {
 8469: 	&load_hosts_tab() if (!$loaded);
 8470: 
 8471: 	my %seen;
 8472: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8473: 	return @uniq;
 8474:     }
 8475: }
 8476: 
 8477: { 
 8478:     my %iphost;
 8479:     my %name_to_ip;
 8480:     my %lonid_to_ip;
 8481: 
 8482:     sub get_hosts_from_ip {
 8483: 	my ($ip) = @_;
 8484: 	my %iphosts = &get_iphost();
 8485: 	if (ref($iphosts{$ip})) {
 8486: 	    return @{$iphosts{$ip}};
 8487: 	}
 8488: 	return;
 8489:     }
 8490:     
 8491:     sub reset_hosts_ip_info {
 8492: 	undef(%iphost);
 8493: 	undef(%name_to_ip);
 8494: 	undef(%lonid_to_ip);
 8495:     }
 8496: 
 8497:     sub get_host_ip {
 8498: 	my ($lonid) = @_;
 8499: 	if (exists($lonid_to_ip{$lonid})) {
 8500: 	    return $lonid_to_ip{$lonid};
 8501: 	}
 8502: 	my $name=&hostname($lonid);
 8503:    	my $ip = gethostbyname($name);
 8504: 	return if (!$ip || length($ip) ne 4);
 8505: 	$ip=inet_ntoa($ip);
 8506: 	$name_to_ip{$name}   = $ip;
 8507: 	$lonid_to_ip{$lonid} = $ip;
 8508: 	return $ip;
 8509:     }
 8510:     
 8511:     sub get_iphost {
 8512: 	my ($ignore_cache) = @_;
 8513: 
 8514: 	if (!$ignore_cache) {
 8515: 	    if (%iphost) {
 8516: 		return %iphost;
 8517: 	    }
 8518: 	    my ($ip_info,$cached)=
 8519: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8520: 	    if ($cached) {
 8521: 		%iphost      = %{$ip_info->[0]};
 8522: 		%name_to_ip  = %{$ip_info->[1]};
 8523: 		%lonid_to_ip = %{$ip_info->[2]};
 8524: 		return %iphost;
 8525: 	    }
 8526: 	}
 8527: 
 8528: 	# get yesterday's info for fallback
 8529: 	my %old_name_to_ip;
 8530: 	my ($ip_info,$cached)=
 8531: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8532: 	if ($cached) {
 8533: 	    %old_name_to_ip = %{$ip_info->[1]};
 8534: 	}
 8535: 
 8536: 	my %name_to_host = &all_names();
 8537: 	foreach my $name (keys(%name_to_host)) {
 8538: 	    my $ip;
 8539: 	    if (!exists($name_to_ip{$name})) {
 8540: 		$ip = gethostbyname($name);
 8541: 		if (!$ip || length($ip) ne 4) {
 8542: 		    if (defined($old_name_to_ip{$name})) {
 8543: 			$ip = $old_name_to_ip{$name};
 8544: 			&logthis("Can't find $name defaulting to old $ip");
 8545: 		    } else {
 8546: 			&logthis("Name $name no IP found");
 8547: 			next;
 8548: 		    }
 8549: 		} else {
 8550: 		    $ip=inet_ntoa($ip);
 8551: 		}
 8552: 		$name_to_ip{$name} = $ip;
 8553: 	    } else {
 8554: 		$ip = $name_to_ip{$name};
 8555: 	    }
 8556: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8557: 		$lonid_to_ip{$id} = $ip;
 8558: 	    }
 8559: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8560: 	}
 8561: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8562: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8563: 				      48*60*60);
 8564: 
 8565: 	return %iphost;
 8566:     }
 8567: }
 8568: 
 8569: BEGIN {
 8570: 
 8571: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8572:     unless ($readit) {
 8573: {
 8574:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8575:     %perlvar = (%perlvar,%{$configvars});
 8576: }
 8577: 
 8578: 
 8579: # ------------------------------------------------------ Read spare server file
 8580: {
 8581:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8582: 
 8583:     while (my $configline=<$config>) {
 8584:        chomp($configline);
 8585:        if ($configline) {
 8586: 	   my ($host,$type) = split(':',$configline,2);
 8587: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8588: 	   push(@{ $spareid{$type} }, $host);
 8589:        }
 8590:     }
 8591:     close($config);
 8592: }
 8593: # ------------------------------------------------------------ Read permissions
 8594: {
 8595:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8596: 
 8597:     while (my $configline=<$config>) {
 8598: 	chomp($configline);
 8599: 	if ($configline) {
 8600: 	    my ($role,$perm)=split(/ /,$configline);
 8601: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8602: 	}
 8603:     }
 8604:     close($config);
 8605: }
 8606: 
 8607: # -------------------------------------------- Read plain texts for permissions
 8608: {
 8609:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8610: 
 8611:     while (my $configline=<$config>) {
 8612: 	chomp($configline);
 8613: 	if ($configline) {
 8614: 	    my ($short,@plain)=split(/:/,$configline);
 8615:             %{$prp{$short}} = ();
 8616: 	    if (@plain > 0) {
 8617:                 $prp{$short}{'std'} = $plain[0];
 8618:                 for (my $i=1; $i<@plain; $i++) {
 8619:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8620:                 }
 8621:             }
 8622: 	}
 8623:     }
 8624:     close($config);
 8625: }
 8626: 
 8627: # ---------------------------------------------------------- Read package table
 8628: {
 8629:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8630: 
 8631:     while (my $configline=<$config>) {
 8632: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8633: 	chomp($configline);
 8634: 	my ($short,$plain)=split(/:/,$configline);
 8635: 	my ($pack,$name)=split(/\&/,$short);
 8636: 	if ($plain ne '') {
 8637: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8638: 	    $packagetab{$short}=$plain; 
 8639: 	}
 8640:     }
 8641:     close($config);
 8642: }
 8643: 
 8644: # ------------- set up temporary directory
 8645: {
 8646:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8647: 
 8648: }
 8649: 
 8650: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8651: 				'compress_threshold'=> 20_000,
 8652:  			        });
 8653: 
 8654: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8655: $dumpcount=0;
 8656: 
 8657: &logtouch();
 8658: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8659: $readit=1;
 8660:     {
 8661: 	use integer;
 8662: 	my $test=(2**32)+1;
 8663: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8664: 	&logthis(" Detected 64bit platform ($_64bit)");
 8665:     }
 8666: }
 8667: }
 8668: 
 8669: 1;
 8670: __END__
 8671: 
 8672: =pod
 8673: 
 8674: =head1 NAME
 8675: 
 8676: Apache::lonnet - Subroutines to ask questions about things in the network.
 8677: 
 8678: =head1 SYNOPSIS
 8679: 
 8680: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8681: 
 8682:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8683: 
 8684: Common parameters:
 8685: 
 8686: =over 4
 8687: 
 8688: =item *
 8689: 
 8690: $uname : an internal username (if $cname expecting a course Id specifically)
 8691: 
 8692: =item *
 8693: 
 8694: $udom : a domain (if $cdom expecting a course's domain specifically)
 8695: 
 8696: =item *
 8697: 
 8698: $symb : a resource instance identifier
 8699: 
 8700: =item *
 8701: 
 8702: $namespace : the name of a .db file that contains the data needed or
 8703: being set.
 8704: 
 8705: =back
 8706: 
 8707: =head1 OVERVIEW
 8708: 
 8709: lonnet provides subroutines which interact with the
 8710: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8711: about classes, users, and resources.
 8712: 
 8713: For many of these objects you can also use this to store data about
 8714: them or modify them in various ways.
 8715: 
 8716: =head2 Symbs
 8717: 
 8718: To identify a specific instance of a resource, LON-CAPA uses symbols
 8719: or "symbs"X<symb>. These identifiers are built from the URL of the
 8720: map, the resource number of the resource in the map, and the URL of
 8721: the resource itself. The latter is somewhat redundant, but might help
 8722: if maps change.
 8723: 
 8724: An example is
 8725: 
 8726:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8727: 
 8728: The respective map entry is
 8729: 
 8730:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8731:   title="Problem 2">
 8732:  </resource>
 8733: 
 8734: Symbs are used by the random number generator, as well as to store and
 8735: restore data specific to a certain instance of for example a problem.
 8736: 
 8737: =head2 Storing And Retrieving Data
 8738: 
 8739: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8740: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8741: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8742: is is the non-critical message twin of cstore. These functions are for
 8743: handlers to store a perl hash to a user's permanent data space in an
 8744: easy manner, and to retrieve it again on another call. It is expected
 8745: that a handler would use this once at the beginning to retrieve data,
 8746: and then again once at the end to send only the new data back.
 8747: 
 8748: The data is stored in the user's data directory on the user's
 8749: homeserver under the ID of the course.
 8750: 
 8751: The hash that is returned by restore will have all of the previous
 8752: value for all of the elements of the hash.
 8753: 
 8754: Example:
 8755: 
 8756:  #creating a hash
 8757:  my %hash;
 8758:  $hash{'foo'}='bar';
 8759: 
 8760:  #storing it
 8761:  &Apache::lonnet::cstore(\%hash);
 8762: 
 8763:  #changing a value
 8764:  $hash{'foo'}='notbar';
 8765: 
 8766:  #adding a new value
 8767:  $hash{'bar'}='foo';
 8768:  &Apache::lonnet::cstore(\%hash);
 8769: 
 8770:  #retrieving the hash
 8771:  my %history=&Apache::lonnet::restore();
 8772: 
 8773:  #print the hash
 8774:  foreach my $key (sort(keys(%history))) {
 8775:    print("\%history{$key} = $history{$key}");
 8776:  }
 8777: 
 8778: Will print out:
 8779: 
 8780:  %history{1:foo} = bar
 8781:  %history{1:keys} = foo:timestamp
 8782:  %history{1:timestamp} = 990455579
 8783:  %history{2:bar} = foo
 8784:  %history{2:foo} = notbar
 8785:  %history{2:keys} = foo:bar:timestamp
 8786:  %history{2:timestamp} = 990455580
 8787:  %history{bar} = foo
 8788:  %history{foo} = notbar
 8789:  %history{timestamp} = 990455580
 8790:  %history{version} = 2
 8791: 
 8792: Note that the special hash entries C<keys>, C<version> and
 8793: C<timestamp> were added to the hash. C<version> will be equal to the
 8794: total number of versions of the data that have been stored. The
 8795: C<timestamp> attribute will be the UNIX time the hash was
 8796: stored. C<keys> is available in every historical section to list which
 8797: keys were added or changed at a specific historical revision of a
 8798: hash.
 8799: 
 8800: B<Warning>: do not store the hash that restore returns directly. This
 8801: will cause a mess since it will restore the historical keys as if the
 8802: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8803: 
 8804: Calling convention:
 8805: 
 8806:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8807:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8808: 
 8809: For more detailed information, see lonnet specific documentation.
 8810: 
 8811: =head1 RETURN MESSAGES
 8812: 
 8813: =over 4
 8814: 
 8815: =item * B<con_lost>: unable to contact remote host
 8816: 
 8817: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8818: when the connection is brought back up
 8819: 
 8820: =item * B<con_failed>: unable to contact remote host and unable to save message
 8821: for later delivery
 8822: 
 8823: =item * B<error:>: an error a occured, a description of the error follows the :
 8824: 
 8825: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8826: that was requested
 8827: 
 8828: =back
 8829: 
 8830: =head1 PUBLIC SUBROUTINES
 8831: 
 8832: =head2 Session Environment Functions
 8833: 
 8834: =over 4
 8835: 
 8836: =item * 
 8837: X<appenv()>
 8838: B<appenv(%hash)>: the value of %hash is written to
 8839: the user envirnoment file, and will be restored for each access this
 8840: user makes during this session, also modifies the %env for the current
 8841: process
 8842: 
 8843: =item *
 8844: X<delenv()>
 8845: B<delenv($regexp)>: removes all items from the session
 8846: environment file that matches the regular expression in $regexp. The
 8847: values are also delted from the current processes %env.
 8848: 
 8849: =item * get_env_multiple($name) 
 8850: 
 8851: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8852: values may be defined and end up as an array ref.
 8853: 
 8854: returns an array of values
 8855: 
 8856: =back
 8857: 
 8858: =head2 User Information
 8859: 
 8860: =over 4
 8861: 
 8862: =item *
 8863: X<queryauthenticate()>
 8864: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8865: authentication scheme
 8866: 
 8867: =item *
 8868: X<authenticate()>
 8869: B<authenticate($uname,$upass,$udom)>: try to
 8870: authenticate user from domain's lib servers (first use the current
 8871: one). C<$upass> should be the users password.
 8872: 
 8873: =item *
 8874: X<homeserver()>
 8875: B<homeserver($uname,$udom)>: find the server which has
 8876: the user's directory and files (there must be only one), this caches
 8877: the answer, and also caches if there is a borken connection.
 8878: 
 8879: =item *
 8880: X<idget()>
 8881: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8882: (IDs are a unique resource in a domain, there must be only 1 ID per
 8883: username, and only 1 username per ID in a specific domain) (returns
 8884: hash: id=>name,id=>name)
 8885: 
 8886: =item *
 8887: X<idrget()>
 8888: B<idrget($udom,@unames)>: find the IDs behind a list of
 8889: usernames (returns hash: name=>id,name=>id)
 8890: 
 8891: =item *
 8892: X<idput()>
 8893: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8894: 
 8895: =item *
 8896: X<rolesinit()>
 8897: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8898: 
 8899: =item *
 8900: X<getsection()>
 8901: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8902: course $cname, return section name/number or '' for "not in course"
 8903: and '-1' for "no section"
 8904: 
 8905: =item *
 8906: X<userenvironment()>
 8907: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8908: passed in @what from the requested user's environment, returns a hash
 8909: 
 8910: =item * 
 8911: X<userlog_query()>
 8912: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8913: activity.log file. %filters defines filters applied when parsing the
 8914: log file. These can be start or end timestamps, or the type of action
 8915: - log to look for Login or Logout events, check for Checkin or
 8916: Checkout, role for role selection. The response is in the form
 8917: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8918: escaped strings of the action recorded in the activity.log file.
 8919: 
 8920: =back
 8921: 
 8922: =head2 User Roles
 8923: 
 8924: =over 4
 8925: 
 8926: =item *
 8927: 
 8928: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8929:  F: full access
 8930:  U,I,K: authentication modes (cxx only)
 8931:  '': forbidden
 8932:  1: user needs to choose course
 8933:  2: browse allowed
 8934:  A: passphrase authentication needed
 8935: 
 8936: =item *
 8937: 
 8938: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8939: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8940: and course level
 8941: 
 8942: =item *
 8943: 
 8944: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8945: explanation of a user role term
 8946: 
 8947: =item *
 8948: 
 8949: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 8950: All arguments are optional. Returns a hash of a roles, either for
 8951: co-author/assistant author roles for a user's Construction Space
 8952: (default), or if $context is 'userroles', roles for the user himself,
 8953: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 8954: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 8955: For each key, value is set to colon-separated start and end times for
 8956: the role.  If no username and domain are specified, will default to
 8957: current user/domain. Types, roles, and roledoms are references to arrays
 8958: of role statuses (active, future or previous), roles 
 8959: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8960: to restrict the list of roles reported. If no array ref is 
 8961: provided for types, will default to return only active roles.
 8962: 
 8963: =back
 8964: 
 8965: =head2 User Modification
 8966: 
 8967: =over 4
 8968: 
 8969: =item *
 8970: 
 8971: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8972: user for the level given by URL.  Optional start and end dates (leave empty
 8973: string or zero for "no date")
 8974: 
 8975: =item *
 8976: 
 8977: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8978: change a users, password, possible return values are: ok,
 8979: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8980: refused
 8981: 
 8982: =item *
 8983: 
 8984: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8985: 
 8986: =item *
 8987: 
 8988: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8989: modify user
 8990: 
 8991: =item *
 8992: 
 8993: modifystudent
 8994: 
 8995: modify a students enrollment and identification information.
 8996: The course id is resolved based on the current users environment.  
 8997: This means the envoking user must be a course coordinator or otherwise
 8998: associated with a course.
 8999: 
 9000: This call is essentially a wrapper for lonnet::modifyuser and
 9001: lonnet::modify_student_enrollment
 9002: 
 9003: Inputs: 
 9004: 
 9005: =over 4
 9006: 
 9007: =item B<$udom> Students loncapa domain
 9008: 
 9009: =item B<$uname> Students loncapa login name
 9010: 
 9011: =item B<$uid> Students id/student number
 9012: 
 9013: =item B<$umode> Students authentication mode
 9014: 
 9015: =item B<$upass> Students password
 9016: 
 9017: =item B<$first> Students first name
 9018: 
 9019: =item B<$middle> Students middle name
 9020: 
 9021: =item B<$last> Students last name
 9022: 
 9023: =item B<$gene> Students generation
 9024: 
 9025: =item B<$usec> Students section in course
 9026: 
 9027: =item B<$end> Unix time of the roles expiration
 9028: 
 9029: =item B<$start> Unix time of the roles start date
 9030: 
 9031: =item B<$forceid> If defined, allow $uid to be changed
 9032: 
 9033: =item B<$desiredhome> server to use as home server for student
 9034: 
 9035: =back
 9036: 
 9037: =item *
 9038: 
 9039: modify_student_enrollment
 9040: 
 9041: Change a students enrollment status in a class.  The environment variable
 9042: 'role.request.course' must be defined for this function to proceed.
 9043: 
 9044: Inputs:
 9045: 
 9046: =over 4
 9047: 
 9048: =item $udom, students domain
 9049: 
 9050: =item $uname, students name
 9051: 
 9052: =item $uid, students user id
 9053: 
 9054: =item $first, students first name
 9055: 
 9056: =item $middle
 9057: 
 9058: =item $last
 9059: 
 9060: =item $gene
 9061: 
 9062: =item $usec
 9063: 
 9064: =item $end
 9065: 
 9066: =item $start
 9067: 
 9068: =back
 9069: 
 9070: 
 9071: =item *
 9072: 
 9073: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9074: custom role; give a custom role to a user for the level given by URL.  Specify
 9075: name and domain of role author, and role name
 9076: 
 9077: =item *
 9078: 
 9079: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9080: 
 9081: =item *
 9082: 
 9083: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9084: 
 9085: =back
 9086: 
 9087: =head2 Course Infomation
 9088: 
 9089: =over 4
 9090: 
 9091: =item *
 9092: 
 9093: coursedescription($courseid) : returns a hash of information about the
 9094: specified course id, including all environment settings for the
 9095: course, the description of the course will be in the hash under the
 9096: key 'description'
 9097: 
 9098: =item *
 9099: 
 9100: resdata($name,$domain,$type,@which) : request for current parameter
 9101: setting for a specific $type, where $type is either 'course' or 'user',
 9102: @what should be a list of parameters to ask about. This routine caches
 9103: answers for 5 minutes.
 9104: 
 9105: =item *
 9106: 
 9107: get_courseresdata($courseid, $domain) : dump the entire course resource
 9108: data base, returning a hash that is keyed by the resource name and has
 9109: values that are the resource value.  I believe that the timestamps and
 9110: versions are also returned.
 9111: 
 9112: 
 9113: =back
 9114: 
 9115: =head2 Course Modification
 9116: 
 9117: =over 4
 9118: 
 9119: =item *
 9120: 
 9121: writecoursepref($courseid,%prefs) : write preferences (environment
 9122: database) for a course
 9123: 
 9124: =item *
 9125: 
 9126: createcourse($udom,$description,$url) : make/modify course
 9127: 
 9128: =back
 9129: 
 9130: =head2 Resource Subroutines
 9131: 
 9132: =over 4
 9133: 
 9134: =item *
 9135: 
 9136: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9137: 
 9138: =item *
 9139: 
 9140: repcopy($filename) : subscribes to the requested file, and attempts to
 9141: replicate from the owning library server, Might return
 9142: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9143: 'bad_request', also attempts to grab the metadata for the
 9144: resource. Expects the local filesystem pathname
 9145: (/home/httpd/html/res/....)
 9146: 
 9147: =back
 9148: 
 9149: =head2 Resource Information
 9150: 
 9151: =over 4
 9152: 
 9153: =item *
 9154: 
 9155: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9156: a vairety of different possible values, $varname should be a request
 9157: string, and the other parameters can be used to specify who and what
 9158: one is asking about.
 9159: 
 9160: Possible values for $varname are environment.lastname (or other item
 9161: from the envirnment hash), user.name (or someother aspect about the
 9162: user), resource.0.maxtries (or some other part and parameter of a
 9163: resource)
 9164: 
 9165: =item *
 9166: 
 9167: directcondval($number) : get current value of a condition; reads from a state
 9168: string
 9169: 
 9170: =item *
 9171: 
 9172: condval($condidx) : value of condition index based on state
 9173: 
 9174: =item *
 9175: 
 9176: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9177: resource's metadata, $what should be either a specific key, or either
 9178: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9179: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9180: 
 9181: this function automatically caches all requests
 9182: 
 9183: =item *
 9184: 
 9185: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9186: network of library servers; returns file handle of where SQL and regex results
 9187: will be stored for query
 9188: 
 9189: =item *
 9190: 
 9191: symbread($filename) : return symbolic list entry (filename argument optional);
 9192: returns the data handle
 9193: 
 9194: =item *
 9195: 
 9196: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9197: a possible symb for the URL in $thisfn, and if is an encryypted
 9198: resource that the user accessed using /enc/ returns a 1 on success, 0
 9199: on failure, user must be in a course, as it assumes the existance of
 9200: the course initial hash, and uses $env('request.course.id'}
 9201: 
 9202: 
 9203: =item *
 9204: 
 9205: symbclean($symb) : removes versions numbers from a symb, returns the
 9206: cleaned symb
 9207: 
 9208: =item *
 9209: 
 9210: is_on_map($uri) : checks if the $uri is somewhere on the current
 9211: course map, user must be in a course for it to work.
 9212: 
 9213: =item *
 9214: 
 9215: numval($salt) : return random seed value (addend for rndseed)
 9216: 
 9217: =item *
 9218: 
 9219: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9220: a random seed, all arguments are optional, if they aren't sent it uses the
 9221: environment to derive them. Note: if symb isn't sent and it can't get one
 9222: from &symbread it will use the current time as its return value
 9223: 
 9224: =item *
 9225: 
 9226: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9227: unfakeable, receipt
 9228: 
 9229: =item *
 9230: 
 9231: receipt() : API to ireceipt working off of env values; given out to users
 9232: 
 9233: =item *
 9234: 
 9235: countacc($url) : count the number of accesses to a given URL
 9236: 
 9237: =item *
 9238: 
 9239: 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
 9240: 
 9241: =item *
 9242: 
 9243: 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)
 9244: 
 9245: =item *
 9246: 
 9247: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9248: 
 9249: =item *
 9250: 
 9251: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9252: forcing spreadsheet to reevaluate the resource scores next time.
 9253: 
 9254: =back
 9255: 
 9256: =head2 Storing/Retreiving Data
 9257: 
 9258: =over 4
 9259: 
 9260: =item *
 9261: 
 9262: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9263: for this url; hashref needs to be given and should be a \%hashname; the
 9264: remaining args aren't required and if they aren't passed or are '' they will
 9265: be derived from the env
 9266: 
 9267: =item *
 9268: 
 9269: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9270: uses critical subroutine
 9271: 
 9272: =item *
 9273: 
 9274: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9275: all args are optional
 9276: 
 9277: =item *
 9278: 
 9279: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9280: dumps the complete (or key matching regexp) namespace into a hash
 9281: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9282: normally &store()ed into
 9283: 
 9284: $range should be either an integer '100' (give me the first 100
 9285:                                            matching records)
 9286:               or be  two integers sperated by a - with no spaces
 9287:                  '30-50' (give me the 30th through the 50th matching
 9288:                           records)
 9289: 
 9290: 
 9291: =item *
 9292: 
 9293: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9294: replaces a &store() version of data with a replacement set of data
 9295: for a particular resource in a namespace passed in the $storehash hash 
 9296: reference
 9297: 
 9298: =item *
 9299: 
 9300: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9301: works very similar to store/cstore, but all data is stored in a
 9302: temporary location and can be reset using tmpreset, $storehash should
 9303: be a hash reference, returns nothing on success
 9304: 
 9305: =item *
 9306: 
 9307: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9308: similar to restore, but all data is stored in a temporary location and
 9309: can be reset using tmpreset. Returns a hash of values on success,
 9310: error string otherwise.
 9311: 
 9312: =item *
 9313: 
 9314: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9315: deltes all keys for $symb form the temporary storage hash.
 9316: 
 9317: =item *
 9318: 
 9319: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9320: reference filled in from namesp ($udom and $uname are optional)
 9321: 
 9322: =item *
 9323: 
 9324: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9325: namesp ($udom and $uname are optional)
 9326: 
 9327: =item *
 9328: 
 9329: dump($namespace,$udom,$uname,$regexp,$range) : 
 9330: dumps the complete (or key matching regexp) namespace into a hash
 9331: ($udom, $uname, $regexp, $range are optional)
 9332: 
 9333: $range should be either an integer '100' (give me the first 100
 9334:                                            matching records)
 9335:               or be  two integers sperated by a - with no spaces
 9336:                  '30-50' (give me the 30th through the 50th matching
 9337:                           records)
 9338: =item *
 9339: 
 9340: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9341: $store can be a scalar, an array reference, or if the amount to be 
 9342: incremented is > 1, a hash reference.
 9343: 
 9344: ($udom and $uname are optional)
 9345: 
 9346: =item *
 9347: 
 9348: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9349: ($udom and $uname are optional)
 9350: 
 9351: =item *
 9352: 
 9353: cput($namespace,$storehash,$udom,$uname) : critical put
 9354: ($udom and $uname are optional)
 9355: 
 9356: =item *
 9357: 
 9358: newput($namespace,$storehash,$udom,$uname) :
 9359: 
 9360: Attempts to store the items in the $storehash, but only if they don't
 9361: currently exist, if this succeeds you can be certain that you have 
 9362: successfully created a new key value pair in the $namespace db.
 9363: 
 9364: 
 9365: Args:
 9366:  $namespace: name of database to store values to
 9367:  $storehash: hashref to store to the db
 9368:  $udom: (optional) domain of user containing the db
 9369:  $uname: (optional) name of user caontaining the db
 9370: 
 9371: Returns:
 9372:  'ok' -> succeeded in storing all keys of $storehash
 9373:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9374:                         least <key> already existed in the db (other
 9375:                         requested keys may also already exist)
 9376:  'error: <msg>' -> unable to tie the DB or other erorr occured
 9377:  'con_lost' -> unable to contact request server
 9378:  'refused' -> action was not allowed by remote machine
 9379: 
 9380: 
 9381: =item *
 9382: 
 9383: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9384: reference filled in from namesp (encrypts the return communication)
 9385: ($udom and $uname are optional)
 9386: 
 9387: =item *
 9388: 
 9389: log($udom,$name,$home,$message) : write to permanent log for user; use
 9390: critical subroutine
 9391: 
 9392: =item *
 9393: 
 9394: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9395: array reference filled in from namespace found in domain level on either
 9396: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9397: 
 9398: =item *
 9399: 
 9400: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9401: domain level either on specified domain server ($uhome) or primary domain 
 9402: server ($udom and $uhome are optional)
 9403: 
 9404: =item * 
 9405: 
 9406: get_domain_defaults($target_domain) : returns hash with defaults for
 9407: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9408: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9409: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9410: Values are retrieved from cache (if current), or from domain's configuration.db
 9411: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9412: or lonTabs/domain.tab. 
 9413: 
 9414: %domdefaults = &get_auth_defaults($target_domain);
 9415: 
 9416: =back
 9417: 
 9418: =head2 Network Status Functions
 9419: 
 9420: =over 4
 9421: 
 9422: =item *
 9423: 
 9424: dirlist($uri) : return directory list based on URI
 9425: 
 9426: =item *
 9427: 
 9428: spareserver() : find server with least workload from spare.tab
 9429: 
 9430: =back
 9431: 
 9432: =head2 Apache Request
 9433: 
 9434: =over 4
 9435: 
 9436: =item *
 9437: 
 9438: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9439: localhost, posts hash
 9440: 
 9441: =back
 9442: 
 9443: =head2 Data to String to Data
 9444: 
 9445: =over 4
 9446: 
 9447: =item *
 9448: 
 9449: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9450: and '&' separators, supports elements that are arrayrefs and hashrefs
 9451: 
 9452: =item *
 9453: 
 9454: hashref2str($hashref) : convert a hashref into a string complete with
 9455: escaping and '=' and '&' separators, supports elements that are
 9456: arrayrefs and hashrefs
 9457: 
 9458: =item *
 9459: 
 9460: arrayref2str($arrayref) : convert an arrayref into a string complete
 9461: with escaping and '&' separators, supports elements that are arrayrefs
 9462: and hashrefs
 9463: 
 9464: =item *
 9465: 
 9466: str2hash($string) : convert string to hash using unescaping and
 9467: splitting on '=' and '&', supports elements that are arrayrefs and
 9468: hashrefs
 9469: 
 9470: =item *
 9471: 
 9472: str2array($string) : convert string to hash using unescaping and
 9473: splitting on '&', supports elements that are arrayrefs and hashrefs
 9474: 
 9475: =back
 9476: 
 9477: =head2 Logging Routines
 9478: 
 9479: =over 4
 9480: 
 9481: These routines allow one to make log messages in the lonnet.log and
 9482: lonnet.perm logfiles.
 9483: 
 9484: =item *
 9485: 
 9486: logtouch() : make sure the logfile, lonnet.log, exists
 9487: 
 9488: =item *
 9489: 
 9490: logthis() : append message to the normal lonnet.log file, it gets
 9491: preiodically rolled over and deleted.
 9492: 
 9493: =item *
 9494: 
 9495: logperm() : append a permanent message to lonnet.perm.log, this log
 9496: file never gets deleted by any automated portion of the system, only
 9497: messages of critical importance should go in here.
 9498: 
 9499: =back
 9500: 
 9501: =head2 General File Helper Routines
 9502: 
 9503: =over 4
 9504: 
 9505: =item *
 9506: 
 9507: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9508: (a) files in /uploaded
 9509:   (i) If a local copy of the file exists - 
 9510:       compares modification date of local copy with last-modified date for 
 9511:       definitive version stored on home server for course. If local copy is 
 9512:       stale, requests a new version from the home server and stores it. 
 9513:       If the original has been removed from the home server, then local copy 
 9514:       is unlinked.
 9515:   (ii) If local copy does not exist -
 9516:       requests the file from the home server and stores it. 
 9517:   
 9518:   If $caller is 'uploadrep':  
 9519:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9520:     for request for files originally uploaded via DOCS. 
 9521:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9522:   
 9523:   Otherwise:
 9524:      This indicates a call from the content generation phase of the request.
 9525:      -  returns the entire contents of the file or -1.
 9526:      
 9527: (b) files in /res
 9528:    - returns the entire contents of a file or -1; 
 9529:    it properly subscribes to and replicates the file if neccessary.
 9530: 
 9531: 
 9532: =item *
 9533: 
 9534: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9535:                   reference
 9536: 
 9537: returns either a stat() list of data about the file or an empty list
 9538: if the file doesn't exist or couldn't find out about it (connection
 9539: problems or user unknown)
 9540: 
 9541: =item *
 9542: 
 9543: filelocation($dir,$file) : returns file system location of a file
 9544: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9545: directory that relative $file lookups are to looked in ($dir of /a/dir
 9546: and a file of ../bob will become /a/bob)
 9547: 
 9548: =item *
 9549: 
 9550: hreflocation($dir,$file) : returns file system location or a URL; same as
 9551: filelocation except for hrefs
 9552: 
 9553: =item *
 9554: 
 9555: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9556: 
 9557: =back
 9558: 
 9559: =head2 Usererfile file routines (/uploaded*)
 9560: 
 9561: =over 4
 9562: 
 9563: =item *
 9564: 
 9565: userfileupload(): main rotine for putting a file in a user or course's
 9566:                   filespace, arguments are,
 9567: 
 9568:  formname - required - this is the name of the element in $env where the
 9569:            filename, and the contents of the file to create/modifed exist
 9570:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9571:            contents of the file is located in $env{'form.'.$formname}
 9572:  coursedoc - if true, store the file in the course of the active role
 9573:              of the current user
 9574:  subdir - required - subdirectory to put the file in under ../userfiles/
 9575:          if undefined, it will be placed in "unknown"
 9576: 
 9577:  (This routine calls clean_filename() to remove any dangerous
 9578:  characters from the filename, and then calls finuserfileupload() to
 9579:  complete the transaction)
 9580: 
 9581:  returns either the url of the uploaded file (/uploaded/....) if successful
 9582:  and /adm/notfound.html if unsuccessful
 9583: 
 9584: =item *
 9585: 
 9586: clean_filename(): routine for cleaing a filename up for storage in
 9587:                  userfile space, argument is:
 9588: 
 9589:  filename - proposed filename
 9590: 
 9591: returns: the new clean filename
 9592: 
 9593: =item *
 9594: 
 9595: finishuserfileupload(): routine that creaes and sends the file to
 9596: userspace, probably shouldn't be called directly
 9597: 
 9598:   docuname: username or courseid of destination for the file
 9599:   docudom: domain of user/course of destination for the file
 9600:   formname: same as for userfileupload()
 9601:   fname: filename (inculding subdirectories) for the file
 9602: 
 9603:  returns either the url of the uploaded file (/uploaded/....) if successful
 9604:  and /adm/notfound.html if unsuccessful
 9605: 
 9606: =item *
 9607: 
 9608: renameuserfile(): renames an existing userfile to a new name
 9609: 
 9610:   Args:
 9611:    docuname: username or courseid of destination for the file
 9612:    docudom: domain of user/course of destination for the file
 9613:    old: current file name (including any subdirs under userfiles)
 9614:    new: desired file name (including any subdirs under userfiles)
 9615: 
 9616: =item *
 9617: 
 9618: mkdiruserfile(): creates a directory is a userfiles dir
 9619: 
 9620:   Args:
 9621:    docuname: username or courseid of destination for the file
 9622:    docudom: domain of user/course of destination for the file
 9623:    dir: dir to create (including any subdirs under userfiles)
 9624: 
 9625: =item *
 9626: 
 9627: removeuserfile(): removes a file that exists in userfiles
 9628: 
 9629:   Args:
 9630:    docuname: username or courseid of destination for the file
 9631:    docudom: domain of user/course of destination for the file
 9632:    fname: filname to delete (including any subdirs under userfiles)
 9633: 
 9634: =item *
 9635: 
 9636: removeuploadedurl(): convience function for removeuserfile()
 9637: 
 9638:   Args:
 9639:    url:  a full /uploaded/... url to delete
 9640: 
 9641: =item * 
 9642: 
 9643: get_portfile_permissions():
 9644:   Args:
 9645:     domain: domain of user or course contain the portfolio files
 9646:     user: name of user or num of course contain the portfolio files
 9647:   Returns:
 9648:     hashref of a dump of the proper file_permissions.db
 9649:    
 9650: 
 9651: =item * 
 9652: 
 9653: get_access_controls():
 9654: 
 9655: Args:
 9656:   current_permissions: the hash ref returned from get_portfile_permissions()
 9657:   group: (optional) the group you want the files associated with
 9658:   file: (optional) the file you want access info on
 9659: 
 9660: Returns:
 9661:     a hash (keys are file names) of hashes containing
 9662:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9663:         values are XML containing access control settings (see below) 
 9664: 
 9665: Internal notes:
 9666: 
 9667:  access controls are stored in file_permissions.db as key=value pairs.
 9668:     key -> path to file/file_name\0uniqueID:scope_end_start
 9669:         where scope -> public,guest,course,group,domains or users.
 9670:               end -> UNIX time for end of access (0 -> no end date)
 9671:               start -> UNIX time for start of access
 9672: 
 9673:     value -> XML description of access control
 9674:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9675:             <start></start>
 9676:             <end></end>
 9677: 
 9678:             <password></password>  for scope type = guest
 9679: 
 9680:             <domain></domain>     for scope type = course or group
 9681:             <number></number>
 9682:             <roles id="">
 9683:              <role></role>
 9684:              <access></access>
 9685:              <section></section>
 9686:              <group></group>
 9687:             </roles>
 9688: 
 9689:             <dom></dom>         for scope type = domains
 9690: 
 9691:             <users>             for scope type = users
 9692:              <user>
 9693:               <uname></uname>
 9694:               <udom></udom>
 9695:              </user>
 9696:             </users>
 9697:            </scope> 
 9698:               
 9699:  Access data is also aggregated for each file in an additional key=value pair:
 9700:  key -> path to file/file_name\0accesscontrol 
 9701:  value -> reference to hash
 9702:           hash contains key = value pairs
 9703:           where key = uniqueID:scope_end_start
 9704:                 value = UNIX time record was last updated
 9705: 
 9706:           Used to improve speed of look-ups of access controls for each file.  
 9707:  
 9708:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9709: 
 9710: modify_access_controls():
 9711: 
 9712: Modifies access controls for a portfolio file
 9713: Args
 9714: 1. file name
 9715: 2. reference to hash of required changes,
 9716: 3. domain
 9717: 4. username
 9718:   where domain,username are the domain of the portfolio owner 
 9719:   (either a user or a course) 
 9720: 
 9721: Returns:
 9722: 1. result of additions or updates ('ok' or 'error', with error message). 
 9723: 2. result of deletions ('ok' or 'error', with error message).
 9724: 3. reference to hash of any new or updated access controls.
 9725: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9726:    key = integer (inbound ID)
 9727:    value = uniqueID  
 9728: 
 9729: =back
 9730: 
 9731: =head2 HTTP Helper Routines
 9732: 
 9733: =over 4
 9734: 
 9735: =item *
 9736: 
 9737: escape() : unpack non-word characters into CGI-compatible hex codes
 9738: 
 9739: =item *
 9740: 
 9741: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9742: 
 9743: =back
 9744: 
 9745: =head1 PRIVATE SUBROUTINES
 9746: 
 9747: =head2 Underlying communication routines (Shouldn't call)
 9748: 
 9749: =over 4
 9750: 
 9751: =item *
 9752: 
 9753: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9754: 
 9755: =item *
 9756: 
 9757: reply() : uses subreply to send a message to remote machine, logs all failures
 9758: 
 9759: =item *
 9760: 
 9761: critical() : passes a critical message to another server; if cannot
 9762: get through then place message in connection buffer directory and
 9763: returns con_delayed, if incapable of saving message, returns
 9764: con_failed
 9765: 
 9766: =item *
 9767: 
 9768: reconlonc() : tries to reconnect lonc client processes.
 9769: 
 9770: =back
 9771: 
 9772: =head2 Resource Access Logging
 9773: 
 9774: =over 4
 9775: 
 9776: =item *
 9777: 
 9778: flushcourselogs() : flush (save) buffer logs and access logs
 9779: 
 9780: =item *
 9781: 
 9782: courselog($what) : save message for course in hash
 9783: 
 9784: =item *
 9785: 
 9786: courseacclog($what) : save message for course using &courselog().  Perform
 9787: special processing for specific resource types (problems, exams, quizzes, etc).
 9788: 
 9789: =item *
 9790: 
 9791: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9792: as a PerlChildExitHandler
 9793: 
 9794: =back
 9795: 
 9796: =head2 Other
 9797: 
 9798: =over 4
 9799: 
 9800: =item *
 9801: 
 9802: symblist($mapname,%newhash) : update symbolic storage links
 9803: 
 9804: =back
 9805: 
 9806: =cut
 9807: 

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