File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.941.2.2: download - view: text, annotated - select for diffs
Fri Apr 4 16:58:44 2008 UTC (16 years, 4 months ago) by raeburn
Branches: version_2_6_X
CVS tags: version_2_6_3
Diff to branchpoint 1.941: preferred, unified
- backport 1.953, 1.954

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.941.2.2 2008/04/04 16:58:44 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:                 }
 1068:                 if ($response ne 'refused') {
 1069:                     my @pairs=split(/\&/,$response);
 1070:                     foreach my $item (@pairs) {
 1071:                         my ($key,$value)=split(/=/,$item,2);
 1072:                         $key = &unescape($key);
 1073:                         next if ($key =~ /^error: 2 /);
 1074:                         $returnhash{$key}=&thaw_unescape($value);
 1075:                     }
 1076:                 }
 1077:             }
 1078:         }
 1079:     }
 1080:     return %returnhash;
 1081: }
 1082: 
 1083: sub inst_userrules {
 1084:     my ($udom,$check) = @_;
 1085:     my (%ruleshash,@ruleorder);
 1086:     if ($udom ne '') {
 1087:         my $homeserver=&domain($udom,'primary');
 1088:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1089:             my $response;
 1090:             if ($check eq 'id') {
 1091:                 $response=&reply('instidrules:'.&escape($udom),
 1092:                                  $homeserver);
 1093:             } else {
 1094:                 $response=&reply('instuserrules:'.&escape($udom),
 1095:                                  $homeserver);
 1096:             }
 1097:             if (($response ne 'refused') && ($response ne 'error') && 
 1098:                 ($response ne 'unknown_cmd') && 
 1099:                 ($response ne 'no_such_host')) {
 1100:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1101:                 my @pairs=split(/\&/,$hashitems);
 1102:                 foreach my $item (@pairs) {
 1103:                     my ($key,$value)=split(/=/,$item,2);
 1104:                     $key = &unescape($key);
 1105:                     next if ($key =~ /^error: 2 /);
 1106:                     $ruleshash{$key}=&thaw_unescape($value);
 1107:                 }
 1108:                 my @esc_order = split(/\&/,$orderitems);
 1109:                 foreach my $item (@esc_order) {
 1110:                     push(@ruleorder,&unescape($item));
 1111:                 }
 1112:             }
 1113:         }
 1114:     }
 1115:     return (\%ruleshash,\@ruleorder);
 1116: }
 1117: 
 1118: # --------------------------------------------------- Assign a key to a student
 1119: 
 1120: sub assign_access_key {
 1121: #
 1122: # a valid key looks like uname:udom#comments
 1123: # comments are being appended
 1124: #
 1125:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1126:     $kdom=
 1127:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1128:     $knum=
 1129:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1130:     $cdom=
 1131:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1132:     $cnum=
 1133:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1134:     $udom=$env{'user.name'} unless (defined($udom));
 1135:     $uname=$env{'user.domain'} unless (defined($uname));
 1136:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1137:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1138:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1139:                                                   # assigned to this person
 1140:                                                   # - this should not happen,
 1141:                                                   # unless something went wrong
 1142:                                                   # the first time around
 1143: # ready to assign
 1144:         $logentry=$1.'; '.$logentry;
 1145:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1146:                                                  $kdom,$knum) eq 'ok') {
 1147: # key now belongs to user
 1148: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1149:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1150:                 &appenv('environment.'.$envkey => $ckey);
 1151:                 return 'ok';
 1152:             } else {
 1153:                 return 
 1154:   'error: Count not permanently assign key, will need to be re-entered later.';
 1155: 	    }
 1156:         } else {
 1157:             return 'error: Could not assign key, try again later.';
 1158:         }
 1159:     } elsif (!$existing{$ckey}) {
 1160: # the key does not exist
 1161: 	return 'error: The key does not exist';
 1162:     } else {
 1163: # the key is somebody else's
 1164: 	return 'error: The key is already in use';
 1165:     }
 1166: }
 1167: 
 1168: # ------------------------------------------ put an additional comment on a key
 1169: 
 1170: sub comment_access_key {
 1171: #
 1172: # a valid key looks like uname:udom#comments
 1173: # comments are being appended
 1174: #
 1175:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1176:     $cdom=
 1177:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1178:     $cnum=
 1179:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1180:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1181:     if ($existing{$ckey}) {
 1182:         $existing{$ckey}.='; '.$logentry;
 1183: # ready to assign
 1184:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1185:                                                  $cdom,$cnum) eq 'ok') {
 1186: 	    return 'ok';
 1187:         } else {
 1188: 	    return 'error: Count not store comment.';
 1189:         }
 1190:     } else {
 1191: # the key does not exist
 1192: 	return 'error: The key does not exist';
 1193:     }
 1194: }
 1195: 
 1196: # ------------------------------------------------------ Generate a set of keys
 1197: 
 1198: sub generate_access_keys {
 1199:     my ($number,$cdom,$cnum,$logentry)=@_;
 1200:     $cdom=
 1201:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1202:     $cnum=
 1203:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1204:     unless (&allowed('mky',$cdom)) { return 0; }
 1205:     unless (($cdom) && ($cnum)) { return 0; }
 1206:     if ($number>10000) { return 0; }
 1207:     sleep(2); # make sure don't get same seed twice
 1208:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1209:     my $total=0;
 1210:     for (my $i=1;$i<=$number;$i++) {
 1211:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1212:                   sprintf("%lx",int(100000*rand)).'-'.
 1213:                   sprintf("%lx",int(100000*rand));
 1214:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1215:        $newkey=~s/0/h/g; # and also 0 and O
 1216:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1217:        if ($existing{$newkey}) {
 1218:            $i--;
 1219:        } else {
 1220: 	  if (&put('accesskeys',
 1221:               { $newkey => '# generated '.localtime().
 1222:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1223:                            '; '.$logentry },
 1224: 		   $cdom,$cnum) eq 'ok') {
 1225:               $total++;
 1226: 	  }
 1227:        }
 1228:     }
 1229:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1230:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1231:     return $total;
 1232: }
 1233: 
 1234: # ------------------------------------------------------- Validate an accesskey
 1235: 
 1236: sub validate_access_key {
 1237:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1238:     $cdom=
 1239:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1240:     $cnum=
 1241:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1242:     $udom=$env{'user.domain'} unless (defined($udom));
 1243:     $uname=$env{'user.name'} unless (defined($uname));
 1244:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1245:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1246: }
 1247: 
 1248: # ------------------------------------- Find the section of student in a course
 1249: sub devalidate_getsection_cache {
 1250:     my ($udom,$unam,$courseid)=@_;
 1251:     my $hashid="$udom:$unam:$courseid";
 1252:     &devalidate_cache_new('getsection',$hashid);
 1253: }
 1254: 
 1255: sub courseid_to_courseurl {
 1256:     my ($courseid) = @_;
 1257:     #already url style courseid
 1258:     return $courseid if ($courseid =~ m{^/});
 1259: 
 1260:     if (exists($env{'course.'.$courseid.'.num'})) {
 1261: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1262: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1263: 	return "/$cdom/$cnum";
 1264:     }
 1265: 
 1266:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1267:     if (exists($courseinfo{'num'})) {
 1268: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1269:     }
 1270: 
 1271:     return undef;
 1272: }
 1273: 
 1274: sub getsection {
 1275:     my ($udom,$unam,$courseid)=@_;
 1276:     my $cachetime=1800;
 1277: 
 1278:     my $hashid="$udom:$unam:$courseid";
 1279:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1280:     if (defined($cached)) { return $result; }
 1281: 
 1282:     my %Pending; 
 1283:     my %Expired;
 1284:     #
 1285:     # Each role can either have not started yet (pending), be active, 
 1286:     #    or have expired.
 1287:     #
 1288:     # If there is an active role, we are done.
 1289:     #
 1290:     # If there is more than one role which has not started yet, 
 1291:     #     choose the one which will start sooner
 1292:     # If there is one role which has not started yet, return it.
 1293:     #
 1294:     # If there is more than one expired role, choose the one which ended last.
 1295:     # If there is a role which has expired, return it.
 1296:     #
 1297:     $courseid = &courseid_to_courseurl($courseid);
 1298:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1299:     foreach my $key (keys(%roleshash)) {
 1300:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1301:         my $section=$1;
 1302:         if ($key eq $courseid.'_st') { $section=''; }
 1303:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1304:         my $now=time;
 1305:         if (defined($end) && $end && ($now > $end)) {
 1306:             $Expired{$end}=$section;
 1307:             next;
 1308:         }
 1309:         if (defined($start) && $start && ($now < $start)) {
 1310:             $Pending{$start}=$section;
 1311:             next;
 1312:         }
 1313:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1314:     }
 1315:     #
 1316:     # Presumedly there will be few matching roles from the above
 1317:     # loop and the sorting time will be negligible.
 1318:     if (scalar(keys(%Pending))) {
 1319:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1320:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1321:     } 
 1322:     if (scalar(keys(%Expired))) {
 1323:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1324:         my $time = pop(@sorted);
 1325:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1326:     }
 1327:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1328: }
 1329: 
 1330: sub save_cache {
 1331:     &purge_remembered();
 1332:     #&Apache::loncommon::validate_page();
 1333:     undef(%env);
 1334:     undef($env_loaded);
 1335: }
 1336: 
 1337: my $to_remember=-1;
 1338: my %remembered;
 1339: my %accessed;
 1340: my $kicks=0;
 1341: my $hits=0;
 1342: sub make_key {
 1343:     my ($name,$id) = @_;
 1344:     if (length($id) > 65 
 1345: 	&& length(&escape($id)) > 200) {
 1346: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1347:     }
 1348:     return &escape($name.':'.$id);
 1349: }
 1350: 
 1351: sub devalidate_cache_new {
 1352:     my ($name,$id,$debug) = @_;
 1353:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1354:     $id=&make_key($name,$id);
 1355:     $memcache->delete($id);
 1356:     delete($remembered{$id});
 1357:     delete($accessed{$id});
 1358: }
 1359: 
 1360: sub is_cached_new {
 1361:     my ($name,$id,$debug) = @_;
 1362:     $id=&make_key($name,$id);
 1363:     if (exists($remembered{$id})) {
 1364: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1365: 	$accessed{$id}=[&gettimeofday()];
 1366: 	$hits++;
 1367: 	return ($remembered{$id},1);
 1368:     }
 1369:     my $value = $memcache->get($id);
 1370:     if (!(defined($value))) {
 1371: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1372: 	return (undef,undef);
 1373:     }
 1374:     if ($value eq '__undef__') {
 1375: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1376: 	$value=undef;
 1377:     }
 1378:     &make_room($id,$value,$debug);
 1379:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1380:     return ($value,1);
 1381: }
 1382: 
 1383: sub do_cache_new {
 1384:     my ($name,$id,$value,$time,$debug) = @_;
 1385:     $id=&make_key($name,$id);
 1386:     my $setvalue=$value;
 1387:     if (!defined($setvalue)) {
 1388: 	$setvalue='__undef__';
 1389:     }
 1390:     if (!defined($time) ) {
 1391: 	$time=600;
 1392:     }
 1393:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1394:     my $result = $memcache->set($id,$setvalue,$time);
 1395:     if (! $result) {
 1396: 	&logthis("caching of id -> $id  failed");
 1397: 	$memcache->disconnect_all();
 1398:     }
 1399:     # need to make a copy of $value
 1400:     &make_room($id,$value,$debug);
 1401:     return $value;
 1402: }
 1403: 
 1404: sub make_room {
 1405:     my ($id,$value,$debug)=@_;
 1406: 
 1407:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1408:                                     : $value;
 1409:     if ($to_remember<0) { return; }
 1410:     $accessed{$id}=[&gettimeofday()];
 1411:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1412:     my $to_kick;
 1413:     my $max_time=0;
 1414:     foreach my $other (keys(%accessed)) {
 1415: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1416: 	    $to_kick=$other;
 1417: 	    $max_time=&tv_interval($accessed{$other});
 1418: 	}
 1419:     }
 1420:     delete($remembered{$to_kick});
 1421:     delete($accessed{$to_kick});
 1422:     $kicks++;
 1423:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1424:     return;
 1425: }
 1426: 
 1427: sub purge_remembered {
 1428:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1429:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1430:     undef(%remembered);
 1431:     undef(%accessed);
 1432: }
 1433: # ------------------------------------- Read an entry from a user's environment
 1434: 
 1435: sub userenvironment {
 1436:     my ($udom,$unam,@what)=@_;
 1437:     my %returnhash=();
 1438:     my @answer=split(/\&/,
 1439:                 &reply('get:'.$udom.':'.$unam.':environment:'.join('&',@what),
 1440:                       &homeserver($unam,$udom)));
 1441:     my $i;
 1442:     for ($i=0;$i<=$#what;$i++) {
 1443: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1444:     }
 1445:     return %returnhash;
 1446: }
 1447: 
 1448: # ---------------------------------------------------------- Get a studentphoto
 1449: sub studentphoto {
 1450:     my ($udom,$unam,$ext) = @_;
 1451:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1452:     if (defined($env{'request.course.id'})) {
 1453:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1454:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1455:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1456:             } else {
 1457:                 my ($result,$perm_reqd)=
 1458: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1459:                 if ($result eq 'ok') {
 1460:                     if (!($perm_reqd eq 'yes')) {
 1461:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1462:                     }
 1463:                 }
 1464:             }
 1465:         }
 1466:     } else {
 1467:         my ($result,$perm_reqd) = 
 1468: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1469:         if ($result eq 'ok') {
 1470:             if (!($perm_reqd eq 'yes')) {
 1471:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1472:             }
 1473:         }
 1474:     }
 1475:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1476: }
 1477: 
 1478: sub retrievestudentphoto {
 1479:     my ($udom,$unam,$ext,$type) = @_;
 1480:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1481:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1482:     if ($ret eq 'ok') {
 1483:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1484:         if ($type eq 'thumbnail') {
 1485:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1486:         }
 1487:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1488:         return $tokenurl;
 1489:     } else {
 1490:         if ($type eq 'thumbnail') {
 1491:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1492:         } else { 
 1493:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1494:         }
 1495:     }
 1496: }
 1497: 
 1498: # -------------------------------------------------------------------- New chat
 1499: 
 1500: sub chatsend {
 1501:     my ($newentry,$anon,$group)=@_;
 1502:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1503:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1504:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1505:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1506: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1507: 		   &escape($newentry)).':'.$group,$chome);
 1508: }
 1509: 
 1510: # ------------------------------------------ Find current version of a resource
 1511: 
 1512: sub getversion {
 1513:     my $fname=&clutter(shift);
 1514:     unless ($fname=~/^\/res\//) { return -1; }
 1515:     return &currentversion(&filelocation('',$fname));
 1516: }
 1517: 
 1518: sub currentversion {
 1519:     my $fname=shift;
 1520:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1521:     if (defined($cached)) { return $result; }
 1522:     my $author=$fname;
 1523:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1524:     my ($udom,$uname)=split(/\//,$author);
 1525:     my $home=homeserver($uname,$udom);
 1526:     if ($home eq 'no_host') { 
 1527:         return -1; 
 1528:     }
 1529:     my $answer=reply("currentversion:$fname",$home);
 1530:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1531: 	return -1;
 1532:     }
 1533:     return &do_cache_new('resversion',$fname,$answer,600);
 1534: }
 1535: 
 1536: # ----------------------------- Subscribe to a resource, return URL if possible
 1537: 
 1538: sub subscribe {
 1539:     my $fname=shift;
 1540:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1541:     $fname=~s/[\n\r]//g;
 1542:     my $author=$fname;
 1543:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1544:     my ($udom,$uname)=split(/\//,$author);
 1545:     my $home=homeserver($uname,$udom);
 1546:     if ($home eq 'no_host') {
 1547:         return 'not_found';
 1548:     }
 1549:     my $answer=reply("sub:$fname",$home);
 1550:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1551: 	$answer.=' by '.$home;
 1552:     }
 1553:     return $answer;
 1554: }
 1555:     
 1556: # -------------------------------------------------------------- Replicate file
 1557: 
 1558: sub repcopy {
 1559:     my $filename=shift;
 1560:     $filename=~s/\/+/\//g;
 1561:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1562:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1563:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1564: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1565: 	return &repcopy_userfile($filename);
 1566:     }
 1567:     $filename=~s/[\n\r]//g;
 1568:     my $transname="$filename.in.transfer";
 1569: # FIXME: this should flock
 1570:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1571:     my $remoteurl=subscribe($filename);
 1572:     if ($remoteurl =~ /^con_lost by/) {
 1573: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1574:            return 'unavailable';
 1575:     } elsif ($remoteurl eq 'not_found') {
 1576: 	   #&logthis("Subscribe returned not_found: $filename");
 1577: 	   return 'not_found';
 1578:     } elsif ($remoteurl =~ /^rejected by/) {
 1579: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1580:            return 'forbidden';
 1581:     } elsif ($remoteurl eq 'directory') {
 1582:            return 'ok';
 1583:     } else {
 1584:         my $author=$filename;
 1585:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1586:         my ($udom,$uname)=split(/\//,$author);
 1587:         my $home=homeserver($uname,$udom);
 1588:         unless ($home eq $perlvar{'lonHostID'}) {
 1589:            my @parts=split(/\//,$filename);
 1590:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1591:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1592:                &logthis("Malconfiguration for replication: $filename");
 1593: 	       return 'bad_request';
 1594:            }
 1595:            my $count;
 1596:            for ($count=5;$count<$#parts;$count++) {
 1597:                $path.="/$parts[$count]";
 1598:                if ((-e $path)!=1) {
 1599: 		   mkdir($path,0777);
 1600:                }
 1601:            }
 1602:            my $ua=new LWP::UserAgent;
 1603:            my $request=new HTTP::Request('GET',"$remoteurl");
 1604:            my $response=$ua->request($request,$transname);
 1605:            if ($response->is_error()) {
 1606: 	       unlink($transname);
 1607:                my $message=$response->status_line;
 1608:                &logthis("<font color=\"blue\">WARNING:"
 1609:                        ." LWP get: $message: $filename</font>");
 1610:                return 'unavailable';
 1611:            } else {
 1612: 	       if ($remoteurl!~/\.meta$/) {
 1613:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1614:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1615:                   if ($mresponse->is_error()) {
 1616: 		      unlink($filename.'.meta');
 1617:                       &logthis(
 1618:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1619:                   }
 1620: 	       }
 1621:                rename($transname,$filename);
 1622:                return 'ok';
 1623:            }
 1624:        }
 1625:     }
 1626: }
 1627: 
 1628: # ------------------------------------------------ Get server side include body
 1629: sub ssi_body {
 1630:     my ($filelink,%form)=@_;
 1631:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1632:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1633:     }
 1634:     my $output='';
 1635:     my $response;
 1636:     if ($filelink=~/^http\:/) {
 1637:         ($output,$response)=&externalssi($filelink);
 1638:     } else {
 1639:         ($output,$response)=&ssi($filelink,%form);
 1640:     }
 1641:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1642:     $output=~s/^.*?\<body[^\>]*\>//si;
 1643:     $output=~s/\<\/body\s*\>.*?$//si;
 1644:     if (wantarray) {
 1645:         return ($output, $response);
 1646:     } else {
 1647:         return $output;
 1648:     }
 1649: }
 1650: 
 1651: # --------------------------------------------------------- Server Side Include
 1652: 
 1653: sub absolute_url {
 1654:     my ($host_name) = @_;
 1655:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1656:     if ($host_name eq '') {
 1657: 	$host_name = $ENV{'SERVER_NAME'};
 1658:     }
 1659:     return $protocol.$host_name;
 1660: }
 1661: 
 1662: #
 1663: #   Server side include.
 1664: # Parameters:
 1665: #  fn     Possibly encrypted resource name/id.
 1666: #  form   Hash that describes how the rendering should be done
 1667: #         and other things.
 1668: # Returns:
 1669: #   Scalar context: The content of the response.
 1670: #   Array context:  2 element list of the content and the full response object.
 1671: #     
 1672: sub ssi {
 1673: 
 1674:     my ($fn,%form)=@_;
 1675:     my $ua=new LWP::UserAgent;
 1676:     my $request;
 1677: 
 1678:     $form{'no_update_last_known'}=1;
 1679:     &Apache::lonenc::check_encrypt(\$fn);
 1680:     if (%form) {
 1681:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1682:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1683:     } else {
 1684:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1685:     }
 1686: 
 1687:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1688:     my $response=$ua->request($request);
 1689: 
 1690:     if (wantarray) {
 1691: 	return ($response->content, $response);
 1692:     } else {
 1693: 	return $response->content;
 1694:     }
 1695: }
 1696: 
 1697: sub externalssi {
 1698:     my ($url)=@_;
 1699:     my $ua=new LWP::UserAgent;
 1700:     my $request=new HTTP::Request('GET',$url);
 1701:     my $response=$ua->request($request);
 1702:     if (wantarray) {
 1703:         return ($response->content, $response);
 1704:     } else {
 1705:         return $response->content;
 1706:     }
 1707: }
 1708: 
 1709: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1710: 
 1711: sub allowuploaded {
 1712:     my ($srcurl,$url)=@_;
 1713:     $url=&clutter(&declutter($url));
 1714:     my $dir=$url;
 1715:     $dir=~s/\/[^\/]+$//;
 1716:     my %httpref=();
 1717:     my $httpurl=&hreflocation('',$url);
 1718:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1719:     &Apache::lonnet::appenv(%httpref);
 1720: }
 1721: 
 1722: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1723: # input: action, courseID, current domain, intended
 1724: #        path to file, source of file, instruction to parse file for objects,
 1725: #        ref to hash for embedded objects,
 1726: #        ref to hash for codebase of java objects.
 1727: #
 1728: # output: url to file (if action was uploaddoc), 
 1729: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1730: #
 1731: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1732: # course.
 1733: #
 1734: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1735: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1736: #          course's home server.
 1737: #
 1738: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1739: #          be copied from $source (current location) to 
 1740: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1741: #         and will then be copied to
 1742: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1743: #         course's home server.
 1744: #
 1745: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1746: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1747: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1748: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1749: #         in course's home server.
 1750: #
 1751: 
 1752: sub process_coursefile {
 1753:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1754:     my $fetchresult;
 1755:     my $home=&homeserver($docuname,$docudom);
 1756:     if ($action eq 'propagate') {
 1757:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1758: 			     $home);
 1759:     } else {
 1760:         my $fpath = '';
 1761:         my $fname = $file;
 1762:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1763:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1764:         my $filepath = &build_filepath($fpath);
 1765:         if ($action eq 'copy') {
 1766:             if ($source eq '') {
 1767:                 $fetchresult = 'no source file';
 1768:                 return $fetchresult;
 1769:             } else {
 1770:                 my $destination = $filepath.'/'.$fname;
 1771:                 rename($source,$destination);
 1772:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1773:                                  $home);
 1774:             }
 1775:         } elsif ($action eq 'uploaddoc') {
 1776:             open(my $fh,'>'.$filepath.'/'.$fname);
 1777:             print $fh $env{'form.'.$source};
 1778:             close($fh);
 1779:             if ($parser eq 'parse') {
 1780:                 my $parse_result = &extract_embedded_items($filepath,$fname,$allfiles,$codebase);
 1781:                 unless ($parse_result eq 'ok') {
 1782:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1783:                 }
 1784:             }
 1785:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1786:                                  $home);
 1787:             if ($fetchresult eq 'ok') {
 1788:                 return '/uploaded/'.$fpath.'/'.$fname;
 1789:             } else {
 1790:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1791:                         ' to host '.$home.': '.$fetchresult);
 1792:                 return '/adm/notfound.html';
 1793:             }
 1794:         }
 1795:     }
 1796:     unless ( $fetchresult eq 'ok') {
 1797:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1798:              ' to host '.$home.': '.$fetchresult);
 1799:     }
 1800:     return $fetchresult;
 1801: }
 1802: 
 1803: sub build_filepath {
 1804:     my ($fpath) = @_;
 1805:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1806:     unless ($fpath eq '') {
 1807:         my @parts=split('/',$fpath);
 1808:         foreach my $part (@parts) {
 1809:             $filepath.= '/'.$part;
 1810:             if ((-e $filepath)!=1) {
 1811:                 mkdir($filepath,0777);
 1812:             }
 1813:         }
 1814:     }
 1815:     return $filepath;
 1816: }
 1817: 
 1818: sub store_edited_file {
 1819:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1820:     my $file = $primary_url;
 1821:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1822:     my $fpath = '';
 1823:     my $fname = $file;
 1824:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1825:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1826:     my $filepath = &build_filepath($fpath);
 1827:     open(my $fh,'>'.$filepath.'/'.$fname);
 1828:     print $fh $content;
 1829:     close($fh);
 1830:     my $home=&homeserver($docuname,$docudom);
 1831:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1832: 			  $home);
 1833:     if ($$fetchresult eq 'ok') {
 1834:         return '/uploaded/'.$fpath.'/'.$fname;
 1835:     } else {
 1836:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1837: 		 ' to host '.$home.': '.$$fetchresult);
 1838:         return '/adm/notfound.html';
 1839:     }
 1840: }
 1841: 
 1842: sub clean_filename {
 1843:     my ($fname,$args)=@_;
 1844: # Replace Windows backslashes by forward slashes
 1845:     $fname=~s/\\/\//g;
 1846:     if (!$args->{'keep_path'}) {
 1847:         # Get rid of everything but the actual filename
 1848: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 1849:     }
 1850: # Replace spaces by underscores
 1851:     $fname=~s/\s+/\_/g;
 1852: # Replace all other weird characters by nothing
 1853:     $fname=~s{[^/\w\.\-]}{}g;
 1854: # Replace all .\d. sequences with _\d. so they no longer look like version
 1855: # numbers
 1856:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 1857:     return $fname;
 1858: }
 1859: 
 1860: # --------------- Take an uploaded file and put it into the userfiles directory
 1861: # input: $formname - the contents of the file are in $env{"form.$formname"}
 1862: #                    the desired filenam is in $env{"form.$formname.filename"}
 1863: #        $coursedoc - if true up to the current course
 1864: #                     if false
 1865: #        $subdir - directory in userfile to store the file into
 1866: #        $parser - instruction to parse file for objects ($parser = parse)    
 1867: #        $allfiles - reference to hash for embedded objects
 1868: #        $codebase - reference to hash for codebase of java objects
 1869: #        $desuname - username for permanent storage of uploaded file
 1870: #        $dsetudom - domain for permanaent storage of uploaded file
 1871: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 1872: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 1873: # 
 1874: # output: url of file in userspace, or error: <message> 
 1875: #             or /adm/notfound.html if failure to upload occurse
 1876: 
 1877: 
 1878: sub userfileupload {
 1879:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 1880:         $destudom,$thumbwidth,$thumbheight)=@_;
 1881:     if (!defined($subdir)) { $subdir='unknown'; }
 1882:     my $fname=$env{'form.'.$formname.'.filename'};
 1883:     $fname=&clean_filename($fname);
 1884: # See if there is anything left
 1885:     unless ($fname) { return 'error: no uploaded file'; }
 1886:     chop($env{'form.'.$formname});
 1887:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 1888:         my $now = time;
 1889:         my $filepath = 'tmp/helprequests/'.$now;
 1890:         my @parts=split(/\//,$filepath);
 1891:         my $fullpath = $perlvar{'lonDaemons'};
 1892:         for (my $i=0;$i<@parts;$i++) {
 1893:             $fullpath .= '/'.$parts[$i];
 1894:             if ((-e $fullpath)!=1) {
 1895:                 mkdir($fullpath,0777);
 1896:             }
 1897:         }
 1898:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1899:         print $fh $env{'form.'.$formname};
 1900:         close($fh);
 1901:         return $fullpath.'/'.$fname;
 1902:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 1903:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 1904:                        '_'.$env{'user.domain'}.'/pending';
 1905:         my @parts=split(/\//,$filepath);
 1906:         my $fullpath = $perlvar{'lonDaemons'};
 1907:         for (my $i=0;$i<@parts;$i++) {
 1908:             $fullpath .= '/'.$parts[$i];
 1909:             if ((-e $fullpath)!=1) {
 1910:                 mkdir($fullpath,0777);
 1911:             }
 1912:         }
 1913:         open(my $fh,'>'.$fullpath.'/'.$fname);
 1914:         print $fh $env{'form.'.$formname};
 1915:         close($fh);
 1916:         return $fullpath.'/'.$fname;
 1917:     }
 1918:     
 1919: # Create the directory if not present
 1920:     $fname="$subdir/$fname";
 1921:     if ($coursedoc) {
 1922: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1923: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1924:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 1925:             return &finishuserfileupload($docuname,$docudom,
 1926: 					 $formname,$fname,$parser,$allfiles,
 1927: 					 $codebase,$thumbwidth,$thumbheight);
 1928:         } else {
 1929:             $fname=$env{'form.folder'}.'/'.$fname;
 1930:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 1931: 				       $fname,$formname,$parser,
 1932: 				       $allfiles,$codebase);
 1933:         }
 1934:     } elsif (defined($destuname)) {
 1935:         my $docuname=$destuname;
 1936:         my $docudom=$destudom;
 1937: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1938: 				     $parser,$allfiles,$codebase,
 1939:                                      $thumbwidth,$thumbheight);
 1940:         
 1941:     } else {
 1942:         my $docuname=$env{'user.name'};
 1943:         my $docudom=$env{'user.domain'};
 1944:         if (exists($env{'form.group'})) {
 1945:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 1946:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1947:         }
 1948: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 1949: 				     $parser,$allfiles,$codebase,
 1950:                                      $thumbwidth,$thumbheight);
 1951:     }
 1952: }
 1953: 
 1954: sub finishuserfileupload {
 1955:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 1956:         $thumbwidth,$thumbheight) = @_;
 1957:     my $path=$docudom.'/'.$docuname.'/';
 1958:     my $filepath=$perlvar{'lonDocRoot'};
 1959:     my ($fnamepath,$file,$fetchthumb);
 1960:     $file=$fname;
 1961:     if ($fname=~m|/|) {
 1962:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 1963: 	$path.=$fnamepath.'/';
 1964:     }
 1965:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 1966:     my $count;
 1967:     for ($count=4;$count<=$#parts;$count++) {
 1968:         $filepath.="/$parts[$count]";
 1969:         if ((-e $filepath)!=1) {
 1970: 	    mkdir($filepath,0777);
 1971:         }
 1972:     }
 1973: # Save the file
 1974:     {
 1975: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 1976: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 1977: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 1978: 	    return '/adm/notfound.html';
 1979: 	}
 1980: 	if (!print FH ($env{'form.'.$formname})) {
 1981: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 1982: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 1983: 	    return '/adm/notfound.html';
 1984: 	}
 1985: 	close(FH);
 1986:     }
 1987:     if ($parser eq 'parse') {
 1988:         my $parse_result = &extract_embedded_items($filepath,$file,$allfiles,
 1989: 						   $codebase);
 1990:         unless ($parse_result eq 'ok') {
 1991:             &logthis('Failed to parse '.$filepath.$file.
 1992: 		     ' for embedded media: '.$parse_result); 
 1993:         }
 1994:     }
 1995:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 1996:         my $input = $filepath.'/'.$file;
 1997:         my $output = $filepath.'/'.'tn-'.$file;
 1998:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 1999:         system("convert -sample $thumbsize $input $output");
 2000:         if (-e $filepath.'/'.'tn-'.$file) {
 2001:             $fetchthumb  = 1; 
 2002:         }
 2003:     }
 2004:  
 2005: # Notify homeserver to grep it
 2006: #
 2007:     my $docuhome=&homeserver($docuname,$docudom);
 2008:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2009:     if ($fetchresult eq 'ok') {
 2010:         if ($fetchthumb) {
 2011:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2012:             if ($thumbresult ne 'ok') {
 2013:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2014:                          $docuhome.': '.$thumbresult);
 2015:             }
 2016:         }
 2017: #
 2018: # Return the URL to it
 2019:         return '/uploaded/'.$path.$file;
 2020:     } else {
 2021:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2022: 		 ': '.$fetchresult);
 2023:         return '/adm/notfound.html';
 2024:     }
 2025: }
 2026: 
 2027: sub extract_embedded_items {
 2028:     my ($filepath,$file,$allfiles,$codebase,$content) = @_;
 2029:     my @state = ();
 2030:     my %javafiles = (
 2031:                       codebase => '',
 2032:                       code => '',
 2033:                       archive => ''
 2034:                     );
 2035:     my %mediafiles = (
 2036:                       src => '',
 2037:                       movie => '',
 2038:                      );
 2039:     my $p;
 2040:     if ($content) {
 2041:         $p = HTML::LCParser->new($content);
 2042:     } else {
 2043:         $p = HTML::LCParser->new($filepath.'/'.$file);
 2044:     }
 2045:     while (my $t=$p->get_token()) {
 2046: 	if ($t->[0] eq 'S') {
 2047: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2048: 	    push(@state, $tagname);
 2049:             if (lc($tagname) eq 'allow') {
 2050:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2051:             }
 2052: 	    if (lc($tagname) eq 'img') {
 2053: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2054: 	    }
 2055: 	    if (lc($tagname) eq 'a') {
 2056: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2057: 	    }
 2058:             if (lc($tagname) eq 'script') {
 2059:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2060:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2061:                 } else {
 2062:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2063:                 }
 2064:             }
 2065:             if (lc($tagname) eq 'link') {
 2066:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2067:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2068:                 }
 2069:             }
 2070: 	    if (lc($tagname) eq 'object' ||
 2071: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2072: 		foreach my $item (keys(%javafiles)) {
 2073: 		    $javafiles{$item} = '';
 2074: 		}
 2075: 	    }
 2076: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2077: 		my $name = lc($attr->{'name'});
 2078: 		foreach my $item (keys(%javafiles)) {
 2079: 		    if ($name eq $item) {
 2080: 			$javafiles{$item} = $attr->{'value'};
 2081: 			last;
 2082: 		    }
 2083: 		}
 2084: 		foreach my $item (keys(%mediafiles)) {
 2085: 		    if ($name eq $item) {
 2086: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2087: 			last;
 2088: 		    }
 2089: 		}
 2090: 	    }
 2091: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2092: 		foreach my $item (keys(%javafiles)) {
 2093: 		    if ($attr->{$item}) {
 2094: 			$javafiles{$item} = $attr->{$item};
 2095: 			last;
 2096: 		    }
 2097: 		}
 2098: 		foreach my $item (keys(%mediafiles)) {
 2099: 		    if ($attr->{$item}) {
 2100: 			&add_filetype($allfiles,$attr->{$item},$item);
 2101: 			last;
 2102: 		    }
 2103: 		}
 2104: 	    }
 2105: 	} elsif ($t->[0] eq 'E') {
 2106: 	    my ($tagname) = ($t->[1]);
 2107: 	    if ($javafiles{'codebase'} ne '') {
 2108: 		$javafiles{'codebase'} .= '/';
 2109: 	    }  
 2110: 	    if (lc($tagname) eq 'applet' ||
 2111: 		lc($tagname) eq 'object' ||
 2112: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2113: 		) {
 2114: 		foreach my $item (keys(%javafiles)) {
 2115: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2116: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2117: 			&add_filetype($allfiles,$file,$item);
 2118: 		    }
 2119: 		}
 2120: 	    } 
 2121: 	    pop @state;
 2122: 	}
 2123:     }
 2124:     return 'ok';
 2125: }
 2126: 
 2127: sub add_filetype {
 2128:     my ($allfiles,$file,$type)=@_;
 2129:     if (exists($allfiles->{$file})) {
 2130: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2131: 	    push(@{$allfiles->{$file}}, &escape($type));
 2132: 	}
 2133:     } else {
 2134: 	@{$allfiles->{$file}} = (&escape($type));
 2135:     }
 2136: }
 2137: 
 2138: sub removeuploadedurl {
 2139:     my ($url)=@_;
 2140:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2141:     return &removeuserfile($uname,$udom,$fname);
 2142: }
 2143: 
 2144: sub removeuserfile {
 2145:     my ($docuname,$docudom,$fname)=@_;
 2146:     my $home=&homeserver($docuname,$docudom);
 2147:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2148:     if ($result eq 'ok') {
 2149:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2150:             my $metafile = $fname.'.meta';
 2151:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2152: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2153:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2154:             my $sqlresult = 
 2155:                 &update_portfolio_table($docuname,$docudom,$file,
 2156:                                         'portfolio_metadata',$group,
 2157:                                         'delete');
 2158:         }
 2159:     }
 2160:     return $result;
 2161: }
 2162: 
 2163: sub mkdiruserfile {
 2164:     my ($docuname,$docudom,$dir)=@_;
 2165:     my $home=&homeserver($docuname,$docudom);
 2166:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2167: }
 2168: 
 2169: sub renameuserfile {
 2170:     my ($docuname,$docudom,$old,$new)=@_;
 2171:     my $home=&homeserver($docuname,$docudom);
 2172:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2173:                         &escape("$old").':'.&escape("$new"),$home);
 2174:     if ($result eq 'ok') {
 2175:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2176:             my $oldmeta = $old.'.meta';
 2177:             my $newmeta = $new.'.meta';
 2178:             my $metaresult = 
 2179:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2180: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2181:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2182:             my $sqlresult = 
 2183:                 &update_portfolio_table($docuname,$docudom,$file,
 2184:                                         'portfolio_metadata',$group,
 2185:                                         'delete');
 2186:         }
 2187:     }
 2188:     return $result;
 2189: }
 2190: 
 2191: # ------------------------------------------------------------------------- Log
 2192: 
 2193: sub log {
 2194:     my ($dom,$nam,$hom,$what)=@_;
 2195:     return critical("log:$dom:$nam:$what",$hom);
 2196: }
 2197: 
 2198: # ------------------------------------------------------------------ Course Log
 2199: #
 2200: # This routine flushes several buffers of non-mission-critical nature
 2201: #
 2202: 
 2203: sub flushcourselogs {
 2204:     &logthis('Flushing log buffers');
 2205: #
 2206: # course logs
 2207: # This is a log of all transactions in a course, which can be used
 2208: # for data mining purposes
 2209: #
 2210: # It also collects the courseid database, which lists last transaction
 2211: # times and course titles for all courseids
 2212: #
 2213:     my %courseidbuffer=();
 2214:     foreach my $crsid (keys(%courselogs)) {
 2215:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2216: 		          &escape($courselogs{$crsid}),
 2217: 		          $coursehombuf{$crsid}) eq 'ok') {
 2218: 	    delete $courselogs{$crsid};
 2219:         } else {
 2220:             &logthis('Failed to flush log buffer for '.$crsid);
 2221:             if (length($courselogs{$crsid})>40000) {
 2222:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2223:                         " exceeded maximum size, deleting.</font>");
 2224:                delete $courselogs{$crsid};
 2225:             }
 2226:         }
 2227:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2228:             'description' => $coursedescrbuf{$crsid},
 2229:             'inst_code'    => $courseinstcodebuf{$crsid},
 2230:             'type'        => $coursetypebuf{$crsid},
 2231:             'owner'       => $courseownerbuf{$crsid},
 2232:         };
 2233:     }
 2234: #
 2235: # Write course id database (reverse lookup) to homeserver of courses 
 2236: # Is used in pickcourse
 2237: #
 2238:     foreach my $crs_home (keys(%courseidbuffer)) {
 2239:         my $response = &courseidput(&host_domain($crs_home),
 2240:                                     $courseidbuffer{$crs_home},
 2241:                                     $crs_home,'timeonly');
 2242:     }
 2243: #
 2244: # File accesses
 2245: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2246: #
 2247:     foreach my $entry (keys(%accesshash)) {
 2248:         if ($entry =~ /___count$/) {
 2249:             my ($dom,$name);
 2250:             ($dom,$name,undef)=
 2251: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2252:             if (! defined($dom) || $dom eq '' || 
 2253:                 ! defined($name) || $name eq '') {
 2254:                 my $cid = $env{'request.course.id'};
 2255:                 $dom  = $env{'request.'.$cid.'.domain'};
 2256:                 $name = $env{'request.'.$cid.'.num'};
 2257:             }
 2258:             my $value = $accesshash{$entry};
 2259:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2260:             my %temphash=($url => $value);
 2261:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2262:             if ($result eq 'ok') {
 2263:                 delete $accesshash{$entry};
 2264:             } elsif ($result eq 'unknown_cmd') {
 2265:                 # Target server has old code running on it.
 2266:                 my %temphash=($entry => $value);
 2267:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2268:                     delete $accesshash{$entry};
 2269:                 }
 2270:             }
 2271:         } else {
 2272:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2273:             my %temphash=($entry => $accesshash{$entry});
 2274:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2275:                 delete $accesshash{$entry};
 2276:             }
 2277:         }
 2278:     }
 2279: #
 2280: # Roles
 2281: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2282: #
 2283:     foreach my $entry (keys(%userrolehash)) {
 2284:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2285: 	    split(/\:/,$entry);
 2286:         if (&Apache::lonnet::put('nohist_userroles',
 2287:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2288:                 $rudom,$runame) eq 'ok') {
 2289: 	    delete $userrolehash{$entry};
 2290:         }
 2291:     }
 2292: #
 2293: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2294: #
 2295:     my %domrolebuffer = ();
 2296:     foreach my $entry (keys %domainrolehash) {
 2297:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2298:         if ($domrolebuffer{$rudom}) {
 2299:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2300:                       '='.&escape($domainrolehash{$entry});
 2301:         } else {
 2302:             $domrolebuffer{$rudom}.=&escape($entry).
 2303:                       '='.&escape($domainrolehash{$entry});
 2304:         }
 2305:         delete $domainrolehash{$entry};
 2306:     }
 2307:     foreach my $dom (keys(%domrolebuffer)) {
 2308: 	my %servers = &get_servers($dom,'library');
 2309: 	foreach my $tryserver (keys(%servers)) {
 2310: 	    unless (&reply('domroleput:'.$dom.':'.
 2311: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2312: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2313: 	    }
 2314:         }
 2315:     }
 2316:     $dumpcount++;
 2317: }
 2318: 
 2319: sub courselog {
 2320:     my $what=shift;
 2321:     $what=time.':'.$what;
 2322:     unless ($env{'request.course.id'}) { return ''; }
 2323:     $coursedombuf{$env{'request.course.id'}}=
 2324:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2325:     $coursenumbuf{$env{'request.course.id'}}=
 2326:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2327:     $coursehombuf{$env{'request.course.id'}}=
 2328:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2329:     $coursedescrbuf{$env{'request.course.id'}}=
 2330:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2331:     $courseinstcodebuf{$env{'request.course.id'}}=
 2332:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2333:     $courseownerbuf{$env{'request.course.id'}}=
 2334:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2335:     $coursetypebuf{$env{'request.course.id'}}=
 2336:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2337:     if (defined $courselogs{$env{'request.course.id'}}) {
 2338: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2339:     } else {
 2340: 	$courselogs{$env{'request.course.id'}}.=$what;
 2341:     }
 2342:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2343: 	&flushcourselogs();
 2344:     }
 2345: }
 2346: 
 2347: sub courseacclog {
 2348:     my $fnsymb=shift;
 2349:     unless ($env{'request.course.id'}) { return ''; }
 2350:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2351:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2352:         $what.=':POST';
 2353:         # FIXME: Probably ought to escape things....
 2354: 	foreach my $key (keys(%env)) {
 2355:             if ($key=~/^form\.(.*)/) {
 2356: 		$what.=':'.$1.'='.$env{$key};
 2357:             }
 2358:         }
 2359:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2360:         # FIXME: We should not be depending on a form parameter that someone
 2361:         # editing lonsearchcat.pm might change in the future.
 2362:         if ($env{'form.phase'} eq 'course_search') {
 2363:             $what.= ':POST';
 2364:             # FIXME: Probably ought to escape things....
 2365:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2366:                                  'crsdiscuss') {
 2367:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2368:             }
 2369:         }
 2370:     }
 2371:     &courselog($what);
 2372: }
 2373: 
 2374: sub countacc {
 2375:     my $url=&declutter(shift);
 2376:     return if (! defined($url) || $url eq '');
 2377:     unless ($env{'request.course.id'}) { return ''; }
 2378:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2379:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2380:     $accesshash{$key}++;
 2381: }
 2382: 
 2383: sub linklog {
 2384:     my ($from,$to)=@_;
 2385:     $from=&declutter($from);
 2386:     $to=&declutter($to);
 2387:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2388:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2389: }
 2390:   
 2391: sub userrolelog {
 2392:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2393:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2394:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2395:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2396:         ($trole=~/^ta/)) {
 2397:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2398:        $userrolehash
 2399:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2400:                     =$tend.':'.$tstart;
 2401:     }
 2402:     if (($env{'request.role'} =~ /dc\./) &&
 2403: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2404: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2405: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2406:        $userrolehash
 2407:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2408:                     =$tend.':'.$tstart;
 2409:     }
 2410:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2411:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2412:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2413:         ($trole=~/^sc/)) {
 2414:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2415:        $domainrolehash
 2416:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2417:                     = $tend.':'.$tstart;
 2418:     }
 2419: }
 2420: 
 2421: sub get_course_adv_roles {
 2422:     my $cid=shift;
 2423:     $cid=$env{'request.course.id'} unless (defined($cid));
 2424:     my %coursehash=&coursedescription($cid);
 2425:     my %nothide=();
 2426:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2427:         if ($user !~ /:/) {
 2428: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2429:         } else {
 2430:             $nothide{$user}=1;
 2431:         }
 2432:     }
 2433:     my %returnhash=();
 2434:     my %dumphash=
 2435:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2436:     my $now=time;
 2437:     foreach my $entry (keys %dumphash) {
 2438: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2439:         if (($tstart) && ($tstart<0)) { next; }
 2440:         if (($tend) && ($tend<$now)) { next; }
 2441:         if (($tstart) && ($now<$tstart)) { next; }
 2442:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2443: 	if ($username eq '' || $domain eq '') { next; }
 2444: 	if ((&privileged($username,$domain)) && 
 2445: 	    (!$nothide{$username.':'.$domain})) { next; }
 2446: 	if ($role eq 'cr') { next; }
 2447:         my $key=&plaintext($role);
 2448:         if ($section) { $key.=' (Sec/Grp '.$section.')'; }
 2449:         if ($returnhash{$key}) {
 2450: 	    $returnhash{$key}.=','.$username.':'.$domain;
 2451:         } else {
 2452:             $returnhash{$key}=$username.':'.$domain;
 2453:         }
 2454:      }
 2455:     return %returnhash;
 2456: }
 2457: 
 2458: sub get_my_roles {
 2459:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2460:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2461:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2462:     my (%dumphash,%nothide);
 2463:     if ($context eq 'userroles') { 
 2464:         %dumphash = &dump('roles',$udom,$uname);
 2465:     } else {
 2466:         %dumphash=
 2467:             &dump('nohist_userroles',$udom,$uname);
 2468:         if ($hidepriv) {
 2469:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2470:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2471:                 if ($user !~ /:/) {
 2472:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2473:                 } else {
 2474:                     $nothide{$user} = 1;
 2475:                 }
 2476:             }
 2477:         }
 2478:     }
 2479:     my %returnhash=();
 2480:     my $now=time;
 2481:     foreach my $entry (keys(%dumphash)) {
 2482:         my ($role,$tend,$tstart);
 2483:         if ($context eq 'userroles') {
 2484: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2485:         } else {
 2486:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2487:         }
 2488:         if (($tstart) && ($tstart<0)) { next; }
 2489:         my $status = 'active';
 2490:         if (($tend) && ($tend<=$now)) {
 2491:             $status = 'previous';
 2492:         } 
 2493:         if (($tstart) && ($now<$tstart)) {
 2494:             $status = 'future';
 2495:         }
 2496:         if (ref($types) eq 'ARRAY') {
 2497:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2498:                 next;
 2499:             } 
 2500:         } else {
 2501:             if ($status ne 'active') {
 2502:                 next;
 2503:             }
 2504:         }
 2505:         my ($rolecode,$username,$domain,$section,$area);
 2506:         if ($context eq 'userroles') {
 2507:             ($area,$rolecode) = split(/_/,$entry);
 2508:             (undef,$domain,$username,$section) = split(/\//,$area);
 2509:         } else {
 2510:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2511:         }
 2512:         if (ref($roledoms) eq 'ARRAY') {
 2513:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2514:                 next;
 2515:             }
 2516:         }
 2517:         if (ref($roles) eq 'ARRAY') {
 2518:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2519:                 if ($role =~ /^cr\//) {
 2520:                     if (!grep(/^cr$/,@{$roles})) {
 2521:                         next;
 2522:                     }
 2523:                 } else {
 2524:                     next;
 2525:                 }
 2526:             }
 2527:         }
 2528:         if ($hidepriv) {
 2529:             if ((&privileged($username,$domain)) &&
 2530:                 (!$nothide{$username.':'.$domain})) { 
 2531:                 next;
 2532:             }
 2533:         }
 2534:         if ($withsec) {
 2535:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2536:                 $tstart.':'.$tend;
 2537:         } else {
 2538:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2539:         }
 2540:     }
 2541:     return %returnhash;
 2542: }
 2543: 
 2544: # ----------------------------------------------------- Frontpage Announcements
 2545: #
 2546: #
 2547: 
 2548: sub postannounce {
 2549:     my ($server,$text)=@_;
 2550:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2551:     unless ($text=~/\w/) { $text=''; }
 2552:     return &reply('setannounce:'.&escape($text),$server);
 2553: }
 2554: 
 2555: sub getannounce {
 2556: 
 2557:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2558: 	my $announcement='';
 2559: 	while (my $line = <$fh>) { $announcement .= $line; }
 2560: 	close($fh);
 2561: 	if ($announcement=~/\w/) { 
 2562: 	    return 
 2563:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2564:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2565: 	} else {
 2566: 	    return '';
 2567: 	}
 2568:     } else {
 2569: 	return '';
 2570:     }
 2571: }
 2572: 
 2573: # ---------------------------------------------------------- Course ID routines
 2574: # Deal with domain's nohist_courseid.db files
 2575: #
 2576: 
 2577: sub courseidput {
 2578:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2579:     my $outcome;
 2580:     if ($caller eq 'timeonly') {
 2581:         my $cids = '';
 2582:         foreach my $item (keys(%$storehash)) {
 2583:             $cids.=&escape($item).'&';
 2584:         }
 2585:         $cids=~s/\&$//;
 2586:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2587:                           $coursehome);       
 2588:     } else {
 2589:         my $items = '';
 2590:         foreach my $item (keys(%$storehash)) {
 2591:             $items.= &escape($item).'='.
 2592:                      &freeze_escape($$storehash{$item}).'&';
 2593:         }
 2594:         $items=~s/\&$//;
 2595:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2596:                           $coursehome);
 2597:     }
 2598:     if ($outcome eq 'unknown_cmd') {
 2599:         my $what;
 2600:         foreach my $cid (keys(%$storehash)) {
 2601:             $what .= &escape($cid).'=';
 2602:             foreach my $item ('description','inst_code','owner','type') {
 2603:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2604:             }
 2605:             $what =~ s/\:$/&/;
 2606:         }
 2607:         $what =~ s/\&$//;  
 2608:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2609:     } else {
 2610:         return $outcome;
 2611:     }
 2612: }
 2613: 
 2614: sub courseiddump {
 2615:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2616:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok)=@_;
 2617:     my $as_hash = 1;
 2618:     my %returnhash;
 2619:     if (!$domfilter) { $domfilter=''; }
 2620:     my %libserv = &all_library();
 2621:     foreach my $tryserver (keys(%libserv)) {
 2622:         if ( (  $hostidflag == 1 
 2623: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2624: 	     || (!defined($hostidflag)) ) {
 2625: 
 2626: 	    if (($domfilter eq '') ||
 2627: 		(&host_domain($tryserver) eq $domfilter)) {
 2628:                 my $rep = 
 2629:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2630:                          $sincefilter.':'.&escape($descfilter).':'.
 2631:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2632:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2633:                          ':'.&escape($regexp_ok).':'.$as_hash,$tryserver);
 2634:                 my @pairs=split(/\&/,$rep);
 2635:                 foreach my $item (@pairs) {
 2636:                     my ($key,$value)=split(/\=/,$item,2);
 2637:                     $key = &unescape($key);
 2638:                     next if ($key =~ /^error: 2 /);
 2639:                     my $result = &thaw_unescape($value);
 2640:                     if (ref($result) eq 'HASH') {
 2641:                         $returnhash{$key}=$result;
 2642:                     } else {
 2643:                         my @responses = split(/:/,$value);
 2644:                         my @items = ('description','inst_code','owner','type');
 2645:                         for (my $i=0; $i<@responses; $i++) {
 2646:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2647:                         }
 2648:                     } 
 2649:                 }
 2650:             }
 2651:         }
 2652:     }
 2653:     return %returnhash;
 2654: }
 2655: 
 2656: # ---------------------------------------------------------- DC e-mail
 2657: 
 2658: sub dcmailput {
 2659:     my ($domain,$msgid,$message,$server)=@_;
 2660:     my $status = &Apache::lonnet::critical(
 2661:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2662:        &escape($message),$server);
 2663:     return $status;
 2664: }
 2665: 
 2666: sub dcmaildump {
 2667:     my ($dom,$startdate,$enddate,$senders) = @_;
 2668:     my %returnhash=();
 2669: 
 2670:     if (defined(&domain($dom,'primary'))) {
 2671:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2672:                                                          &escape($enddate).':';
 2673: 	my @esc_senders=map { &escape($_)} @$senders;
 2674: 	$cmd.=&escape(join('&',@esc_senders));
 2675: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2676:             my ($key,$value) = split(/\=/,$line,2);
 2677:             if (($key) && ($value)) {
 2678:                 $returnhash{&unescape($key)} = &unescape($value);
 2679:             }
 2680:         }
 2681:     }
 2682:     return %returnhash;
 2683: }
 2684: # ---------------------------------------------------------- Domain roles
 2685: 
 2686: sub get_domain_roles {
 2687:     my ($dom,$roles,$startdate,$enddate)=@_;
 2688:     if (undef($startdate) || $startdate eq '') {
 2689:         $startdate = '.';
 2690:     }
 2691:     if (undef($enddate) || $enddate eq '') {
 2692:         $enddate = '.';
 2693:     }
 2694:     my $rolelist;
 2695:     if (ref($roles) eq 'ARRAY') {
 2696:         $rolelist = join(':',@{$roles});
 2697:     }
 2698:     my %personnel = ();
 2699: 
 2700:     my %servers = &get_servers($dom,'library');
 2701:     foreach my $tryserver (keys(%servers)) {
 2702: 	%{$personnel{$tryserver}}=();
 2703: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2704: 					    &escape($startdate).':'.
 2705: 					    &escape($enddate).':'.
 2706: 					    &escape($rolelist), $tryserver))) {
 2707: 	    my ($key,$value) = split(/\=/,$line,2);
 2708: 	    if (($key) && ($value)) {
 2709: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2710: 	    }
 2711: 	}
 2712:     }
 2713:     return %personnel;
 2714: }
 2715: 
 2716: # ----------------------------------------------------------- Check out an item
 2717: 
 2718: sub get_first_access {
 2719:     my ($type,$argsymb)=@_;
 2720:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2721:     if ($argsymb) { $symb=$argsymb; }
 2722:     my ($map,$id,$res)=&decode_symb($symb);
 2723:     if ($type eq 'course') {
 2724: 	$res='course';
 2725:     } elsif ($type eq 'map') {
 2726: 	$res=&symbread($map);
 2727:     } else {
 2728: 	$res=$symb;
 2729:     }
 2730:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2731:     return $times{"$courseid\0$res"};
 2732: }
 2733: 
 2734: sub set_first_access {
 2735:     my ($type)=@_;
 2736:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2737:     my ($map,$id,$res)=&decode_symb($symb);
 2738:     if ($type eq 'course') {
 2739: 	$res='course';
 2740:     } elsif ($type eq 'map') {
 2741: 	$res=&symbread($map);
 2742:     } else {
 2743: 	$res=$symb;
 2744:     }
 2745:     my $firstaccess=&get_first_access($type,$symb);
 2746:     if (!$firstaccess) {
 2747: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2748:     }
 2749:     return 'already_set';
 2750: }
 2751: 
 2752: sub checkout {
 2753:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2754:     my $now=time;
 2755:     my $lonhost=$perlvar{'lonHostID'};
 2756:     my $infostr=&escape(
 2757:                  'CHECKOUTTOKEN&'.
 2758:                  $tuname.'&'.
 2759:                  $tudom.'&'.
 2760:                  $tcrsid.'&'.
 2761:                  $symb.'&'.
 2762: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2763:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2764:     if ($token=~/^error\:/) { 
 2765:         &logthis("<font color=\"blue\">WARNING: ".
 2766:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2767:                  "</font>");
 2768:         return ''; 
 2769:     }
 2770: 
 2771:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2772:     $token=~tr/a-z/A-Z/;
 2773: 
 2774:     my %infohash=('resource.0.outtoken' => $token,
 2775:                   'resource.0.checkouttime' => $now,
 2776:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2777: 
 2778:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2779:        return '';
 2780:     } else {
 2781:         &logthis("<font color=\"blue\">WARNING: ".
 2782:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2783:                  "</font>");
 2784:     }    
 2785: 
 2786:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2787:                          &escape('Checkout '.$infostr.' - '.
 2788:                                                  $token)) ne 'ok') {
 2789: 	return '';
 2790:     } else {
 2791:         &logthis("<font color=\"blue\">WARNING: ".
 2792:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2793:                  "</font>");
 2794:     }
 2795:     return $token;
 2796: }
 2797: 
 2798: # ------------------------------------------------------------ Check in an item
 2799: 
 2800: sub checkin {
 2801:     my $token=shift;
 2802:     my $now=time;
 2803:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 2804:     $lonhost=~tr/A-Z/a-z/;
 2805:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 2806:     $dtoken=~s/\W/\_/g;
 2807:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 2808:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 2809: 
 2810:     unless (($tuname) && ($tudom)) {
 2811:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 2812:         return '';
 2813:     }
 2814:     
 2815:     unless (&allowed('mgr',$tcrsid)) {
 2816:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 2817:                  $env{'user.name'}.' - '.$env{'user.domain'});
 2818:         return '';
 2819:     }
 2820: 
 2821:     my %infohash=('resource.0.intoken' => $token,
 2822:                   'resource.0.checkintime' => $now,
 2823:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 2824: 
 2825:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2826:        return '';
 2827:     }    
 2828: 
 2829:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2830:                          &escape('Checkin - '.$token)) ne 'ok') {
 2831: 	return '';
 2832:     }
 2833: 
 2834:     return ($symb,$tuname,$tudom,$tcrsid);    
 2835: }
 2836: 
 2837: # --------------------------------------------- Set Expire Date for Spreadsheet
 2838: 
 2839: sub expirespread {
 2840:     my ($uname,$udom,$stype,$usymb)=@_;
 2841:     my $cid=$env{'request.course.id'}; 
 2842:     if ($cid) {
 2843:        my $now=time;
 2844:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 2845:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 2846:                             $env{'course.'.$cid.'.num'}.
 2847: 	        	    ':nohist_expirationdates:'.
 2848:                             &escape($key).'='.$now,
 2849:                             $env{'course.'.$cid.'.home'})
 2850:     }
 2851:     return 'ok';
 2852: }
 2853: 
 2854: # ----------------------------------------------------- Devalidate Spreadsheets
 2855: 
 2856: sub devalidate {
 2857:     my ($symb,$uname,$udom)=@_;
 2858:     my $cid=$env{'request.course.id'}; 
 2859:     if ($cid) {
 2860:         # delete the stored spreadsheets for
 2861:         # - the student level sheet of this user in course's homespace
 2862:         # - the assessment level sheet for this resource 
 2863:         #   for this user in user's homespace
 2864: 	# - current conditional state info
 2865: 	my $key=$uname.':'.$udom.':';
 2866:         my $status=
 2867: 	    &del('nohist_calculatedsheets',
 2868: 		 [$key.'studentcalc:'],
 2869: 		 $env{'course.'.$cid.'.domain'},
 2870: 		 $env{'course.'.$cid.'.num'})
 2871: 		.' '.
 2872: 	    &del('nohist_calculatedsheets_'.$cid,
 2873: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 2874:         unless ($status eq 'ok ok') {
 2875:            &logthis('Could not devalidate spreadsheet '.
 2876:                     $uname.' at '.$udom.' for '.
 2877: 		    $symb.': '.$status);
 2878:         }
 2879: 	&delenv('user.state.'.$cid);
 2880:     }
 2881: }
 2882: 
 2883: sub get_scalar {
 2884:     my ($string,$end) = @_;
 2885:     my $value;
 2886:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 2887: 	$value = $1;
 2888:     } elsif ($$string =~ s/^([^&]*?)&//) {
 2889: 	$value = $1;
 2890:     }
 2891:     return &unescape($value);
 2892: }
 2893: 
 2894: sub array2str {
 2895:   my (@array) = @_;
 2896:   my $result=&arrayref2str(\@array);
 2897:   $result=~s/^__ARRAY_REF__//;
 2898:   $result=~s/__END_ARRAY_REF__$//;
 2899:   return $result;
 2900: }
 2901: 
 2902: sub arrayref2str {
 2903:   my ($arrayref) = @_;
 2904:   my $result='__ARRAY_REF__';
 2905:   foreach my $elem (@$arrayref) {
 2906:     if(ref($elem) eq 'ARRAY') {
 2907:       $result.=&arrayref2str($elem).'&';
 2908:     } elsif(ref($elem) eq 'HASH') {
 2909:       $result.=&hashref2str($elem).'&';
 2910:     } elsif(ref($elem)) {
 2911:       #print("Got a ref of ".(ref($elem))." skipping.");
 2912:     } else {
 2913:       $result.=&escape($elem).'&';
 2914:     }
 2915:   }
 2916:   $result=~s/\&$//;
 2917:   $result .= '__END_ARRAY_REF__';
 2918:   return $result;
 2919: }
 2920: 
 2921: sub hash2str {
 2922:   my (%hash) = @_;
 2923:   my $result=&hashref2str(\%hash);
 2924:   $result=~s/^__HASH_REF__//;
 2925:   $result=~s/__END_HASH_REF__$//;
 2926:   return $result;
 2927: }
 2928: 
 2929: sub hashref2str {
 2930:   my ($hashref)=@_;
 2931:   my $result='__HASH_REF__';
 2932:   foreach my $key (sort(keys(%$hashref))) {
 2933:     if (ref($key) eq 'ARRAY') {
 2934:       $result.=&arrayref2str($key).'=';
 2935:     } elsif (ref($key) eq 'HASH') {
 2936:       $result.=&hashref2str($key).'=';
 2937:     } elsif (ref($key)) {
 2938:       $result.='=';
 2939:       #print("Got a ref of ".(ref($key))." skipping.");
 2940:     } else {
 2941: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 2942:     }
 2943: 
 2944:     if(ref($hashref->{$key}) eq 'ARRAY') {
 2945:       $result.=&arrayref2str($hashref->{$key}).'&';
 2946:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 2947:       $result.=&hashref2str($hashref->{$key}).'&';
 2948:     } elsif(ref($hashref->{$key})) {
 2949:        $result.='&';
 2950:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 2951:     } else {
 2952:       $result.=&escape($hashref->{$key}).'&';
 2953:     }
 2954:   }
 2955:   $result=~s/\&$//;
 2956:   $result .= '__END_HASH_REF__';
 2957:   return $result;
 2958: }
 2959: 
 2960: sub str2hash {
 2961:     my ($string)=@_;
 2962:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 2963:     return %$hash;
 2964: }
 2965: 
 2966: sub str2hashref {
 2967:   my ($string) = @_;
 2968: 
 2969:   my %hash;
 2970: 
 2971:   if($string !~ /^__HASH_REF__/) {
 2972:       if (! ($string eq '' || !defined($string))) {
 2973: 	  $hash{'error'}='Not hash reference';
 2974:       }
 2975:       return (\%hash, $string);
 2976:   }
 2977: 
 2978:   $string =~ s/^__HASH_REF__//;
 2979: 
 2980:   while($string !~ /^__END_HASH_REF__/) {
 2981:       #key
 2982:       my $key='';
 2983:       if($string =~ /^__HASH_REF__/) {
 2984:           ($key, $string)=&str2hashref($string);
 2985:           if(defined($key->{'error'})) {
 2986:               $hash{'error'}='Bad data';
 2987:               return (\%hash, $string);
 2988:           }
 2989:       } elsif($string =~ /^__ARRAY_REF__/) {
 2990:           ($key, $string)=&str2arrayref($string);
 2991:           if($key->[0] eq 'Array reference error') {
 2992:               $hash{'error'}='Bad data';
 2993:               return (\%hash, $string);
 2994:           }
 2995:       } else {
 2996:           $string =~ s/^(.*?)=//;
 2997: 	  $key=&unescape($1);
 2998:       }
 2999:       $string =~ s/^=//;
 3000: 
 3001:       #value
 3002:       my $value='';
 3003:       if($string =~ /^__HASH_REF__/) {
 3004:           ($value, $string)=&str2hashref($string);
 3005:           if(defined($value->{'error'})) {
 3006:               $hash{'error'}='Bad data';
 3007:               return (\%hash, $string);
 3008:           }
 3009:       } elsif($string =~ /^__ARRAY_REF__/) {
 3010:           ($value, $string)=&str2arrayref($string);
 3011:           if($value->[0] eq 'Array reference error') {
 3012:               $hash{'error'}='Bad data';
 3013:               return (\%hash, $string);
 3014:           }
 3015:       } else {
 3016: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3017:       }
 3018:       $string =~ s/^&//;
 3019: 
 3020:       $hash{$key}=$value;
 3021:   }
 3022: 
 3023:   $string =~ s/^__END_HASH_REF__//;
 3024: 
 3025:   return (\%hash, $string);
 3026: }
 3027: 
 3028: sub str2array {
 3029:     my ($string)=@_;
 3030:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3031:     return @$array;
 3032: }
 3033: 
 3034: sub str2arrayref {
 3035:   my ($string) = @_;
 3036:   my @array;
 3037: 
 3038:   if($string !~ /^__ARRAY_REF__/) {
 3039:       if (! ($string eq '' || !defined($string))) {
 3040: 	  $array[0]='Array reference error';
 3041:       }
 3042:       return (\@array, $string);
 3043:   }
 3044: 
 3045:   $string =~ s/^__ARRAY_REF__//;
 3046: 
 3047:   while($string !~ /^__END_ARRAY_REF__/) {
 3048:       my $value='';
 3049:       if($string =~ /^__HASH_REF__/) {
 3050:           ($value, $string)=&str2hashref($string);
 3051:           if(defined($value->{'error'})) {
 3052:               $array[0] ='Array reference error';
 3053:               return (\@array, $string);
 3054:           }
 3055:       } elsif($string =~ /^__ARRAY_REF__/) {
 3056:           ($value, $string)=&str2arrayref($string);
 3057:           if($value->[0] eq 'Array reference error') {
 3058:               $array[0] ='Array reference error';
 3059:               return (\@array, $string);
 3060:           }
 3061:       } else {
 3062: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3063:       }
 3064:       $string =~ s/^&//;
 3065: 
 3066:       push(@array, $value);
 3067:   }
 3068: 
 3069:   $string =~ s/^__END_ARRAY_REF__//;
 3070: 
 3071:   return (\@array, $string);
 3072: }
 3073: 
 3074: # -------------------------------------------------------------------Temp Store
 3075: 
 3076: sub tmpreset {
 3077:   my ($symb,$namespace,$domain,$stuname) = @_;
 3078:   if (!$symb) {
 3079:     $symb=&symbread();
 3080:     if (!$symb) { $symb= $env{'request.url'}; }
 3081:   }
 3082:   $symb=escape($symb);
 3083: 
 3084:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3085:   $namespace=~s/\//\_/g;
 3086:   $namespace=~s/\W//g;
 3087: 
 3088:   if (!$domain) { $domain=$env{'user.domain'}; }
 3089:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3090:   if ($domain eq 'public' && $stuname eq 'public') {
 3091:       $stuname=$ENV{'REMOTE_ADDR'};
 3092:   }
 3093:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3094:   my %hash;
 3095:   if (tie(%hash,'GDBM_File',
 3096: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3097: 	  &GDBM_WRCREAT(),0640)) {
 3098:     foreach my $key (keys %hash) {
 3099:       if ($key=~ /:$symb/) {
 3100: 	delete($hash{$key});
 3101:       }
 3102:     }
 3103:   }
 3104: }
 3105: 
 3106: sub tmpstore {
 3107:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3108: 
 3109:   if (!$symb) {
 3110:     $symb=&symbread();
 3111:     if (!$symb) { $symb= $env{'request.url'}; }
 3112:   }
 3113:   $symb=escape($symb);
 3114: 
 3115:   if (!$namespace) {
 3116:     # I don't think we would ever want to store this for a course.
 3117:     # it seems this will only be used if we don't have a course.
 3118:     #$namespace=$env{'request.course.id'};
 3119:     #if (!$namespace) {
 3120:       $namespace=$env{'request.state'};
 3121:     #}
 3122:   }
 3123:   $namespace=~s/\//\_/g;
 3124:   $namespace=~s/\W//g;
 3125:   if (!$domain) { $domain=$env{'user.domain'}; }
 3126:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3127:   if ($domain eq 'public' && $stuname eq 'public') {
 3128:       $stuname=$ENV{'REMOTE_ADDR'};
 3129:   }
 3130:   my $now=time;
 3131:   my %hash;
 3132:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3133:   if (tie(%hash,'GDBM_File',
 3134: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3135: 	  &GDBM_WRCREAT(),0640)) {
 3136:     $hash{"version:$symb"}++;
 3137:     my $version=$hash{"version:$symb"};
 3138:     my $allkeys=''; 
 3139:     foreach my $key (keys(%$storehash)) {
 3140:       $allkeys.=$key.':';
 3141:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3142:     }
 3143:     $hash{"$version:$symb:timestamp"}=$now;
 3144:     $allkeys.='timestamp';
 3145:     $hash{"$version:keys:$symb"}=$allkeys;
 3146:     if (untie(%hash)) {
 3147:       return 'ok';
 3148:     } else {
 3149:       return "error:$!";
 3150:     }
 3151:   } else {
 3152:     return "error:$!";
 3153:   }
 3154: }
 3155: 
 3156: # -----------------------------------------------------------------Temp Restore
 3157: 
 3158: sub tmprestore {
 3159:   my ($symb,$namespace,$domain,$stuname) = @_;
 3160: 
 3161:   if (!$symb) {
 3162:     $symb=&symbread();
 3163:     if (!$symb) { $symb= $env{'request.url'}; }
 3164:   }
 3165:   $symb=escape($symb);
 3166: 
 3167:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3168: 
 3169:   if (!$domain) { $domain=$env{'user.domain'}; }
 3170:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3171:   if ($domain eq 'public' && $stuname eq 'public') {
 3172:       $stuname=$ENV{'REMOTE_ADDR'};
 3173:   }
 3174:   my %returnhash;
 3175:   $namespace=~s/\//\_/g;
 3176:   $namespace=~s/\W//g;
 3177:   my %hash;
 3178:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3179:   if (tie(%hash,'GDBM_File',
 3180: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3181: 	  &GDBM_READER(),0640)) {
 3182:     my $version=$hash{"version:$symb"};
 3183:     $returnhash{'version'}=$version;
 3184:     my $scope;
 3185:     for ($scope=1;$scope<=$version;$scope++) {
 3186:       my $vkeys=$hash{"$scope:keys:$symb"};
 3187:       my @keys=split(/:/,$vkeys);
 3188:       my $key;
 3189:       $returnhash{"$scope:keys"}=$vkeys;
 3190:       foreach $key (@keys) {
 3191: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3192: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3193:       }
 3194:     }
 3195:     if (!(untie(%hash))) {
 3196:       return "error:$!";
 3197:     }
 3198:   } else {
 3199:     return "error:$!";
 3200:   }
 3201:   return %returnhash;
 3202: }
 3203: 
 3204: # ----------------------------------------------------------------------- Store
 3205: 
 3206: sub store {
 3207:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3208:     my $home='';
 3209: 
 3210:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3211: 
 3212:     $symb=&symbclean($symb);
 3213:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3214: 
 3215:     if (!$domain) { $domain=$env{'user.domain'}; }
 3216:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3217: 
 3218:     &devalidate($symb,$stuname,$domain);
 3219: 
 3220:     $symb=escape($symb);
 3221:     if (!$namespace) { 
 3222:        unless ($namespace=$env{'request.course.id'}) { 
 3223:           return ''; 
 3224:        } 
 3225:     }
 3226:     if (!$home) { $home=$env{'user.home'}; }
 3227: 
 3228:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3229:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3230: 
 3231:     my $namevalue='';
 3232:     foreach my $key (keys(%$storehash)) {
 3233:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3234:     }
 3235:     $namevalue=~s/\&$//;
 3236:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3237:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3238: }
 3239: 
 3240: # -------------------------------------------------------------- Critical Store
 3241: 
 3242: sub cstore {
 3243:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3244:     my $home='';
 3245: 
 3246:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3247: 
 3248:     $symb=&symbclean($symb);
 3249:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3250: 
 3251:     if (!$domain) { $domain=$env{'user.domain'}; }
 3252:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3253: 
 3254:     &devalidate($symb,$stuname,$domain);
 3255: 
 3256:     $symb=escape($symb);
 3257:     if (!$namespace) { 
 3258:        unless ($namespace=$env{'request.course.id'}) { 
 3259:           return ''; 
 3260:        } 
 3261:     }
 3262:     if (!$home) { $home=$env{'user.home'}; }
 3263: 
 3264:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3265:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3266: 
 3267:     my $namevalue='';
 3268:     foreach my $key (keys(%$storehash)) {
 3269:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3270:     }
 3271:     $namevalue=~s/\&$//;
 3272:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3273:     return critical
 3274:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3275: }
 3276: 
 3277: # --------------------------------------------------------------------- Restore
 3278: 
 3279: sub restore {
 3280:     my ($symb,$namespace,$domain,$stuname) = @_;
 3281:     my $home='';
 3282: 
 3283:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3284: 
 3285:     if (!$symb) {
 3286:       unless ($symb=escape(&symbread())) { return ''; }
 3287:     } else {
 3288:       $symb=&escape(&symbclean($symb));
 3289:     }
 3290:     if (!$namespace) { 
 3291:        unless ($namespace=$env{'request.course.id'}) { 
 3292:           return ''; 
 3293:        } 
 3294:     }
 3295:     if (!$domain) { $domain=$env{'user.domain'}; }
 3296:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3297:     if (!$home) { $home=$env{'user.home'}; }
 3298:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3299: 
 3300:     my %returnhash=();
 3301:     foreach my $line (split(/\&/,$answer)) {
 3302: 	my ($name,$value)=split(/\=/,$line);
 3303:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3304:     }
 3305:     my $version;
 3306:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3307:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3308:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3309:        }
 3310:     }
 3311:     return %returnhash;
 3312: }
 3313: 
 3314: # ---------------------------------------------------------- Course Description
 3315: 
 3316: sub coursedescription {
 3317:     my ($courseid,$args)=@_;
 3318:     $courseid=~s/^\///;
 3319:     $courseid=~s/\_/\//g;
 3320:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3321:     my $chome=&homeserver($cnum,$cdomain);
 3322:     my $normalid=$cdomain.'_'.$cnum;
 3323:     # need to always cache even if we get errors otherwise we keep 
 3324:     # trying and trying and trying to get the course description.
 3325:     my %envhash=();
 3326:     my %returnhash=();
 3327:     
 3328:     my $expiretime=600;
 3329:     if ($env{'request.course.id'} eq $normalid) {
 3330: 	$expiretime=120;
 3331:     }
 3332: 
 3333:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3334:     if (!$args->{'freshen_cache'}
 3335: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3336: 	foreach my $key (keys(%env)) {
 3337: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3338: 	    my ($setting) = $1;
 3339: 	    $returnhash{$setting} = $env{$key};
 3340: 	}
 3341: 	return %returnhash;
 3342:     }
 3343: 
 3344:     # get the data agin
 3345:     if (!$args->{'one_time'}) {
 3346: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3347:     }
 3348: 
 3349:     if ($chome ne 'no_host') {
 3350:        %returnhash=&dump('environment',$cdomain,$cnum);
 3351:        if (!exists($returnhash{'con_lost'})) {
 3352:            $returnhash{'home'}= $chome;
 3353: 	   $returnhash{'domain'} = $cdomain;
 3354: 	   $returnhash{'num'} = $cnum;
 3355:            if (!defined($returnhash{'type'})) {
 3356:                $returnhash{'type'} = 'Course';
 3357:            }
 3358:            while (my ($name,$value) = each %returnhash) {
 3359:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3360:            }
 3361:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3362:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3363: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3364:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3365:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3366:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3367:        }
 3368:     }
 3369:     if (!$args->{'one_time'}) {
 3370: 	&appenv(%envhash);
 3371:     }
 3372:     return %returnhash;
 3373: }
 3374: 
 3375: # -------------------------------------------------See if a user is privileged
 3376: 
 3377: sub privileged {
 3378:     my ($username,$domain)=@_;
 3379:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3380: 			&homeserver($username,$domain));
 3381:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3382:     my $now=time;
 3383:     if ($rolesdump ne '') {
 3384:         foreach my $entry (split(/&/,$rolesdump)) {
 3385: 	    if ($entry!~/^rolesdef_/) {
 3386: 		my ($area,$role)=split(/=/,$entry);
 3387: 		$area=~s/\_\w\w$//;
 3388: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3389: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3390: 		    my $active=1;
 3391: 		    if ($tend) {
 3392: 			if ($tend<$now) { $active=0; }
 3393: 		    }
 3394: 		    if ($tstart) {
 3395: 			if ($tstart>$now) { $active=0; }
 3396: 		    }
 3397: 		    if ($active) { return 1; }
 3398: 		}
 3399: 	    }
 3400: 	}
 3401:     }
 3402:     return 0;
 3403: }
 3404: 
 3405: # -------------------------------------------------------- Get user privileges
 3406: 
 3407: sub rolesinit {
 3408:     my ($domain,$username,$authhost)=@_;
 3409:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3410:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return ''; }
 3411:     my %allroles=();
 3412:     my %allgroups=();   
 3413:     my $now=time;
 3414:     my %userroles = ('user.login.time' => $now);
 3415:     my $group_privs;
 3416: 
 3417:     if ($rolesdump ne '') {
 3418:         foreach my $entry (split(/&/,$rolesdump)) {
 3419: 	  if ($entry!~/^rolesdef_/) {
 3420:             my ($area,$role)=split(/=/,$entry);
 3421: 	    $area=~s/\_\w\w$//;
 3422:             my ($trole,$tend,$tstart,$group_privs);
 3423: 	    if ($role=~/^cr/) { 
 3424: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3425: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3426: 		    ($tend,$tstart)=split('_',$trest);
 3427: 		} else {
 3428: 		    $trole=$role;
 3429: 		}
 3430:             } elsif ($role =~ m|^gr/|) {
 3431:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3432:                 ($trole,$group_privs) = split(/\//,$trole);
 3433:                 $group_privs = &unescape($group_privs);
 3434: 	    } else {
 3435: 		($trole,$tend,$tstart)=split(/_/,$role);
 3436: 	    }
 3437: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3438: 					 $username);
 3439: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3440:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3441:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3442:             if (($area ne '') && ($trole ne '')) {
 3443: 		my $spec=$trole.'.'.$area;
 3444: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3445: 		if ($trole =~ /^cr\//) {
 3446:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3447:                 } elsif ($trole eq 'gr') {
 3448:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3449: 		} else {
 3450:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3451: 		}
 3452:             }
 3453:           }
 3454:         }
 3455:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3456:         $userroles{'user.adv'}    = $adv;
 3457: 	$userroles{'user.author'} = $author;
 3458:         $env{'user.adv'}=$adv;
 3459:     }
 3460:     return \%userroles;  
 3461: }
 3462: 
 3463: sub set_arearole {
 3464:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3465: # log the associated role with the area
 3466:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3467:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3468: }
 3469: 
 3470: sub custom_roleprivs {
 3471:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3472:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3473:     my $homsvr=homeserver($rauthor,$rdomain);
 3474:     if (&hostname($homsvr) ne '') {
 3475:         my ($rdummy,$roledef)=
 3476:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3477:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3478:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3479:             if (defined($syspriv)) {
 3480:                 $$allroles{'cm./'}.=':'.$syspriv;
 3481:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3482:             }
 3483:             if ($tdomain ne '') {
 3484:                 if (defined($dompriv)) {
 3485:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3486:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3487:                 }
 3488:                 if (($trest ne '') && (defined($coursepriv))) {
 3489:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3490:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3491:                 }
 3492:             }
 3493:         }
 3494:     }
 3495: }
 3496: 
 3497: sub group_roleprivs {
 3498:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3499:     my $access = 1;
 3500:     my $now = time;
 3501:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3502:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3503:     if ($access) {
 3504:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3505:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3506:     }
 3507: }
 3508: 
 3509: sub standard_roleprivs {
 3510:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3511:     if (defined($pr{$trole.':s'})) {
 3512:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3513:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3514:     }
 3515:     if ($tdomain ne '') {
 3516:         if (defined($pr{$trole.':d'})) {
 3517:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3518:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3519:         }
 3520:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3521:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3522:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3523:         }
 3524:     }
 3525: }
 3526: 
 3527: sub set_userprivs {
 3528:     my ($userroles,$allroles,$allgroups) = @_; 
 3529:     my $author=0;
 3530:     my $adv=0;
 3531:     my %grouproles = ();
 3532:     if (keys(%{$allgroups}) > 0) {
 3533:         foreach my $role (keys %{$allroles}) {
 3534:             my ($trole,$area,$sec,$extendedarea);
 3535:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3536:                 $trole = $1;
 3537:                 $area = $2;
 3538:                 $sec = $3;
 3539:                 $extendedarea = $area.$sec;
 3540:                 if (exists($$allgroups{$area})) {
 3541:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3542:                         my $spec = $trole.'.'.$extendedarea;
 3543:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3544:                                                 $$allgroups{$area}{$group};
 3545:                     }
 3546:                 }
 3547:             }
 3548:         }
 3549:     }
 3550:     foreach my $group (keys(%grouproles)) {
 3551:         $$allroles{$group} = $grouproles{$group};
 3552:     }
 3553:     foreach my $role (keys(%{$allroles})) {
 3554:         my %thesepriv;
 3555:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3556:         foreach my $item (split(/:/,$$allroles{$role})) {
 3557:             if ($item ne '') {
 3558:                 my ($privilege,$restrictions)=split(/&/,$item);
 3559:                 if ($restrictions eq '') {
 3560:                     $thesepriv{$privilege}='F';
 3561:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3562:                     $thesepriv{$privilege}.=$restrictions;
 3563:                 }
 3564:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3565:             }
 3566:         }
 3567:         my $thesestr='';
 3568:         foreach my $priv (keys(%thesepriv)) {
 3569: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3570: 	}
 3571:         $userroles->{'user.priv.'.$role} = $thesestr;
 3572:     }
 3573:     return ($author,$adv);
 3574: }
 3575: 
 3576: # --------------------------------------------------------------- get interface
 3577: 
 3578: sub get {
 3579:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3580:    my $items='';
 3581:    foreach my $item (@$storearr) {
 3582:        $items.=&escape($item).'&';
 3583:    }
 3584:    $items=~s/\&$//;
 3585:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3586:    if (!$uname) { $uname=$env{'user.name'}; }
 3587:    my $uhome=&homeserver($uname,$udomain);
 3588: 
 3589:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3590:    my @pairs=split(/\&/,$rep);
 3591:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3592:      return @pairs;
 3593:    }
 3594:    my %returnhash=();
 3595:    my $i=0;
 3596:    foreach my $item (@$storearr) {
 3597:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3598:       $i++;
 3599:    }
 3600:    return %returnhash;
 3601: }
 3602: 
 3603: # --------------------------------------------------------------- del interface
 3604: 
 3605: sub del {
 3606:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3607:    my $items='';
 3608:    foreach my $item (@$storearr) {
 3609:        $items.=&escape($item).'&';
 3610:    }
 3611:    $items=~s/\&$//;
 3612:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3613:    if (!$uname) { $uname=$env{'user.name'}; }
 3614:    my $uhome=&homeserver($uname,$udomain);
 3615: 
 3616:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3617: }
 3618: 
 3619: # -------------------------------------------------------------- dump interface
 3620: 
 3621: sub dump {
 3622:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3623:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3624:     if (!$uname) { $uname=$env{'user.name'}; }
 3625:     my $uhome=&homeserver($uname,$udomain);
 3626:     if ($regexp) {
 3627: 	$regexp=&escape($regexp);
 3628:     } else {
 3629: 	$regexp='.';
 3630:     }
 3631:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3632:     my @pairs=split(/\&/,$rep);
 3633:     my %returnhash=();
 3634:     foreach my $item (@pairs) {
 3635: 	my ($key,$value)=split(/=/,$item,2);
 3636: 	$key = &unescape($key);
 3637: 	next if ($key =~ /^error: 2 /);
 3638: 	$returnhash{$key}=&thaw_unescape($value);
 3639:     }
 3640:     return %returnhash;
 3641: }
 3642: 
 3643: # --------------------------------------------------------- dumpstore interface
 3644: 
 3645: sub dumpstore {
 3646:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3647:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3648:    if (!$uname) { $uname=$env{'user.name'}; }
 3649:    my $uhome=&homeserver($uname,$udomain);
 3650:    if ($regexp) {
 3651:        $regexp=&escape($regexp);
 3652:    } else {
 3653:        $regexp='.';
 3654:    }
 3655:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3656:    my @pairs=split(/\&/,$rep);
 3657:    my %returnhash=();
 3658:    foreach my $item (@pairs) {
 3659:        my ($key,$value)=split(/=/,$item,2);
 3660:        next if ($key =~ /^error: 2 /);
 3661:        $returnhash{$key}=&thaw_unescape($value);
 3662:    }
 3663:    return %returnhash;
 3664: }
 3665: 
 3666: # -------------------------------------------------------------- keys interface
 3667: 
 3668: sub getkeys {
 3669:    my ($namespace,$udomain,$uname)=@_;
 3670:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3671:    if (!$uname) { $uname=$env{'user.name'}; }
 3672:    my $uhome=&homeserver($uname,$udomain);
 3673:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3674:    my @keyarray=();
 3675:    foreach my $key (split(/\&/,$rep)) {
 3676:       next if ($key =~ /^error: 2 /);
 3677:       push(@keyarray,&unescape($key));
 3678:    }
 3679:    return @keyarray;
 3680: }
 3681: 
 3682: # --------------------------------------------------------------- currentdump
 3683: sub currentdump {
 3684:    my ($courseid,$sdom,$sname)=@_;
 3685:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3686:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3687:    $sname    = $env{'user.name'}         if (! defined($sname));
 3688:    my $uhome = &homeserver($sname,$sdom);
 3689:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3690:    return if ($rep =~ /^(error:|no_such_host)/);
 3691:    #
 3692:    my %returnhash=();
 3693:    #
 3694:    if ($rep eq "unknown_cmd") { 
 3695:        # an old lond will not know currentdump
 3696:        # Do a dump and make it look like a currentdump
 3697:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3698:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3699:        my %hash = @tmp;
 3700:        @tmp=();
 3701:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3702:    } else {
 3703:        my @pairs=split(/\&/,$rep);
 3704:        foreach my $pair (@pairs) {
 3705:            my ($key,$value)=split(/=/,$pair,2);
 3706:            my ($symb,$param) = split(/:/,$key);
 3707:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3708:                                                         &thaw_unescape($value);
 3709:        }
 3710:    }
 3711:    return %returnhash;
 3712: }
 3713: 
 3714: sub convert_dump_to_currentdump{
 3715:     my %hash = %{shift()};
 3716:     my %returnhash;
 3717:     # Code ripped from lond, essentially.  The only difference
 3718:     # here is the unescaping done by lonnet::dump().  Conceivably
 3719:     # we might run in to problems with parameter names =~ /^v\./
 3720:     while (my ($key,$value) = each(%hash)) {
 3721:         my ($v,$symb,$param) = split(/:/,$key);
 3722: 	$symb  = &unescape($symb);
 3723: 	$param = &unescape($param);
 3724:         next if ($v eq 'version' || $symb eq 'keys');
 3725:         next if (exists($returnhash{$symb}) &&
 3726:                  exists($returnhash{$symb}->{$param}) &&
 3727:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3728:         $returnhash{$symb}->{$param}=$value;
 3729:         $returnhash{$symb}->{'v.'.$param}=$v;
 3730:     }
 3731:     #
 3732:     # Remove all of the keys in the hashes which keep track of
 3733:     # the version of the parameter.
 3734:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3735:         # use a foreach because we are going to delete from the hash.
 3736:         foreach my $key (keys(%$param_hash)) {
 3737:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3738:         }
 3739:     }
 3740:     return \%returnhash;
 3741: }
 3742: 
 3743: # ------------------------------------------------------ critical inc interface
 3744: 
 3745: sub cinc {
 3746:     return &inc(@_,'critical');
 3747: }
 3748: 
 3749: # --------------------------------------------------------------- inc interface
 3750: 
 3751: sub inc {
 3752:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3753:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3754:     if (!$uname) { $uname=$env{'user.name'}; }
 3755:     my $uhome=&homeserver($uname,$udomain);
 3756:     my $items='';
 3757:     if (! ref($store)) {
 3758:         # got a single value, so use that instead
 3759:         $items = &escape($store).'=&';
 3760:     } elsif (ref($store) eq 'SCALAR') {
 3761:         $items = &escape($$store).'=&';        
 3762:     } elsif (ref($store) eq 'ARRAY') {
 3763:         $items = join('=&',map {&escape($_);} @{$store});
 3764:     } elsif (ref($store) eq 'HASH') {
 3765:         while (my($key,$value) = each(%{$store})) {
 3766:             $items.= &escape($key).'='.&escape($value).'&';
 3767:         }
 3768:     }
 3769:     $items=~s/\&$//;
 3770:     if ($critical) {
 3771: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3772:     } else {
 3773: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3774:     }
 3775: }
 3776: 
 3777: # --------------------------------------------------------------- put interface
 3778: 
 3779: sub put {
 3780:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3781:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3782:    if (!$uname) { $uname=$env{'user.name'}; }
 3783:    my $uhome=&homeserver($uname,$udomain);
 3784:    my $items='';
 3785:    foreach my $item (keys(%$storehash)) {
 3786:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3787:    }
 3788:    $items=~s/\&$//;
 3789:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3790: }
 3791: 
 3792: # ------------------------------------------------------------ newput interface
 3793: 
 3794: sub newput {
 3795:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3796:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3797:    if (!$uname) { $uname=$env{'user.name'}; }
 3798:    my $uhome=&homeserver($uname,$udomain);
 3799:    my $items='';
 3800:    foreach my $key (keys(%$storehash)) {
 3801:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3802:    }
 3803:    $items=~s/\&$//;
 3804:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 3805: }
 3806: 
 3807: # ---------------------------------------------------------  putstore interface
 3808: 
 3809: sub putstore {
 3810:    my ($namespace,$symb,$version,$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 $key (keys(%$storehash)) {
 3816:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 3817:    }
 3818:    $items=~s/\&$//;
 3819:    my $esc_symb=&escape($symb);
 3820:    my $esc_v=&escape($version);
 3821:    my $reply =
 3822:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 3823: 	      $uhome);
 3824:    if ($reply eq 'unknown_cmd') {
 3825:        # gfall back to way things use to be done
 3826:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 3827: 			    $uname);
 3828:    }
 3829:    return $reply;
 3830: }
 3831: 
 3832: sub old_putstore {
 3833:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 3834:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3835:     if (!$uname) { $uname=$env{'user.name'}; }
 3836:     my $uhome=&homeserver($uname,$udomain);
 3837:     my %newstorehash;
 3838:     foreach my $item (keys(%$storehash)) {
 3839: 	my $key = $version.':'.&escape($symb).':'.$item;
 3840: 	$newstorehash{$key} = $storehash->{$item};
 3841:     }
 3842:     my $items='';
 3843:     my %allitems = ();
 3844:     foreach my $item (keys(%newstorehash)) {
 3845: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 3846: 	    my $key = $1.':keys:'.$2;
 3847: 	    $allitems{$key} .= $3.':';
 3848: 	}
 3849: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 3850:     }
 3851:     foreach my $item (keys(%allitems)) {
 3852: 	$allitems{$item} =~ s/\:$//;
 3853: 	$items.= $item.'='.$allitems{$item}.'&';
 3854:     }
 3855:     $items=~s/\&$//;
 3856:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3857: }
 3858: 
 3859: # ------------------------------------------------------ critical put interface
 3860: 
 3861: sub cput {
 3862:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3863:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3864:    if (!$uname) { $uname=$env{'user.name'}; }
 3865:    my $uhome=&homeserver($uname,$udomain);
 3866:    my $items='';
 3867:    foreach my $item (keys(%$storehash)) {
 3868:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3869:    }
 3870:    $items=~s/\&$//;
 3871:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 3872: }
 3873: 
 3874: # -------------------------------------------------------------- eget interface
 3875: 
 3876: sub eget {
 3877:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3878:    my $items='';
 3879:    foreach my $item (@$storearr) {
 3880:        $items.=&escape($item).'&';
 3881:    }
 3882:    $items=~s/\&$//;
 3883:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3884:    if (!$uname) { $uname=$env{'user.name'}; }
 3885:    my $uhome=&homeserver($uname,$udomain);
 3886:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 3887:    my @pairs=split(/\&/,$rep);
 3888:    my %returnhash=();
 3889:    my $i=0;
 3890:    foreach my $item (@$storearr) {
 3891:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3892:       $i++;
 3893:    }
 3894:    return %returnhash;
 3895: }
 3896: 
 3897: # ------------------------------------------------------------ tmpput interface
 3898: sub tmpput {
 3899:     my ($storehash,$server,$context)=@_;
 3900:     my $items='';
 3901:     foreach my $item (keys(%$storehash)) {
 3902: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3903:     }
 3904:     $items=~s/\&$//;
 3905:     if (defined($context)) {
 3906:         $items .= ':'.&escape($context);
 3907:     }
 3908:     return &reply("tmpput:$items",$server);
 3909: }
 3910: 
 3911: # ------------------------------------------------------------ tmpget interface
 3912: sub tmpget {
 3913:     my ($token,$server)=@_;
 3914:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3915:     my $rep=&reply("tmpget:$token",$server);
 3916:     my %returnhash;
 3917:     foreach my $item (split(/\&/,$rep)) {
 3918: 	my ($key,$value)=split(/=/,$item);
 3919: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 3920:     }
 3921:     return %returnhash;
 3922: }
 3923: 
 3924: # ------------------------------------------------------------ tmpget interface
 3925: sub tmpdel {
 3926:     my ($token,$server)=@_;
 3927:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 3928:     return &reply("tmpdel:$token",$server);
 3929: }
 3930: 
 3931: # -------------------------------------------------- portfolio access checking
 3932: 
 3933: sub portfolio_access {
 3934:     my ($requrl) = @_;
 3935:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 3936:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 3937:     if ($result) {
 3938:         my %setters;
 3939:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 3940:             my ($startblock,$endblock) =
 3941:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 3942:             if ($startblock && $endblock) {
 3943:                 return 'B';
 3944:             }
 3945:         } else {
 3946:             my ($startblock,$endblock) =
 3947:                 &Apache::loncommon::blockcheck(\%setters,'port');
 3948:             if ($startblock && $endblock) {
 3949:                 return 'B';
 3950:             }
 3951:         }
 3952:     }
 3953:     if ($result eq 'ok') {
 3954:        return 'F';
 3955:     } elsif ($result =~ /^[^:]+:guest_/) {
 3956:        return 'A';
 3957:     }
 3958:     return '';
 3959: }
 3960: 
 3961: sub get_portfolio_access {
 3962:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 3963: 
 3964:     if (!ref($access_hash)) {
 3965: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 3966: 	my %access_controls = &get_access_controls($current_perms,$group,
 3967: 						   $file_name);
 3968: 	$access_hash = $access_controls{$file_name};
 3969:     }
 3970: 
 3971:     my ($public,$guest,@domains,@users,@courses,@groups);
 3972:     my $now = time;
 3973:     if (ref($access_hash) eq 'HASH') {
 3974:         foreach my $key (keys(%{$access_hash})) {
 3975:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 3976:             if ($start > $now) {
 3977:                 next;
 3978:             }
 3979:             if ($end && $end<$now) {
 3980:                 next;
 3981:             }
 3982:             if ($scope eq 'public') {
 3983:                 $public = $key;
 3984:                 last;
 3985:             } elsif ($scope eq 'guest') {
 3986:                 $guest = $key;
 3987:             } elsif ($scope eq 'domains') {
 3988:                 push(@domains,$key);
 3989:             } elsif ($scope eq 'users') {
 3990:                 push(@users,$key);
 3991:             } elsif ($scope eq 'course') {
 3992:                 push(@courses,$key);
 3993:             } elsif ($scope eq 'group') {
 3994:                 push(@groups,$key);
 3995:             }
 3996:         }
 3997:         if ($public) {
 3998:             return 'ok';
 3999:         }
 4000:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4001:             if ($guest) {
 4002:                 return $guest;
 4003:             }
 4004:         } else {
 4005:             if (@domains > 0) {
 4006:                 foreach my $domkey (@domains) {
 4007:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4008:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4009:                             return 'ok';
 4010:                         }
 4011:                     }
 4012:                 }
 4013:             }
 4014:             if (@users > 0) {
 4015:                 foreach my $userkey (@users) {
 4016:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4017:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4018:                             if (ref($item) eq 'HASH') {
 4019:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4020:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4021:                                     return 'ok';
 4022:                                 }
 4023:                             }
 4024:                         }
 4025:                     } 
 4026:                 }
 4027:             }
 4028:             my %roleshash;
 4029:             my @courses_and_groups = @courses;
 4030:             push(@courses_and_groups,@groups); 
 4031:             if (@courses_and_groups > 0) {
 4032:                 my (%allgroups,%allroles); 
 4033:                 my ($start,$end,$role,$sec,$group);
 4034:                 foreach my $envkey (%env) {
 4035:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4036:                         my $cid = $2.'_'.$3; 
 4037:                         if ($1 eq 'gr') {
 4038:                             $group = $4;
 4039:                             $allgroups{$cid}{$group} = $env{$envkey};
 4040:                         } else {
 4041:                             if ($4 eq '') {
 4042:                                 $sec = 'none';
 4043:                             } else {
 4044:                                 $sec = $4;
 4045:                             }
 4046:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4047:                         }
 4048:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4049:                         my $cid = $2.'_'.$3;
 4050:                         if ($4 eq '') {
 4051:                             $sec = 'none';
 4052:                         } else {
 4053:                             $sec = $4;
 4054:                         }
 4055:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4056:                     }
 4057:                 }
 4058:                 if (keys(%allroles) == 0) {
 4059:                     return;
 4060:                 }
 4061:                 foreach my $key (@courses_and_groups) {
 4062:                     my %content = %{$$access_hash{$key}};
 4063:                     my $cnum = $content{'number'};
 4064:                     my $cdom = $content{'domain'};
 4065:                     my $cid = $cdom.'_'.$cnum;
 4066:                     if (!exists($allroles{$cid})) {
 4067:                         next;
 4068:                     }    
 4069:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4070:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4071:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4072:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4073:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4074:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4075:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4076:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4077:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4078:                                         if (grep/^all$/,@sections) {
 4079:                                             return 'ok';
 4080:                                         } else {
 4081:                                             if (grep/^$sec$/,@sections) {
 4082:                                                 return 'ok';
 4083:                                             }
 4084:                                         }
 4085:                                     }
 4086:                                 }
 4087:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4088:                                     if (grep/^none$/,@groups) {
 4089:                                         return 'ok';
 4090:                                     }
 4091:                                 } else {
 4092:                                     if (grep/^all$/,@groups) {
 4093:                                         return 'ok';
 4094:                                     } 
 4095:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4096:                                         if (grep/^$group$/,@groups) {
 4097:                                             return 'ok';
 4098:                                         }
 4099:                                     }
 4100:                                 } 
 4101:                             }
 4102:                         }
 4103:                     }
 4104:                 }
 4105:             }
 4106:             if ($guest) {
 4107:                 return $guest;
 4108:             }
 4109:         }
 4110:     }
 4111:     return;
 4112: }
 4113: 
 4114: sub course_group_datechecker {
 4115:     my ($dates,$now,$status) = @_;
 4116:     my ($start,$end) = split(/\./,$dates);
 4117:     if (!$start && !$end) {
 4118:         return 'ok';
 4119:     }
 4120:     if (grep/^active$/,@{$status}) {
 4121:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4122:             return 'ok';
 4123:         }
 4124:     }
 4125:     if (grep/^previous$/,@{$status}) {
 4126:         if ($end > $now ) {
 4127:             return 'ok';
 4128:         }
 4129:     }
 4130:     if (grep/^future$/,@{$status}) {
 4131:         if ($start > $now) {
 4132:             return 'ok';
 4133:         }
 4134:     }
 4135:     return; 
 4136: }
 4137: 
 4138: sub parse_portfolio_url {
 4139:     my ($url) = @_;
 4140: 
 4141:     my ($type,$udom,$unum,$group,$file_name);
 4142:     
 4143:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4144: 	$type = 1;
 4145:         $udom = $1;
 4146:         $unum = $2;
 4147:         $file_name = $3;
 4148:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4149: 	$type = 2;
 4150:         $udom = $1;
 4151:         $unum = $2;
 4152:         $group = $3;
 4153:         $file_name = $3.'/'.$4;
 4154:     }
 4155:     if (wantarray) {
 4156: 	return ($type,$udom,$unum,$file_name,$group);
 4157:     }
 4158:     return $type;
 4159: }
 4160: 
 4161: sub is_portfolio_url {
 4162:     my ($url) = @_;
 4163:     return scalar(&parse_portfolio_url($url));
 4164: }
 4165: 
 4166: sub is_portfolio_file {
 4167:     my ($file) = @_;
 4168:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4169:         return 1;
 4170:     }
 4171:     return;
 4172: }
 4173: 
 4174: 
 4175: # ---------------------------------------------- Custom access rule evaluation
 4176: 
 4177: sub customaccess {
 4178:     my ($priv,$uri)=@_;
 4179:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4180:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4181:     $udom = &LONCAPA::clean_domain($udom);
 4182:     $ucrs = &LONCAPA::clean_username($ucrs);
 4183:     my $access=0;
 4184:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4185: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4186: 	if ($type eq 'user') {
 4187: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4188: 		my ($tdom,$tuname)=split(m{/},$scope);
 4189: 		if ($tdom) {
 4190: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4191: 		}
 4192: 		if ($tuname) {
 4193: 		    if ($tuname ne $env{'user.name'}) { next; }
 4194: 		}
 4195: 		$access=($effect eq 'allow');
 4196: 		last;
 4197: 	    }
 4198: 	} else {
 4199: 	    if ($role) {
 4200: 		if ($role ne $urole) { next; }
 4201: 	    }
 4202: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4203: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4204: 		if ($tdom) {
 4205: 		    if ($tdom ne $udom) { next; }
 4206: 		}
 4207: 		if ($tcrs) {
 4208: 		    if ($tcrs ne $ucrs) { next; }
 4209: 		}
 4210: 		if ($tsec) {
 4211: 		    if ($tsec ne $usec) { next; }
 4212: 		}
 4213: 		$access=($effect eq 'allow');
 4214: 		last;
 4215: 	    }
 4216: 	    if ($realm eq '' && $role eq '') {
 4217: 		$access=($effect eq 'allow');
 4218: 	    }
 4219: 	}
 4220:     }
 4221:     return $access;
 4222: }
 4223: 
 4224: # ------------------------------------------------- Check for a user privilege
 4225: 
 4226: sub allowed {
 4227:     my ($priv,$uri,$symb,$role)=@_;
 4228:     my $ver_orguri=$uri;
 4229:     $uri=&deversion($uri);
 4230:     my $orguri=$uri;
 4231:     $uri=&declutter($uri);
 4232: 
 4233:     if ($priv eq 'evb') {
 4234: # Evade communication block restrictions for specified role in a course
 4235:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4236:             return $1;
 4237:         } else {
 4238:             return;
 4239:         }
 4240:     }
 4241: 
 4242:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4243: # Free bre access to adm and meta resources
 4244:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4245: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4246: 	&& ($priv eq 'bre')) {
 4247: 	return 'F';
 4248:     }
 4249: 
 4250: # Free bre access to user's own portfolio contents
 4251:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4252:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4253: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4254:         my %setters;
 4255:         my ($startblock,$endblock) = 
 4256:             &Apache::loncommon::blockcheck(\%setters,'port');
 4257:         if ($startblock && $endblock) {
 4258:             return 'B';
 4259:         } else {
 4260:             return 'F';
 4261:         }
 4262:     }
 4263: 
 4264: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4265:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4266:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4267:         if (exists($env{'request.course.id'})) {
 4268:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4269:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4270:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4271:                 my $courseprivid=$env{'request.course.id'};
 4272:                 $courseprivid=~s/\_/\//;
 4273:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4274:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4275:                     return $1; 
 4276:                 } else {
 4277:                     if ($env{'request.course.sec'}) {
 4278:                         $courseprivid.='/'.$env{'request.course.sec'};
 4279:                     }
 4280:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4281:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4282:                         return $2;
 4283:                     }
 4284:                 }
 4285:             }
 4286:         }
 4287:     }
 4288: 
 4289: # Free bre to public access
 4290: 
 4291:     if ($priv eq 'bre') {
 4292:         my $copyright=&metadata($uri,'copyright');
 4293: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4294:            return 'F'; 
 4295:         }
 4296:         if ($copyright eq 'priv') {
 4297:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4298: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4299: 		return '';
 4300:             }
 4301:         }
 4302:         if ($copyright eq 'domain') {
 4303:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4304: 	    unless (($env{'user.domain'} eq $1) ||
 4305:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4306: 		return '';
 4307:             }
 4308:         }
 4309:         if ($env{'request.role'}=~ /li\.\//) {
 4310:             # Library role, so allow browsing of resources in this domain.
 4311:             return 'F';
 4312:         }
 4313:         if ($copyright eq 'custom') {
 4314: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4315:         }
 4316:     }
 4317:     # Domain coordinator is trying to create a course
 4318:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4319:         # uri is the requested domain in this case.
 4320:         # comparison to 'request.role.domain' shows if the user has selected
 4321:         # a role of dc for the domain in question.
 4322:         return 'F' if ($uri eq $env{'request.role.domain'});
 4323:     }
 4324: 
 4325:     my $thisallowed='';
 4326:     my $statecond=0;
 4327:     my $courseprivid='';
 4328: 
 4329: # Course
 4330: 
 4331:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4332:        $thisallowed.=$1;
 4333:     }
 4334: 
 4335: # Domain
 4336: 
 4337:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4338:        =~/\Q$priv\E\&([^\:]*)/) {
 4339:        $thisallowed.=$1;
 4340:     }
 4341: 
 4342: # Course: uri itself is a course
 4343:     my $courseuri=$uri;
 4344:     $courseuri=~s/\_(\d)/\/$1/;
 4345:     $courseuri=~s/^([^\/])/\/$1/;
 4346: 
 4347:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4348:        =~/\Q$priv\E\&([^\:]*)/) {
 4349:        $thisallowed.=$1;
 4350:     }
 4351: 
 4352: # URI is an uploaded document for this course, default permissions don't matter
 4353: # not allowing 'edit' access (editupload) to uploaded course docs
 4354:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4355: 	$thisallowed='';
 4356:         my ($match)=&is_on_map($uri);
 4357:         if ($match) {
 4358:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4359:                   =~/\Q$priv\E\&([^\:]*)/) {
 4360:                 $thisallowed.=$1;
 4361:             }
 4362:         } else {
 4363:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4364:             if ($refuri) {
 4365:                 if ($refuri =~ m|^/adm/|) {
 4366:                     $thisallowed='F';
 4367:                 } else {
 4368:                     $refuri=&declutter($refuri);
 4369:                     my ($match) = &is_on_map($refuri);
 4370:                     if ($match) {
 4371:                         $thisallowed='F';
 4372:                     }
 4373:                 }
 4374:             }
 4375:         }
 4376:     }
 4377: 
 4378:     if ($priv eq 'bre'
 4379: 	&& $thisallowed ne 'F' 
 4380: 	&& $thisallowed ne '2'
 4381: 	&& &is_portfolio_url($uri)) {
 4382: 	$thisallowed = &portfolio_access($uri);
 4383:     }
 4384:     
 4385: # Full access at system, domain or course-wide level? Exit.
 4386: 
 4387:     if ($thisallowed=~/F/) {
 4388: 	return 'F';
 4389:     }
 4390: 
 4391: # If this is generating or modifying users, exit with special codes
 4392: 
 4393:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4394: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4395: 	    my ($audom,$auname)=split('/',$uri);
 4396: # no author name given, so this just checks on the general right to make a co-author in this domain
 4397: 	    unless ($auname) { return $thisallowed; }
 4398: # an author name is given, so we are about to actually make a co-author for a certain account
 4399: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4400: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4401: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4402: 	}
 4403: 	return $thisallowed;
 4404:     }
 4405: #
 4406: # Gathered so far: system, domain and course wide privileges
 4407: #
 4408: # Course: See if uri or referer is an individual resource that is part of 
 4409: # the course
 4410: 
 4411:     if ($env{'request.course.id'}) {
 4412: 
 4413:        $courseprivid=$env{'request.course.id'};
 4414:        if ($env{'request.course.sec'}) {
 4415:           $courseprivid.='/'.$env{'request.course.sec'};
 4416:        }
 4417:        $courseprivid=~s/\_/\//;
 4418:        my $checkreferer=1;
 4419:        my ($match,$cond)=&is_on_map($uri);
 4420:        if ($match) {
 4421:            $statecond=$cond;
 4422:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4423:                =~/\Q$priv\E\&([^\:]*)/) {
 4424:                $thisallowed.=$1;
 4425:                $checkreferer=0;
 4426:            }
 4427:        }
 4428:        
 4429:        if ($checkreferer) {
 4430: 	  my $refuri=$env{'httpref.'.$orguri};
 4431:             unless ($refuri) {
 4432:                 foreach my $key (keys(%env)) {
 4433: 		    if ($key=~/^httpref\..*\*/) {
 4434: 			my $pattern=$key;
 4435:                         $pattern=~s/^httpref\.\/res\///;
 4436:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4437:                         $pattern=~s/\//\\\//g;
 4438:                         if ($orguri=~/$pattern/) {
 4439: 			    $refuri=$env{$key};
 4440:                         }
 4441:                     }
 4442:                 }
 4443:             }
 4444: 
 4445:          if ($refuri) { 
 4446: 	  $refuri=&declutter($refuri);
 4447:           my ($match,$cond)=&is_on_map($refuri);
 4448:             if ($match) {
 4449:               my $refstatecond=$cond;
 4450:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4451:                   =~/\Q$priv\E\&([^\:]*)/) {
 4452:                   $thisallowed.=$1;
 4453:                   $uri=$refuri;
 4454:                   $statecond=$refstatecond;
 4455:               }
 4456:           }
 4457:         }
 4458:        }
 4459:    }
 4460: 
 4461: #
 4462: # Gathered now: all privileges that could apply, and condition number
 4463: # 
 4464: #
 4465: # Full or no access?
 4466: #
 4467: 
 4468:     if ($thisallowed=~/F/) {
 4469: 	return 'F';
 4470:     }
 4471: 
 4472:     unless ($thisallowed) {
 4473:         return '';
 4474:     }
 4475: 
 4476: # Restrictions exist, deal with them
 4477: #
 4478: #   C:according to course preferences
 4479: #   R:according to resource settings
 4480: #   L:unless locked
 4481: #   X:according to user session state
 4482: #
 4483: 
 4484: # Possibly locked functionality, check all courses
 4485: # Locks might take effect only after 10 minutes cache expiration for other
 4486: # courses, and 2 minutes for current course
 4487: 
 4488:     my $envkey;
 4489:     if ($thisallowed=~/L/) {
 4490:         foreach $envkey (keys %env) {
 4491:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4492:                my $courseid=$2;
 4493:                my $roleid=$1.'.'.$2;
 4494:                $courseid=~s/^\///;
 4495:                my $expiretime=600;
 4496:                if ($env{'request.role'} eq $roleid) {
 4497: 		  $expiretime=120;
 4498:                }
 4499: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4500:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4501:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4502: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4503:                }
 4504:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4505:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4506: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4507:                        &log($env{'user.domain'},$env{'user.name'},
 4508:                             $env{'user.home'},
 4509:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4510:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4511:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4512: 		       return '';
 4513:                    }
 4514:                }
 4515:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4516:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4517: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4518:                        &log($env{'user.domain'},$env{'user.name'},
 4519:                             $env{'user.home'},
 4520:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4521:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4522:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4523: 		       return '';
 4524:                    }
 4525:                }
 4526: 	   }
 4527:        }
 4528:     }
 4529:    
 4530: #
 4531: # Rest of the restrictions depend on selected course
 4532: #
 4533: 
 4534:     unless ($env{'request.course.id'}) {
 4535: 	if ($thisallowed eq 'A') {
 4536: 	    return 'A';
 4537:         } elsif ($thisallowed eq 'B') {
 4538:             return 'B';
 4539: 	} else {
 4540: 	    return '1';
 4541: 	}
 4542:     }
 4543: 
 4544: #
 4545: # Now user is definitely in a course
 4546: #
 4547: 
 4548: 
 4549: # Course preferences
 4550: 
 4551:    if ($thisallowed=~/C/) {
 4552:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4553:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4554:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4555: 	   =~/\Q$rolecode\E/) {
 4556: 	   if ($priv ne 'pch') { 
 4557: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4558: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4559: 			$env{'request.course.id'});
 4560: 	   }
 4561:            return '';
 4562:        }
 4563: 
 4564:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4565: 	   =~/\Q$unamedom\E/) {
 4566: 	   if ($priv ne 'pch') { 
 4567: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4568: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4569: 			$env{'request.course.id'});
 4570: 	   }
 4571:            return '';
 4572:        }
 4573:    }
 4574: 
 4575: # Resource preferences
 4576: 
 4577:    if ($thisallowed=~/R/) {
 4578:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4579:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4580: 	   if ($priv ne 'pch') { 
 4581: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4582: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4583: 	   }
 4584: 	   return '';
 4585:        }
 4586:    }
 4587: 
 4588: # Restricted by state or randomout?
 4589: 
 4590:    if ($thisallowed=~/X/) {
 4591:       if ($env{'acc.randomout'}) {
 4592: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4593:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4594:             return ''; 
 4595:          }
 4596:       }
 4597:       if (&condval($statecond)) {
 4598: 	 return '2';
 4599:       } else {
 4600:          return '';
 4601:       }
 4602:    }
 4603: 
 4604:     if ($thisallowed eq 'A') {
 4605: 	return 'A';
 4606:     } elsif ($thisallowed eq 'B') {
 4607:         return 'B';
 4608:     }
 4609:    return 'F';
 4610: }
 4611: 
 4612: sub split_uri_for_cond {
 4613:     my $uri=&deversion(&declutter(shift));
 4614:     my @uriparts=split(/\//,$uri);
 4615:     my $filename=pop(@uriparts);
 4616:     my $pathname=join('/',@uriparts);
 4617:     return ($pathname,$filename);
 4618: }
 4619: # --------------------------------------------------- Is a resource on the map?
 4620: 
 4621: sub is_on_map {
 4622:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4623:     #Trying to find the conditional for the file
 4624:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4625: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4626:     if ($match) {
 4627: 	return (1,$1);
 4628:     } else {
 4629: 	return (0,0);
 4630:     }
 4631: }
 4632: 
 4633: # --------------------------------------------------------- Get symb from alias
 4634: 
 4635: sub get_symb_from_alias {
 4636:     my $symb=shift;
 4637:     my ($map,$resid,$url)=&decode_symb($symb);
 4638: # Already is a symb
 4639:     if ($url) { return $symb; }
 4640: # Must be an alias
 4641:     my $aliassymb='';
 4642:     my %bighash;
 4643:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4644:                             &GDBM_READER(),0640)) {
 4645:         my $rid=$bighash{'mapalias_'.$symb};
 4646: 	if ($rid) {
 4647: 	    my ($mapid,$resid)=split(/\./,$rid);
 4648: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4649: 				    $resid,$bighash{'src_'.$rid});
 4650: 	}
 4651:         untie %bighash;
 4652:     }
 4653:     return $aliassymb;
 4654: }
 4655: 
 4656: # ----------------------------------------------------------------- Define Role
 4657: 
 4658: sub definerole {
 4659:   if (allowed('mcr','/')) {
 4660:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4661:     foreach my $role (split(':',$sysrole)) {
 4662: 	my ($crole,$cqual)=split(/\&/,$role);
 4663:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4664:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4665: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4666:                return "refused:s:$crole&$cqual"; 
 4667:             }
 4668:         }
 4669:     }
 4670:     foreach my $role (split(':',$domrole)) {
 4671: 	my ($crole,$cqual)=split(/\&/,$role);
 4672:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4673:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 4674: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 4675:                return "refused:d:$crole&$cqual"; 
 4676:             }
 4677:         }
 4678:     }
 4679:     foreach my $role (split(':',$courole)) {
 4680: 	my ($crole,$cqual)=split(/\&/,$role);
 4681:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 4682:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 4683: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4684:                return "refused:c:$crole&$cqual"; 
 4685:             }
 4686:         }
 4687:     }
 4688:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 4689:                 "$env{'user.domain'}:$env{'user.name'}:".
 4690: 	        "rolesdef_$rolename=".
 4691:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 4692:     return reply($command,$env{'user.home'});
 4693:   } else {
 4694:     return 'refused';
 4695:   }
 4696: }
 4697: 
 4698: # ---------------- Make a metadata query against the network of library servers
 4699: 
 4700: sub metadata_query {
 4701:     my ($query,$custom,$customshow,$server_array)=@_;
 4702:     my %rhash;
 4703:     my %libserv = &all_library();
 4704:     my @server_list = (defined($server_array) ? @$server_array
 4705:                                               : keys(%libserv) );
 4706:     for my $server (@server_list) {
 4707: 	unless ($custom or $customshow) {
 4708: 	    my $reply=&reply("querysend:".&escape($query),$server);
 4709: 	    $rhash{$server}=$reply;
 4710: 	}
 4711: 	else {
 4712: 	    my $reply=&reply("querysend:".&escape($query).':'.
 4713: 			     &escape($custom).':'.&escape($customshow),
 4714: 			     $server);
 4715: 	    $rhash{$server}=$reply;
 4716: 	}
 4717:     }
 4718:     return \%rhash;
 4719: }
 4720: 
 4721: # ----------------------------------------- Send log queries and wait for reply
 4722: 
 4723: sub log_query {
 4724:     my ($uname,$udom,$query,%filters)=@_;
 4725:     my $uhome=&homeserver($uname,$udom);
 4726:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 4727:     my $uhost=&hostname($uhome);
 4728:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 4729:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 4730:                        $uhome);
 4731:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 4732:     return get_query_reply($queryid);
 4733: }
 4734: 
 4735: # -------------------------- Update MySQL table for portfolio file
 4736: 
 4737: sub update_portfolio_table {
 4738:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 4739:     my $homeserver = &homeserver($uname,$udom);
 4740:     my $queryid=
 4741:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 4742:                ':'.&escape($file_name).':'.$action,$homeserver);
 4743:     my $reply = &get_query_reply($queryid);
 4744:     return $reply;
 4745: }
 4746: 
 4747: # -------------------------- Update MySQL allusers table
 4748: 
 4749: sub update_allusers_table {
 4750:     my ($uname,$udom,$names) = @_;
 4751:     my $homeserver = &homeserver($uname,$udom);
 4752:     my $queryid=
 4753:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 4754:                'lastname='.&escape($names->{'lastname'}).'%%'.
 4755:                'firstname='.&escape($names->{'firstname'}).'%%'.
 4756:                'middlename='.&escape($names->{'middlename'}).'%%'.
 4757:                'generation='.&escape($names->{'generation'}).'%%'.
 4758:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 4759:                'id='.&escape($names->{'id'}),$homeserver);
 4760:     my $reply = &get_query_reply($queryid);
 4761:     return $reply;
 4762: }
 4763: 
 4764: # ------- Request retrieval of institutional classlists for course(s)
 4765: 
 4766: sub fetch_enrollment_query {
 4767:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 4768:     my $homeserver;
 4769:     my $maxtries = 1;
 4770:     if ($context eq 'automated') {
 4771:         $homeserver = $perlvar{'lonHostID'};
 4772:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 4773:     } else {
 4774:         $homeserver = &homeserver($cnum,$dom);
 4775:     }
 4776:     my $host=&hostname($homeserver);
 4777:     my $cmd = '';
 4778:     foreach my $affiliate (keys %{$affiliatesref}) {
 4779:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 4780:     }
 4781:     $cmd =~ s/%%$//;
 4782:     $cmd = &escape($cmd);
 4783:     my $query = 'fetchenrollment';
 4784:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 4785:     unless ($queryid=~/^\Q$host\E\_/) { 
 4786:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 4787:         return 'error: '.$queryid;
 4788:     }
 4789:     my $reply = &get_query_reply($queryid);
 4790:     my $tries = 1;
 4791:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 4792:         $reply = &get_query_reply($queryid);
 4793:         $tries ++;
 4794:     }
 4795:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 4796:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 4797:     } else {
 4798:         my @responses = split(/:/,$reply);
 4799:         if ($homeserver eq $perlvar{'lonHostID'}) {
 4800:             foreach my $line (@responses) {
 4801:                 my ($key,$value) = split(/=/,$line,2);
 4802:                 $$replyref{$key} = $value;
 4803:             }
 4804:         } else {
 4805:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 4806:             foreach my $line (@responses) {
 4807:                 my ($key,$value) = split(/=/,$line);
 4808:                 $$replyref{$key} = $value;
 4809:                 if ($value > 0) {
 4810:                     foreach my $item (@{$$affiliatesref{$key}}) {
 4811:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 4812:                         my $destname = $pathname.'/'.$filename;
 4813:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 4814:                         if ($xml_classlist =~ /^error/) {
 4815:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 4816:                         } else {
 4817:                             if ( open(FILE,">$destname") ) {
 4818:                                 print FILE &unescape($xml_classlist);
 4819:                                 close(FILE);
 4820:                             } else {
 4821:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 4822:                             }
 4823:                         }
 4824:                     }
 4825:                 }
 4826:             }
 4827:         }
 4828:         return 'ok';
 4829:     }
 4830:     return 'error';
 4831: }
 4832: 
 4833: sub get_query_reply {
 4834:     my $queryid=shift;
 4835:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 4836:     my $reply='';
 4837:     for (1..100) {
 4838: 	sleep 2;
 4839:         if (-e $replyfile.'.end') {
 4840: 	    if (open(my $fh,$replyfile)) {
 4841: 		$reply = join('',<$fh>);
 4842: 		close($fh);
 4843: 	   } else { return 'error: reply_file_error'; }
 4844:            return &unescape($reply);
 4845: 	}
 4846:     }
 4847:     return 'timeout:'.$queryid;
 4848: }
 4849: 
 4850: sub courselog_query {
 4851: #
 4852: # possible filters:
 4853: # url: url or symb
 4854: # username
 4855: # domain
 4856: # action: view, submit, grade
 4857: # start: timestamp
 4858: # end: timestamp
 4859: #
 4860:     my (%filters)=@_;
 4861:     unless ($env{'request.course.id'}) { return 'no_course'; }
 4862:     if ($filters{'url'}) {
 4863: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 4864:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 4865:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 4866:     }
 4867:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 4868:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 4869:     return &log_query($cname,$cdom,'courselog',%filters);
 4870: }
 4871: 
 4872: sub userlog_query {
 4873: #
 4874: # possible filters:
 4875: # action: log check role
 4876: # start: timestamp
 4877: # end: timestamp
 4878: #
 4879:     my ($uname,$udom,%filters)=@_;
 4880:     return &log_query($uname,$udom,'userlog',%filters);
 4881: }
 4882: 
 4883: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 4884: 
 4885: sub auto_run {
 4886:     my ($cnum,$cdom) = @_;
 4887:     my $response = 0;
 4888:     my $settings;
 4889:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 4890:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 4891:         $settings = $domconfig{'autoenroll'};
 4892:         if ($settings->{'run'} eq '1') {
 4893:             $response = 1;
 4894:         }
 4895:     } else {
 4896:         my $homeserver;
 4897:         if (&is_course($cdom,$cnum)) {
 4898:             $homeserver = &homeserver($cnum,$cdom);
 4899:         } else {
 4900:             $homeserver = &domain($cdom,'primary');
 4901:         }
 4902:         if ($homeserver ne 'no_host') {
 4903:             $response = &reply('autorun:'.$cdom,$homeserver);
 4904:         }
 4905:     }
 4906:     return $response;
 4907: }
 4908: 
 4909: sub auto_get_sections {
 4910:     my ($cnum,$cdom,$inst_coursecode) = @_;
 4911:     my $homeserver = &homeserver($cnum,$cdom);
 4912:     my @secs = ();
 4913:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 4914:     unless ($response eq 'refused') {
 4915:         @secs = split(/:/,$response);
 4916:     }
 4917:     return @secs;
 4918: }
 4919: 
 4920: sub auto_new_course {
 4921:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 4922:     my $homeserver = &homeserver($cnum,$cdom);
 4923:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 4924:     return $response;
 4925: }
 4926: 
 4927: sub auto_validate_courseID {
 4928:     my ($cnum,$cdom,$inst_course_id) = @_;
 4929:     my $homeserver = &homeserver($cnum,$cdom);
 4930:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 4931:     return $response;
 4932: }
 4933: 
 4934: sub auto_create_password {
 4935:     my ($cnum,$cdom,$authparam,$udom) = @_;
 4936:     my ($homeserver,$response);
 4937:     my $create_passwd = 0;
 4938:     my $authchk = '';
 4939:     if ($udom =~ /^$match_domain$/) {
 4940:         $homeserver = &domain($udom,'primary');
 4941:     }
 4942:     if ($homeserver eq '') {
 4943:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 4944:             $homeserver = &homeserver($cnum,$cdom);
 4945:         }
 4946:     }
 4947:     if ($homeserver eq '') {
 4948:         $authchk = 'nodomain';
 4949:     } else {
 4950:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 4951:         if ($response eq 'refused') {
 4952:             $authchk = 'refused';
 4953:         } else {
 4954:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 4955:         }
 4956:     }
 4957:     return ($authparam,$create_passwd,$authchk);
 4958: }
 4959: 
 4960: sub auto_photo_permission {
 4961:     my ($cnum,$cdom,$students) = @_;
 4962:     my $homeserver = &homeserver($cnum,$cdom);
 4963:     my ($outcome,$perm_reqd,$conditions) = 
 4964: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 4965:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4966: 	return (undef,undef);
 4967:     }
 4968:     return ($outcome,$perm_reqd,$conditions);
 4969: }
 4970: 
 4971: sub auto_checkphotos {
 4972:     my ($uname,$udom,$pid) = @_;
 4973:     my $homeserver = &homeserver($uname,$udom);
 4974:     my ($result,$resulttype);
 4975:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 4976: 				   &escape($uname).':'.&escape($pid),
 4977: 				   $homeserver));
 4978:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4979: 	return (undef,undef);
 4980:     }
 4981:     if ($outcome) {
 4982:         ($result,$resulttype) = split(/:/,$outcome);
 4983:     } 
 4984:     return ($result,$resulttype);
 4985: }
 4986: 
 4987: sub auto_photochoice {
 4988:     my ($cnum,$cdom) = @_;
 4989:     my $homeserver = &homeserver($cnum,$cdom);
 4990:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 4991: 						       &escape($cdom),
 4992: 						       $homeserver)));
 4993:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 4994: 	return (undef,undef);
 4995:     }
 4996:     return ($update,$comment);
 4997: }
 4998: 
 4999: sub auto_photoupdate {
 5000:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5001:     my $homeserver = &homeserver($cnum,$dom);
 5002:     my $host=&hostname($homeserver);
 5003:     my $cmd = '';
 5004:     my $maxtries = 1;
 5005:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5006:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5007:     }
 5008:     $cmd =~ s/%%$//;
 5009:     $cmd = &escape($cmd);
 5010:     my $query = 'institutionalphotos';
 5011:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5012:     unless ($queryid=~/^\Q$host\E\_/) {
 5013:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5014:         return 'error: '.$queryid;
 5015:     }
 5016:     my $reply = &get_query_reply($queryid);
 5017:     my $tries = 1;
 5018:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5019:         $reply = &get_query_reply($queryid);
 5020:         $tries ++;
 5021:     }
 5022:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5023:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5024:     } else {
 5025:         my @responses = split(/:/,$reply);
 5026:         my $outcome = shift(@responses); 
 5027:         foreach my $item (@responses) {
 5028:             my ($key,$value) = split(/=/,$item);
 5029:             $$photo{$key} = $value;
 5030:         }
 5031:         return $outcome;
 5032:     }
 5033:     return 'error';
 5034: }
 5035: 
 5036: sub auto_instcode_format {
 5037:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5038: 	$cat_order) = @_;
 5039:     my $courses = '';
 5040:     my @homeservers;
 5041:     if ($caller eq 'global') {
 5042: 	my %servers = &get_servers($codedom,'library');
 5043: 	foreach my $tryserver (keys(%servers)) {
 5044: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5045: 		push(@homeservers,$tryserver);
 5046: 	    }
 5047:         }
 5048:     } else {
 5049:         push(@homeservers,&homeserver($caller,$codedom));
 5050:     }
 5051:     foreach my $code (keys(%{$instcodes})) {
 5052:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5053:     }
 5054:     chop($courses);
 5055:     my $ok_response = 0;
 5056:     my $response;
 5057:     while (@homeservers > 0 && $ok_response == 0) {
 5058:         my $server = shift(@homeservers); 
 5059:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5060:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5061:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5062: 		split(/:/,$response);
 5063:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5064:             push(@{$codetitles},&str2array($codetitles_str));
 5065:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5066:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5067:             $ok_response = 1;
 5068:         }
 5069:     }
 5070:     if ($ok_response) {
 5071:         return 'ok';
 5072:     } else {
 5073:         return $response;
 5074:     }
 5075: }
 5076: 
 5077: sub auto_instcode_defaults {
 5078:     my ($domain,$returnhash,$code_order) = @_;
 5079:     my @homeservers;
 5080: 
 5081:     my %servers = &get_servers($domain,'library');
 5082:     foreach my $tryserver (keys(%servers)) {
 5083: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5084: 	    push(@homeservers,$tryserver);
 5085: 	}
 5086:     }
 5087: 
 5088:     my $response;
 5089:     foreach my $server (@homeservers) {
 5090:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5091:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5092: 	
 5093: 	foreach my $pair (split(/\&/,$response)) {
 5094: 	    my ($name,$value)=split(/\=/,$pair);
 5095: 	    if ($name eq 'code_order') {
 5096: 		@{$code_order} = split(/\&/,&unescape($value));
 5097: 	    } else {
 5098: 		$returnhash->{&unescape($name)}=&unescape($value);
 5099: 	    }
 5100: 	}
 5101: 	return 'ok';
 5102:     }
 5103: 
 5104:     return $response;
 5105: } 
 5106: 
 5107: sub auto_validate_class_sec {
 5108:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5109:     my $homeserver = &homeserver($cnum,$cdom);
 5110:     my $ownerlist;
 5111:     if (ref($owners) eq 'ARRAY') {
 5112:         $ownerlist = join(',',@{$owners});
 5113:     } else {
 5114:         $ownerlist = $owners;
 5115:     }
 5116:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5117:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5118:     return $response;
 5119: }
 5120: 
 5121: # ------------------------------------------------------- Course Group routines
 5122: 
 5123: sub get_coursegroups {
 5124:     my ($cdom,$cnum,$group,$namespace) = @_;
 5125:     return(&dump($namespace,$cdom,$cnum,$group));
 5126: }
 5127: 
 5128: sub modify_coursegroup {
 5129:     my ($cdom,$cnum,$groupsettings) = @_;
 5130:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5131: }
 5132: 
 5133: sub toggle_coursegroup_status {
 5134:     my ($cdom,$cnum,$group,$action) = @_;
 5135:     my ($from_namespace,$to_namespace);
 5136:     if ($action eq 'delete') {
 5137:         $from_namespace = 'coursegroups';
 5138:         $to_namespace = 'deleted_groups';
 5139:     } else {
 5140:         $from_namespace = 'deleted_groups';
 5141:         $to_namespace = 'coursegroups';
 5142:     }
 5143:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5144:     if (my $tmp = &error(%curr_group)) {
 5145:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5146:         return ('read error',$tmp);
 5147:     } else {
 5148:         my %savedsettings = %curr_group; 
 5149:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5150:         my $deloutcome;
 5151:         if ($result eq 'ok') {
 5152:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5153:         } else {
 5154:             return ('write error',$result);
 5155:         }
 5156:         if ($deloutcome eq 'ok') {
 5157:             return 'ok';
 5158:         } else {
 5159:             return ('delete error',$deloutcome);
 5160:         }
 5161:     }
 5162: }
 5163: 
 5164: sub modify_group_roles {
 5165:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs) = @_;
 5166:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5167:     my $role = 'gr/'.&escape($userprivs);
 5168:     my ($uname,$udom) = split(/:/,$user);
 5169:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start);
 5170:     if ($result eq 'ok') {
 5171:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5172:     }
 5173:     return $result;
 5174: }
 5175: 
 5176: sub modify_coursegroup_membership {
 5177:     my ($cdom,$cnum,$membership) = @_;
 5178:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5179:     return $result;
 5180: }
 5181: 
 5182: sub get_active_groups {
 5183:     my ($udom,$uname,$cdom,$cnum) = @_;
 5184:     my $now = time;
 5185:     my %groups = ();
 5186:     foreach my $key (keys(%env)) {
 5187:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5188:             my ($start,$end) = split(/\./,$env{$key});
 5189:             if (($end!=0) && ($end<$now)) { next; }
 5190:             if (($start!=0) && ($start>$now)) { next; }
 5191:             if ($1 eq $cdom && $2 eq $cnum) {
 5192:                 $groups{$3} = $env{$key} ;
 5193:             }
 5194:         }
 5195:     }
 5196:     return %groups;
 5197: }
 5198: 
 5199: sub get_group_membership {
 5200:     my ($cdom,$cnum,$group) = @_;
 5201:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5202: }
 5203: 
 5204: sub get_users_groups {
 5205:     my ($udom,$uname,$courseid) = @_;
 5206:     my @usersgroups;
 5207:     my $cachetime=1800;
 5208: 
 5209:     my $hashid="$udom:$uname:$courseid";
 5210:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5211:     if (defined($cached)) {
 5212:         @usersgroups = split(/:/,$grouplist);
 5213:     } else {  
 5214:         $grouplist = '';
 5215:         my $courseurl = &courseid_to_courseurl($courseid);
 5216:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5217:         my $access_end = $env{'course.'.$courseid.
 5218:                               '.default_enrollment_end_date'};
 5219:         my $now = time;
 5220:         foreach my $key (keys(%roleshash)) {
 5221:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5222:                 my $group = $1;
 5223:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5224:                     my $start = $2;
 5225:                     my $end = $1;
 5226:                     if ($start == -1) { next; } # deleted from group
 5227:                     if (($start!=0) && ($start>$now)) { next; }
 5228:                     if (($end!=0) && ($end<$now)) {
 5229:                         if ($access_end && $access_end < $now) {
 5230:                             if ($access_end - $end < 86400) {
 5231:                                 push(@usersgroups,$group);
 5232:                             }
 5233:                         }
 5234:                         next;
 5235:                     }
 5236:                     push(@usersgroups,$group);
 5237:                 }
 5238:             }
 5239:         }
 5240:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5241:         $grouplist = join(':',@usersgroups);
 5242:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5243:     }
 5244:     return @usersgroups;
 5245: }
 5246: 
 5247: sub devalidate_getgroups_cache {
 5248:     my ($udom,$uname,$cdom,$cnum)=@_;
 5249:     my $courseid = $cdom.'_'.$cnum;
 5250: 
 5251:     my $hashid="$udom:$uname:$courseid";
 5252:     &devalidate_cache_new('getgroups',$hashid);
 5253: }
 5254: 
 5255: # ------------------------------------------------------------------ Plain Text
 5256: 
 5257: sub plaintext {
 5258:     my ($short,$type,$cid) = @_;
 5259:     if ($short =~ /^cr/) {
 5260: 	return (split('/',$short))[-1];
 5261:     }
 5262:     if (!defined($cid)) {
 5263:         $cid = $env{'request.course.id'};
 5264:     }
 5265:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5266:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5267:                                           '.plaintext'});
 5268:     }
 5269:     my %rolenames = (
 5270:                       Course => 'std',
 5271:                       Group => 'alt1',
 5272:                     );
 5273:     if (defined($type) && 
 5274:          defined($rolenames{$type}) && 
 5275:          defined($prp{$short}{$rolenames{$type}})) {
 5276:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5277:     } else {
 5278:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5279:     }
 5280: }
 5281: 
 5282: # ----------------------------------------------------------------- Assign Role
 5283: 
 5284: sub assignrole {
 5285:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag)=@_;
 5286:     my $mrole;
 5287:     if ($role =~ /^cr\//) {
 5288:         my $cwosec=$url;
 5289:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5290: 	unless (&allowed('ccr',$cwosec)) {
 5291:            &logthis('Refused custom assignrole: '.
 5292:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5293: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5294:            return 'refused'; 
 5295:         }
 5296:         $mrole='cr';
 5297:     } elsif ($role =~ /^gr\//) {
 5298:         my $cwogrp=$url;
 5299:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5300:         unless (&allowed('mdg',$cwogrp)) {
 5301:             &logthis('Refused group assignrole: '.
 5302:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5303:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5304:             return 'refused';
 5305:         }
 5306:         $mrole='gr';
 5307:     } else {
 5308:         my $cwosec=$url;
 5309:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5310:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5311:             my $refused;
 5312:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5313:                 if (!(&allowed('c'.$role,$url))) {
 5314:                     $refused = 1;
 5315:                 }
 5316:             } else {
 5317:                 $refused = 1;
 5318:             }
 5319:             if ($refused) { 
 5320:                 &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5321:                          ' '.$role.' '.$end.' '.$start.' by '.
 5322: 	  	         $env{'user.name'}.' at '.$env{'user.domain'});
 5323:                 return 'refused';
 5324:             }
 5325:         }
 5326:         $mrole=$role;
 5327:     }
 5328:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5329:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5330:     if ($end) { $command.='_'.$end; }
 5331:     if ($start) {
 5332: 	if ($end) { 
 5333:            $command.='_'.$start; 
 5334:         } else {
 5335:            $command.='_0_'.$start;
 5336:         }
 5337:     }
 5338:     my $origstart = $start;
 5339:     my $origend = $end;
 5340: # actually delete
 5341:     if ($deleteflag) {
 5342: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5343: # modify command to delete the role
 5344:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5345:                 "$udom:$uname:$url".'_'."$mrole";
 5346: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5347: # set start and finish to negative values for userrolelog
 5348:            $start=-1;
 5349:            $end=-1;
 5350:         }
 5351:     }
 5352: # send command
 5353:     my $answer=&reply($command,&homeserver($uname,$udom));
 5354: # log new user role if status is ok
 5355:     if ($answer eq 'ok') {
 5356: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5357: # for course roles, perform group memberships changes triggered by role change.
 5358:         unless ($role =~ /^gr/) {
 5359:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5360:                                              $origstart);
 5361:         }
 5362:     }
 5363:     return $answer;
 5364: }
 5365: 
 5366: # -------------------------------------------------- Modify user authentication
 5367: # Overrides without validation
 5368: 
 5369: sub modifyuserauth {
 5370:     my ($udom,$uname,$umode,$upass)=@_;
 5371:     my $uhome=&homeserver($uname,$udom);
 5372:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5373:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5374:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5375:              ' in domain '.$env{'request.role.domain'});  
 5376:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5377: 		     &escape($upass),$uhome);
 5378:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5379:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5380:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5381:     &log($udom,,$uname,$uhome,
 5382:         'Authentication changed by '.$env{'user.domain'}.', '.
 5383:                                      $env{'user.name'}.', '.$umode.
 5384:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5385:     unless ($reply eq 'ok') {
 5386:         &logthis('Authentication mode error: '.$reply);
 5387: 	return 'error: '.$reply;
 5388:     }   
 5389:     return 'ok';
 5390: }
 5391: 
 5392: # --------------------------------------------------------------- Modify a user
 5393: 
 5394: sub modifyuser {
 5395:     my ($udom,    $uname, $uid,
 5396:         $umode,   $upass, $first,
 5397:         $middle,  $last,  $gene,
 5398:         $forceid, $desiredhome, $email)=@_;
 5399:     $udom= &LONCAPA::clean_domain($udom);
 5400:     $uname=&LONCAPA::clean_username($uname);
 5401:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5402:              $umode.', '.$first.', '.$middle.', '.
 5403: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5404:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5405:                                      ' desiredhome not specified'). 
 5406:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5407:              ' in domain '.$env{'request.role.domain'});
 5408:     my $uhome=&homeserver($uname,$udom,'true');
 5409: # ----------------------------------------------------------------- Create User
 5410:     if (($uhome eq 'no_host') && 
 5411: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5412:         my $unhome='';
 5413:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5414:             $unhome = $desiredhome;
 5415: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5416: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5417:         } else { # load balancing routine for determining $unhome
 5418:             my $loadm=10000000;
 5419: 	    my %servers = &get_servers($udom,'library');
 5420: 	    foreach my $tryserver (keys(%servers)) {
 5421: 		my $answer=reply('load',$tryserver);
 5422: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5423: 		    $loadm=$answer;
 5424: 		    $unhome=$tryserver;
 5425: 		}
 5426: 	    }
 5427:         }
 5428:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5429: 	    return 'error: unable to find a home server for '.$uname.
 5430:                    ' in domain '.$udom;
 5431:         }
 5432:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5433:                          &escape($upass),$unhome);
 5434: 	unless ($reply eq 'ok') {
 5435:             return 'error: '.$reply;
 5436:         }   
 5437:         $uhome=&homeserver($uname,$udom,'true');
 5438:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5439: 	    return 'error: unable verify users home machine.';
 5440:         }
 5441:     }   # End of creation of new user
 5442: # ---------------------------------------------------------------------- Add ID
 5443:     if ($uid) {
 5444:        $uid=~tr/A-Z/a-z/;
 5445:        my %uidhash=&idrget($udom,$uname);
 5446:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5447:          && (!$forceid)) {
 5448: 	  unless ($uid eq $uidhash{$uname}) {
 5449: 	      return 'error: user id "'.$uid.'" does not match '.
 5450:                   'current user id "'.$uidhash{$uname}.'".';
 5451:           }
 5452:        } else {
 5453: 	  &idput($udom,($uname => $uid));
 5454:        }
 5455:     }
 5456: # -------------------------------------------------------------- Add names, etc
 5457:     my @tmp=&get('environment',
 5458: 		   ['firstname','middlename','lastname','generation','id',
 5459:                     'permanentemail'],
 5460: 		   $udom,$uname);
 5461:     my %names;
 5462:     if ($tmp[0] =~ m/^error:.*/) { 
 5463:         %names=(); 
 5464:     } else {
 5465:         %names = @tmp;
 5466:     }
 5467: #
 5468: # Make sure to not trash student environment if instructor does not bother
 5469: # to supply name and email information
 5470: #
 5471:     if ($first)  { $names{'firstname'}  = $first; }
 5472:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5473:     if ($last)   { $names{'lastname'}   = $last; }
 5474:     if (defined($gene))   { $names{'generation'} = $gene; }
 5475:     if ($email) {
 5476:        $email=~s/[^\w\@\.\-\,]//gs;
 5477:        if ($email=~/\@/) { $names{'notification'} = $email;
 5478: 			   $names{'critnotification'} = $email;
 5479: 			   $names{'permanentemail'} = $email; }
 5480:     }
 5481:     if ($uid) { $names{'id'}  = $uid; }
 5482:     my $reply = &put('environment', \%names, $udom,$uname);
 5483:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5484:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5485:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5486:     &logthis('Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5487:              $umode.', '.$first.', '.$middle.', '.
 5488: 	     $last.', '.$gene.' by '.
 5489:              $env{'user.name'}.' at '.$env{'user.domain'});
 5490:     return 'ok';
 5491: }
 5492: 
 5493: # -------------------------------------------------------------- Modify student
 5494: 
 5495: sub modifystudent {
 5496:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5497:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid)=@_;
 5498:     if (!$cid) {
 5499: 	unless ($cid=$env{'request.course.id'}) {
 5500: 	    return 'not_in_class';
 5501: 	}
 5502:     }
 5503: # --------------------------------------------------------------- Make the user
 5504:     my $reply=&modifyuser
 5505: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5506:          $desiredhome,$email);
 5507:     unless ($reply eq 'ok') { return $reply; }
 5508:     # This will cause &modify_student_enrollment to get the uid from the
 5509:     # students environment
 5510:     $uid = undef if (!$forceid);
 5511:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5512: 					$gene,$usec,$end,$start,$type,$locktype,$cid);
 5513:     return $reply;
 5514: }
 5515: 
 5516: sub modify_student_enrollment {
 5517:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid) = @_;
 5518:     my ($cdom,$cnum,$chome);
 5519:     if (!$cid) {
 5520: 	unless ($cid=$env{'request.course.id'}) {
 5521: 	    return 'not_in_class';
 5522: 	}
 5523: 	$cdom=$env{'course.'.$cid.'.domain'};
 5524: 	$cnum=$env{'course.'.$cid.'.num'};
 5525:     } else {
 5526: 	($cdom,$cnum)=split(/_/,$cid);
 5527:     }
 5528:     $chome=$env{'course.'.$cid.'.home'};
 5529:     if (!$chome) {
 5530: 	$chome=&homeserver($cnum,$cdom);
 5531:     }
 5532:     if (!$chome) { return 'unknown_course'; }
 5533:     # Make sure the user exists
 5534:     my $uhome=&homeserver($uname,$udom);
 5535:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5536: 	return 'error: no such user';
 5537:     }
 5538:     # Get student data if we were not given enough information
 5539:     if (!defined($first)  || $first  eq '' || 
 5540:         !defined($last)   || $last   eq '' || 
 5541:         !defined($uid)    || $uid    eq '' || 
 5542:         !defined($middle) || $middle eq '' || 
 5543:         !defined($gene)   || $gene   eq '') {
 5544:         # They did not supply us with enough data to enroll the student, so
 5545:         # we need to pick up more information.
 5546:         my %tmp = &get('environment',
 5547:                        ['firstname','middlename','lastname', 'generation','id']
 5548:                        ,$udom,$uname);
 5549: 
 5550:         #foreach my $key (keys(%tmp)) {
 5551:         #    &logthis("key $key = ".$tmp{$key});
 5552:         #}
 5553:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5554:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5555:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5556:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5557:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5558:     }
 5559:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5560:     my $reply=cput('classlist',
 5561: 		   {"$uname:$udom" => 
 5562: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5563: 		   $cdom,$cnum);
 5564:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5565: 	return 'error: '.$reply;
 5566:     } else {
 5567: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5568:     }
 5569:     # Add student role to user
 5570:     my $uurl='/'.$cid;
 5571:     $uurl=~s/\_/\//g;
 5572:     if ($usec) {
 5573: 	$uurl.='/'.$usec;
 5574:     }
 5575:     return &assignrole($udom,$uname,$uurl,'st',$end,$start);
 5576: }
 5577: 
 5578: sub format_name {
 5579:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5580:     my $name;
 5581:     if ($first ne 'lastname') {
 5582: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5583:     } else {
 5584: 	if ($lastname=~/\S/) {
 5585: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5586: 	    $name=~s/\s+,/,/;
 5587: 	} else {
 5588: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5589: 	}
 5590:     }
 5591:     $name=~s/^\s+//;
 5592:     $name=~s/\s+$//;
 5593:     $name=~s/\s+/ /g;
 5594:     return $name;
 5595: }
 5596: 
 5597: # ------------------------------------------------- Write to course preferences
 5598: 
 5599: sub writecoursepref {
 5600:     my ($courseid,%prefs)=@_;
 5601:     $courseid=~s/^\///;
 5602:     $courseid=~s/\_/\//g;
 5603:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5604:     my $chome=homeserver($cnum,$cdomain);
 5605:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5606: 	return 'error: no such course';
 5607:     }
 5608:     my $cstring='';
 5609:     foreach my $pref (keys(%prefs)) {
 5610: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5611:     }
 5612:     $cstring=~s/\&$//;
 5613:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5614: }
 5615: 
 5616: # ---------------------------------------------------------- Make/modify course
 5617: 
 5618: sub createcourse {
 5619:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5620:         $course_owner,$crstype)=@_;
 5621:     $url=&declutter($url);
 5622:     my $cid='';
 5623:     unless (&allowed('ccc',$udom)) {
 5624:         return 'refused';
 5625:     }
 5626: # ------------------------------------------------------------------- Create ID
 5627:    my $uname=int(1+rand(9)).
 5628:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5629:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5630:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5631: # ----------------------------------------------- Make sure that does not exist
 5632:    my $uhome=&homeserver($uname,$udom,'true');
 5633:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5634:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5635:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5636:        $uhome=&homeserver($uname,$udom,'true');       
 5637:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5638:            return 'error: unable to generate unique course-ID';
 5639:        } 
 5640:    }
 5641: # ------------------------------------------------ Check supplied server name
 5642:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5643:     if (! &is_library($course_server)) {
 5644:         return 'error:bad server name '.$course_server;
 5645:     }
 5646: # ------------------------------------------------------------- Make the course
 5647:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5648:                       $course_server);
 5649:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5650:     $uhome=&homeserver($uname,$udom,'true');
 5651:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5652: 	return 'error: no such course';
 5653:     }
 5654: # ----------------------------------------------------------------- Course made
 5655: # log existence
 5656:     my $newcourse = {
 5657:                     $udom.'_'.$uname => {
 5658:                                      description => $description,
 5659:                                      inst_code   => $inst_code,
 5660:                                      owner       => $course_owner,
 5661:                                      type        => $crstype,
 5662:                                                 },
 5663:                     };
 5664:     &courseidput($udom,$newcourse,$uhome,'notime');
 5665: # set toplevel url
 5666:     my $topurl=$url;
 5667:     unless ($nonstandard) {
 5668: # ------------------------------------------ For standard courses, make top url
 5669:         my $mapurl=&clutter($url);
 5670:         if ($mapurl eq '/res/') { $mapurl=''; }
 5671:         $env{'form.initmap'}=(<<ENDINITMAP);
 5672: <map>
 5673: <resource id="1" type="start"></resource>
 5674: <resource id="2" src="$mapurl"></resource>
 5675: <resource id="3" type="finish"></resource>
 5676: <link index="1" from="1" to="2"></link>
 5677: <link index="2" from="2" to="3"></link>
 5678: </map>
 5679: ENDINITMAP
 5680:         $topurl=&declutter(
 5681:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 5682:                           );
 5683:     }
 5684: # ----------------------------------------------------------- Write preferences
 5685:     &writecoursepref($udom.'_'.$uname,
 5686:                      ('description' => $description,
 5687:                       'url'         => $topurl));
 5688:     return '/'.$udom.'/'.$uname;
 5689: }
 5690: 
 5691: sub is_course {
 5692:     my ($cdom,$cnum) = @_;
 5693:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 5694: 				undef,'.',undef,1);
 5695:     if (exists($courses{$cdom.'_'.$cnum})) {
 5696:         return 1;
 5697:     }
 5698:     return 0;
 5699: }
 5700: 
 5701: # ---------------------------------------------------------- Assign Custom Role
 5702: 
 5703: sub assigncustomrole {
 5704:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag)=@_;
 5705:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 5706:                        $end,$start,$deleteflag);
 5707: }
 5708: 
 5709: # ----------------------------------------------------------------- Revoke Role
 5710: 
 5711: sub revokerole {
 5712:     my ($udom,$uname,$url,$role,$deleteflag)=@_;
 5713:     my $now=time;
 5714:     return &assignrole($udom,$uname,$url,$role,$now,$deleteflag);
 5715: }
 5716: 
 5717: # ---------------------------------------------------------- Revoke Custom Role
 5718: 
 5719: sub revokecustomrole {
 5720:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag)=@_;
 5721:     my $now=time;
 5722:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 5723:            $deleteflag);
 5724: }
 5725: 
 5726: # ------------------------------------------------------------ Disk usage
 5727: sub diskusage {
 5728:     my ($udom,$uname,$directoryRoot)=@_;
 5729:     $directoryRoot =~ s/\/$//;
 5730:     my $listing=&reply('du:'.$directoryRoot,homeserver($uname,$udom));
 5731:     return $listing;
 5732: }
 5733: 
 5734: sub is_locked {
 5735:     my ($file_name, $domain, $user) = @_;
 5736:     my @check;
 5737:     my $is_locked;
 5738:     push @check, $file_name;
 5739:     my %locked = &get('file_permissions',\@check,
 5740: 		      $env{'user.domain'},$env{'user.name'});
 5741:     my ($tmp)=keys(%locked);
 5742:     if ($tmp=~/^error:/) { undef(%locked); }
 5743:     
 5744:     if (ref($locked{$file_name}) eq 'ARRAY') {
 5745:         $is_locked = 'false';
 5746:         foreach my $entry (@{$locked{$file_name}}) {
 5747:            if (ref($entry) eq 'ARRAY') { 
 5748:                $is_locked = 'true';
 5749:                last;
 5750:            }
 5751:        }
 5752:     } else {
 5753:         $is_locked = 'false';
 5754:     }
 5755: }
 5756: 
 5757: sub declutter_portfile {
 5758:     my ($file) = @_;
 5759:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 5760:     return $file;
 5761: }
 5762: 
 5763: # ------------------------------------------------------------- Mark as Read Only
 5764: 
 5765: sub mark_as_readonly {
 5766:     my ($domain,$user,$files,$what) = @_;
 5767:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5768:     my ($tmp)=keys(%current_permissions);
 5769:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5770:     foreach my $file (@{$files}) {
 5771: 	$file = &declutter_portfile($file);
 5772:         push(@{$current_permissions{$file}},$what);
 5773:     }
 5774:     &put('file_permissions',\%current_permissions,$domain,$user);
 5775:     return;
 5776: }
 5777: 
 5778: # ------------------------------------------------------------Save Selected Files
 5779: 
 5780: sub save_selected_files {
 5781:     my ($user, $path, @files) = @_;
 5782:     my $filename = $user."savedfiles";
 5783:     my @other_files = &files_not_in_path($user, $path);
 5784:     open (OUT, '>'.$tmpdir.$filename);
 5785:     foreach my $file (@files) {
 5786:         print (OUT $env{'form.currentpath'}.$file."\n");
 5787:     }
 5788:     foreach my $file (@other_files) {
 5789:         print (OUT $file."\n");
 5790:     }
 5791:     close (OUT);
 5792:     return 'ok';
 5793: }
 5794: 
 5795: sub clear_selected_files {
 5796:     my ($user) = @_;
 5797:     my $filename = $user."savedfiles";
 5798:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5799:     print (OUT undef);
 5800:     close (OUT);
 5801:     return ("ok");    
 5802: }
 5803: 
 5804: sub files_in_path {
 5805:     my ($user, $path) = @_;
 5806:     my $filename = $user."savedfiles";
 5807:     my %return_files;
 5808:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5809:     while (my $line_in = <IN>) {
 5810:         chomp ($line_in);
 5811:         my @paths_and_file = split (m!/!, $line_in);
 5812:         my $file_part = pop (@paths_and_file);
 5813:         my $path_part = join ('/', @paths_and_file);
 5814:         $path_part.='/';
 5815:         my $path_and_file = $path_part.$file_part;
 5816:         if ($path_part eq $path) {
 5817:             $return_files{$file_part}= 'selected';
 5818:         }
 5819:     }
 5820:     close (IN);
 5821:     return (\%return_files);
 5822: }
 5823: 
 5824: # called in portfolio select mode, to show files selected NOT in current directory
 5825: sub files_not_in_path {
 5826:     my ($user, $path) = @_;
 5827:     my $filename = $user."savedfiles";
 5828:     my @return_files;
 5829:     my $path_part;
 5830:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 5831:     while (my $line = <IN>) {
 5832:         #ok, I know it's clunky, but I want it to work
 5833:         my @paths_and_file = split(m|/|, $line);
 5834:         my $file_part = pop(@paths_and_file);
 5835:         chomp($file_part);
 5836:         my $path_part = join('/', @paths_and_file);
 5837:         $path_part .= '/';
 5838:         my $path_and_file = $path_part.$file_part;
 5839:         if ($path_part ne $path) {
 5840:             push(@return_files, ($path_and_file));
 5841:         }
 5842:     }
 5843:     close(OUT);
 5844:     return (@return_files);
 5845: }
 5846: 
 5847: #----------------------------------------------Get portfolio file permissions
 5848: 
 5849: sub get_portfile_permissions {
 5850:     my ($domain,$user) = @_;
 5851:     my %current_permissions = &dump('file_permissions',$domain,$user);
 5852:     my ($tmp)=keys(%current_permissions);
 5853:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 5854:     return \%current_permissions;
 5855: }
 5856: 
 5857: #---------------------------------------------Get portfolio file access controls
 5858: 
 5859: sub get_access_controls {
 5860:     my ($current_permissions,$group,$file) = @_;
 5861:     my %access;
 5862:     my $real_file = $file;
 5863:     $file =~ s/\.meta$//;
 5864:     if (defined($file)) {
 5865:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 5866:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 5867:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 5868:             }
 5869:         }
 5870:     } else {
 5871:         foreach my $key (keys(%{$current_permissions})) {
 5872:             if ($key =~ /\0accesscontrol$/) {
 5873:                 if (defined($group)) {
 5874:                     if ($key !~ m-^\Q$group\E/-) {
 5875:                         next;
 5876:                     }
 5877:                 }
 5878:                 my ($fullpath) = split(/\0/,$key);
 5879:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 5880:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 5881:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 5882:                     }
 5883:                 }
 5884:             }
 5885:         }
 5886:     }
 5887:     return %access;
 5888: }
 5889: 
 5890: sub modify_access_controls {
 5891:     my ($file_name,$changes,$domain,$user)=@_;
 5892:     my ($outcome,$deloutcome);
 5893:     my %store_permissions;
 5894:     my %new_values;
 5895:     my %new_control;
 5896:     my %translation;
 5897:     my @deletions = ();
 5898:     my $now = time;
 5899:     if (exists($$changes{'activate'})) {
 5900:         if (ref($$changes{'activate'}) eq 'HASH') {
 5901:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 5902:             my $numnew = scalar(@newitems);
 5903:             for (my $i=0; $i<$numnew; $i++) {
 5904:                 my $newkey = $newitems[$i];
 5905:                 my $newid = &Apache::loncommon::get_cgi_id();
 5906:                 if ($newkey =~ /^\d+:/) { 
 5907:                     $newkey =~ s/^(\d+)/$newid/;
 5908:                     $translation{$1} = $newid;
 5909:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 5910:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 5911:                     $translation{$1} = $newid;
 5912:                 }
 5913:                 $new_values{$file_name."\0".$newkey} = 
 5914:                                           $$changes{'activate'}{$newitems[$i]};
 5915:                 $new_control{$newkey} = $now;
 5916:             }
 5917:         }
 5918:     }
 5919:     my %todelete;
 5920:     my %changed_items;
 5921:     foreach my $action ('delete','update') {
 5922:         if (exists($$changes{$action})) {
 5923:             if (ref($$changes{$action}) eq 'HASH') {
 5924:                 foreach my $key (keys(%{$$changes{$action}})) {
 5925:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 5926:                     if ($action eq 'delete') { 
 5927:                         $todelete{$itemnum} = 1;
 5928:                     } else {
 5929:                         $changed_items{$itemnum} = $key;
 5930:                     }
 5931:                 }
 5932:             }
 5933:         }
 5934:     }
 5935:     # get lock on access controls for file.
 5936:     my $lockhash = {
 5937:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 5938:                                                        ':'.$env{'user.domain'},
 5939:                    }; 
 5940:     my $tries = 0;
 5941:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5942:    
 5943:     while (($gotlock ne 'ok') && $tries <3) {
 5944:         $tries ++;
 5945:         sleep 1;
 5946:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 5947:     }
 5948:     if ($gotlock eq 'ok') {
 5949:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 5950:         my ($tmp)=keys(%curr_permissions);
 5951:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 5952:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 5953:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 5954:             if (ref($curr_controls) eq 'HASH') {
 5955:                 foreach my $control_item (keys(%{$curr_controls})) {
 5956:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 5957:                     if (defined($todelete{$itemnum})) {
 5958:                         push(@deletions,$file_name."\0".$control_item);
 5959:                     } else {
 5960:                         if (defined($changed_items{$itemnum})) {
 5961:                             $new_control{$changed_items{$itemnum}} = $now;
 5962:                             push(@deletions,$file_name."\0".$control_item);
 5963:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 5964:                         } else {
 5965:                             $new_control{$control_item} = $$curr_controls{$control_item};
 5966:                         }
 5967:                     }
 5968:                 }
 5969:             }
 5970:         }
 5971:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 5972:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 5973:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 5974:         #  remove lock
 5975:         my @del_lock = ($file_name."\0".'locked_access_records');
 5976:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 5977:         my ($file,$group);
 5978:         if (&is_course($domain,$user)) {
 5979:             ($group,$file) = split(/\//,$file_name,2);
 5980:         } else {
 5981:             $file = $file_name;
 5982:         }
 5983:         my $sqlresult =
 5984:             &update_portfolio_table($user,$domain,$file,'portfolio_access',
 5985:                                     $group);
 5986:     } else {
 5987:         $outcome = "error: could not obtain lockfile\n";  
 5988:     }
 5989:     return ($outcome,$deloutcome,\%new_values,\%translation);
 5990: }
 5991: 
 5992: sub make_public_indefinitely {
 5993:     my ($requrl) = @_;
 5994:     my $now = time;
 5995:     my $action = 'activate';
 5996:     my $aclnum = 0;
 5997:     if (&is_portfolio_url($requrl)) {
 5998:         my (undef,$udom,$unum,$file_name,$group) =
 5999:             &parse_portfolio_url($requrl);
 6000:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6001:         my %access_controls = &get_access_controls($current_perms,
 6002:                                                    $group,$file_name);
 6003:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6004:             my ($num,$scope,$end,$start) = 
 6005:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6006:             if ($scope eq 'public') {
 6007:                 if ($start <= $now && $end == 0) {
 6008:                     $action = 'none';
 6009:                 } else {
 6010:                     $action = 'update';
 6011:                     $aclnum = $num;
 6012:                 }
 6013:                 last;
 6014:             }
 6015:         }
 6016:         if ($action eq 'none') {
 6017:              return 'ok';
 6018:         } else {
 6019:             my %changes;
 6020:             my $newend = 0;
 6021:             my $newstart = $now;
 6022:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6023:             $changes{$action}{$newkey} = {
 6024:                 type => 'public',
 6025:                 time => {
 6026:                     start => $newstart,
 6027:                     end   => $newend,
 6028:                 },
 6029:             };
 6030:             my ($outcome,$deloutcome,$new_values,$translation) =
 6031:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6032:             return $outcome;
 6033:         }
 6034:     } else {
 6035:         return 'invalid';
 6036:     }
 6037: }
 6038: 
 6039: #------------------------------------------------------Get Marked as Read Only
 6040: 
 6041: sub get_marked_as_readonly {
 6042:     my ($domain,$user,$what,$group) = @_;
 6043:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6044:     my @readonly_files;
 6045:     my $cmp1=$what;
 6046:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6047:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6048:         if (defined($group)) {
 6049:             if ($file_name !~ m-^\Q$group\E/-) {
 6050:                 next;
 6051:             }
 6052:         }
 6053:         if (ref($value) eq "ARRAY"){
 6054:             foreach my $stored_what (@{$value}) {
 6055:                 my $cmp2=$stored_what;
 6056:                 if (ref($stored_what) eq 'ARRAY') {
 6057:                     $cmp2=join('',@{$stored_what});
 6058:                 }
 6059:                 if ($cmp1 eq $cmp2) {
 6060:                     push(@readonly_files, $file_name);
 6061:                     last;
 6062:                 } elsif (!defined($what)) {
 6063:                     push(@readonly_files, $file_name);
 6064:                     last;
 6065:                 }
 6066:             }
 6067:         }
 6068:     }
 6069:     return @readonly_files;
 6070: }
 6071: #-----------------------------------------------------------Get Marked as Read Only Hash
 6072: 
 6073: sub get_marked_as_readonly_hash {
 6074:     my ($current_permissions,$group,$what) = @_;
 6075:     my %readonly_files;
 6076:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6077:         if (defined($group)) {
 6078:             if ($file_name !~ m-^\Q$group\E/-) {
 6079:                 next;
 6080:             }
 6081:         }
 6082:         if (ref($value) eq "ARRAY"){
 6083:             foreach my $stored_what (@{$value}) {
 6084:                 if (ref($stored_what) eq 'ARRAY') {
 6085:                     foreach my $lock_descriptor(@{$stored_what}) {
 6086:                         if ($lock_descriptor eq 'graded') {
 6087:                             $readonly_files{$file_name} = 'graded';
 6088:                         } elsif ($lock_descriptor eq 'handback') {
 6089:                             $readonly_files{$file_name} = 'handback';
 6090:                         } else {
 6091:                             if (!exists($readonly_files{$file_name})) {
 6092:                                 $readonly_files{$file_name} = 'locked';
 6093:                             }
 6094:                         }
 6095:                     }
 6096:                 } 
 6097:             }
 6098:         } 
 6099:     }
 6100:     return %readonly_files;
 6101: }
 6102: # ------------------------------------------------------------ Unmark as Read Only
 6103: 
 6104: sub unmark_as_readonly {
 6105:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6106:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6107:     my ($domain,$user,$what,$file_name,$group) = @_;
 6108:     $file_name = &declutter_portfile($file_name);
 6109:     my $symb_crs = $what;
 6110:     if (ref($what)) { $symb_crs=join('',@$what); }
 6111:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6112:     my ($tmp)=keys(%current_permissions);
 6113:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6114:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6115:     foreach my $file (@readonly_files) {
 6116: 	my $clean_file = &declutter_portfile($file);
 6117: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6118: 	my $current_locks = $current_permissions{$file};
 6119:         my @new_locks;
 6120:         my @del_keys;
 6121:         if (ref($current_locks) eq "ARRAY"){
 6122:             foreach my $locker (@{$current_locks}) {
 6123:                 my $compare=$locker;
 6124:                 if (ref($locker) eq 'ARRAY') {
 6125:                     $compare=join('',@{$locker});
 6126:                     if ($compare ne $symb_crs) {
 6127:                         push(@new_locks, $locker);
 6128:                     }
 6129:                 }
 6130:             }
 6131:             if (scalar(@new_locks) > 0) {
 6132:                 $current_permissions{$file} = \@new_locks;
 6133:             } else {
 6134:                 push(@del_keys, $file);
 6135:                 &del('file_permissions',\@del_keys, $domain, $user);
 6136:                 delete($current_permissions{$file});
 6137:             }
 6138:         }
 6139:     }
 6140:     &put('file_permissions',\%current_permissions,$domain,$user);
 6141:     return;
 6142: }
 6143: 
 6144: # ------------------------------------------------------------ Directory lister
 6145: 
 6146: sub dirlist {
 6147:     my ($uri,$userdomain,$username,$alternateDirectoryRoot)=@_;
 6148: 
 6149:     $uri=~s/^\///;
 6150:     $uri=~s/\/$//;
 6151:     my ($udom, $uname);
 6152:     (undef,$udom,$uname)=split(/\//,$uri);
 6153:     if(defined($userdomain)) {
 6154:         $udom = $userdomain;
 6155:     }
 6156:     if(defined($username)) {
 6157:         $uname = $username;
 6158:     }
 6159: 
 6160:     my $dirRoot = $perlvar{'lonDocRoot'};
 6161:     if(defined($alternateDirectoryRoot)) {
 6162:         $dirRoot = $alternateDirectoryRoot;
 6163:         $dirRoot =~ s/\/$//;
 6164:     }
 6165: 
 6166:     if($udom) {
 6167:         if($uname) {
 6168:             my $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6169: 				 &homeserver($uname,$udom));
 6170:             my @listing_results;
 6171:             if ($listing eq 'unknown_cmd') {
 6172:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6173: 				  &homeserver($uname,$udom));
 6174:                 @listing_results = split(/:/,$listing);
 6175:             } else {
 6176:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6177:             }
 6178:             return @listing_results;
 6179:         } elsif(!defined($alternateDirectoryRoot)) {
 6180:             my %allusers;
 6181: 	    my %servers = &get_servers($udom,'library');
 6182: 	    foreach my $tryserver (keys(%servers)) {
 6183: 		my $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6184: 				     $udom, $tryserver);
 6185: 		my @listing_results;
 6186: 		if ($listing eq 'unknown_cmd') {
 6187: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6188: 				      $udom, $tryserver);
 6189: 		    @listing_results = split(/:/,$listing);
 6190: 		} else {
 6191: 		    @listing_results =
 6192: 			map { &unescape($_); } split(/:/,$listing);
 6193: 		}
 6194: 		if ($listing_results[0] ne 'no_such_dir' && 
 6195: 		    $listing_results[0] ne 'empty'       &&
 6196: 		    $listing_results[0] ne 'con_lost') {
 6197: 		    foreach my $line (@listing_results) {
 6198: 			my ($entry) = split(/&/,$line,2);
 6199: 			$allusers{$entry} = 1;
 6200: 		    }
 6201: 		}
 6202:             }
 6203:             my $alluserstr='';
 6204:             foreach my $user (sort(keys(%allusers))) {
 6205:                 $alluserstr.=$user.'&user:';
 6206:             }
 6207:             $alluserstr=~s/:$//;
 6208:             return split(/:/,$alluserstr);
 6209:         } else {
 6210:             return ('missing user name');
 6211:         }
 6212:     } elsif(!defined($alternateDirectoryRoot)) {
 6213:         my @all_domains = sort(&all_domains());
 6214:          foreach my $domain (@all_domains) {
 6215:              $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6216:          }
 6217:          return @all_domains;
 6218:      } else {
 6219:         return ('missing domain');
 6220:     }
 6221: }
 6222: 
 6223: # --------------------------------------------- GetFileTimestamp
 6224: # This function utilizes dirlist and returns the date stamp for
 6225: # when it was last modified.  It will also return an error of -1
 6226: # if an error occurs
 6227: 
 6228: ##
 6229: ## FIXME: This subroutine assumes its caller knows something about the
 6230: ## directory structure of the home server for the student ($root).
 6231: ## Not a good assumption to make.  Since this is for looking up files
 6232: ## in user directories, the full path should be constructed by lond, not
 6233: ## whatever machine we request data from.
 6234: ##
 6235: sub GetFileTimestamp {
 6236:     my ($studentDomain,$studentName,$filename,$root)=@_;
 6237:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6238:     $studentName   = &LONCAPA::clean_username($studentName);
 6239:     my $subdir=$studentName.'__';
 6240:     $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6241:     my $proname="$studentDomain/$subdir/$studentName";
 6242:     $proname .= '/'.$filename;
 6243:     my ($fileStat) = &Apache::lonnet::dirlist($proname, $studentDomain, 
 6244:                                               $studentName, $root);
 6245:     my @stats = split('&', $fileStat);
 6246:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6247:         # @stats contains first the filename, then the stat output
 6248:         return $stats[10]; # so this is 10 instead of 9.
 6249:     } else {
 6250:         return -1;
 6251:     }
 6252: }
 6253: 
 6254: sub stat_file {
 6255:     my ($uri) = @_;
 6256:     $uri = &clutter_with_no_wrapper($uri);
 6257: 
 6258:     my ($udom,$uname,$file,$dir);
 6259:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6260: 	($udom,$uname,$file) =
 6261: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6262: 	$file = 'userfiles/'.$file;
 6263: 	$dir = &propath($udom,$uname);
 6264:     }
 6265:     if ($uri =~ m-^/res/-) {
 6266: 	($udom,$uname) = 
 6267: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6268: 	$file = $uri;
 6269:     }
 6270: 
 6271:     if (!$udom || !$uname || !$file) {
 6272: 	# unable to handle the uri
 6273: 	return ();
 6274:     }
 6275: 
 6276:     my ($result) = &dirlist($file,$udom,$uname,$dir);
 6277:     my @stats = split('&', $result);
 6278:     
 6279:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6280: 	shift(@stats); #filename is first
 6281: 	return @stats;
 6282:     }
 6283:     return ();
 6284: }
 6285: 
 6286: # -------------------------------------------------------- Value of a Condition
 6287: 
 6288: # gets the value of a specific preevaluated condition
 6289: #    stored in the string  $env{user.state.<cid>}
 6290: # or looks up a condition reference in the bighash and if if hasn't
 6291: # already been evaluated recurses into docondval to get the value of
 6292: # the condition, then memoizing it to 
 6293: #   $env{user.state.<cid>.<condition>}
 6294: sub directcondval {
 6295:     my $number=shift;
 6296:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6297: 	&Apache::lonuserstate::evalstate();
 6298:     }
 6299:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6300: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6301:     } elsif ($number =~ /^_/) {
 6302: 	my $sub_condition;
 6303: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6304: 		&GDBM_READER(),0640)) {
 6305: 	    $sub_condition=$bighash{'conditions'.$number};
 6306: 	    untie(%bighash);
 6307: 	}
 6308: 	my $value = &docondval($sub_condition);
 6309: 	&appenv('user.state.'.$env{'request.course.id'}.".$number" => $value);
 6310: 	return $value;
 6311:     }
 6312:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6313:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6314:     } else {
 6315:        return 2;
 6316:     }
 6317: }
 6318: 
 6319: # get the collection of conditions for this resource
 6320: sub condval {
 6321:     my $condidx=shift;
 6322:     my $allpathcond='';
 6323:     foreach my $cond (split(/\|/,$condidx)) {
 6324: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6325: 	    $allpathcond.=
 6326: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6327: 	}
 6328:     }
 6329:     $allpathcond=~s/\|$//;
 6330:     return &docondval($allpathcond);
 6331: }
 6332: 
 6333: #evaluates an expression of conditions
 6334: sub docondval {
 6335:     my ($allpathcond) = @_;
 6336:     my $result=0;
 6337:     if ($env{'request.course.id'}
 6338: 	&& defined($allpathcond)) {
 6339: 	my $operand='|';
 6340: 	my @stack;
 6341: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6342: 	    if ($chunk eq '(') {
 6343: 		push @stack,($operand,$result);
 6344: 	    } elsif ($chunk eq ')') {
 6345: 		my $before=pop @stack;
 6346: 		if (pop @stack eq '&') {
 6347: 		    $result=$result>$before?$before:$result;
 6348: 		} else {
 6349: 		    $result=$result>$before?$result:$before;
 6350: 		}
 6351: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6352: 		$operand=$chunk;
 6353: 	    } else {
 6354: 		my $new=directcondval($chunk);
 6355: 		if ($operand eq '&') {
 6356: 		    $result=$result>$new?$new:$result;
 6357: 		} else {
 6358: 		    $result=$result>$new?$result:$new;
 6359: 		}
 6360: 	    }
 6361: 	}
 6362:     }
 6363:     return $result;
 6364: }
 6365: 
 6366: # ---------------------------------------------------- Devalidate courseresdata
 6367: 
 6368: sub devalidatecourseresdata {
 6369:     my ($coursenum,$coursedomain)=@_;
 6370:     my $hashid=$coursenum.':'.$coursedomain;
 6371:     &devalidate_cache_new('courseres',$hashid);
 6372: }
 6373: 
 6374: 
 6375: # --------------------------------------------------- Course Resourcedata Query
 6376: #
 6377: #  Parameters:
 6378: #      $coursenum    - Number of the course.
 6379: #      $coursedomain - Domain at which the course was created.
 6380: #  Returns:
 6381: #     A hash of the course parameters along (I think) with timestamps
 6382: #     and version info.
 6383: 
 6384: sub get_courseresdata {
 6385:     my ($coursenum,$coursedomain)=@_;
 6386:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6387:     my $hashid=$coursenum.':'.$coursedomain;
 6388:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6389:     my %dumpreply;
 6390:     unless (defined($cached)) {
 6391: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6392: 	$result=\%dumpreply;
 6393: 	my ($tmp) = keys(%dumpreply);
 6394: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6395: 	    &do_cache_new('courseres',$hashid,$result,600);
 6396: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6397: 	    return $tmp;
 6398: 	} elsif ($tmp =~ /^(error)/) {
 6399: 	    $result=undef;
 6400: 	    &do_cache_new('courseres',$hashid,$result,600);
 6401: 	}
 6402:     }
 6403:     return $result;
 6404: }
 6405: 
 6406: sub devalidateuserresdata {
 6407:     my ($uname,$udom)=@_;
 6408:     my $hashid="$udom:$uname";
 6409:     &devalidate_cache_new('userres',$hashid);
 6410: }
 6411: 
 6412: sub get_userresdata {
 6413:     my ($uname,$udom)=@_;
 6414:     #most student don\'t have any data set, check if there is some data
 6415:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6416: 
 6417:     my $hashid="$udom:$uname";
 6418:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6419:     if (!defined($cached)) {
 6420: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6421: 	$result=\%resourcedata;
 6422: 	&do_cache_new('userres',$hashid,$result,600);
 6423:     }
 6424:     my ($tmp)=keys(%$result);
 6425:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6426: 	return $result;
 6427:     }
 6428:     #error 2 occurs when the .db doesn't exist
 6429:     if ($tmp!~/error: 2 /) {
 6430: 	&logthis("<font color=\"blue\">WARNING:".
 6431: 		 " Trying to get resource data for ".
 6432: 		 $uname." at ".$udom.": ".
 6433: 		 $tmp."</font>");
 6434:     } elsif ($tmp=~/error: 2 /) {
 6435: 	#&EXT_cache_set($udom,$uname);
 6436: 	&do_cache_new('userres',$hashid,undef,600);
 6437: 	undef($tmp); # not really an error so don't send it back
 6438:     }
 6439:     return $tmp;
 6440: }
 6441: #----------------------------------------------- resdata - return resource data
 6442: #  Purpose:
 6443: #    Return resource data for either users or for a course.
 6444: #  Parameters:
 6445: #     $name      - Course/user name.
 6446: #     $domain    - Name of the domain the user/course is registered on.
 6447: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6448: #     @which     - Array of names of resources desired.
 6449: #  Returns:
 6450: #     The value of the first reasource in @which that is found in the
 6451: #     resource hash.
 6452: #  Exceptional Conditions:
 6453: #     If the $type passed in is not valid (not the string 'course' or 
 6454: #     'user', an undefined  reference is returned.
 6455: #     If none of the resources are found, an undef is returned
 6456: sub resdata {
 6457:     my ($name,$domain,$type,@which)=@_;
 6458:     my $result;
 6459:     if ($type eq 'course') {
 6460: 	$result=&get_courseresdata($name,$domain);
 6461:     } elsif ($type eq 'user') {
 6462: 	$result=&get_userresdata($name,$domain);
 6463:     }
 6464:     if (!ref($result)) { return $result; }    
 6465:     foreach my $item (@which) {
 6466: 	if (defined($result->{$item->[0]})) {
 6467: 	    return [$result->{$item->[0]},$item->[1]];
 6468: 	}
 6469:     }
 6470:     return undef;
 6471: }
 6472: 
 6473: #
 6474: # EXT resource caching routines
 6475: #
 6476: 
 6477: sub clear_EXT_cache_status {
 6478:     &delenv('cache.EXT.');
 6479: }
 6480: 
 6481: sub EXT_cache_status {
 6482:     my ($target_domain,$target_user) = @_;
 6483:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6484:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6485:         # We know already the user has no data
 6486:         return 1;
 6487:     } else {
 6488:         return 0;
 6489:     }
 6490: }
 6491: 
 6492: sub EXT_cache_set {
 6493:     my ($target_domain,$target_user) = @_;
 6494:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6495:     #&appenv($cachename => time);
 6496: }
 6497: 
 6498: # --------------------------------------------------------- Value of a Variable
 6499: sub EXT {
 6500: 
 6501:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6502:     unless ($varname) { return ''; }
 6503:     #get real user name/domain, courseid and symb
 6504:     my $courseid;
 6505:     my $publicuser;
 6506:     if ($symbparm) {
 6507: 	$symbparm=&get_symb_from_alias($symbparm);
 6508:     }
 6509:     if (!($uname && $udom)) {
 6510:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6511:       if (!$symbparm) {	$symbparm=$cursymb; }
 6512:     } else {
 6513: 	$courseid=$env{'request.course.id'};
 6514:     }
 6515:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6516:     my $rest;
 6517:     if (defined($therest[0])) {
 6518:        $rest=join('.',@therest);
 6519:     } else {
 6520:        $rest='';
 6521:     }
 6522: 
 6523:     my $qualifierrest=$qualifier;
 6524:     if ($rest) { $qualifierrest.='.'.$rest; }
 6525:     my $spacequalifierrest=$space;
 6526:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6527:     if ($realm eq 'user') {
 6528: # --------------------------------------------------------------- user.resource
 6529: 	if ($space eq 'resource') {
 6530: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6531: 		  || defined($Apache::lonhomework::parsing_a_task))
 6532: 		 &&
 6533: 		 ($symbparm eq &symbread()) ) {	
 6534: 		# if we are in the middle of processing the resource the
 6535: 		# get the value we are planning on committing
 6536:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6537:                     return $Apache::lonhomework::results{$qualifierrest};
 6538:                 } else {
 6539:                     return $Apache::lonhomework::history{$qualifierrest};
 6540:                 }
 6541: 	    } else {
 6542: 		my %restored;
 6543: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6544: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6545: 		} else {
 6546: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6547: 		}
 6548: 		return $restored{$qualifierrest};
 6549: 	    }
 6550: # ----------------------------------------------------------------- user.access
 6551:         } elsif ($space eq 'access') {
 6552: 	    # FIXME - not supporting calls for a specific user
 6553:             return &allowed($qualifier,$rest);
 6554: # ------------------------------------------ user.preferences, user.environment
 6555:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6556: 	    if (($uname eq $env{'user.name'}) &&
 6557: 		($udom eq $env{'user.domain'})) {
 6558: 		return $env{join('.',('environment',$qualifierrest))};
 6559: 	    } else {
 6560: 		my %returnhash;
 6561: 		if (!$publicuser) {
 6562: 		    %returnhash=&userenvironment($udom,$uname,
 6563: 						 $qualifierrest);
 6564: 		}
 6565: 		return $returnhash{$qualifierrest};
 6566: 	    }
 6567: # ----------------------------------------------------------------- user.course
 6568:         } elsif ($space eq 'course') {
 6569: 	    # FIXME - not supporting calls for a specific user
 6570:             return $env{join('.',('request.course',$qualifier))};
 6571: # ------------------------------------------------------------------- user.role
 6572:         } elsif ($space eq 'role') {
 6573: 	    # FIXME - not supporting calls for a specific user
 6574:             my ($role,$where)=split(/\./,$env{'request.role'});
 6575:             if ($qualifier eq 'value') {
 6576: 		return $role;
 6577:             } elsif ($qualifier eq 'extent') {
 6578:                 return $where;
 6579:             }
 6580: # ----------------------------------------------------------------- user.domain
 6581:         } elsif ($space eq 'domain') {
 6582:             return $udom;
 6583: # ------------------------------------------------------------------- user.name
 6584:         } elsif ($space eq 'name') {
 6585:             return $uname;
 6586: # ---------------------------------------------------- Any other user namespace
 6587:         } else {
 6588: 	    my %reply;
 6589: 	    if (!$publicuser) {
 6590: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6591: 	    }
 6592: 	    return $reply{$qualifierrest};
 6593:         }
 6594:     } elsif ($realm eq 'query') {
 6595: # ---------------------------------------------- pull stuff out of query string
 6596:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6597: 						[$spacequalifierrest]);
 6598: 	return $env{'form.'.$spacequalifierrest}; 
 6599:    } elsif ($realm eq 'request') {
 6600: # ------------------------------------------------------------- request.browser
 6601:         if ($space eq 'browser') {
 6602: 	    if ($qualifier eq 'textremote') {
 6603: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6604: 		    return 1;
 6605: 		} else {
 6606: 		    return 0;
 6607: 		}
 6608: 	    } else {
 6609: 		return $env{'browser.'.$qualifier};
 6610: 	    }
 6611: # ------------------------------------------------------------ request.filename
 6612:         } else {
 6613:             return $env{'request.'.$spacequalifierrest};
 6614:         }
 6615:     } elsif ($realm eq 'course') {
 6616: # ---------------------------------------------------------- course.description
 6617:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6618:     } elsif ($realm eq 'resource') {
 6619: 
 6620: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6621: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6622: 	}
 6623: 
 6624: 	if ($space eq 'title') {
 6625: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6626: 	    return &gettitle($symbparm);
 6627: 	}
 6628: 	
 6629: 	if ($space eq 'map') {
 6630: 	    my ($map) = &decode_symb($symbparm);
 6631: 	    return &symbread($map);
 6632: 	}
 6633: 	if ($space eq 'filename') {
 6634: 	    if ($symbparm) {
 6635: 		return &clutter((&decode_symb($symbparm))[2]);
 6636: 	    }
 6637: 	    return &hreflocation('',$env{'request.filename'});
 6638: 	}
 6639: 
 6640: 	my ($section, $group, @groups);
 6641: 	my ($courselevelm,$courselevel);
 6642: 	if ($symbparm && defined($courseid) && 
 6643: 	    $courseid eq $env{'request.course.id'}) {
 6644: 
 6645: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 6646: 
 6647: # ----------------------------------------------------- Cascading lookup scheme
 6648: 	    my $symbp=$symbparm;
 6649: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 6650: 
 6651: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 6652: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 6653: 
 6654: 	    if (($env{'user.name'} eq $uname) &&
 6655: 		($env{'user.domain'} eq $udom)) {
 6656: 		$section=$env{'request.course.sec'};
 6657:                 @groups = split(/:/,$env{'request.course.groups'});  
 6658:                 @groups=&sort_course_groups($courseid,@groups); 
 6659: 	    } else {
 6660: 		if (! defined($usection)) {
 6661: 		    $section=&getsection($udom,$uname,$courseid);
 6662: 		} else {
 6663: 		    $section = $usection;
 6664: 		}
 6665:                 @groups = &get_users_groups($udom,$uname,$courseid);
 6666: 	    }
 6667: 
 6668: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 6669: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 6670: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 6671: 
 6672: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 6673: 	    my $courselevelr=$courseid.'.'.$symbparm;
 6674: 	    $courselevelm=$courseid.'.'.$mapparm;
 6675: 
 6676: # ----------------------------------------------------------- first, check user
 6677: 
 6678: 	    my $userreply=&resdata($uname,$udom,'user',
 6679: 				       ([$courselevelr,'resource'],
 6680: 					[$courselevelm,'map'     ],
 6681: 					[$courselevel, 'course'  ]));
 6682: 	    if (defined($userreply)) { return &get_reply($userreply); }
 6683: 
 6684: # ------------------------------------------------ second, check some of course
 6685:             my $coursereply;
 6686:             if (@groups > 0) {
 6687:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 6688:                                        $mapparm,$spacequalifierrest);
 6689:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 6690:             }
 6691: 
 6692: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6693: 				  $env{'course.'.$courseid.'.domain'},
 6694: 				  'course',
 6695: 				  ([$seclevelr,   'resource'],
 6696: 				   [$seclevelm,   'map'     ],
 6697: 				   [$seclevel,    'course'  ],
 6698: 				   [$courselevelr,'resource']));
 6699: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6700: 
 6701: # ------------------------------------------------------ third, check map parms
 6702: 	    my %parmhash=();
 6703: 	    my $thisparm='';
 6704: 	    if (tie(%parmhash,'GDBM_File',
 6705: 		    $env{'request.course.fn'}.'_parms.db',
 6706: 		    &GDBM_READER(),0640)) {
 6707: 		$thisparm=$parmhash{$symbparm};
 6708: 		untie(%parmhash);
 6709: 	    }
 6710: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 6711: 	}
 6712: # ------------------------------------------ fourth, look in resource metadata
 6713: 
 6714: 	$spacequalifierrest=~s/\./\_/;
 6715: 	my $filename;
 6716: 	if (!$symbparm) { $symbparm=&symbread(); }
 6717: 	if ($symbparm) {
 6718: 	    $filename=(&decode_symb($symbparm))[2];
 6719: 	} else {
 6720: 	    $filename=$env{'request.filename'};
 6721: 	}
 6722: 	my $metadata=&metadata($filename,$spacequalifierrest);
 6723: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6724: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 6725: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 6726: 
 6727: # ---------------------------------------------- fourth, look in rest of course
 6728: 	if ($symbparm && defined($courseid) && 
 6729: 	    $courseid eq $env{'request.course.id'}) {
 6730: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 6731: 				     $env{'course.'.$courseid.'.domain'},
 6732: 				     'course',
 6733: 				     ([$courselevelm,'map'   ],
 6734: 				      [$courselevel, 'course']));
 6735: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 6736: 	}
 6737: # ------------------------------------------------------------------ Cascade up
 6738: 	unless ($space eq '0') {
 6739: 	    my @parts=split(/_/,$space);
 6740: 	    my $id=pop(@parts);
 6741: 	    my $part=join('_',@parts);
 6742: 	    if ($part eq '') { $part='0'; }
 6743: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 6744: 				 $symbparm,$udom,$uname,$section,1);
 6745: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 6746: 	}
 6747: 	if ($recurse) { return undef; }
 6748: 	my $pack_def=&packages_tab_default($filename,$varname);
 6749: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 6750: # ---------------------------------------------------- Any other user namespace
 6751:     } elsif ($realm eq 'environment') {
 6752: # ----------------------------------------------------------------- environment
 6753: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 6754: 	    return $env{'environment.'.$spacequalifierrest};
 6755: 	} else {
 6756: 	    if ($uname eq 'anonymous' && $udom eq '') {
 6757: 		return '';
 6758: 	    }
 6759: 	    my %returnhash=&userenvironment($udom,$uname,
 6760: 					    $spacequalifierrest);
 6761: 	    return $returnhash{$spacequalifierrest};
 6762: 	}
 6763:     } elsif ($realm eq 'system') {
 6764: # ----------------------------------------------------------------- system.time
 6765: 	if ($space eq 'time') {
 6766: 	    return time;
 6767:         }
 6768:     } elsif ($realm eq 'server') {
 6769: # ----------------------------------------------------------------- system.time
 6770: 	if ($space eq 'name') {
 6771: 	    return $ENV{'SERVER_NAME'};
 6772:         }
 6773:     }
 6774:     return '';
 6775: }
 6776: 
 6777: sub get_reply {
 6778:     my ($reply_value) = @_;
 6779:     if (ref($reply_value) eq 'ARRAY') {
 6780:         if (wantarray) {
 6781: 	    return @$reply_value;
 6782:         }
 6783:         return $reply_value->[0];
 6784:     } else {
 6785:         return $reply_value;
 6786:     }
 6787: }
 6788: 
 6789: sub check_group_parms {
 6790:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 6791:     my @groupitems = ();
 6792:     my $resultitem;
 6793:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 6794:     foreach my $group (@{$groups}) {
 6795:         foreach my $level (@levels) {
 6796:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 6797:              push(@groupitems,[$item,$level->[1]]);
 6798:         }
 6799:     }
 6800:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 6801:                             $env{'course.'.$courseid.'.domain'},
 6802:                                      'course',@groupitems);
 6803:     return $coursereply;
 6804: }
 6805: 
 6806: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 6807:     my ($courseid,@groups) = @_;
 6808:     @groups = sort(@groups);
 6809:     return @groups;
 6810: }
 6811: 
 6812: sub packages_tab_default {
 6813:     my ($uri,$varname)=@_;
 6814:     my (undef,$part,$name)=split(/\./,$varname);
 6815: 
 6816:     my (@extension,@specifics,$do_default);
 6817:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 6818: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 6819: 	if ($pack_type eq 'default') {
 6820: 	    $do_default=1;
 6821: 	} elsif ($pack_type eq 'extension') {
 6822: 	    push(@extension,[$package,$pack_type,$pack_part]);
 6823: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 6824: 	    # only look at packages defaults for packages that this id is
 6825: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 6826: 	}
 6827:     }
 6828:     # first look for a package that matches the requested part id
 6829:     foreach my $package (@specifics) {
 6830: 	my (undef,$pack_type,$pack_part)=@{$package};
 6831: 	next if ($pack_part ne $part);
 6832: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6833: 	    return $packagetab{"$pack_type&$name&default"};
 6834: 	}
 6835:     }
 6836:     # look for any possible matching non extension_ package
 6837:     foreach my $package (@specifics) {
 6838: 	my (undef,$pack_type,$pack_part)=@{$package};
 6839: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6840: 	    return $packagetab{"$pack_type&$name&default"};
 6841: 	}
 6842: 	if ($pack_type eq 'part') { $pack_part='0'; }
 6843: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 6844: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 6845: 	}
 6846:     }
 6847:     # look for any posible extension_ match
 6848:     foreach my $package (@extension) {
 6849: 	my ($package,$pack_type)=@{$package};
 6850: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 6851: 	    return $packagetab{"$pack_type&$name&default"};
 6852: 	}
 6853: 	if (defined($packagetab{$package."&$name&default"})) {
 6854: 	    return $packagetab{$package."&$name&default"};
 6855: 	}
 6856:     }
 6857:     # look for a global default setting
 6858:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 6859: 	return $packagetab{"default&$name&default"};
 6860:     }
 6861:     return undef;
 6862: }
 6863: 
 6864: sub add_prefix_and_part {
 6865:     my ($prefix,$part)=@_;
 6866:     my $keyroot;
 6867:     if (defined($prefix) && $prefix !~ /^__/) {
 6868: 	# prefix that has a part already
 6869: 	$keyroot=$prefix;
 6870:     } elsif (defined($prefix)) {
 6871: 	# prefix that is missing a part
 6872: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 6873:     } else {
 6874: 	# no prefix at all
 6875: 	if (defined($part)) { $keyroot='_'.$part; }
 6876:     }
 6877:     return $keyroot;
 6878: }
 6879: 
 6880: # ---------------------------------------------------------------- Get metadata
 6881: 
 6882: my %metaentry;
 6883: sub metadata {
 6884:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 6885:     $uri=&declutter($uri);
 6886:     # if it is a non metadata possible uri return quickly
 6887:     if (($uri eq '') || 
 6888: 	(($uri =~ m|^/*adm/|) && 
 6889: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 6890:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 6891: 	return undef;
 6892:     }
 6893:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 6894: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 6895: 	return undef;
 6896:     }
 6897:     my $filename=$uri;
 6898:     $uri=~s/\.meta$//;
 6899: #
 6900: # Is the metadata already cached?
 6901: # Look at timestamp of caching
 6902: # Everything is cached by the main uri, libraries are never directly cached
 6903: #
 6904:     if (!defined($liburi)) {
 6905: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 6906: 	if (defined($cached)) { return $result->{':'.$what}; }
 6907:     }
 6908:     {
 6909: #
 6910: # Is this a recursive call for a library?
 6911: #
 6912: #	if (! exists($metacache{$uri})) {
 6913: #	    $metacache{$uri}={};
 6914: #	}
 6915: 	my $cachetime = 60*60;
 6916:         if ($liburi) {
 6917: 	    $liburi=&declutter($liburi);
 6918:             $filename=$liburi;
 6919:         } else {
 6920: 	    &devalidate_cache_new('meta',$uri);
 6921: 	    undef(%metaentry);
 6922: 	}
 6923:         my %metathesekeys=();
 6924:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 6925: 	my $metastring;
 6926: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 6927: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 6928: 	    $metastring = 
 6929: 		&Apache::lonnet::ssi_body($which,
 6930: 					  ('grade_target' => 'meta'));
 6931: 	    $cachetime = 1; # only want this cached in the child not long term
 6932: 	} elsif ($uri !~ m -^(editupload)/-) {
 6933: 	    my $file=&filelocation('',&clutter($filename));
 6934: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 6935: 	    $metastring=&getfile($file);
 6936: 	}
 6937:         my $parser=HTML::LCParser->new(\$metastring);
 6938:         my $token;
 6939:         undef %metathesekeys;
 6940:         while ($token=$parser->get_token) {
 6941: 	    if ($token->[0] eq 'S') {
 6942: 		if (defined($token->[2]->{'package'})) {
 6943: #
 6944: # This is a package - get package info
 6945: #
 6946: 		    my $package=$token->[2]->{'package'};
 6947: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6948: 		    if (defined($token->[2]->{'id'})) { 
 6949: 			$keyroot.='_'.$token->[2]->{'id'}; 
 6950: 		    }
 6951: 		    if ($metaentry{':packages'}) {
 6952: 			$metaentry{':packages'}.=','.$package.$keyroot;
 6953: 		    } else {
 6954: 			$metaentry{':packages'}=$package.$keyroot;
 6955: 		    }
 6956: 		    foreach my $pack_entry (keys(%packagetab)) {
 6957: 			my $part=$keyroot;
 6958: 			$part=~s/^\_//;
 6959: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 6960: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 6961: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 6962: 			    # ignore package.tab specified default values
 6963:                             # here &package_tab_default() will fetch those
 6964: 			    if ($subp eq 'default') { next; }
 6965: 			    my $value=$packagetab{$pack_entry};
 6966: 			    my $unikey;
 6967: 			    if ($pack =~ /_0$/) {
 6968: 				$unikey='parameter_0_'.$name;
 6969: 				$part=0;
 6970: 			    } else {
 6971: 				$unikey='parameter'.$keyroot.'_'.$name;
 6972: 			    }
 6973: 			    if ($subp eq 'display') {
 6974: 				$value.=' [Part: '.$part.']';
 6975: 			    }
 6976: 			    $metaentry{':'.$unikey.'.part'}=$part;
 6977: 			    $metathesekeys{$unikey}=1;
 6978: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 6979: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 6980: 			    }
 6981: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 6982: 				$metaentry{':'.$unikey}=
 6983: 				    $metaentry{':'.$unikey.'.default'};
 6984: 			    }
 6985: 			}
 6986: 		    }
 6987: 		} else {
 6988: #
 6989: # This is not a package - some other kind of start tag
 6990: #
 6991: 		    my $entry=$token->[1];
 6992: 		    my $unikey;
 6993: 		    if ($entry eq 'import') {
 6994: 			$unikey='';
 6995: 		    } else {
 6996: 			$unikey=$entry;
 6997: 		    }
 6998: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 6999: 
 7000: 		    if (defined($token->[2]->{'id'})) { 
 7001: 			$unikey.='_'.$token->[2]->{'id'}; 
 7002: 		    }
 7003: 
 7004: 		    if ($entry eq 'import') {
 7005: #
 7006: # Importing a library here
 7007: #
 7008: 			if ($depthcount<20) {
 7009: 			    my $location=$parser->get_text('/import');
 7010: 			    my $dir=$filename;
 7011: 			    $dir=~s|[^/]*$||;
 7012: 			    $location=&filelocation($dir,$location);
 7013: 			    my $metadata = 
 7014: 				&metadata($uri,'keys', $location,$unikey,
 7015: 					  $depthcount+1);
 7016: 			    foreach my $meta (split(',',$metadata)) {
 7017: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7018: 				$metathesekeys{$meta}=1;
 7019: 			    }
 7020: 			}
 7021: 		    } else { 
 7022: 			
 7023: 			if (defined($token->[2]->{'name'})) { 
 7024: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7025: 			}
 7026: 			$metathesekeys{$unikey}=1;
 7027: 			foreach my $param (@{$token->[3]}) {
 7028: 			    $metaentry{':'.$unikey.'.'.$param} =
 7029: 				$token->[2]->{$param};
 7030: 			}
 7031: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7032: 			my $default=$metaentry{':'.$unikey.'.default'};
 7033: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7034: 		 # only ws inside the tag, and not in default, so use default
 7035: 		 # as value
 7036: 			    $metaentry{':'.$unikey}=$default;
 7037: 			} elsif ( $internaltext =~ /\S/ ) {
 7038: 		  # something interesting inside the tag
 7039: 			    $metaentry{':'.$unikey}=$internaltext;
 7040: 			} else {
 7041: 		  # no interesting values, don't set a default
 7042: 			}
 7043: # end of not-a-package not-a-library import
 7044: 		    }
 7045: # end of not-a-package start tag
 7046: 		}
 7047: # the next is the end of "start tag"
 7048: 	    }
 7049: 	}
 7050: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7051: 	$extension = lc($extension);
 7052: 	if ($extension eq 'htm') { $extension='html'; }
 7053: 
 7054: 	foreach my $key (keys(%packagetab)) {
 7055: 	    #no specific packages #how's our extension
 7056: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7057: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7058: 					 \%metathesekeys);
 7059: 	}
 7060: 
 7061: 	if (!exists($metaentry{':packages'})
 7062: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7063: 	    foreach my $key (keys(%packagetab)) {
 7064: 		#no specific packages well let's get default then
 7065: 		if ($key!~/^default&/) { next; }
 7066: 		&metadata_create_package_def($uri,$key,'default',
 7067: 					     \%metathesekeys);
 7068: 	    }
 7069: 	}
 7070: # are there custom rights to evaluate
 7071: 	if ($metaentry{':copyright'} eq 'custom') {
 7072: 
 7073:     #
 7074:     # Importing a rights file here
 7075:     #
 7076: 	    unless ($depthcount) {
 7077: 		my $location=$metaentry{':customdistributionfile'};
 7078: 		my $dir=$filename;
 7079: 		$dir=~s|[^/]*$||;
 7080: 		$location=&filelocation($dir,$location);
 7081: 		my $rights_metadata =
 7082: 		    &metadata($uri,'keys',$location,'_rights',
 7083: 			      $depthcount+1);
 7084: 		foreach my $rights (split(',',$rights_metadata)) {
 7085: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7086: 		    $metathesekeys{$rights}=1;
 7087: 		}
 7088: 	    }
 7089: 	}
 7090: 	# uniqifiy package listing
 7091: 	my %seen;
 7092: 	my @uniq_packages =
 7093: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7094: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7095: 
 7096: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7097: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7098: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7099: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7100: # this is the end of "was not already recently cached
 7101:     }
 7102:     return $metaentry{':'.$what};
 7103: }
 7104: 
 7105: sub metadata_create_package_def {
 7106:     my ($uri,$key,$package,$metathesekeys)=@_;
 7107:     my ($pack,$name,$subp)=split(/\&/,$key);
 7108:     if ($subp eq 'default') { next; }
 7109:     
 7110:     if (defined($metaentry{':packages'})) {
 7111: 	$metaentry{':packages'}.=','.$package;
 7112:     } else {
 7113: 	$metaentry{':packages'}=$package;
 7114:     }
 7115:     my $value=$packagetab{$key};
 7116:     my $unikey;
 7117:     $unikey='parameter_0_'.$name;
 7118:     $metaentry{':'.$unikey.'.part'}=0;
 7119:     $$metathesekeys{$unikey}=1;
 7120:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7121: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7122:     }
 7123:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7124: 	$metaentry{':'.$unikey}=
 7125: 	    $metaentry{':'.$unikey.'.default'};
 7126:     }
 7127: }
 7128: 
 7129: sub metadata_generate_part0 {
 7130:     my ($metadata,$metacache,$uri) = @_;
 7131:     my %allnames;
 7132:     foreach my $metakey (keys(%$metadata)) {
 7133: 	if ($metakey=~/^parameter\_(.*)/) {
 7134: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7135: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7136: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7137: 	    $allnames{$name}=$part;
 7138: 	  }
 7139: 	}
 7140:     }
 7141:     foreach my $name (keys(%allnames)) {
 7142:       $$metadata{"parameter_0_$name"}=1;
 7143:       my $key=":parameter_0_$name";
 7144:       $$metacache{"$key.part"}='0';
 7145:       $$metacache{"$key.name"}=$name;
 7146:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7147: 					   $allnames{$name}.'_'.$name.
 7148: 					   '.type'};
 7149:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7150: 			     '.display'};
 7151:       my $expr='[Part: '.$allnames{$name}.']';
 7152:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7153:       $$metacache{"$key.display"}=$olddis;
 7154:     }
 7155: }
 7156: 
 7157: # ------------------------------------------------------ Devalidate title cache
 7158: 
 7159: sub devalidate_title_cache {
 7160:     my ($url)=@_;
 7161:     if (!$env{'request.course.id'}) { return; }
 7162:     my $symb=&symbread($url);
 7163:     if (!$symb) { return; }
 7164:     my $key=$env{'request.course.id'}."\0".$symb;
 7165:     &devalidate_cache_new('title',$key);
 7166: }
 7167: 
 7168: # ------------------------------------------------- Get the title of a resource
 7169: 
 7170: sub gettitle {
 7171:     my $urlsymb=shift;
 7172:     my $symb=&symbread($urlsymb);
 7173:     if ($symb) {
 7174: 	my $key=$env{'request.course.id'}."\0".$symb;
 7175: 	my ($result,$cached)=&is_cached_new('title',$key);
 7176: 	if (defined($cached)) { 
 7177: 	    return $result;
 7178: 	}
 7179: 	my ($map,$resid,$url)=&decode_symb($symb);
 7180: 	my $title='';
 7181: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7182: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7183: 	} else {
 7184: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7185: 		    &GDBM_READER(),0640)) {
 7186: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7187: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7188: 		untie(%bighash);
 7189: 	    }
 7190: 	}
 7191: 	$title=~s/\&colon\;/\:/gs;
 7192: 	if ($title) {
 7193: 	    return &do_cache_new('title',$key,$title,600);
 7194: 	}
 7195: 	$urlsymb=$url;
 7196:     }
 7197:     my $title=&metadata($urlsymb,'title');
 7198:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7199:     return $title;
 7200: }
 7201: 
 7202: sub get_slot {
 7203:     my ($which,$cnum,$cdom)=@_;
 7204:     if (!$cnum || !$cdom) {
 7205: 	(undef,my $courseid)=&whichuser();
 7206: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7207: 	$cnum=$env{'course.'.$courseid.'.num'};
 7208:     }
 7209:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7210:     my %slotinfo;
 7211:     if (exists($remembered{$key})) {
 7212: 	$slotinfo{$which} = $remembered{$key};
 7213:     } else {
 7214: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7215: 	&Apache::lonhomework::showhash(%slotinfo);
 7216: 	my ($tmp)=keys(%slotinfo);
 7217: 	if ($tmp=~/^error:/) { return (); }
 7218: 	$remembered{$key} = $slotinfo{$which};
 7219:     }
 7220:     if (ref($slotinfo{$which}) eq 'HASH') {
 7221: 	return %{$slotinfo{$which}};
 7222:     }
 7223:     return $slotinfo{$which};
 7224: }
 7225: # ------------------------------------------------- Update symbolic store links
 7226: 
 7227: sub symblist {
 7228:     my ($mapname,%newhash)=@_;
 7229:     $mapname=&deversion(&declutter($mapname));
 7230:     my %hash;
 7231:     if (($env{'request.course.fn'}) && (%newhash)) {
 7232:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7233:                       &GDBM_WRCREAT(),0640)) {
 7234: 	    foreach my $url (keys %newhash) {
 7235: 		next if ($url eq 'last_known'
 7236: 			 && $env{'form.no_update_last_known'});
 7237: 		$hash{declutter($url)}=&encode_symb($mapname,
 7238: 						    $newhash{$url}->[1],
 7239: 						    $newhash{$url}->[0]);
 7240:             }
 7241:             if (untie(%hash)) {
 7242: 		return 'ok';
 7243:             }
 7244:         }
 7245:     }
 7246:     return 'error';
 7247: }
 7248: 
 7249: # --------------------------------------------------------------- Verify a symb
 7250: 
 7251: sub symbverify {
 7252:     my ($symb,$thisurl)=@_;
 7253:     my $thisfn=$thisurl;
 7254:     $thisfn=&declutter($thisfn);
 7255: # direct jump to resource in page or to a sequence - will construct own symbs
 7256:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7257: # check URL part
 7258:     my ($map,$resid,$url)=&decode_symb($symb);
 7259: 
 7260:     unless ($url eq $thisfn) { return 0; }
 7261: 
 7262:     $symb=&symbclean($symb);
 7263:     $thisurl=&deversion($thisurl);
 7264:     $thisfn=&deversion($thisfn);
 7265: 
 7266:     my %bighash;
 7267:     my $okay=0;
 7268: 
 7269:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7270:                             &GDBM_READER(),0640)) {
 7271:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7272:         unless ($ids) { 
 7273:            $ids=$bighash{'ids_/'.$thisurl};
 7274:         }
 7275:         if ($ids) {
 7276: # ------------------------------------------------------------------- Has ID(s)
 7277: 	    foreach my $id (split(/\,/,$ids)) {
 7278: 	       my ($mapid,$resid)=split(/\./,$id);
 7279:                if (
 7280:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7281:    eq $symb) { 
 7282: 		   if (($env{'request.role.adv'}) ||
 7283: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7284: 		       $okay=1; 
 7285: 		   }
 7286: 	       }
 7287: 	   }
 7288:         }
 7289: 	untie(%bighash);
 7290:     }
 7291:     return $okay;
 7292: }
 7293: 
 7294: # --------------------------------------------------------------- Clean-up symb
 7295: 
 7296: sub symbclean {
 7297:     my $symb=shift;
 7298:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7299: # remove version from map
 7300:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7301: 
 7302: # remove version from URL
 7303:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7304: 
 7305: # remove wrapper
 7306: 
 7307:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7308:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7309:     return $symb;
 7310: }
 7311: 
 7312: # ---------------------------------------------- Split symb to find map and url
 7313: 
 7314: sub encode_symb {
 7315:     my ($map,$resid,$url)=@_;
 7316:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7317: }
 7318: 
 7319: sub decode_symb {
 7320:     my $symb=shift;
 7321:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7322:     my ($map,$resid,$url)=split(/___/,$symb);
 7323:     return (&fixversion($map),$resid,&fixversion($url));
 7324: }
 7325: 
 7326: sub fixversion {
 7327:     my $fn=shift;
 7328:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7329:     my %bighash;
 7330:     my $uri=&clutter($fn);
 7331:     my $key=$env{'request.course.id'}.'_'.$uri;
 7332: # is this cached?
 7333:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7334:     if (defined($cached)) { return $result; }
 7335: # unfortunately not cached, or expired
 7336:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7337: 	    &GDBM_READER(),0640)) {
 7338:  	if ($bighash{'version_'.$uri}) {
 7339:  	    my $version=$bighash{'version_'.$uri};
 7340:  	    unless (($version eq 'mostrecent') || 
 7341: 		    ($version==&getversion($uri))) {
 7342:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7343:  	    }
 7344:  	}
 7345:  	untie %bighash;
 7346:     }
 7347:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7348: }
 7349: 
 7350: sub deversion {
 7351:     my $url=shift;
 7352:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7353:     return $url;
 7354: }
 7355: 
 7356: # ------------------------------------------------------ Return symb list entry
 7357: 
 7358: sub symbread {
 7359:     my ($thisfn,$donotrecurse)=@_;
 7360:     my $cache_str='request.symbread.cached.'.$thisfn;
 7361:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7362: # no filename provided? try from environment
 7363:     unless ($thisfn) {
 7364:         if ($env{'request.symb'}) {
 7365: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7366: 	}
 7367: 	$thisfn=$env{'request.filename'};
 7368:     }
 7369:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7370: # is that filename actually a symb? Verify, clean, and return
 7371:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7372: 	if (&symbverify($thisfn,$1)) {
 7373: 	    return $env{$cache_str}=&symbclean($thisfn);
 7374: 	}
 7375:     }
 7376:     $thisfn=declutter($thisfn);
 7377:     my %hash;
 7378:     my %bighash;
 7379:     my $syval='';
 7380:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7381:         my $targetfn = $thisfn;
 7382:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7383:             $targetfn = 'adm/wrapper/'.$thisfn;
 7384:         }
 7385: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7386: 	    $targetfn=$1;
 7387: 	}
 7388:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7389:                       &GDBM_READER(),0640)) {
 7390: 	    $syval=$hash{$targetfn};
 7391:             untie(%hash);
 7392:         }
 7393: # ---------------------------------------------------------- There was an entry
 7394:         if ($syval) {
 7395: 	    #unless ($syval=~/\_\d+$/) {
 7396: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7397: 		    #&appenv('request.ambiguous' => $thisfn);
 7398: 		    #return $env{$cache_str}='';
 7399: 		#}    
 7400: 		#$syval.=$1;
 7401: 	    #}
 7402:         } else {
 7403: # ------------------------------------------------------- Was not in symb table
 7404:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7405:                             &GDBM_READER(),0640)) {
 7406: # ---------------------------------------------- Get ID(s) for current resource
 7407:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7408:               unless ($ids) { 
 7409:                  $ids=$bighash{'ids_/'.$thisfn};
 7410:               }
 7411:               unless ($ids) {
 7412: # alias?
 7413: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7414:               }
 7415:               if ($ids) {
 7416: # ------------------------------------------------------------------- Has ID(s)
 7417:                  my @possibilities=split(/\,/,$ids);
 7418:                  if ($#possibilities==0) {
 7419: # ----------------------------------------------- There is only one possibility
 7420: 		     my ($mapid,$resid)=split(/\./,$ids);
 7421: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7422: 						    $resid,$thisfn);
 7423:                  } elsif (!$donotrecurse) {
 7424: # ------------------------------------------ There is more than one possibility
 7425:                      my $realpossible=0;
 7426:                      foreach my $id (@possibilities) {
 7427: 			 my $file=$bighash{'src_'.$id};
 7428:                          if (&allowed('bre',$file)) {
 7429:          		    my ($mapid,$resid)=split(/\./,$id);
 7430:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7431: 				$realpossible++;
 7432:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7433: 						    $resid,$thisfn);
 7434:                             }
 7435: 			 }
 7436:                      }
 7437: 		     if ($realpossible!=1) { $syval=''; }
 7438:                  } else {
 7439:                      $syval='';
 7440:                  }
 7441: 	      }
 7442:               untie(%bighash)
 7443:            }
 7444:         }
 7445:         if ($syval) {
 7446: 	    return $env{$cache_str}=$syval;
 7447:         }
 7448:     }
 7449:     &appenv('request.ambiguous' => $thisfn);
 7450:     return $env{$cache_str}='';
 7451: }
 7452: 
 7453: # ---------------------------------------------------------- Return random seed
 7454: 
 7455: sub numval {
 7456:     my $txt=shift;
 7457:     $txt=~tr/A-J/0-9/;
 7458:     $txt=~tr/a-j/0-9/;
 7459:     $txt=~tr/K-T/0-9/;
 7460:     $txt=~tr/k-t/0-9/;
 7461:     $txt=~tr/U-Z/0-5/;
 7462:     $txt=~tr/u-z/0-5/;
 7463:     $txt=~s/\D//g;
 7464:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7465:     return int($txt);
 7466: }
 7467: 
 7468: sub numval2 {
 7469:     my $txt=shift;
 7470:     $txt=~tr/A-J/0-9/;
 7471:     $txt=~tr/a-j/0-9/;
 7472:     $txt=~tr/K-T/0-9/;
 7473:     $txt=~tr/k-t/0-9/;
 7474:     $txt=~tr/U-Z/0-5/;
 7475:     $txt=~tr/u-z/0-5/;
 7476:     $txt=~s/\D//g;
 7477:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7478:     my $total;
 7479:     foreach my $val (@txts) { $total+=$val; }
 7480:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7481:     return int($total);
 7482: }
 7483: 
 7484: sub numval3 {
 7485:     use integer;
 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:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7495:     my $total;
 7496:     foreach my $val (@txts) { $total+=$val; }
 7497:     if ($_64bit) { $total=(($total<<32)>>32); }
 7498:     return $total;
 7499: }
 7500: 
 7501: sub digest {
 7502:     my ($data)=@_;
 7503:     my $digest=&Digest::MD5::md5($data);
 7504:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7505:     my ($e,$f);
 7506:     {
 7507:         use integer;
 7508:         $e=($a+$b);
 7509:         $f=($c+$d);
 7510:         if ($_64bit) {
 7511:             $e=(($e<<32)>>32);
 7512:             $f=(($f<<32)>>32);
 7513:         }
 7514:     }
 7515:     if (wantarray) {
 7516: 	return ($e,$f);
 7517:     } else {
 7518: 	my $g;
 7519: 	{
 7520: 	    use integer;
 7521: 	    $g=($e+$f);
 7522: 	    if ($_64bit) {
 7523: 		$g=(($g<<32)>>32);
 7524: 	    }
 7525: 	}
 7526: 	return $g;
 7527:     }
 7528: }
 7529: 
 7530: sub latest_rnd_algorithm_id {
 7531:     return '64bit5';
 7532: }
 7533: 
 7534: sub get_rand_alg {
 7535:     my ($courseid)=@_;
 7536:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7537:     if ($courseid) {
 7538: 	return $env{"course.$courseid.rndseed"};
 7539:     }
 7540:     return &latest_rnd_algorithm_id();
 7541: }
 7542: 
 7543: sub validCODE {
 7544:     my ($CODE)=@_;
 7545:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7546:     return 0;
 7547: }
 7548: 
 7549: sub getCODE {
 7550:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7551:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7552: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7553: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7554: 	return $Apache::lonhomework::history{'resource.CODE'};
 7555:     }
 7556:     return undef;
 7557: }
 7558: 
 7559: sub rndseed {
 7560:     my ($symb,$courseid,$domain,$username)=@_;
 7561:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7562:     if (!defined($symb)) {
 7563: 	unless ($symb=$wsymb) { return time; }
 7564:     }
 7565:     if (!$courseid) { $courseid=$wcourseid; }
 7566:     if (!$domain) { $domain=$wdomain; }
 7567:     if (!$username) { $username=$wusername }
 7568:     my $which=&get_rand_alg();
 7569: 
 7570:     if (defined(&getCODE())) {
 7571: 	if ($which eq '64bit5') {
 7572: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7573: 	} elsif ($which eq '64bit4') {
 7574: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7575: 	} else {
 7576: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7577: 	}
 7578:     } elsif ($which eq '64bit5') {
 7579: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7580:     } elsif ($which eq '64bit4') {
 7581: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7582:     } elsif ($which eq '64bit3') {
 7583: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7584:     } elsif ($which eq '64bit2') {
 7585: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7586:     } elsif ($which eq '64bit') {
 7587: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7588:     }
 7589:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7590: }
 7591: 
 7592: sub rndseed_32bit {
 7593:     my ($symb,$courseid,$domain,$username)=@_;
 7594:     {
 7595: 	use integer;
 7596: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7597: 	my $symbseed=numval($symb) << 22;
 7598: 	my $namechck=unpack("%32C*",$username) << 17;
 7599: 	my $nameseed=numval($username) << 12;
 7600: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7601: 	my $courseseed=unpack("%32C*",$courseid);
 7602: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7603: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7604: 	#&logthis("rndseed :$num:$symb");
 7605: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7606: 	return $num;
 7607:     }
 7608: }
 7609: 
 7610: sub rndseed_64bit {
 7611:     my ($symb,$courseid,$domain,$username)=@_;
 7612:     {
 7613: 	use integer;
 7614: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7615: 	my $symbseed=numval($symb) << 10;
 7616: 	my $namechck=unpack("%32S*",$username);
 7617: 	
 7618: 	my $nameseed=numval($username) << 21;
 7619: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7620: 	my $courseseed=unpack("%32S*",$courseid);
 7621: 	
 7622: 	my $num1=$symbchck+$symbseed+$namechck;
 7623: 	my $num2=$nameseed+$domainseed+$courseseed;
 7624: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7625: 	#&logthis("rndseed :$num:$symb");
 7626: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7627: 	return "$num1,$num2";
 7628:     }
 7629: }
 7630: 
 7631: sub rndseed_64bit2 {
 7632:     my ($symb,$courseid,$domain,$username)=@_;
 7633:     {
 7634: 	use integer;
 7635: 	# strings need to be an even # of cahracters long, it it is odd the
 7636:         # last characters gets thrown away
 7637: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7638: 	my $symbseed=numval($symb) << 10;
 7639: 	my $namechck=unpack("%32S*",$username.' ');
 7640: 	
 7641: 	my $nameseed=numval($username) << 21;
 7642: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7643: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7644: 	
 7645: 	my $num1=$symbchck+$symbseed+$namechck;
 7646: 	my $num2=$nameseed+$domainseed+$courseseed;
 7647: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7648: 	#&logthis("rndseed :$num:$symb");
 7649: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7650: 	return "$num1,$num2";
 7651:     }
 7652: }
 7653: 
 7654: sub rndseed_64bit3 {
 7655:     my ($symb,$courseid,$domain,$username)=@_;
 7656:     {
 7657: 	use integer;
 7658: 	# strings need to be an even # of cahracters long, it it is odd the
 7659:         # last characters gets thrown away
 7660: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7661: 	my $symbseed=numval2($symb) << 10;
 7662: 	my $namechck=unpack("%32S*",$username.' ');
 7663: 	
 7664: 	my $nameseed=numval2($username) << 21;
 7665: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7666: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7667: 	
 7668: 	my $num1=$symbchck+$symbseed+$namechck;
 7669: 	my $num2=$nameseed+$domainseed+$courseseed;
 7670: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7671: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7672: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7673: 	
 7674: 	return "$num1:$num2";
 7675:     }
 7676: }
 7677: 
 7678: sub rndseed_64bit4 {
 7679:     my ($symb,$courseid,$domain,$username)=@_;
 7680:     {
 7681: 	use integer;
 7682: 	# strings need to be an even # of cahracters long, it it is odd the
 7683:         # last characters gets thrown away
 7684: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 7685: 	my $symbseed=numval3($symb) << 10;
 7686: 	my $namechck=unpack("%32S*",$username.' ');
 7687: 	
 7688: 	my $nameseed=numval3($username) << 21;
 7689: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 7690: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7691: 	
 7692: 	my $num1=$symbchck+$symbseed+$namechck;
 7693: 	my $num2=$nameseed+$domainseed+$courseseed;
 7694: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7695: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 7696: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7697: 	
 7698: 	return "$num1:$num2";
 7699:     }
 7700: }
 7701: 
 7702: sub rndseed_64bit5 {
 7703:     my ($symb,$courseid,$domain,$username)=@_;
 7704:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 7705:     return "$num1:$num2";
 7706: }
 7707: 
 7708: sub rndseed_CODE_64bit {
 7709:     my ($symb,$courseid,$domain,$username)=@_;
 7710:     {
 7711: 	use integer;
 7712: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7713: 	my $symbseed=numval2($symb);
 7714: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7715: 	my $CODEseed=numval(&getCODE());
 7716: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7717: 	my $num1=$symbseed+$CODEchck;
 7718: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7719: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7720: 	#&logthis("rndseed :$num1:$num2:$symb");
 7721: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7722: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7723: 	return "$num1:$num2";
 7724:     }
 7725: }
 7726: 
 7727: sub rndseed_CODE_64bit4 {
 7728:     my ($symb,$courseid,$domain,$username)=@_;
 7729:     {
 7730: 	use integer;
 7731: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 7732: 	my $symbseed=numval3($symb);
 7733: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 7734: 	my $CODEseed=numval3(&getCODE());
 7735: 	my $courseseed=unpack("%32S*",$courseid.' ');
 7736: 	my $num1=$symbseed+$CODEchck;
 7737: 	my $num2=$CODEseed+$courseseed+$symbchck;
 7738: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 7739: 	#&logthis("rndseed :$num1:$num2:$symb");
 7740: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 7741: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 7742: 	return "$num1:$num2";
 7743:     }
 7744: }
 7745: 
 7746: sub rndseed_CODE_64bit5 {
 7747:     my ($symb,$courseid,$domain,$username)=@_;
 7748:     my $code = &getCODE();
 7749:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 7750:     return "$num1:$num2";
 7751: }
 7752: 
 7753: sub setup_random_from_rndseed {
 7754:     my ($rndseed)=@_;
 7755:     if ($rndseed =~/([,:])/) {
 7756: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 7757: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 7758:     } else {
 7759: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 7760:     }
 7761: }
 7762: 
 7763: sub latest_receipt_algorithm_id {
 7764:     return 'receipt3';
 7765: }
 7766: 
 7767: sub recunique {
 7768:     my $fucourseid=shift;
 7769:     my $unique;
 7770:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 7771: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7772: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 7773:     } else {
 7774: 	$unique=$perlvar{'lonReceipt'};
 7775:     }
 7776:     return unpack("%32C*",$unique);
 7777: }
 7778: 
 7779: sub recprefix {
 7780:     my $fucourseid=shift;
 7781:     my $prefix;
 7782:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 7783: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 7784: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 7785:     } else {
 7786: 	$prefix=$perlvar{'lonHostID'};
 7787:     }
 7788:     return unpack("%32C*",$prefix);
 7789: }
 7790: 
 7791: sub ireceipt {
 7792:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 7793: 
 7794:     my $return =&recprefix($fucourseid).'-';
 7795: 
 7796:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 7797: 	$env{'request.state'} eq 'construct') {
 7798: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 7799: 	return $return;
 7800:     }
 7801: 
 7802:     my $cuname=unpack("%32C*",$funame);
 7803:     my $cudom=unpack("%32C*",$fudom);
 7804:     my $cucourseid=unpack("%32C*",$fucourseid);
 7805:     my $cusymb=unpack("%32C*",$fusymb);
 7806:     my $cunique=&recunique($fucourseid);
 7807:     my $cpart=unpack("%32S*",$part);
 7808:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 7809: 
 7810: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 7811: 			       
 7812: 	$return.= ($cunique%$cuname+
 7813: 		   $cunique%$cudom+
 7814: 		   $cusymb%$cuname+
 7815: 		   $cusymb%$cudom+
 7816: 		   $cucourseid%$cuname+
 7817: 		   $cucourseid%$cudom+
 7818: 		   $cpart%$cuname+
 7819: 		   $cpart%$cudom);
 7820:     } else {
 7821: 	$return.= ($cunique%$cuname+
 7822: 		   $cunique%$cudom+
 7823: 		   $cusymb%$cuname+
 7824: 		   $cusymb%$cudom+
 7825: 		   $cucourseid%$cuname+
 7826: 		   $cucourseid%$cudom);
 7827:     }
 7828:     return $return;
 7829: }
 7830: 
 7831: sub receipt {
 7832:     my ($part)=@_;
 7833:     my ($symb,$courseid,$domain,$name) = &whichuser();
 7834:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 7835: }
 7836: 
 7837: sub whichuser {
 7838:     my ($passedsymb)=@_;
 7839:     my ($symb,$courseid,$domain,$name,$publicuser);
 7840:     if (defined($env{'form.grade_symb'})) {
 7841: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 7842: 	my $allowed=&allowed('vgr',$tmp_courseid);
 7843: 	if (!$allowed &&
 7844: 	    exists($env{'request.course.sec'}) &&
 7845: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 7846: 	    $allowed=&allowed('vgr',$tmp_courseid.
 7847: 			      '/'.$env{'request.course.sec'});
 7848: 	}
 7849: 	if ($allowed) {
 7850: 	    ($symb)=&get_env_multiple('form.grade_symb');
 7851: 	    $courseid=$tmp_courseid;
 7852: 	    ($domain)=&get_env_multiple('form.grade_domain');
 7853: 	    ($name)=&get_env_multiple('form.grade_username');
 7854: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 7855: 	}
 7856:     }
 7857:     if (!$passedsymb) {
 7858: 	$symb=&symbread();
 7859:     } else {
 7860: 	$symb=$passedsymb;
 7861:     }
 7862:     $courseid=$env{'request.course.id'};
 7863:     $domain=$env{'user.domain'};
 7864:     $name=$env{'user.name'};
 7865:     if ($name eq 'public' && $domain eq 'public') {
 7866: 	if (!defined($env{'form.username'})) {
 7867: 	    $env{'form.username'}.=time.rand(10000000);
 7868: 	}
 7869: 	$name.=$env{'form.username'};
 7870:     }
 7871:     return ($symb,$courseid,$domain,$name,$publicuser);
 7872: 
 7873: }
 7874: 
 7875: # ------------------------------------------------------------ Serves up a file
 7876: # returns either the contents of the file or 
 7877: # -1 if the file doesn't exist
 7878: #
 7879: # if the target is a file that was uploaded via DOCS, 
 7880: # a check will be made to see if a current copy exists on the local server,
 7881: # if it does this will be served, otherwise a copy will be retrieved from
 7882: # the home server for the course and stored in /home/httpd/html/userfiles on
 7883: # the local server.   
 7884: 
 7885: sub getfile {
 7886:     my ($file) = @_;
 7887:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7888:     &repcopy($file);
 7889:     return &readfile($file);
 7890: }
 7891: 
 7892: sub repcopy_userfile {
 7893:     my ($file)=@_;
 7894:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 7895:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 7896:     my ($cdom,$cnum,$filename) = 
 7897: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 7898:     my $uri="/uploaded/$cdom/$cnum/$filename";
 7899:     if (-e "$file") {
 7900: # we already have a local copy, check it out
 7901: 	my @fileinfo = stat($file);
 7902: 	my $rtncode;
 7903: 	my $info;
 7904: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 7905: 	if ($lwpresp ne 'ok') {
 7906: # there is no such file anymore, even though we had a local copy
 7907: 	    if ($rtncode eq '404') {
 7908: 		unlink($file);
 7909: 	    }
 7910: 	    return -1;
 7911: 	}
 7912: 	if ($info < $fileinfo[9]) {
 7913: # nice, the file we have is up-to-date, just say okay
 7914: 	    return 'ok';
 7915: 	} else {
 7916: # the file is outdated, get rid of it
 7917: 	    unlink($file);
 7918: 	}
 7919:     }
 7920: # one way or the other, at this point, we don't have the file
 7921: # construct the correct path for the file
 7922:     my @parts = ($cdom,$cnum); 
 7923:     if ($filename =~ m|^(.+)/[^/]+$|) {
 7924: 	push @parts, split(/\//,$1);
 7925:     }
 7926:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 7927:     foreach my $part (@parts) {
 7928: 	$path .= '/'.$part;
 7929: 	if (!-e $path) {
 7930: 	    mkdir($path,0770);
 7931: 	}
 7932:     }
 7933: # now the path exists for sure
 7934: # get a user agent
 7935:     my $ua=new LWP::UserAgent;
 7936:     my $transferfile=$file.'.in.transfer';
 7937: # FIXME: this should flock
 7938:     if (-e $transferfile) { return 'ok'; }
 7939:     my $request;
 7940:     $uri=~s/^\///;
 7941:     $request=new HTTP::Request('GET','http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri);
 7942:     my $response=$ua->request($request,$transferfile);
 7943: # did it work?
 7944:     if ($response->is_error()) {
 7945: 	unlink($transferfile);
 7946: 	&logthis("Userfile repcopy failed for $uri");
 7947: 	return -1;
 7948:     }
 7949: # worked, rename the transfer file
 7950:     rename($transferfile,$file);
 7951:     return 'ok';
 7952: }
 7953: 
 7954: sub tokenwrapper {
 7955:     my $uri=shift;
 7956:     $uri=~s|^http\://([^/]+)||;
 7957:     $uri=~s|^/||;
 7958:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 7959:     my $token=$1;
 7960:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 7961:     if ($udom && $uname && $file) {
 7962: 	$file=~s|(\?\.*)*$||;
 7963:         &appenv("userfile.$udom/$uname/$file" => $env{'request.course.id'});
 7964:         return 'http://'.&hostname(&homeserver($uname,$udom)).'/'.$uri.
 7965:                (($uri=~/\?/)?'&':'?').'token='.$token.
 7966:                                '&tokenissued='.$perlvar{'lonHostID'};
 7967:     } else {
 7968:         return '/adm/notfound.html';
 7969:     }
 7970: }
 7971: 
 7972: # call with reqtype HEAD: get last modification time
 7973: # call with reqtype GET: get the file contents
 7974: # Do not call this with reqtype GET for large files! It loads everything into memory
 7975: #
 7976: sub getuploaded {
 7977:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 7978:     $uri=~s/^\///;
 7979:     $uri = 'http://'.&hostname(&homeserver($cnum,$cdom)).'/raw/'.$uri;
 7980:     my $ua=new LWP::UserAgent;
 7981:     my $request=new HTTP::Request($reqtype,$uri);
 7982:     my $response=$ua->request($request);
 7983:     $$rtncode = $response->code;
 7984:     if (! $response->is_success()) {
 7985: 	return 'failed';
 7986:     }      
 7987:     if ($reqtype eq 'HEAD') {
 7988: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 7989:     } elsif ($reqtype eq 'GET') {
 7990: 	$$info = $response->content;
 7991:     }
 7992:     return 'ok';
 7993: }
 7994: 
 7995: sub readfile {
 7996:     my $file = shift;
 7997:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 7998:     my $fh;
 7999:     open($fh,"<$file");
 8000:     my $a='';
 8001:     while (my $line = <$fh>) { $a .= $line; }
 8002:     return $a;
 8003: }
 8004: 
 8005: sub filelocation {
 8006:     my ($dir,$file) = @_;
 8007:     my $location;
 8008:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8009: 
 8010:     if ($file =~ m-^/adm/-) {
 8011: 	$file=~s-^/adm/wrapper/-/-;
 8012: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8013:     }
 8014: 
 8015:     if ($file=~m:^/~:) { # is a contruction space reference
 8016:         $location = $file;
 8017:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8018:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8019: 	# is a correct contruction space reference
 8020:         $location = $file;
 8021:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8022:         my ($udom,$uname,$filename)=
 8023:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8024:         my $home=&homeserver($uname,$udom);
 8025:         my $is_me=0;
 8026:         my @ids=&current_machine_ids();
 8027:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8028:         if ($is_me) {
 8029:   	    $location=&propath($udom,$uname).
 8030:   	      '/userfiles/'.$filename;
 8031:         } else {
 8032:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8033:   	      $udom.'/'.$uname.'/'.$filename;
 8034:         }
 8035:     } elsif ($file =~ m-^/adm/-) {
 8036: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8037:     } else {
 8038:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8039:         $file=~s:^/res/:/:;
 8040:         if ( !( $file =~ m:^/:) ) {
 8041:             $location = $dir. '/'.$file;
 8042:         } else {
 8043:             $location = '/home/httpd/html/res'.$file;
 8044:         }
 8045:     }
 8046:     $location=~s://+:/:g; # remove duplicate /
 8047:     while ($location=~m{/\.\./}) {
 8048: 	if ($location =~ m{/[^/]+/\.\./}) {
 8049: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8050: 	} else {
 8051: 	    $location=~ s{/\.\./}{/}g;
 8052: 	}
 8053:     } #remove dir/..
 8054:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8055:     return $location;
 8056: }
 8057: 
 8058: sub hreflocation {
 8059:     my ($dir,$file)=@_;
 8060:     unless (($file=~m-^http://-i) || ($file=~m-^/-)) {
 8061: 	$file=filelocation($dir,$file);
 8062:     } elsif ($file=~m-^/adm/-) {
 8063: 	$file=~s-^/adm/wrapper/-/-;
 8064: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8065:     }
 8066:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8067: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8068:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8069: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8070:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8071: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8072: 	    -/uploaded/$1/$2/-x;
 8073:     }
 8074:     if ($file=~ m{^/userfiles/}) {
 8075: 	$file =~ s{^/userfiles/}{/uploaded/};
 8076:     }
 8077:     return $file;
 8078: }
 8079: 
 8080: sub current_machine_domains {
 8081:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8082: }
 8083: 
 8084: sub machine_domains {
 8085:     my ($hostname) = @_;
 8086:     my @domains;
 8087:     my %hostname = &all_hostnames();
 8088:     while( my($id, $name) = each(%hostname)) {
 8089: #	&logthis("-$id-$name-$hostname-");
 8090: 	if ($hostname eq $name) {
 8091: 	    push(@domains,&host_domain($id));
 8092: 	}
 8093:     }
 8094:     return @domains;
 8095: }
 8096: 
 8097: sub current_machine_ids {
 8098:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8099: }
 8100: 
 8101: sub machine_ids {
 8102:     my ($hostname) = @_;
 8103:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8104:     my @ids;
 8105:     my %name_to_host = &all_names();
 8106:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8107: 	return @{ $name_to_host{$hostname} };
 8108:     }
 8109:     return;
 8110: }
 8111: 
 8112: sub additional_machine_domains {
 8113:     my @domains;
 8114:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8115:     while( my $line = <$fh>) {
 8116:         $line =~ s/\s//g;
 8117:         push(@domains,$line);
 8118:     }
 8119:     return @domains;
 8120: }
 8121: 
 8122: sub default_login_domain {
 8123:     my $domain = $perlvar{'lonDefDomain'};
 8124:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8125:     foreach my $posdom (&current_machine_domains(),
 8126:                         &additional_machine_domains()) {
 8127:         if (lc($posdom) eq lc($testdomain)) {
 8128:             $domain=$posdom;
 8129:             last;
 8130:         }
 8131:     }
 8132:     return $domain;
 8133: }
 8134: 
 8135: # ------------------------------------------------------------- Declutters URLs
 8136: 
 8137: sub declutter {
 8138:     my $thisfn=shift;
 8139:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8140:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8141:     $thisfn=~s/^\///;
 8142:     $thisfn=~s|^adm/wrapper/||;
 8143:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8144:     $thisfn=~s/^res\///;
 8145:     $thisfn=~s/\?.+$//;
 8146:     return $thisfn;
 8147: }
 8148: 
 8149: # ------------------------------------------------------------- Clutter up URLs
 8150: 
 8151: sub clutter {
 8152:     my $thisfn='/'.&declutter(shift);
 8153:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8154: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8155:        $thisfn='/res'.$thisfn; 
 8156:     }
 8157:     if ($thisfn !~m|/adm|) {
 8158: 	if ($thisfn =~ m|/ext/|) {
 8159: 	    $thisfn='/adm/wrapper'.$thisfn;
 8160: 	} else {
 8161: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8162: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8163: 	    if ($embstyle eq 'ssi'
 8164: 		|| ($embstyle eq 'hdn')
 8165: 		|| ($embstyle eq 'rat')
 8166: 		|| ($embstyle eq 'prv')
 8167: 		|| ($embstyle eq 'ign')) {
 8168: 		#do nothing with these
 8169: 	    } elsif (($embstyle eq 'img') 
 8170: 		|| ($embstyle eq 'emb')
 8171: 		|| ($embstyle eq 'wrp')) {
 8172: 		$thisfn='/adm/wrapper'.$thisfn;
 8173: 	    } elsif ($embstyle eq 'unk'
 8174: 		     && $thisfn!~/\.(sequence|page)$/) {
 8175: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8176: 	    } else {
 8177: #		&logthis("Got a blank emb style");
 8178: 	    }
 8179: 	}
 8180:     }
 8181:     return $thisfn;
 8182: }
 8183: 
 8184: sub clutter_with_no_wrapper {
 8185:     my $uri = &clutter(shift);
 8186:     if ($uri =~ m-^/adm/-) {
 8187: 	$uri =~ s-^/adm/wrapper/-/-;
 8188: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8189:     }
 8190:     return $uri;
 8191: }
 8192: 
 8193: sub freeze_escape {
 8194:     my ($value)=@_;
 8195:     if (ref($value)) {
 8196: 	$value=&nfreeze($value);
 8197: 	return '__FROZEN__'.&escape($value);
 8198:     }
 8199:     return &escape($value);
 8200: }
 8201: 
 8202: 
 8203: sub thaw_unescape {
 8204:     my ($value)=@_;
 8205:     if ($value =~ /^__FROZEN__/) {
 8206: 	substr($value,0,10,undef);
 8207: 	$value=&unescape($value);
 8208: 	return &thaw($value);
 8209:     }
 8210:     return &unescape($value);
 8211: }
 8212: 
 8213: sub correct_line_ends {
 8214:     my ($result)=@_;
 8215:     $$result =~s/\r\n/\n/mg;
 8216:     $$result =~s/\r/\n/mg;
 8217: }
 8218: # ================================================================ Main Program
 8219: 
 8220: sub goodbye {
 8221:    &logthis("Starting Shut down");
 8222: #not converted to using infrastruture and probably shouldn't be
 8223:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8224: #converted
 8225: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8226:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8227: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8228: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8229: #1.1 only
 8230: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8231: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8232: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8233: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8234:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8235:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8236:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8237:    &flushcourselogs();
 8238:    &logthis("Shutting down");
 8239: }
 8240: 
 8241: sub get_dns {
 8242:     my ($url,$func,$ignore_cache) = @_;
 8243:     if (!$ignore_cache) {
 8244: 	my ($content,$cached)=
 8245: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8246: 	if ($cached) {
 8247: 	    &$func($content);
 8248: 	    return;
 8249: 	}
 8250:     }
 8251: 
 8252:     my %alldns;
 8253:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8254:     foreach my $dns (<$config>) {
 8255: 	next if ($dns !~ /^\^(\S*)/x);
 8256: 	$alldns{$1} = 1;
 8257:     }
 8258:     while (%alldns) {
 8259: 	my ($dns) = keys(%alldns);
 8260: 	delete($alldns{$dns});
 8261: 	my $ua=new LWP::UserAgent;
 8262: 	my $request=new HTTP::Request('GET',"http://$dns$url");
 8263: 	my $response=$ua->request($request);
 8264: 	next if ($response->is_error());
 8265: 	my @content = split("\n",$response->content);
 8266: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8267: 	&$func(\@content);
 8268: 	return;
 8269:     }
 8270:     close($config);
 8271:     my $which = (split('/',$url))[3];
 8272:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8273:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8274:     my @content = <$config>;
 8275:     &$func(\@content);
 8276:     return;
 8277: }
 8278: # ------------------------------------------------------------ Read domain file
 8279: {
 8280:     my $loaded;
 8281:     my %domain;
 8282: 
 8283:     sub parse_domain_tab {
 8284: 	my ($lines) = @_;
 8285: 	foreach my $line (@$lines) {
 8286: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8287: 
 8288: 	    chomp($line);
 8289: 	    my ($name,@elements) = split(/:/,$line,9);
 8290: 	    my %this_domain;
 8291: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8292: 			       'lang_def', 'city', 'longi', 'lati',
 8293: 			       'primary') {
 8294: 		$this_domain{$field} = shift(@elements);
 8295: 	    }
 8296: 	    $domain{$name} = \%this_domain;
 8297: 	}
 8298:     }
 8299: 
 8300:     sub reset_domain_info {
 8301: 	undef($loaded);
 8302: 	undef(%domain);
 8303:     }
 8304: 
 8305:     sub load_domain_tab {
 8306: 	my ($ignore_cache) = @_;
 8307: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8308: 	my $fh;
 8309: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8310: 	    my @lines = <$fh>;
 8311: 	    &parse_domain_tab(\@lines);
 8312: 	}
 8313: 	close($fh);
 8314: 	$loaded = 1;
 8315:     }
 8316: 
 8317:     sub domain {
 8318: 	&load_domain_tab() if (!$loaded);
 8319: 
 8320: 	my ($name,$what) = @_;
 8321: 	return if ( !exists($domain{$name}) );
 8322: 
 8323: 	if (!$what) {
 8324: 	    return $domain{$name}{'description'};
 8325: 	}
 8326: 	return $domain{$name}{$what};
 8327:     }
 8328: }
 8329: 
 8330: 
 8331: # ------------------------------------------------------------- Read hosts file
 8332: {
 8333:     my %hostname;
 8334:     my %hostdom;
 8335:     my %libserv;
 8336:     my $loaded;
 8337:     my %name_to_host;
 8338: 
 8339:     sub parse_hosts_tab {
 8340: 	my ($file) = @_;
 8341: 	foreach my $configline (@$file) {
 8342: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8343: 	    next if ($configline =~ /^\^/);
 8344: 	    chomp($configline);
 8345: 	    my ($id,$domain,$role,$name)=split(/:/,$configline);
 8346: 	    $name=~s/\s//g;
 8347: 	    if ($id && $domain && $role && $name) {
 8348: 		$hostname{$id}=$name;
 8349: 		push(@{$name_to_host{$name}}, $id);
 8350: 		$hostdom{$id}=$domain;
 8351: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8352: 	    }
 8353: 	}
 8354:     }
 8355:     
 8356:     sub reset_hosts_info {
 8357: 	&purge_remembered();
 8358: 	&reset_domain_info();
 8359: 	&reset_hosts_ip_info();
 8360: 	undef(%name_to_host);
 8361: 	undef(%hostname);
 8362: 	undef(%hostdom);
 8363: 	undef(%libserv);
 8364: 	undef($loaded);
 8365:     }
 8366: 
 8367:     sub load_hosts_tab {
 8368: 	my ($ignore_cache) = @_;
 8369: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8370: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8371: 	my @config = <$config>;
 8372: 	&parse_hosts_tab(\@config);
 8373: 	close($config);
 8374: 	$loaded=1;
 8375:     }
 8376: 
 8377:     sub hostname {
 8378: 	&load_hosts_tab() if (!$loaded);
 8379: 
 8380: 	my ($lonid) = @_;
 8381: 	return $hostname{$lonid};
 8382:     }
 8383: 
 8384:     sub all_hostnames {
 8385: 	&load_hosts_tab() if (!$loaded);
 8386: 
 8387: 	return %hostname;
 8388:     }
 8389: 
 8390:     sub all_names {
 8391: 	&load_hosts_tab() if (!$loaded);
 8392: 
 8393: 	return %name_to_host;
 8394:     }
 8395: 
 8396:     sub is_library {
 8397: 	&load_hosts_tab() if (!$loaded);
 8398: 
 8399: 	return exists($libserv{$_[0]});
 8400:     }
 8401: 
 8402:     sub all_library {
 8403: 	&load_hosts_tab() if (!$loaded);
 8404: 
 8405: 	return %libserv;
 8406:     }
 8407: 
 8408:     sub get_servers {
 8409: 	&load_hosts_tab() if (!$loaded);
 8410: 
 8411: 	my ($domain,$type) = @_;
 8412: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8413: 	                                          : %hostname;
 8414: 	my %result;
 8415: 	if (ref($domain) eq 'ARRAY') {
 8416: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8417: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8418: 		    $result{$host} = $hostname;
 8419: 		}
 8420: 	    }
 8421: 	} else {
 8422: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8423: 		if ($hostdom{$host} eq $domain) {
 8424: 		    $result{$host} = $hostname;
 8425: 		}
 8426: 	    }
 8427: 	}
 8428: 	return %result;
 8429:     }
 8430: 
 8431:     sub host_domain {
 8432: 	&load_hosts_tab() if (!$loaded);
 8433: 
 8434: 	my ($lonid) = @_;
 8435: 	return $hostdom{$lonid};
 8436:     }
 8437: 
 8438:     sub all_domains {
 8439: 	&load_hosts_tab() if (!$loaded);
 8440: 
 8441: 	my %seen;
 8442: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8443: 	return @uniq;
 8444:     }
 8445: }
 8446: 
 8447: { 
 8448:     my %iphost;
 8449:     my %name_to_ip;
 8450:     my %lonid_to_ip;
 8451: 
 8452:     sub get_hosts_from_ip {
 8453: 	my ($ip) = @_;
 8454: 	my %iphosts = &get_iphost();
 8455: 	if (ref($iphosts{$ip})) {
 8456: 	    return @{$iphosts{$ip}};
 8457: 	}
 8458: 	return;
 8459:     }
 8460:     
 8461:     sub reset_hosts_ip_info {
 8462: 	undef(%iphost);
 8463: 	undef(%name_to_ip);
 8464: 	undef(%lonid_to_ip);
 8465:     }
 8466: 
 8467:     sub get_host_ip {
 8468: 	my ($lonid) = @_;
 8469: 	if (exists($lonid_to_ip{$lonid})) {
 8470: 	    return $lonid_to_ip{$lonid};
 8471: 	}
 8472: 	my $name=&hostname($lonid);
 8473:    	my $ip = gethostbyname($name);
 8474: 	return if (!$ip || length($ip) ne 4);
 8475: 	$ip=inet_ntoa($ip);
 8476: 	$name_to_ip{$name}   = $ip;
 8477: 	$lonid_to_ip{$lonid} = $ip;
 8478: 	return $ip;
 8479:     }
 8480:     
 8481:     sub get_iphost {
 8482: 	my ($ignore_cache) = @_;
 8483: 
 8484: 	if (!$ignore_cache) {
 8485: 	    if (%iphost) {
 8486: 		return %iphost;
 8487: 	    }
 8488: 	    my ($ip_info,$cached)=
 8489: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8490: 	    if ($cached) {
 8491: 		%iphost      = %{$ip_info->[0]};
 8492: 		%name_to_ip  = %{$ip_info->[1]};
 8493: 		%lonid_to_ip = %{$ip_info->[2]};
 8494: 		return %iphost;
 8495: 	    }
 8496: 	}
 8497: 
 8498: 	# get yesterday's info for fallback
 8499: 	my %old_name_to_ip;
 8500: 	my ($ip_info,$cached)=
 8501: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8502: 	if ($cached) {
 8503: 	    %old_name_to_ip = %{$ip_info->[1]};
 8504: 	}
 8505: 
 8506: 	my %name_to_host = &all_names();
 8507: 	foreach my $name (keys(%name_to_host)) {
 8508: 	    my $ip;
 8509: 	    if (!exists($name_to_ip{$name})) {
 8510: 		$ip = gethostbyname($name);
 8511: 		if (!$ip || length($ip) ne 4) {
 8512: 		    if (defined($old_name_to_ip{$name})) {
 8513: 			$ip = $old_name_to_ip{$name};
 8514: 			&logthis("Can't find $name defaulting to old $ip");
 8515: 		    } else {
 8516: 			&logthis("Name $name no IP found");
 8517: 			next;
 8518: 		    }
 8519: 		} else {
 8520: 		    $ip=inet_ntoa($ip);
 8521: 		}
 8522: 		$name_to_ip{$name} = $ip;
 8523: 	    } else {
 8524: 		$ip = $name_to_ip{$name};
 8525: 	    }
 8526: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8527: 		$lonid_to_ip{$id} = $ip;
 8528: 	    }
 8529: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8530: 	}
 8531: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8532: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8533: 				      48*60*60);
 8534: 
 8535: 	return %iphost;
 8536:     }
 8537: }
 8538: 
 8539: BEGIN {
 8540: 
 8541: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8542:     unless ($readit) {
 8543: {
 8544:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8545:     %perlvar = (%perlvar,%{$configvars});
 8546: }
 8547: 
 8548: 
 8549: # ------------------------------------------------------ Read spare server file
 8550: {
 8551:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8552: 
 8553:     while (my $configline=<$config>) {
 8554:        chomp($configline);
 8555:        if ($configline) {
 8556: 	   my ($host,$type) = split(':',$configline,2);
 8557: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8558: 	   push(@{ $spareid{$type} }, $host);
 8559:        }
 8560:     }
 8561:     close($config);
 8562: }
 8563: # ------------------------------------------------------------ Read permissions
 8564: {
 8565:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8566: 
 8567:     while (my $configline=<$config>) {
 8568: 	chomp($configline);
 8569: 	if ($configline) {
 8570: 	    my ($role,$perm)=split(/ /,$configline);
 8571: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8572: 	}
 8573:     }
 8574:     close($config);
 8575: }
 8576: 
 8577: # -------------------------------------------- Read plain texts for permissions
 8578: {
 8579:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8580: 
 8581:     while (my $configline=<$config>) {
 8582: 	chomp($configline);
 8583: 	if ($configline) {
 8584: 	    my ($short,@plain)=split(/:/,$configline);
 8585:             %{$prp{$short}} = ();
 8586: 	    if (@plain > 0) {
 8587:                 $prp{$short}{'std'} = $plain[0];
 8588:                 for (my $i=1; $i<@plain; $i++) {
 8589:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8590:                 }
 8591:             }
 8592: 	}
 8593:     }
 8594:     close($config);
 8595: }
 8596: 
 8597: # ---------------------------------------------------------- Read package table
 8598: {
 8599:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8600: 
 8601:     while (my $configline=<$config>) {
 8602: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 8603: 	chomp($configline);
 8604: 	my ($short,$plain)=split(/:/,$configline);
 8605: 	my ($pack,$name)=split(/\&/,$short);
 8606: 	if ($plain ne '') {
 8607: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 8608: 	    $packagetab{$short}=$plain; 
 8609: 	}
 8610:     }
 8611:     close($config);
 8612: }
 8613: 
 8614: # ------------- set up temporary directory
 8615: {
 8616:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 8617: 
 8618: }
 8619: 
 8620: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 8621: 				'compress_threshold'=> 20_000,
 8622:  			        });
 8623: 
 8624: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 8625: $dumpcount=0;
 8626: 
 8627: &logtouch();
 8628: &logthis('<font color="yellow">INFO: Read configuration</font>');
 8629: $readit=1;
 8630:     {
 8631: 	use integer;
 8632: 	my $test=(2**32)+1;
 8633: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 8634: 	&logthis(" Detected 64bit platform ($_64bit)");
 8635:     }
 8636: }
 8637: }
 8638: 
 8639: 1;
 8640: __END__
 8641: 
 8642: =pod
 8643: 
 8644: =head1 NAME
 8645: 
 8646: Apache::lonnet - Subroutines to ask questions about things in the network.
 8647: 
 8648: =head1 SYNOPSIS
 8649: 
 8650: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 8651: 
 8652:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 8653: 
 8654: Common parameters:
 8655: 
 8656: =over 4
 8657: 
 8658: =item *
 8659: 
 8660: $uname : an internal username (if $cname expecting a course Id specifically)
 8661: 
 8662: =item *
 8663: 
 8664: $udom : a domain (if $cdom expecting a course's domain specifically)
 8665: 
 8666: =item *
 8667: 
 8668: $symb : a resource instance identifier
 8669: 
 8670: =item *
 8671: 
 8672: $namespace : the name of a .db file that contains the data needed or
 8673: being set.
 8674: 
 8675: =back
 8676: 
 8677: =head1 OVERVIEW
 8678: 
 8679: lonnet provides subroutines which interact with the
 8680: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 8681: about classes, users, and resources.
 8682: 
 8683: For many of these objects you can also use this to store data about
 8684: them or modify them in various ways.
 8685: 
 8686: =head2 Symbs
 8687: 
 8688: To identify a specific instance of a resource, LON-CAPA uses symbols
 8689: or "symbs"X<symb>. These identifiers are built from the URL of the
 8690: map, the resource number of the resource in the map, and the URL of
 8691: the resource itself. The latter is somewhat redundant, but might help
 8692: if maps change.
 8693: 
 8694: An example is
 8695: 
 8696:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 8697: 
 8698: The respective map entry is
 8699: 
 8700:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 8701:   title="Problem 2">
 8702:  </resource>
 8703: 
 8704: Symbs are used by the random number generator, as well as to store and
 8705: restore data specific to a certain instance of for example a problem.
 8706: 
 8707: =head2 Storing And Retrieving Data
 8708: 
 8709: X<store()>X<cstore()>X<restore()>Three of the most important functions
 8710: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 8711: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 8712: is is the non-critical message twin of cstore. These functions are for
 8713: handlers to store a perl hash to a user's permanent data space in an
 8714: easy manner, and to retrieve it again on another call. It is expected
 8715: that a handler would use this once at the beginning to retrieve data,
 8716: and then again once at the end to send only the new data back.
 8717: 
 8718: The data is stored in the user's data directory on the user's
 8719: homeserver under the ID of the course.
 8720: 
 8721: The hash that is returned by restore will have all of the previous
 8722: value for all of the elements of the hash.
 8723: 
 8724: Example:
 8725: 
 8726:  #creating a hash
 8727:  my %hash;
 8728:  $hash{'foo'}='bar';
 8729: 
 8730:  #storing it
 8731:  &Apache::lonnet::cstore(\%hash);
 8732: 
 8733:  #changing a value
 8734:  $hash{'foo'}='notbar';
 8735: 
 8736:  #adding a new value
 8737:  $hash{'bar'}='foo';
 8738:  &Apache::lonnet::cstore(\%hash);
 8739: 
 8740:  #retrieving the hash
 8741:  my %history=&Apache::lonnet::restore();
 8742: 
 8743:  #print the hash
 8744:  foreach my $key (sort(keys(%history))) {
 8745:    print("\%history{$key} = $history{$key}");
 8746:  }
 8747: 
 8748: Will print out:
 8749: 
 8750:  %history{1:foo} = bar
 8751:  %history{1:keys} = foo:timestamp
 8752:  %history{1:timestamp} = 990455579
 8753:  %history{2:bar} = foo
 8754:  %history{2:foo} = notbar
 8755:  %history{2:keys} = foo:bar:timestamp
 8756:  %history{2:timestamp} = 990455580
 8757:  %history{bar} = foo
 8758:  %history{foo} = notbar
 8759:  %history{timestamp} = 990455580
 8760:  %history{version} = 2
 8761: 
 8762: Note that the special hash entries C<keys>, C<version> and
 8763: C<timestamp> were added to the hash. C<version> will be equal to the
 8764: total number of versions of the data that have been stored. The
 8765: C<timestamp> attribute will be the UNIX time the hash was
 8766: stored. C<keys> is available in every historical section to list which
 8767: keys were added or changed at a specific historical revision of a
 8768: hash.
 8769: 
 8770: B<Warning>: do not store the hash that restore returns directly. This
 8771: will cause a mess since it will restore the historical keys as if the
 8772: were new keys. I.E. 1:foo will become 1:1:foo etc.
 8773: 
 8774: Calling convention:
 8775: 
 8776:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 8777:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 8778: 
 8779: For more detailed information, see lonnet specific documentation.
 8780: 
 8781: =head1 RETURN MESSAGES
 8782: 
 8783: =over 4
 8784: 
 8785: =item * B<con_lost>: unable to contact remote host
 8786: 
 8787: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 8788: when the connection is brought back up
 8789: 
 8790: =item * B<con_failed>: unable to contact remote host and unable to save message
 8791: for later delivery
 8792: 
 8793: =item * B<error:>: an error a occured, a description of the error follows the :
 8794: 
 8795: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 8796: that was requested
 8797: 
 8798: =back
 8799: 
 8800: =head1 PUBLIC SUBROUTINES
 8801: 
 8802: =head2 Session Environment Functions
 8803: 
 8804: =over 4
 8805: 
 8806: =item * 
 8807: X<appenv()>
 8808: B<appenv(%hash)>: the value of %hash is written to
 8809: the user envirnoment file, and will be restored for each access this
 8810: user makes during this session, also modifies the %env for the current
 8811: process
 8812: 
 8813: =item *
 8814: X<delenv()>
 8815: B<delenv($regexp)>: removes all items from the session
 8816: environment file that matches the regular expression in $regexp. The
 8817: values are also delted from the current processes %env.
 8818: 
 8819: =item * get_env_multiple($name) 
 8820: 
 8821: gets $name from the %env hash, it seemlessly handles the cases where multiple
 8822: values may be defined and end up as an array ref.
 8823: 
 8824: returns an array of values
 8825: 
 8826: =back
 8827: 
 8828: =head2 User Information
 8829: 
 8830: =over 4
 8831: 
 8832: =item *
 8833: X<queryauthenticate()>
 8834: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 8835: authentication scheme
 8836: 
 8837: =item *
 8838: X<authenticate()>
 8839: B<authenticate($uname,$upass,$udom)>: try to
 8840: authenticate user from domain's lib servers (first use the current
 8841: one). C<$upass> should be the users password.
 8842: 
 8843: =item *
 8844: X<homeserver()>
 8845: B<homeserver($uname,$udom)>: find the server which has
 8846: the user's directory and files (there must be only one), this caches
 8847: the answer, and also caches if there is a borken connection.
 8848: 
 8849: =item *
 8850: X<idget()>
 8851: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 8852: (IDs are a unique resource in a domain, there must be only 1 ID per
 8853: username, and only 1 username per ID in a specific domain) (returns
 8854: hash: id=>name,id=>name)
 8855: 
 8856: =item *
 8857: X<idrget()>
 8858: B<idrget($udom,@unames)>: find the IDs behind a list of
 8859: usernames (returns hash: name=>id,name=>id)
 8860: 
 8861: =item *
 8862: X<idput()>
 8863: B<idput($udom,%ids)>: store away a list of names and associated IDs
 8864: 
 8865: =item *
 8866: X<rolesinit()>
 8867: B<rolesinit($udom,$username,$authhost)>: get user privileges
 8868: 
 8869: =item *
 8870: X<getsection()>
 8871: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 8872: course $cname, return section name/number or '' for "not in course"
 8873: and '-1' for "no section"
 8874: 
 8875: =item *
 8876: X<userenvironment()>
 8877: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 8878: passed in @what from the requested user's environment, returns a hash
 8879: 
 8880: =item * 
 8881: X<userlog_query()>
 8882: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 8883: activity.log file. %filters defines filters applied when parsing the
 8884: log file. These can be start or end timestamps, or the type of action
 8885: - log to look for Login or Logout events, check for Checkin or
 8886: Checkout, role for role selection. The response is in the form
 8887: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 8888: escaped strings of the action recorded in the activity.log file.
 8889: 
 8890: =back
 8891: 
 8892: =head2 User Roles
 8893: 
 8894: =over 4
 8895: 
 8896: =item *
 8897: 
 8898: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 8899:  F: full access
 8900:  U,I,K: authentication modes (cxx only)
 8901:  '': forbidden
 8902:  1: user needs to choose course
 8903:  2: browse allowed
 8904:  A: passphrase authentication needed
 8905: 
 8906: =item *
 8907: 
 8908: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 8909: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 8910: and course level
 8911: 
 8912: =item *
 8913: 
 8914: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 8915: explanation of a user role term
 8916: 
 8917: =item *
 8918: 
 8919: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 8920: All arguments are optional. Returns a hash of a roles, either for
 8921: co-author/assistant author roles for a user's Construction Space
 8922: (default), or if $context is 'userroles', roles for the user himself,
 8923: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 8924: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 8925: For each key, value is set to colon-separated start and end times for
 8926: the role.  If no username and domain are specified, will default to
 8927: current user/domain. Types, roles, and roledoms are references to arrays
 8928: of role statuses (active, future or previous), roles 
 8929: (e.g., cc,in, st etc.) and domains of the roles which can be used
 8930: to restrict the list of roles reported. If no array ref is 
 8931: provided for types, will default to return only active roles.
 8932: 
 8933: =back
 8934: 
 8935: =head2 User Modification
 8936: 
 8937: =over 4
 8938: 
 8939: =item *
 8940: 
 8941: assignrole($udom,$uname,$url,$role,$end,$start) : assign role; give a role to a
 8942: user for the level given by URL.  Optional start and end dates (leave empty
 8943: string or zero for "no date")
 8944: 
 8945: =item *
 8946: 
 8947: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 8948: change a users, password, possible return values are: ok,
 8949: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 8950: refused
 8951: 
 8952: =item *
 8953: 
 8954: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 8955: 
 8956: =item *
 8957: 
 8958: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene) : 
 8959: modify user
 8960: 
 8961: =item *
 8962: 
 8963: modifystudent
 8964: 
 8965: modify a students enrollment and identification information.
 8966: The course id is resolved based on the current users environment.  
 8967: This means the envoking user must be a course coordinator or otherwise
 8968: associated with a course.
 8969: 
 8970: This call is essentially a wrapper for lonnet::modifyuser and
 8971: lonnet::modify_student_enrollment
 8972: 
 8973: Inputs: 
 8974: 
 8975: =over 4
 8976: 
 8977: =item B<$udom> Students loncapa domain
 8978: 
 8979: =item B<$uname> Students loncapa login name
 8980: 
 8981: =item B<$uid> Students id/student number
 8982: 
 8983: =item B<$umode> Students authentication mode
 8984: 
 8985: =item B<$upass> Students password
 8986: 
 8987: =item B<$first> Students first name
 8988: 
 8989: =item B<$middle> Students middle name
 8990: 
 8991: =item B<$last> Students last name
 8992: 
 8993: =item B<$gene> Students generation
 8994: 
 8995: =item B<$usec> Students section in course
 8996: 
 8997: =item B<$end> Unix time of the roles expiration
 8998: 
 8999: =item B<$start> Unix time of the roles start date
 9000: 
 9001: =item B<$forceid> If defined, allow $uid to be changed
 9002: 
 9003: =item B<$desiredhome> server to use as home server for student
 9004: 
 9005: =back
 9006: 
 9007: =item *
 9008: 
 9009: modify_student_enrollment
 9010: 
 9011: Change a students enrollment status in a class.  The environment variable
 9012: 'role.request.course' must be defined for this function to proceed.
 9013: 
 9014: Inputs:
 9015: 
 9016: =over 4
 9017: 
 9018: =item $udom, students domain
 9019: 
 9020: =item $uname, students name
 9021: 
 9022: =item $uid, students user id
 9023: 
 9024: =item $first, students first name
 9025: 
 9026: =item $middle
 9027: 
 9028: =item $last
 9029: 
 9030: =item $gene
 9031: 
 9032: =item $usec
 9033: 
 9034: =item $end
 9035: 
 9036: =item $start
 9037: 
 9038: =back
 9039: 
 9040: 
 9041: =item *
 9042: 
 9043: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9044: custom role; give a custom role to a user for the level given by URL.  Specify
 9045: name and domain of role author, and role name
 9046: 
 9047: =item *
 9048: 
 9049: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9050: 
 9051: =item *
 9052: 
 9053: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9054: 
 9055: =back
 9056: 
 9057: =head2 Course Infomation
 9058: 
 9059: =over 4
 9060: 
 9061: =item *
 9062: 
 9063: coursedescription($courseid) : returns a hash of information about the
 9064: specified course id, including all environment settings for the
 9065: course, the description of the course will be in the hash under the
 9066: key 'description'
 9067: 
 9068: =item *
 9069: 
 9070: resdata($name,$domain,$type,@which) : request for current parameter
 9071: setting for a specific $type, where $type is either 'course' or 'user',
 9072: @what should be a list of parameters to ask about. This routine caches
 9073: answers for 5 minutes.
 9074: 
 9075: =item *
 9076: 
 9077: get_courseresdata($courseid, $domain) : dump the entire course resource
 9078: data base, returning a hash that is keyed by the resource name and has
 9079: values that are the resource value.  I believe that the timestamps and
 9080: versions are also returned.
 9081: 
 9082: 
 9083: =back
 9084: 
 9085: =head2 Course Modification
 9086: 
 9087: =over 4
 9088: 
 9089: =item *
 9090: 
 9091: writecoursepref($courseid,%prefs) : write preferences (environment
 9092: database) for a course
 9093: 
 9094: =item *
 9095: 
 9096: createcourse($udom,$description,$url) : make/modify course
 9097: 
 9098: =back
 9099: 
 9100: =head2 Resource Subroutines
 9101: 
 9102: =over 4
 9103: 
 9104: =item *
 9105: 
 9106: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9107: 
 9108: =item *
 9109: 
 9110: repcopy($filename) : subscribes to the requested file, and attempts to
 9111: replicate from the owning library server, Might return
 9112: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9113: 'bad_request', also attempts to grab the metadata for the
 9114: resource. Expects the local filesystem pathname
 9115: (/home/httpd/html/res/....)
 9116: 
 9117: =back
 9118: 
 9119: =head2 Resource Information
 9120: 
 9121: =over 4
 9122: 
 9123: =item *
 9124: 
 9125: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9126: a vairety of different possible values, $varname should be a request
 9127: string, and the other parameters can be used to specify who and what
 9128: one is asking about.
 9129: 
 9130: Possible values for $varname are environment.lastname (or other item
 9131: from the envirnment hash), user.name (or someother aspect about the
 9132: user), resource.0.maxtries (or some other part and parameter of a
 9133: resource)
 9134: 
 9135: =item *
 9136: 
 9137: directcondval($number) : get current value of a condition; reads from a state
 9138: string
 9139: 
 9140: =item *
 9141: 
 9142: condval($condidx) : value of condition index based on state
 9143: 
 9144: =item *
 9145: 
 9146: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9147: resource's metadata, $what should be either a specific key, or either
 9148: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9149: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9150: 
 9151: this function automatically caches all requests
 9152: 
 9153: =item *
 9154: 
 9155: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9156: network of library servers; returns file handle of where SQL and regex results
 9157: will be stored for query
 9158: 
 9159: =item *
 9160: 
 9161: symbread($filename) : return symbolic list entry (filename argument optional);
 9162: returns the data handle
 9163: 
 9164: =item *
 9165: 
 9166: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9167: a possible symb for the URL in $thisfn, and if is an encryypted
 9168: resource that the user accessed using /enc/ returns a 1 on success, 0
 9169: on failure, user must be in a course, as it assumes the existance of
 9170: the course initial hash, and uses $env('request.course.id'}
 9171: 
 9172: 
 9173: =item *
 9174: 
 9175: symbclean($symb) : removes versions numbers from a symb, returns the
 9176: cleaned symb
 9177: 
 9178: =item *
 9179: 
 9180: is_on_map($uri) : checks if the $uri is somewhere on the current
 9181: course map, user must be in a course for it to work.
 9182: 
 9183: =item *
 9184: 
 9185: numval($salt) : return random seed value (addend for rndseed)
 9186: 
 9187: =item *
 9188: 
 9189: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9190: a random seed, all arguments are optional, if they aren't sent it uses the
 9191: environment to derive them. Note: if symb isn't sent and it can't get one
 9192: from &symbread it will use the current time as its return value
 9193: 
 9194: =item *
 9195: 
 9196: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9197: unfakeable, receipt
 9198: 
 9199: =item *
 9200: 
 9201: receipt() : API to ireceipt working off of env values; given out to users
 9202: 
 9203: =item *
 9204: 
 9205: countacc($url) : count the number of accesses to a given URL
 9206: 
 9207: =item *
 9208: 
 9209: 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
 9210: 
 9211: =item *
 9212: 
 9213: 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)
 9214: 
 9215: =item *
 9216: 
 9217: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9218: 
 9219: =item *
 9220: 
 9221: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9222: forcing spreadsheet to reevaluate the resource scores next time.
 9223: 
 9224: =back
 9225: 
 9226: =head2 Storing/Retreiving Data
 9227: 
 9228: =over 4
 9229: 
 9230: =item *
 9231: 
 9232: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9233: for this url; hashref needs to be given and should be a \%hashname; the
 9234: remaining args aren't required and if they aren't passed or are '' they will
 9235: be derived from the env
 9236: 
 9237: =item *
 9238: 
 9239: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9240: uses critical subroutine
 9241: 
 9242: =item *
 9243: 
 9244: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9245: all args are optional
 9246: 
 9247: =item *
 9248: 
 9249: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9250: dumps the complete (or key matching regexp) namespace into a hash
 9251: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9252: normally &store()ed into
 9253: 
 9254: $range should be either an integer '100' (give me the first 100
 9255:                                            matching records)
 9256:               or be  two integers sperated by a - with no spaces
 9257:                  '30-50' (give me the 30th through the 50th matching
 9258:                           records)
 9259: 
 9260: 
 9261: =item *
 9262: 
 9263: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9264: replaces a &store() version of data with a replacement set of data
 9265: for a particular resource in a namespace passed in the $storehash hash 
 9266: reference
 9267: 
 9268: =item *
 9269: 
 9270: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9271: works very similar to store/cstore, but all data is stored in a
 9272: temporary location and can be reset using tmpreset, $storehash should
 9273: be a hash reference, returns nothing on success
 9274: 
 9275: =item *
 9276: 
 9277: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9278: similar to restore, but all data is stored in a temporary location and
 9279: can be reset using tmpreset. Returns a hash of values on success,
 9280: error string otherwise.
 9281: 
 9282: =item *
 9283: 
 9284: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9285: deltes all keys for $symb form the temporary storage hash.
 9286: 
 9287: =item *
 9288: 
 9289: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9290: reference filled in from namesp ($udom and $uname are optional)
 9291: 
 9292: =item *
 9293: 
 9294: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9295: namesp ($udom and $uname are optional)
 9296: 
 9297: =item *
 9298: 
 9299: dump($namespace,$udom,$uname,$regexp,$range) : 
 9300: dumps the complete (or key matching regexp) namespace into a hash
 9301: ($udom, $uname, $regexp, $range are optional)
 9302: 
 9303: $range should be either an integer '100' (give me the first 100
 9304:                                            matching records)
 9305:               or be  two integers sperated by a - with no spaces
 9306:                  '30-50' (give me the 30th through the 50th matching
 9307:                           records)
 9308: =item *
 9309: 
 9310: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9311: $store can be a scalar, an array reference, or if the amount to be 
 9312: incremented is > 1, a hash reference.
 9313: 
 9314: ($udom and $uname are optional)
 9315: 
 9316: =item *
 9317: 
 9318: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9319: ($udom and $uname are optional)
 9320: 
 9321: =item *
 9322: 
 9323: cput($namespace,$storehash,$udom,$uname) : critical put
 9324: ($udom and $uname are optional)
 9325: 
 9326: =item *
 9327: 
 9328: newput($namespace,$storehash,$udom,$uname) :
 9329: 
 9330: Attempts to store the items in the $storehash, but only if they don't
 9331: currently exist, if this succeeds you can be certain that you have 
 9332: successfully created a new key value pair in the $namespace db.
 9333: 
 9334: 
 9335: Args:
 9336:  $namespace: name of database to store values to
 9337:  $storehash: hashref to store to the db
 9338:  $udom: (optional) domain of user containing the db
 9339:  $uname: (optional) name of user caontaining the db
 9340: 
 9341: Returns:
 9342:  'ok' -> succeeded in storing all keys of $storehash
 9343:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9344:                         least <key> already existed in the db (other
 9345:                         requested keys may also already exist)
 9346:  'error: <msg>' -> unable to tie the DB or other erorr occured
 9347:  'con_lost' -> unable to contact request server
 9348:  'refused' -> action was not allowed by remote machine
 9349: 
 9350: 
 9351: =item *
 9352: 
 9353: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9354: reference filled in from namesp (encrypts the return communication)
 9355: ($udom and $uname are optional)
 9356: 
 9357: =item *
 9358: 
 9359: log($udom,$name,$home,$message) : write to permanent log for user; use
 9360: critical subroutine
 9361: 
 9362: =item *
 9363: 
 9364: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9365: array reference filled in from namespace found in domain level on either
 9366: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9367: 
 9368: =item *
 9369: 
 9370: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9371: domain level either on specified domain server ($uhome) or primary domain 
 9372: server ($udom and $uhome are optional)
 9373: 
 9374: =back
 9375: 
 9376: =head2 Network Status Functions
 9377: 
 9378: =over 4
 9379: 
 9380: =item *
 9381: 
 9382: dirlist($uri) : return directory list based on URI
 9383: 
 9384: =item *
 9385: 
 9386: spareserver() : find server with least workload from spare.tab
 9387: 
 9388: =back
 9389: 
 9390: =head2 Apache Request
 9391: 
 9392: =over 4
 9393: 
 9394: =item *
 9395: 
 9396: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9397: localhost, posts hash
 9398: 
 9399: =back
 9400: 
 9401: =head2 Data to String to Data
 9402: 
 9403: =over 4
 9404: 
 9405: =item *
 9406: 
 9407: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9408: and '&' separators, supports elements that are arrayrefs and hashrefs
 9409: 
 9410: =item *
 9411: 
 9412: hashref2str($hashref) : convert a hashref into a string complete with
 9413: escaping and '=' and '&' separators, supports elements that are
 9414: arrayrefs and hashrefs
 9415: 
 9416: =item *
 9417: 
 9418: arrayref2str($arrayref) : convert an arrayref into a string complete
 9419: with escaping and '&' separators, supports elements that are arrayrefs
 9420: and hashrefs
 9421: 
 9422: =item *
 9423: 
 9424: str2hash($string) : convert string to hash using unescaping and
 9425: splitting on '=' and '&', supports elements that are arrayrefs and
 9426: hashrefs
 9427: 
 9428: =item *
 9429: 
 9430: str2array($string) : convert string to hash using unescaping and
 9431: splitting on '&', supports elements that are arrayrefs and hashrefs
 9432: 
 9433: =back
 9434: 
 9435: =head2 Logging Routines
 9436: 
 9437: =over 4
 9438: 
 9439: These routines allow one to make log messages in the lonnet.log and
 9440: lonnet.perm logfiles.
 9441: 
 9442: =item *
 9443: 
 9444: logtouch() : make sure the logfile, lonnet.log, exists
 9445: 
 9446: =item *
 9447: 
 9448: logthis() : append message to the normal lonnet.log file, it gets
 9449: preiodically rolled over and deleted.
 9450: 
 9451: =item *
 9452: 
 9453: logperm() : append a permanent message to lonnet.perm.log, this log
 9454: file never gets deleted by any automated portion of the system, only
 9455: messages of critical importance should go in here.
 9456: 
 9457: =back
 9458: 
 9459: =head2 General File Helper Routines
 9460: 
 9461: =over 4
 9462: 
 9463: =item *
 9464: 
 9465: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9466: (a) files in /uploaded
 9467:   (i) If a local copy of the file exists - 
 9468:       compares modification date of local copy with last-modified date for 
 9469:       definitive version stored on home server for course. If local copy is 
 9470:       stale, requests a new version from the home server and stores it. 
 9471:       If the original has been removed from the home server, then local copy 
 9472:       is unlinked.
 9473:   (ii) If local copy does not exist -
 9474:       requests the file from the home server and stores it. 
 9475:   
 9476:   If $caller is 'uploadrep':  
 9477:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9478:     for request for files originally uploaded via DOCS. 
 9479:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9480:   
 9481:   Otherwise:
 9482:      This indicates a call from the content generation phase of the request.
 9483:      -  returns the entire contents of the file or -1.
 9484:      
 9485: (b) files in /res
 9486:    - returns the entire contents of a file or -1; 
 9487:    it properly subscribes to and replicates the file if neccessary.
 9488: 
 9489: 
 9490: =item *
 9491: 
 9492: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9493:                   reference
 9494: 
 9495: returns either a stat() list of data about the file or an empty list
 9496: if the file doesn't exist or couldn't find out about it (connection
 9497: problems or user unknown)
 9498: 
 9499: =item *
 9500: 
 9501: filelocation($dir,$file) : returns file system location of a file
 9502: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9503: directory that relative $file lookups are to looked in ($dir of /a/dir
 9504: and a file of ../bob will become /a/bob)
 9505: 
 9506: =item *
 9507: 
 9508: hreflocation($dir,$file) : returns file system location or a URL; same as
 9509: filelocation except for hrefs
 9510: 
 9511: =item *
 9512: 
 9513: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9514: 
 9515: =back
 9516: 
 9517: =head2 Usererfile file routines (/uploaded*)
 9518: 
 9519: =over 4
 9520: 
 9521: =item *
 9522: 
 9523: userfileupload(): main rotine for putting a file in a user or course's
 9524:                   filespace, arguments are,
 9525: 
 9526:  formname - required - this is the name of the element in $env where the
 9527:            filename, and the contents of the file to create/modifed exist
 9528:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9529:            contents of the file is located in $env{'form.'.$formname}
 9530:  coursedoc - if true, store the file in the course of the active role
 9531:              of the current user
 9532:  subdir - required - subdirectory to put the file in under ../userfiles/
 9533:          if undefined, it will be placed in "unknown"
 9534: 
 9535:  (This routine calls clean_filename() to remove any dangerous
 9536:  characters from the filename, and then calls finuserfileupload() to
 9537:  complete the transaction)
 9538: 
 9539:  returns either the url of the uploaded file (/uploaded/....) if successful
 9540:  and /adm/notfound.html if unsuccessful
 9541: 
 9542: =item *
 9543: 
 9544: clean_filename(): routine for cleaing a filename up for storage in
 9545:                  userfile space, argument is:
 9546: 
 9547:  filename - proposed filename
 9548: 
 9549: returns: the new clean filename
 9550: 
 9551: =item *
 9552: 
 9553: finishuserfileupload(): routine that creaes and sends the file to
 9554: userspace, probably shouldn't be called directly
 9555: 
 9556:   docuname: username or courseid of destination for the file
 9557:   docudom: domain of user/course of destination for the file
 9558:   formname: same as for userfileupload()
 9559:   fname: filename (inculding subdirectories) for the file
 9560: 
 9561:  returns either the url of the uploaded file (/uploaded/....) if successful
 9562:  and /adm/notfound.html if unsuccessful
 9563: 
 9564: =item *
 9565: 
 9566: renameuserfile(): renames an existing userfile to a new name
 9567: 
 9568:   Args:
 9569:    docuname: username or courseid of destination for the file
 9570:    docudom: domain of user/course of destination for the file
 9571:    old: current file name (including any subdirs under userfiles)
 9572:    new: desired file name (including any subdirs under userfiles)
 9573: 
 9574: =item *
 9575: 
 9576: mkdiruserfile(): creates a directory is a userfiles dir
 9577: 
 9578:   Args:
 9579:    docuname: username or courseid of destination for the file
 9580:    docudom: domain of user/course of destination for the file
 9581:    dir: dir to create (including any subdirs under userfiles)
 9582: 
 9583: =item *
 9584: 
 9585: removeuserfile(): removes a file that exists in userfiles
 9586: 
 9587:   Args:
 9588:    docuname: username or courseid of destination for the file
 9589:    docudom: domain of user/course of destination for the file
 9590:    fname: filname to delete (including any subdirs under userfiles)
 9591: 
 9592: =item *
 9593: 
 9594: removeuploadedurl(): convience function for removeuserfile()
 9595: 
 9596:   Args:
 9597:    url:  a full /uploaded/... url to delete
 9598: 
 9599: =item * 
 9600: 
 9601: get_portfile_permissions():
 9602:   Args:
 9603:     domain: domain of user or course contain the portfolio files
 9604:     user: name of user or num of course contain the portfolio files
 9605:   Returns:
 9606:     hashref of a dump of the proper file_permissions.db
 9607:    
 9608: 
 9609: =item * 
 9610: 
 9611: get_access_controls():
 9612: 
 9613: Args:
 9614:   current_permissions: the hash ref returned from get_portfile_permissions()
 9615:   group: (optional) the group you want the files associated with
 9616:   file: (optional) the file you want access info on
 9617: 
 9618: Returns:
 9619:     a hash (keys are file names) of hashes containing
 9620:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
 9621:         values are XML containing access control settings (see below) 
 9622: 
 9623: Internal notes:
 9624: 
 9625:  access controls are stored in file_permissions.db as key=value pairs.
 9626:     key -> path to file/file_name\0uniqueID:scope_end_start
 9627:         where scope -> public,guest,course,group,domains or users.
 9628:               end -> UNIX time for end of access (0 -> no end date)
 9629:               start -> UNIX time for start of access
 9630: 
 9631:     value -> XML description of access control
 9632:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
 9633:             <start></start>
 9634:             <end></end>
 9635: 
 9636:             <password></password>  for scope type = guest
 9637: 
 9638:             <domain></domain>     for scope type = course or group
 9639:             <number></number>
 9640:             <roles id="">
 9641:              <role></role>
 9642:              <access></access>
 9643:              <section></section>
 9644:              <group></group>
 9645:             </roles>
 9646: 
 9647:             <dom></dom>         for scope type = domains
 9648: 
 9649:             <users>             for scope type = users
 9650:              <user>
 9651:               <uname></uname>
 9652:               <udom></udom>
 9653:              </user>
 9654:             </users>
 9655:            </scope> 
 9656:               
 9657:  Access data is also aggregated for each file in an additional key=value pair:
 9658:  key -> path to file/file_name\0accesscontrol 
 9659:  value -> reference to hash
 9660:           hash contains key = value pairs
 9661:           where key = uniqueID:scope_end_start
 9662:                 value = UNIX time record was last updated
 9663: 
 9664:           Used to improve speed of look-ups of access controls for each file.  
 9665:  
 9666:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
 9667: 
 9668: modify_access_controls():
 9669: 
 9670: Modifies access controls for a portfolio file
 9671: Args
 9672: 1. file name
 9673: 2. reference to hash of required changes,
 9674: 3. domain
 9675: 4. username
 9676:   where domain,username are the domain of the portfolio owner 
 9677:   (either a user or a course) 
 9678: 
 9679: Returns:
 9680: 1. result of additions or updates ('ok' or 'error', with error message). 
 9681: 2. result of deletions ('ok' or 'error', with error message).
 9682: 3. reference to hash of any new or updated access controls.
 9683: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
 9684:    key = integer (inbound ID)
 9685:    value = uniqueID  
 9686: 
 9687: =back
 9688: 
 9689: =head2 HTTP Helper Routines
 9690: 
 9691: =over 4
 9692: 
 9693: =item *
 9694: 
 9695: escape() : unpack non-word characters into CGI-compatible hex codes
 9696: 
 9697: =item *
 9698: 
 9699: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
 9700: 
 9701: =back
 9702: 
 9703: =head1 PRIVATE SUBROUTINES
 9704: 
 9705: =head2 Underlying communication routines (Shouldn't call)
 9706: 
 9707: =over 4
 9708: 
 9709: =item *
 9710: 
 9711: subreply() : tries to pass a message to lonc, returns con_lost if incapable
 9712: 
 9713: =item *
 9714: 
 9715: reply() : uses subreply to send a message to remote machine, logs all failures
 9716: 
 9717: =item *
 9718: 
 9719: critical() : passes a critical message to another server; if cannot
 9720: get through then place message in connection buffer directory and
 9721: returns con_delayed, if incapable of saving message, returns
 9722: con_failed
 9723: 
 9724: =item *
 9725: 
 9726: reconlonc() : tries to reconnect lonc client processes.
 9727: 
 9728: =back
 9729: 
 9730: =head2 Resource Access Logging
 9731: 
 9732: =over 4
 9733: 
 9734: =item *
 9735: 
 9736: flushcourselogs() : flush (save) buffer logs and access logs
 9737: 
 9738: =item *
 9739: 
 9740: courselog($what) : save message for course in hash
 9741: 
 9742: =item *
 9743: 
 9744: courseacclog($what) : save message for course using &courselog().  Perform
 9745: special processing for specific resource types (problems, exams, quizzes, etc).
 9746: 
 9747: =item *
 9748: 
 9749: goodbye() : flush course logs and log shutting down; it is called in srm.conf
 9750: as a PerlChildExitHandler
 9751: 
 9752: =back
 9753: 
 9754: =head2 Other
 9755: 
 9756: =over 4
 9757: 
 9758: =item *
 9759: 
 9760: symblist($mapname,%newhash) : update symbolic storage links
 9761: 
 9762: =back
 9763: 
 9764: =cut
 9765: 

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