File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.976.2.5: download - view: text, annotated - select for diffs
Mon Jan 5 16:28:11 2009 UTC (15 years, 6 months ago) by raeburn
Branches: version_2_8_X
Diff to branchpoint 1.976: preferred, unified
- Backport 1.982.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.976.2.5 2009/01/05 16:28:11 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: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: # use Date::Parse;
   77: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   78:             $_64bit %env %protocol);
   79: 
   80: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   81:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   82:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   83:     %courseownerbuf, %coursetypebuf,$locknum);
   84: 
   85: use IO::Socket;
   86: use GDBM_File;
   87: use HTML::LCParser;
   88: use Fcntl qw(:flock);
   89: use Storable qw(thaw nfreeze);
   90: use Time::HiRes qw( gettimeofday tv_interval );
   91: use Cache::Memcached;
   92: use Digest::MD5;
   93: use Math::Random;
   94: use LONCAPA qw(:DEFAULT :match);
   95: use LONCAPA::Configuration;
   96: 
   97: my $readit;
   98: my $max_connection_retries = 10;     # Or some such value.
   99: 
  100: require Exporter;
  101: 
  102: our @ISA = qw (Exporter);
  103: our @EXPORT = qw(%env);
  104: 
  105: 
  106: # --------------------------------------------------------------------- Logging
  107: {
  108:     my $logid;
  109:     sub instructor_log {
  110: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  111:         if (($cnum eq '') || ($cdom eq '')) {
  112:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  113:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  114:         }
  115: 	$logid++;
  116:         my $now = time();
  117: 	my $id=$now.'00000'.$$.'00000'.$logid;
  118: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  119: 				    { $id => {
  120: 					'exe_uname' => $env{'user.name'},
  121: 					'exe_udom'  => $env{'user.domain'},
  122: 					'exe_time'  => $now,
  123: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  124: 					'delflag'   => $delflag,
  125: 					'logentry'  => $storehash,
  126: 					'uname'     => $uname,
  127: 					'udom'      => $udom,
  128: 				    }
  129: 				  },$cdom,$cnum);
  130:     }
  131: }
  132: 
  133: sub logtouch {
  134:     my $execdir=$perlvar{'lonDaemons'};
  135:     unless (-e "$execdir/logs/lonnet.log") {	
  136: 	open(my $fh,">>$execdir/logs/lonnet.log");
  137: 	close $fh;
  138:     }
  139:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  140:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  141: }
  142: 
  143: sub logthis {
  144:     my $message=shift;
  145:     my $execdir=$perlvar{'lonDaemons'};
  146:     my $now=time;
  147:     my $local=localtime($now);
  148:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  149: 	print $fh "$local ($$): $message\n";
  150: 	close($fh);
  151:     }
  152:     return 1;
  153: }
  154: 
  155: sub logperm {
  156:     my $message=shift;
  157:     my $execdir=$perlvar{'lonDaemons'};
  158:     my $now=time;
  159:     my $local=localtime($now);
  160:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  161: 	print $fh "$now:$message:$local\n";
  162: 	close($fh);
  163:     }
  164:     return 1;
  165: }
  166: 
  167: sub create_connection {
  168:     my ($hostname,$lonid) = @_;
  169:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  170: 				     Type    => SOCK_STREAM,
  171: 				     Timeout => 10);
  172:     return 0 if (!$client);
  173:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  174:     my $result = <$client>;
  175:     chomp($result);
  176:     return 1 if ($result eq 'done');
  177:     return 0;
  178: }
  179: 
  180: 
  181: # -------------------------------------------------- Non-critical communication
  182: sub subreply {
  183:     my ($cmd,$server)=@_;
  184:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  185:     #
  186:     #  With loncnew process trimming, there's a timing hole between lonc server
  187:     #  process exit and the master server picking up the listen on the AF_UNIX
  188:     #  socket.  In that time interval, a lock file will exist:
  189: 
  190:     my $lockfile=$peerfile.".lock";
  191:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  192: 	sleep(1);
  193:     }
  194:     # At this point, either a loncnew parent is listening or an old lonc
  195:     # or loncnew child is listening so we can connect or everything's dead.
  196:     #
  197:     #   We'll give the connection a few tries before abandoning it.  If
  198:     #   connection is not possible, we'll con_lost back to the client.
  199:     #   
  200:     my $client;
  201:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  202: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  203: 				      Type    => SOCK_STREAM,
  204: 				      Timeout => 10);
  205: 	if ($client) {
  206: 	    last;		# Connected!
  207: 	} else {
  208: 	    &create_connection(&hostname($server),$server);
  209: 	}
  210:         sleep(1);		# Try again later if failed connection.
  211:     }
  212:     my $answer;
  213:     if ($client) {
  214: 	print $client "sethost:$server:$cmd\n";
  215: 	$answer=<$client>;
  216: 	if (!$answer) { $answer="con_lost"; }
  217: 	chomp($answer);
  218:     } else {
  219: 	$answer = 'con_lost';	# Failed connection.
  220:     }
  221:     return $answer;
  222: }
  223: 
  224: sub reply {
  225:     my ($cmd,$server)=@_;
  226:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  227:     my $answer=subreply($cmd,$server);
  228:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  229:        &logthis("<font color=\"blue\">WARNING:".
  230:                 " $cmd to $server returned $answer</font>");
  231:     }
  232:     return $answer;
  233: }
  234: 
  235: # ----------------------------------------------------------- Send USR1 to lonc
  236: 
  237: sub reconlonc {
  238:     my ($lonid) = @_;
  239:     my $hostname = &hostname($lonid);
  240:     if ($lonid) {
  241: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  242: 	if ($hostname && -e $peerfile) {
  243: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  244: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  245: 					     Type    => SOCK_STREAM,
  246: 					     Timeout => 10);
  247: 	    if ($client) {
  248: 		print $client ("reset_retries\n");
  249: 		my $answer=<$client>;
  250: 		#reset just this one.
  251: 	    }
  252: 	}
  253: 	return;
  254:     }
  255: 
  256:     &logthis("Trying to reconnect lonc");
  257:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  258:     if (open(my $fh,"<$loncfile")) {
  259: 	my $loncpid=<$fh>;
  260:         chomp($loncpid);
  261:         if (kill 0 => $loncpid) {
  262: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  263:             kill USR1 => $loncpid;
  264:             sleep 1;
  265:          } else {
  266: 	    &logthis(
  267:                "<font color=\"blue\">WARNING:".
  268:                " lonc at pid $loncpid not responding, giving up</font>");
  269:         }
  270:     } else {
  271: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  272:     }
  273: }
  274: 
  275: # ------------------------------------------------------ Critical communication
  276: 
  277: sub critical {
  278:     my ($cmd,$server)=@_;
  279:     unless (&hostname($server)) {
  280:         &logthis("<font color=\"blue\">WARNING:".
  281:                " Critical message to unknown server ($server)</font>");
  282:         return 'no_such_host';
  283:     }
  284:     my $answer=reply($cmd,$server);
  285:     if ($answer eq 'con_lost') {
  286: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  287: 	my $answer=reply($cmd,$server);
  288:         if ($answer eq 'con_lost') {
  289:             my $now=time;
  290:             my $middlename=$cmd;
  291:             $middlename=substr($middlename,0,16);
  292:             $middlename=~s/\W//g;
  293:             my $dfilename=
  294:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  295:             $dumpcount++;
  296:             {
  297: 		my $dfh;
  298: 		if (open($dfh,">$dfilename")) {
  299: 		    print $dfh "$cmd\n"; 
  300: 		    close($dfh);
  301: 		}
  302:             }
  303:             sleep 2;
  304:             my $wcmd='';
  305:             {
  306: 		my $dfh;
  307: 		if (open($dfh,"<$dfilename")) {
  308: 		    $wcmd=<$dfh>; 
  309: 		    close($dfh);
  310: 		}
  311:             }
  312:             chomp($wcmd);
  313:             if ($wcmd eq $cmd) {
  314: 		&logthis("<font color=\"blue\">WARNING: ".
  315:                          "Connection buffer $dfilename: $cmd</font>");
  316:                 &logperm("D:$server:$cmd");
  317: 	        return 'con_delayed';
  318:             } else {
  319:                 &logthis("<font color=\"red\">CRITICAL:"
  320:                         ." Critical connection failed: $server $cmd</font>");
  321:                 &logperm("F:$server:$cmd");
  322:                 return 'con_failed';
  323:             }
  324:         }
  325:     }
  326:     return $answer;
  327: }
  328: 
  329: # ------------------------------------------- check if return value is an error
  330: 
  331: sub error {
  332:     my ($result) = @_;
  333:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  334: 	if ($2 == 2) { return undef; }
  335: 	return $1;
  336:     }
  337:     return undef;
  338: }
  339: 
  340: sub convert_and_load_session_env {
  341:     my ($lonidsdir,$handle)=@_;
  342:     my @profile;
  343:     {
  344: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  345: 	if (!$opened) {
  346: 	    return 0;
  347: 	}
  348: 	flock($idf,LOCK_SH);
  349: 	@profile=<$idf>;
  350: 	close($idf);
  351:     }
  352:     my %temp_env;
  353:     foreach my $line (@profile) {
  354: 	if ($line !~ m/=/) {
  355: 	    return 0;
  356: 	}
  357: 	chomp($line);
  358: 	my ($envname,$envvalue)=split(/=/,$line,2);
  359: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  360:     }
  361:     unlink("$lonidsdir/$handle.id");
  362:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  363: 	    0640)) {
  364: 	%disk_env = %temp_env;
  365: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  366: 	untie(%disk_env);
  367:     }
  368:     return 1;
  369: }
  370: 
  371: # ------------------------------------------- Transfer profile into environment
  372: my $env_loaded;
  373: sub transfer_profile_to_env {
  374:     my ($lonidsdir,$handle,$force_transfer) = @_;
  375:     if (!$force_transfer && $env_loaded) { return; } 
  376: 
  377:     if (!defined($lonidsdir)) {
  378: 	$lonidsdir = $perlvar{'lonIDsDir'};
  379:     }
  380:     if (!defined($handle)) {
  381:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  382:     }
  383: 
  384:     my $convert;
  385:     {
  386:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  387: 	if (!$opened) {
  388: 	    return;
  389: 	}
  390: 	flock($idf,LOCK_SH);
  391: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  392: 		&GDBM_READER(),0640)) {
  393: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  394: 	    untie(%disk_env);
  395: 	} else {
  396: 	    $convert = 1;
  397: 	}
  398:     }
  399:     if ($convert) {
  400: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  401: 	    &logthis("Failed to load session, or convert session.");
  402: 	}
  403:     }
  404: 
  405:     my %remove;
  406:     while ( my $envname = each(%env) ) {
  407:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  408:             if ($time < time-300) {
  409:                 $remove{$key}++;
  410:             }
  411:         }
  412:     }
  413: 
  414:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  415:     $env_loaded=1;
  416:     foreach my $expired_key (keys(%remove)) {
  417:         &delenv($expired_key);
  418:     }
  419: }
  420: 
  421: # ---------------------------------------------------- Check for valid session 
  422: sub check_for_valid_session {
  423:     my ($r) = @_;
  424:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  425:     my $lonid=$cookies{'lonID'};
  426:     return undef if (!$lonid);
  427: 
  428:     my $handle=&LONCAPA::clean_handle($lonid->value);
  429:     my $lonidsdir=$r->dir_config('lonIDsDir');
  430:     return undef if (!-e "$lonidsdir/$handle.id");
  431: 
  432:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  433:     return undef if (!$opened);
  434: 
  435:     flock($idf,LOCK_SH);
  436:     my %disk_env;
  437:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  438: 	    &GDBM_READER(),0640)) {
  439: 	return undef;	
  440:     }
  441: 
  442:     if (!defined($disk_env{'user.name'})
  443: 	|| !defined($disk_env{'user.domain'})) {
  444: 	return undef;
  445:     }
  446:     return $handle;
  447: }
  448: 
  449: sub timed_flock {
  450:     my ($file,$lock_type) = @_;
  451:     my $failed=0;
  452:     eval {
  453: 	local $SIG{__DIE__}='DEFAULT';
  454: 	local $SIG{ALRM}=sub {
  455: 	    $failed=1;
  456: 	    die("failed lock");
  457: 	};
  458: 	alarm(13);
  459: 	flock($file,$lock_type);
  460: 	alarm(0);
  461:     };
  462:     if ($failed) {
  463: 	return undef;
  464:     } else {
  465: 	return 1;
  466:     }
  467: }
  468: 
  469: # ---------------------------------------------------------- Append Environment
  470: 
  471: sub appenv {
  472:     my ($newenv,$roles) = @_;
  473:     if (ref($newenv) eq 'HASH') {
  474:         foreach my $key (keys(%{$newenv})) {
  475:             my $refused = 0;
  476: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  477:                 $refused = 1;
  478:                 if (ref($roles) eq 'ARRAY') {
  479:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  480:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  481:                         $refused = 0;
  482:                     }
  483:                 }
  484:             }
  485:             if ($refused) {
  486:                 &logthis("<font color=\"blue\">WARNING: ".
  487:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  488:                          .'</font>');
  489: 	        delete($newenv->{$key});
  490:             } else {
  491:                 $env{$key}=$newenv->{$key};
  492:             }
  493:         }
  494:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  495:         if ($opened
  496: 	    && &timed_flock($env_file,LOCK_EX)
  497: 	    &&
  498: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  499: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  500: 	    while (my ($key,$value) = each(%{$newenv})) {
  501: 	        $disk_env{$key} = $value;
  502: 	    }
  503: 	    untie(%disk_env);
  504:         }
  505:     }
  506:     return 'ok';
  507: }
  508: # ----------------------------------------------------- Delete from Environment
  509: 
  510: sub delenv {
  511:     my $delthis=shift;
  512:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  513:         &logthis("<font color=\"blue\">WARNING: ".
  514:                 "Attempt to delete from environment ".$delthis);
  515:         return 'error';
  516:     }
  517:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  518:     if ($opened
  519: 	&& &timed_flock($env_file,LOCK_EX)
  520: 	&&
  521: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  522: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  523: 	foreach my $key (keys(%disk_env)) {
  524: 	    if ($key=~/^\Q$delthis\E/) { 
  525: 		delete($env{$key});
  526: 		delete($disk_env{$key});
  527: 	    }
  528: 	}
  529: 	untie(%disk_env);
  530:     }
  531:     return 'ok';
  532: }
  533: 
  534: sub get_env_multiple {
  535:     my ($name) = @_;
  536:     my @values;
  537:     if (defined($env{$name})) {
  538:         # exists is it an array
  539:         if (ref($env{$name})) {
  540:             @values=@{ $env{$name} };
  541:         } else {
  542:             $values[0]=$env{$name};
  543:         }
  544:     }
  545:     return(@values);
  546: }
  547: 
  548: # ------------------------------------------------------------------- Locking
  549: 
  550: sub set_lock {
  551:     my ($text)=@_;
  552:     $locknum++;
  553:     my $id=$$.'-'.$locknum;
  554:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  555:              'session.lock.'.$id => $text});
  556:     return $id;
  557: }
  558: 
  559: sub get_locks {
  560:     my $num=0;
  561:     my %texts=();
  562:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  563:        if ($lock=~/\w/) {
  564:           $num++;
  565:           $texts{$lock}=$env{'session.lock.'.$lock};
  566:        }
  567:    }
  568:    return ($num,%texts);
  569: }
  570: 
  571: sub remove_lock {
  572:     my ($id)=@_;
  573:     my $newlocks='';
  574:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  575:        if (($lock=~/\w/) && ($lock ne $id)) {
  576:           $newlocks.=','.$lock;
  577:        }
  578:     }
  579:     &appenv({'session.locks' => $newlocks});
  580:     &delenv('session.lock.'.$id);
  581: }
  582: 
  583: sub remove_all_locks {
  584:     my $activelocks=$env{'session.locks'};
  585:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  586:        if ($lock=~/\w/) {
  587:           &remove_lock($lock);
  588:        }
  589:     }
  590: }
  591: 
  592: 
  593: # ------------------------------------------ Find out current server userload
  594: sub userload {
  595:     my $numusers=0;
  596:     {
  597: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  598: 	my $filename;
  599: 	my $curtime=time;
  600: 	while ($filename=readdir(LONIDS)) {
  601: 	    next if ($filename eq '.' || $filename eq '..');
  602: 	    next if ($filename =~ /publicuser_\d+\.id/);
  603: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  604: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  605: 	}
  606: 	closedir(LONIDS);
  607:     }
  608:     my $userloadpercent=0;
  609:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  610:     if ($maxuserload) {
  611: 	$userloadpercent=100*$numusers/$maxuserload;
  612:     }
  613:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  614:     return $userloadpercent;
  615: }
  616: 
  617: # ------------------------------------------ Fight off request when overloaded
  618: 
  619: sub overloaderror {
  620:     my ($r,$checkserver)=@_;
  621:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  622:     my $loadavg;
  623:     if ($checkserver eq $perlvar{'lonHostID'}) {
  624:        open(my $loadfile,'/proc/loadavg');
  625:        $loadavg=<$loadfile>;
  626:        $loadavg =~ s/\s.*//g;
  627:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  628:        close($loadfile);
  629:     } else {
  630:        $loadavg=&reply('load',$checkserver);
  631:     }
  632:     my $overload=$loadavg-100;
  633:     if ($overload>0) {
  634: 	$r->err_headers_out->{'Retry-After'}=$overload;
  635:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  636:         return 413;
  637:     }    
  638:     return '';
  639: }
  640: 
  641: # ------------------------------ Find server with least workload from spare.tab
  642: 
  643: sub spareserver {
  644:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  645:     my $spare_server;
  646:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  647:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  648:                                                      :  $userloadpercent;
  649:     
  650:     foreach my $try_server (@{ $spareid{'primary'} }) {
  651: 	($spare_server, $lowest_load) =
  652: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  653:     }
  654: 
  655:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  656: 
  657:     if (!$found_server) {
  658: 	foreach my $try_server (@{ $spareid{'default'} }) {
  659: 	    ($spare_server, $lowest_load) =
  660: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  661: 	}
  662:     }
  663: 
  664:     if (!$want_server_name) {
  665:         my $protocol = 'http';
  666:         if ($protocol{$spare_server} eq 'https') {
  667:             $protocol = $protocol{$spare_server};
  668:         }
  669: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  670:     }
  671:     return $spare_server;
  672: }
  673: 
  674: sub compare_server_load {
  675:     my ($try_server, $spare_server, $lowest_load) = @_;
  676: 
  677:     my $loadans     = &reply('load',    $try_server);
  678:     my $userloadans = &reply('userload',$try_server);
  679: 
  680:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  681: 	next; #didn't get a number from the server
  682:     }
  683: 
  684:     my $load;
  685:     if ($loadans =~ /\d/) {
  686: 	if ($userloadans =~ /\d/) {
  687: 	    #both are numbers, pick the bigger one
  688: 	    $load = ($loadans > $userloadans) ? $loadans 
  689: 		                              : $userloadans;
  690: 	} else {
  691: 	    $load = $loadans;
  692: 	}
  693:     } else {
  694: 	$load = $userloadans;
  695:     }
  696: 
  697:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  698: 	$spare_server = $try_server;
  699: 	$lowest_load  = $load;
  700:     }
  701:     return ($spare_server,$lowest_load);
  702: }
  703: 
  704: # --------------------------- ask offload servers if user already has a session
  705: sub find_existing_session {
  706:     my ($udom,$uname) = @_;
  707:     foreach my $try_server (@{ $spareid{'primary'} },
  708: 			    @{ $spareid{'default'} }) {
  709: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  710:     }
  711:     return;
  712: }
  713: 
  714: # -------------------------------- ask if server already has a session for user
  715: sub has_user_session {
  716:     my ($lonid,$udom,$uname) = @_;
  717:     my $result = &reply(join(':','userhassession',
  718: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  719:     return 1 if ($result eq 'ok');
  720: 
  721:     return 0;
  722: }
  723: 
  724: # --------------------------------------------- Try to change a user's password
  725: 
  726: sub changepass {
  727:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  728:     $currentpass = &escape($currentpass);
  729:     $newpass     = &escape($newpass);
  730:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  731: 		       $server);
  732:     if (! $answer) {
  733: 	&logthis("No reply on password change request to $server ".
  734: 		 "by $uname in domain $udom.");
  735:     } elsif ($answer =~ "^ok") {
  736:         &logthis("$uname in $udom successfully changed their password ".
  737: 		 "on $server.");
  738:     } elsif ($answer =~ "^pwchange_failure") {
  739: 	&logthis("$uname in $udom was unable to change their password ".
  740: 		 "on $server.  The action was blocked by either lcpasswd ".
  741: 		 "or pwchange");
  742:     } elsif ($answer =~ "^non_authorized") {
  743:         &logthis("$uname in $udom did not get their password correct when ".
  744: 		 "attempting to change it on $server.");
  745:     } elsif ($answer =~ "^auth_mode_error") {
  746:         &logthis("$uname in $udom attempted to change their password despite ".
  747: 		 "not being locally or internally authenticated on $server.");
  748:     } elsif ($answer =~ "^unknown_user") {
  749:         &logthis("$uname in $udom attempted to change their password ".
  750: 		 "on $server but were unable to because $server is not ".
  751: 		 "their home server.");
  752:     } elsif ($answer =~ "^refused") {
  753: 	&logthis("$server refused to change $uname in $udom password because ".
  754: 		 "it was sent an unencrypted request to change the password.");
  755:     }
  756:     return $answer;
  757: }
  758: 
  759: # ----------------------- Try to determine user's current authentication scheme
  760: 
  761: sub queryauthenticate {
  762:     my ($uname,$udom)=@_;
  763:     my $uhome=&homeserver($uname,$udom);
  764:     if (!$uhome) {
  765: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  766: 	return 'no_host';
  767:     }
  768:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  769:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  770: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  771:     }
  772:     return $answer;
  773: }
  774: 
  775: # --------- Try to authenticate user from domain's lib servers (first this one)
  776: 
  777: sub authenticate {
  778:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  779:     $upass=&escape($upass);
  780:     $uname= &LONCAPA::clean_username($uname);
  781:     my $uhome=&homeserver($uname,$udom,1);
  782:     my $newhome;
  783:     if ((!$uhome) || ($uhome eq 'no_host')) {
  784: # Maybe the machine was offline and only re-appeared again recently?
  785:         &reconlonc();
  786: # One more
  787: 	$uhome=&homeserver($uname,$udom,1);
  788:         if (($uhome eq 'no_host') && $checkdefauth) {
  789:             if (defined(&domain($udom,'primary'))) {
  790:                 $newhome=&domain($udom,'primary');
  791:             }
  792:             if ($newhome ne '') {
  793:                 $uhome = $newhome;
  794:             }
  795:         }
  796: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  797: 	    &logthis("User $uname at $udom is unknown in authenticate");
  798: 	    return 'no_host';
  799:         }
  800:     }
  801:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  802:     if ($answer eq 'authorized') {
  803:         if ($newhome) {
  804:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  805:             return 'no_account_on_host'; 
  806:         } else {
  807:             &logthis("User $uname at $udom authorized by $uhome");
  808:             return $uhome;
  809:         }
  810:     }
  811:     if ($answer eq 'non_authorized') {
  812: 	&logthis("User $uname at $udom rejected by $uhome");
  813: 	return 'no_host'; 
  814:     }
  815:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  816:     return 'no_host';
  817: }
  818: 
  819: # ---------------------- Find the homebase for a user from domain's lib servers
  820: 
  821: my %homecache;
  822: sub homeserver {
  823:     my ($uname,$udom,$ignoreBadCache)=@_;
  824:     my $index="$uname:$udom";
  825: 
  826:     if (exists($homecache{$index})) { return $homecache{$index}; }
  827: 
  828:     my %servers = &get_servers($udom,'library');
  829:     foreach my $tryserver (keys(%servers)) {
  830:         next if ($ignoreBadCache ne 'true' && 
  831: 		 exists($badServerCache{$tryserver}));
  832: 
  833: 	my $answer=reply("home:$udom:$uname",$tryserver);
  834: 	if ($answer eq 'found') {
  835: 	    delete($badServerCache{$tryserver}); 
  836: 	    return $homecache{$index}=$tryserver;
  837: 	} elsif ($answer eq 'no_host') {
  838: 	    $badServerCache{$tryserver}=1;
  839: 	}
  840:     }    
  841:     return 'no_host';
  842: }
  843: 
  844: # ------------------------------------- Find the usernames behind a list of IDs
  845: 
  846: sub idget {
  847:     my ($udom,@ids)=@_;
  848:     my %returnhash=();
  849:     
  850:     my %servers = &get_servers($udom,'library');
  851:     foreach my $tryserver (keys(%servers)) {
  852: 	my $idlist=join('&',@ids);
  853: 	$idlist=~tr/A-Z/a-z/; 
  854: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  855: 	my @answer=();
  856: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  857: 	    @answer=split(/\&/,$reply);
  858: 	}                    ;
  859: 	my $i;
  860: 	for ($i=0;$i<=$#ids;$i++) {
  861: 	    if ($answer[$i]) {
  862: 		$returnhash{$ids[$i]}=$answer[$i];
  863: 	    } 
  864: 	}
  865:     } 
  866:     return %returnhash;
  867: }
  868: 
  869: # ------------------------------------- Find the IDs behind a list of usernames
  870: 
  871: sub idrget {
  872:     my ($udom,@unames)=@_;
  873:     my %returnhash=();
  874:     foreach my $uname (@unames) {
  875:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  876:     }
  877:     return %returnhash;
  878: }
  879: 
  880: # ------------------------------- Store away a list of names and associated IDs
  881: 
  882: sub idput {
  883:     my ($udom,%ids)=@_;
  884:     my %servers=();
  885:     foreach my $uname (keys(%ids)) {
  886: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  887:         my $uhom=&homeserver($uname,$udom);
  888:         if ($uhom ne 'no_host') {
  889:             my $id=&escape($ids{$uname});
  890:             $id=~tr/A-Z/a-z/;
  891:             my $esc_unam=&escape($uname);
  892: 	    if ($servers{$uhom}) {
  893: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  894:             } else {
  895:                 $servers{$uhom}=$id.'='.$esc_unam;
  896:             }
  897:         }
  898:     }
  899:     foreach my $server (keys(%servers)) {
  900:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  901:     }
  902: }
  903: 
  904: # ------------------------------------------- get items from domain db files   
  905: 
  906: sub get_dom {
  907:     my ($namespace,$storearr,$udom,$uhome)=@_;
  908:     my $items='';
  909:     foreach my $item (@$storearr) {
  910:         $items.=&escape($item).'&';
  911:     }
  912:     $items=~s/\&$//;
  913:     if (!$udom) {
  914:         $udom=$env{'user.domain'};
  915:         if (defined(&domain($udom,'primary'))) {
  916:             $uhome=&domain($udom,'primary');
  917:         } else {
  918:             undef($uhome);
  919:         }
  920:     } else {
  921:         if (!$uhome) {
  922:             if (defined(&domain($udom,'primary'))) {
  923:                 $uhome=&domain($udom,'primary');
  924:             }
  925:         }
  926:     }
  927:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  928:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  929:         my %returnhash;
  930:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  931:             return %returnhash;
  932:         }
  933:         my @pairs=split(/\&/,$rep);
  934:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  935:             return @pairs;
  936:         }
  937:         my $i=0;
  938:         foreach my $item (@$storearr) {
  939:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  940:             $i++;
  941:         }
  942:         return %returnhash;
  943:     } else {
  944:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  945:     }
  946: }
  947: 
  948: # -------------------------------------------- put items in domain db files 
  949: 
  950: sub put_dom {
  951:     my ($namespace,$storehash,$udom,$uhome)=@_;
  952:     if (!$udom) {
  953:         $udom=$env{'user.domain'};
  954:         if (defined(&domain($udom,'primary'))) {
  955:             $uhome=&domain($udom,'primary');
  956:         } else {
  957:             undef($uhome);
  958:         }
  959:     } else {
  960:         if (!$uhome) {
  961:             if (defined(&domain($udom,'primary'))) {
  962:                 $uhome=&domain($udom,'primary');
  963:             }
  964:         }
  965:     } 
  966:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  967:         my $items='';
  968:         foreach my $item (keys(%$storehash)) {
  969:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  970:         }
  971:         $items=~s/\&$//;
  972:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  973:     } else {
  974:         &logthis("put_dom failed - no homeserver and/or domain");
  975:     }
  976: }
  977: 
  978: sub retrieve_inst_usertypes {
  979:     my ($udom) = @_;
  980:     my (%returnhash,@order);
  981:     if (defined(&domain($udom,'primary'))) {
  982:         my $uhome=&domain($udom,'primary');
  983:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  984:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
  985:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
  986:             return (\%returnhash,\@order);
  987:         }
  988:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  989:         my @pairs=split(/\&/,$hashitems);
  990:         foreach my $item (@pairs) {
  991:             my ($key,$value)=split(/=/,$item,2);
  992:             $key = &unescape($key);
  993:             next if ($key =~ /^error: 2 /);
  994:             $returnhash{$key}=&thaw_unescape($value);
  995:         }
  996:         my @esc_order = split(/\&/,$orderitems);
  997:         foreach my $item (@esc_order) {
  998:             push(@order,&unescape($item));
  999:         }
 1000:     } else {
 1001:         &logthis("get_dom failed - no primary domain server for $udom");
 1002:     }
 1003:     return (\%returnhash,\@order);
 1004: }
 1005: 
 1006: sub is_domainimage {
 1007:     my ($url) = @_;
 1008:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1009:         if (&domain($1) ne '') {
 1010:             return '1';
 1011:         }
 1012:     }
 1013:     return;
 1014: }
 1015: 
 1016: sub inst_directory_query {
 1017:     my ($srch) = @_;
 1018:     my $udom = $srch->{'srchdomain'};
 1019:     my %results;
 1020:     my $homeserver = &domain($udom,'primary');
 1021:     my $outcome;
 1022:     if ($homeserver ne '') {
 1023: 	my $queryid=&reply("querysend:instdirsearch:".
 1024: 			   &escape($srch->{'srchby'}).':'.
 1025: 			   &escape($srch->{'srchterm'}).':'.
 1026: 			   &escape($srch->{'srchtype'}),$homeserver);
 1027: 	my $host=&hostname($homeserver);
 1028: 	if ($queryid !~/^\Q$host\E\_/) {
 1029: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1030: 	    return;
 1031: 	}
 1032: 	my $response = &get_query_reply($queryid);
 1033: 	my $maxtries = 5;
 1034: 	my $tries = 1;
 1035: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1036: 	    $response = &get_query_reply($queryid);
 1037: 	    $tries ++;
 1038: 	}
 1039: 
 1040:         if (!&error($response) && $response ne 'refused') {
 1041:             if ($response eq 'unavailable') {
 1042:                 $outcome = $response;
 1043:             } else {
 1044:                 $outcome = 'ok';
 1045:                 my @matches = split(/\n/,$response);
 1046:                 foreach my $match (@matches) {
 1047:                     my ($key,$value) = split(/=/,$match);
 1048:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1049:                 }
 1050:             }
 1051:         }
 1052:     }
 1053:     return ($outcome,%results);
 1054: }
 1055: 
 1056: sub usersearch {
 1057:     my ($srch) = @_;
 1058:     my $dom = $srch->{'srchdomain'};
 1059:     my %results;
 1060:     my %libserv = &all_library();
 1061:     my $query = 'usersearch';
 1062:     foreach my $tryserver (keys(%libserv)) {
 1063:         if (&host_domain($tryserver) eq $dom) {
 1064:             my $host=&hostname($tryserver);
 1065:             my $queryid=
 1066:                 &reply("querysend:".&escape($query).':'.
 1067:                        &escape($srch->{'srchby'}).':'.
 1068:                        &escape($srch->{'srchtype'}).':'.
 1069:                        &escape($srch->{'srchterm'}),$tryserver);
 1070:             if ($queryid !~/^\Q$host\E\_/) {
 1071:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1072:                 next;
 1073:             }
 1074:             my $reply = &get_query_reply($queryid);
 1075:             my $maxtries = 1;
 1076:             my $tries = 1;
 1077:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1078:                 $reply = &get_query_reply($queryid);
 1079:                 $tries ++;
 1080:             }
 1081:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1082:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1083:             } else {
 1084:                 my @matches;
 1085:                 if ($reply =~ /\n/) {
 1086:                     @matches = split(/\n/,$reply);
 1087:                 } else {
 1088:                     @matches = split(/\&/,$reply);
 1089:                 }
 1090:                 foreach my $match (@matches) {
 1091:                     my ($uname,$udom,%userhash);
 1092:                     foreach my $entry (split(/:/,$match)) {
 1093:                         my ($key,$value) =
 1094:                             map {&unescape($_);} split(/=/,$entry);
 1095:                         $userhash{$key} = $value;
 1096:                         if ($key eq 'username') {
 1097:                             $uname = $value;
 1098:                         } elsif ($key eq 'domain') {
 1099:                             $udom = $value;
 1100:                         }
 1101:                     }
 1102:                     $results{$uname.':'.$udom} = \%userhash;
 1103:                 }
 1104:             }
 1105:         }
 1106:     }
 1107:     return %results;
 1108: }
 1109: 
 1110: sub get_instuser {
 1111:     my ($udom,$uname,$id) = @_;
 1112:     my $homeserver = &domain($udom,'primary');
 1113:     my ($outcome,%results);
 1114:     if ($homeserver ne '') {
 1115:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1116:                            &escape($id).':'.&escape($udom),$homeserver);
 1117:         my $host=&hostname($homeserver);
 1118:         if ($queryid !~/^\Q$host\E\_/) {
 1119:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1120:             return;
 1121:         }
 1122:         my $response = &get_query_reply($queryid);
 1123:         my $maxtries = 5;
 1124:         my $tries = 1;
 1125:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1126:             $response = &get_query_reply($queryid);
 1127:             $tries ++;
 1128:         }
 1129:         if (!&error($response) && $response ne 'refused') {
 1130:             if ($response eq 'unavailable') {
 1131:                 $outcome = $response;
 1132:             } else {
 1133:                 $outcome = 'ok';
 1134:                 my @matches = split(/\n/,$response);
 1135:                 foreach my $match (@matches) {
 1136:                     my ($key,$value) = split(/=/,$match);
 1137:                     $results{&unescape($key)} = &thaw_unescape($value);
 1138:                 }
 1139:             }
 1140:         }
 1141:     }
 1142:     my %userinfo;
 1143:     if (ref($results{$uname}) eq 'HASH') {
 1144:         %userinfo = %{$results{$uname}};
 1145:     } 
 1146:     return ($outcome,%userinfo);
 1147: }
 1148: 
 1149: sub inst_rulecheck {
 1150:     my ($udom,$uname,$id,$item,$rules) = @_;
 1151:     my %returnhash;
 1152:     if ($udom ne '') {
 1153:         if (ref($rules) eq 'ARRAY') {
 1154:             @{$rules} = map {&escape($_);} (@{$rules});
 1155:             my $rulestr = join(':',@{$rules});
 1156:             my $homeserver=&domain($udom,'primary');
 1157:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1158:                 my $response;
 1159:                 if ($item eq 'username') {                
 1160:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1161:                                               ':'.&escape($uname).':'.$rulestr,
 1162:                                               $homeserver));
 1163:                 } elsif ($item eq 'id') {
 1164:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1165:                                               ':'.&escape($id).':'.$rulestr,
 1166:                                               $homeserver));
 1167:                 } elsif ($item eq 'selfcreate') {
 1168:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1169:                                                &escape($udom).':'.&escape($uname).
 1170:                                               ':'.$rulestr,$homeserver));
 1171:                 }
 1172:                 if ($response ne 'refused') {
 1173:                     my @pairs=split(/\&/,$response);
 1174:                     foreach my $item (@pairs) {
 1175:                         my ($key,$value)=split(/=/,$item,2);
 1176:                         $key = &unescape($key);
 1177:                         next if ($key =~ /^error: 2 /);
 1178:                         $returnhash{$key}=&thaw_unescape($value);
 1179:                     }
 1180:                 }
 1181:             }
 1182:         }
 1183:     }
 1184:     return %returnhash;
 1185: }
 1186: 
 1187: sub inst_userrules {
 1188:     my ($udom,$check) = @_;
 1189:     my (%ruleshash,@ruleorder);
 1190:     if ($udom ne '') {
 1191:         my $homeserver=&domain($udom,'primary');
 1192:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1193:             my $response;
 1194:             if ($check eq 'id') {
 1195:                 $response=&reply('instidrules:'.&escape($udom),
 1196:                                  $homeserver);
 1197:             } elsif ($check eq 'email') {
 1198:                 $response=&reply('instemailrules:'.&escape($udom),
 1199:                                  $homeserver);
 1200:             } else {
 1201:                 $response=&reply('instuserrules:'.&escape($udom),
 1202:                                  $homeserver);
 1203:             }
 1204:             if (($response ne 'refused') && ($response ne 'error') && 
 1205:                 ($response ne 'unknown_cmd') && 
 1206:                 ($response ne 'no_such_host')) {
 1207:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1208:                 my @pairs=split(/\&/,$hashitems);
 1209:                 foreach my $item (@pairs) {
 1210:                     my ($key,$value)=split(/=/,$item,2);
 1211:                     $key = &unescape($key);
 1212:                     next if ($key =~ /^error: 2 /);
 1213:                     $ruleshash{$key}=&thaw_unescape($value);
 1214:                 }
 1215:                 my @esc_order = split(/\&/,$orderitems);
 1216:                 foreach my $item (@esc_order) {
 1217:                     push(@ruleorder,&unescape($item));
 1218:                 }
 1219:             }
 1220:         }
 1221:     }
 1222:     return (\%ruleshash,\@ruleorder);
 1223: }
 1224: 
 1225: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1226: 
 1227: sub get_domain_defaults {
 1228:     my ($domain) = @_;
 1229:     my $cachetime = 60*60*24;
 1230:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1231:     if (defined($cached)) {
 1232:         if (ref($result) eq 'HASH') {
 1233:             return %{$result};
 1234:         }
 1235:     }
 1236:     my %domdefaults;
 1237:     my %domconfig =
 1238:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
 1239:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1240:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1241:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1242:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1243:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1244:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1245:     } else {
 1246:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1247:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1248:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1249:     }
 1250:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1251:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1252:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1253:         } else {
 1254:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1255:         } 
 1256:         my @usertools = ('aboutme','blog','portfolio');
 1257:         foreach my $item (@usertools) {
 1258:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1259:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1260:             }
 1261:         }
 1262:     }
 1263:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1264:                                   $cachetime);
 1265:     return %domdefaults;
 1266: }
 1267: 
 1268: # --------------------------------------------------- Assign a key to a student
 1269: 
 1270: sub assign_access_key {
 1271: #
 1272: # a valid key looks like uname:udom#comments
 1273: # comments are being appended
 1274: #
 1275:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1276:     $kdom=
 1277:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1278:     $knum=
 1279:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1280:     $cdom=
 1281:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1282:     $cnum=
 1283:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1284:     $udom=$env{'user.name'} unless (defined($udom));
 1285:     $uname=$env{'user.domain'} unless (defined($uname));
 1286:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1287:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1288:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1289:                                                   # assigned to this person
 1290:                                                   # - this should not happen,
 1291:                                                   # unless something went wrong
 1292:                                                   # the first time around
 1293: # ready to assign
 1294:         $logentry=$1.'; '.$logentry;
 1295:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1296:                                                  $kdom,$knum) eq 'ok') {
 1297: # key now belongs to user
 1298: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1299:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1300:                 &appenv({'environment.'.$envkey => $ckey});
 1301:                 return 'ok';
 1302:             } else {
 1303:                 return 
 1304:   'error: Count not permanently assign key, will need to be re-entered later.';
 1305: 	    }
 1306:         } else {
 1307:             return 'error: Could not assign key, try again later.';
 1308:         }
 1309:     } elsif (!$existing{$ckey}) {
 1310: # the key does not exist
 1311: 	return 'error: The key does not exist';
 1312:     } else {
 1313: # the key is somebody else's
 1314: 	return 'error: The key is already in use';
 1315:     }
 1316: }
 1317: 
 1318: # ------------------------------------------ put an additional comment on a key
 1319: 
 1320: sub comment_access_key {
 1321: #
 1322: # a valid key looks like uname:udom#comments
 1323: # comments are being appended
 1324: #
 1325:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1326:     $cdom=
 1327:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1328:     $cnum=
 1329:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1330:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1331:     if ($existing{$ckey}) {
 1332:         $existing{$ckey}.='; '.$logentry;
 1333: # ready to assign
 1334:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1335:                                                  $cdom,$cnum) eq 'ok') {
 1336: 	    return 'ok';
 1337:         } else {
 1338: 	    return 'error: Count not store comment.';
 1339:         }
 1340:     } else {
 1341: # the key does not exist
 1342: 	return 'error: The key does not exist';
 1343:     }
 1344: }
 1345: 
 1346: # ------------------------------------------------------ Generate a set of keys
 1347: 
 1348: sub generate_access_keys {
 1349:     my ($number,$cdom,$cnum,$logentry)=@_;
 1350:     $cdom=
 1351:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1352:     $cnum=
 1353:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1354:     unless (&allowed('mky',$cdom)) { return 0; }
 1355:     unless (($cdom) && ($cnum)) { return 0; }
 1356:     if ($number>10000) { return 0; }
 1357:     sleep(2); # make sure don't get same seed twice
 1358:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1359:     my $total=0;
 1360:     for (my $i=1;$i<=$number;$i++) {
 1361:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1362:                   sprintf("%lx",int(100000*rand)).'-'.
 1363:                   sprintf("%lx",int(100000*rand));
 1364:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1365:        $newkey=~s/0/h/g; # and also 0 and O
 1366:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1367:        if ($existing{$newkey}) {
 1368:            $i--;
 1369:        } else {
 1370: 	  if (&put('accesskeys',
 1371:               { $newkey => '# generated '.localtime().
 1372:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1373:                            '; '.$logentry },
 1374: 		   $cdom,$cnum) eq 'ok') {
 1375:               $total++;
 1376: 	  }
 1377:        }
 1378:     }
 1379:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1380:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1381:     return $total;
 1382: }
 1383: 
 1384: # ------------------------------------------------------- Validate an accesskey
 1385: 
 1386: sub validate_access_key {
 1387:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1388:     $cdom=
 1389:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1390:     $cnum=
 1391:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1392:     $udom=$env{'user.domain'} unless (defined($udom));
 1393:     $uname=$env{'user.name'} unless (defined($uname));
 1394:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1395:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1396: }
 1397: 
 1398: # ------------------------------------- Find the section of student in a course
 1399: sub devalidate_getsection_cache {
 1400:     my ($udom,$unam,$courseid)=@_;
 1401:     my $hashid="$udom:$unam:$courseid";
 1402:     &devalidate_cache_new('getsection',$hashid);
 1403: }
 1404: 
 1405: sub courseid_to_courseurl {
 1406:     my ($courseid) = @_;
 1407:     #already url style courseid
 1408:     return $courseid if ($courseid =~ m{^/});
 1409: 
 1410:     if (exists($env{'course.'.$courseid.'.num'})) {
 1411: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1412: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1413: 	return "/$cdom/$cnum";
 1414:     }
 1415: 
 1416:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1417:     if (exists($courseinfo{'num'})) {
 1418: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1419:     }
 1420: 
 1421:     return undef;
 1422: }
 1423: 
 1424: sub getsection {
 1425:     my ($udom,$unam,$courseid)=@_;
 1426:     my $cachetime=1800;
 1427: 
 1428:     my $hashid="$udom:$unam:$courseid";
 1429:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1430:     if (defined($cached)) { return $result; }
 1431: 
 1432:     my %Pending; 
 1433:     my %Expired;
 1434:     #
 1435:     # Each role can either have not started yet (pending), be active, 
 1436:     #    or have expired.
 1437:     #
 1438:     # If there is an active role, we are done.
 1439:     #
 1440:     # If there is more than one role which has not started yet, 
 1441:     #     choose the one which will start sooner
 1442:     # If there is one role which has not started yet, return it.
 1443:     #
 1444:     # If there is more than one expired role, choose the one which ended last.
 1445:     # If there is a role which has expired, return it.
 1446:     #
 1447:     $courseid = &courseid_to_courseurl($courseid);
 1448:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1449:     foreach my $key (keys(%roleshash)) {
 1450:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1451:         my $section=$1;
 1452:         if ($key eq $courseid.'_st') { $section=''; }
 1453:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1454:         my $now=time;
 1455:         if (defined($end) && $end && ($now > $end)) {
 1456:             $Expired{$end}=$section;
 1457:             next;
 1458:         }
 1459:         if (defined($start) && $start && ($now < $start)) {
 1460:             $Pending{$start}=$section;
 1461:             next;
 1462:         }
 1463:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1464:     }
 1465:     #
 1466:     # Presumedly there will be few matching roles from the above
 1467:     # loop and the sorting time will be negligible.
 1468:     if (scalar(keys(%Pending))) {
 1469:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1470:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1471:     } 
 1472:     if (scalar(keys(%Expired))) {
 1473:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1474:         my $time = pop(@sorted);
 1475:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1476:     }
 1477:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1478: }
 1479: 
 1480: sub save_cache {
 1481:     &purge_remembered();
 1482:     #&Apache::loncommon::validate_page();
 1483:     undef(%env);
 1484:     undef($env_loaded);
 1485: }
 1486: 
 1487: my $to_remember=-1;
 1488: my %remembered;
 1489: my %accessed;
 1490: my $kicks=0;
 1491: my $hits=0;
 1492: sub make_key {
 1493:     my ($name,$id) = @_;
 1494:     if (length($id) > 65 
 1495: 	&& length(&escape($id)) > 200) {
 1496: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1497:     }
 1498:     return &escape($name.':'.$id);
 1499: }
 1500: 
 1501: sub devalidate_cache_new {
 1502:     my ($name,$id,$debug) = @_;
 1503:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1504:     $id=&make_key($name,$id);
 1505:     $memcache->delete($id);
 1506:     delete($remembered{$id});
 1507:     delete($accessed{$id});
 1508: }
 1509: 
 1510: sub is_cached_new {
 1511:     my ($name,$id,$debug) = @_;
 1512:     $id=&make_key($name,$id);
 1513:     if (exists($remembered{$id})) {
 1514: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1515: 	$accessed{$id}=[&gettimeofday()];
 1516: 	$hits++;
 1517: 	return ($remembered{$id},1);
 1518:     }
 1519:     my $value = $memcache->get($id);
 1520:     if (!(defined($value))) {
 1521: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1522: 	return (undef,undef);
 1523:     }
 1524:     if ($value eq '__undef__') {
 1525: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1526: 	$value=undef;
 1527:     }
 1528:     &make_room($id,$value,$debug);
 1529:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1530:     return ($value,1);
 1531: }
 1532: 
 1533: sub do_cache_new {
 1534:     my ($name,$id,$value,$time,$debug) = @_;
 1535:     $id=&make_key($name,$id);
 1536:     my $setvalue=$value;
 1537:     if (!defined($setvalue)) {
 1538: 	$setvalue='__undef__';
 1539:     }
 1540:     if (!defined($time) ) {
 1541: 	$time=600;
 1542:     }
 1543:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1544:     my $result = $memcache->set($id,$setvalue,$time);
 1545:     if (! $result) {
 1546: 	&logthis("caching of id -> $id  failed");
 1547: 	$memcache->disconnect_all();
 1548:     }
 1549:     # need to make a copy of $value
 1550:     &make_room($id,$value,$debug);
 1551:     return $value;
 1552: }
 1553: 
 1554: sub make_room {
 1555:     my ($id,$value,$debug)=@_;
 1556: 
 1557:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1558:                                     : $value;
 1559:     if ($to_remember<0) { return; }
 1560:     $accessed{$id}=[&gettimeofday()];
 1561:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1562:     my $to_kick;
 1563:     my $max_time=0;
 1564:     foreach my $other (keys(%accessed)) {
 1565: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1566: 	    $to_kick=$other;
 1567: 	    $max_time=&tv_interval($accessed{$other});
 1568: 	}
 1569:     }
 1570:     delete($remembered{$to_kick});
 1571:     delete($accessed{$to_kick});
 1572:     $kicks++;
 1573:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1574:     return;
 1575: }
 1576: 
 1577: sub purge_remembered {
 1578:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1579:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1580:     undef(%remembered);
 1581:     undef(%accessed);
 1582: }
 1583: # ------------------------------------- Read an entry from a user's environment
 1584: 
 1585: sub userenvironment {
 1586:     my ($udom,$unam,@what)=@_;
 1587:     my $items;
 1588:     foreach my $item (@what) {
 1589:         $items.=&escape($item).'&';
 1590:     }
 1591:     $items=~s/\&$//;
 1592:     my %returnhash=();
 1593:     my @answer=split(/\&/,
 1594:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1595:                       &homeserver($unam,$udom)));
 1596:     my $i;
 1597:     for ($i=0;$i<=$#what;$i++) {
 1598: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1599:     }
 1600:     return %returnhash;
 1601: }
 1602: 
 1603: # ---------------------------------------------------------- Get a studentphoto
 1604: sub studentphoto {
 1605:     my ($udom,$unam,$ext) = @_;
 1606:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1607:     if (defined($env{'request.course.id'})) {
 1608:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1609:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1610:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1611:             } else {
 1612:                 my ($result,$perm_reqd)=
 1613: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1614:                 if ($result eq 'ok') {
 1615:                     if (!($perm_reqd eq 'yes')) {
 1616:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1617:                     }
 1618:                 }
 1619:             }
 1620:         }
 1621:     } else {
 1622:         my ($result,$perm_reqd) = 
 1623: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1624:         if ($result eq 'ok') {
 1625:             if (!($perm_reqd eq 'yes')) {
 1626:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1627:             }
 1628:         }
 1629:     }
 1630:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1631: }
 1632: 
 1633: sub retrievestudentphoto {
 1634:     my ($udom,$unam,$ext,$type) = @_;
 1635:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1636:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1637:     if ($ret eq 'ok') {
 1638:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1639:         if ($type eq 'thumbnail') {
 1640:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1641:         }
 1642:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1643:         return $tokenurl;
 1644:     } else {
 1645:         if ($type eq 'thumbnail') {
 1646:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1647:         } else { 
 1648:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1649:         }
 1650:     }
 1651: }
 1652: 
 1653: # -------------------------------------------------------------------- New chat
 1654: 
 1655: sub chatsend {
 1656:     my ($newentry,$anon,$group)=@_;
 1657:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1658:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1659:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1660:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1661: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1662: 		   &escape($newentry)).':'.$group,$chome);
 1663: }
 1664: 
 1665: # ------------------------------------------ Find current version of a resource
 1666: 
 1667: sub getversion {
 1668:     my $fname=&clutter(shift);
 1669:     unless ($fname=~/^\/res\//) { return -1; }
 1670:     return &currentversion(&filelocation('',$fname));
 1671: }
 1672: 
 1673: sub currentversion {
 1674:     my $fname=shift;
 1675:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1676:     if (defined($cached)) { return $result; }
 1677:     my $author=$fname;
 1678:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1679:     my ($udom,$uname)=split(/\//,$author);
 1680:     my $home=homeserver($uname,$udom);
 1681:     if ($home eq 'no_host') { 
 1682:         return -1; 
 1683:     }
 1684:     my $answer=reply("currentversion:$fname",$home);
 1685:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1686: 	return -1;
 1687:     }
 1688:     return &do_cache_new('resversion',$fname,$answer,600);
 1689: }
 1690: 
 1691: # ----------------------------- Subscribe to a resource, return URL if possible
 1692: 
 1693: sub subscribe {
 1694:     my $fname=shift;
 1695:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1696:     $fname=~s/[\n\r]//g;
 1697:     my $author=$fname;
 1698:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1699:     my ($udom,$uname)=split(/\//,$author);
 1700:     my $home=homeserver($uname,$udom);
 1701:     if ($home eq 'no_host') {
 1702:         return 'not_found';
 1703:     }
 1704:     my $answer=reply("sub:$fname",$home);
 1705:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1706: 	$answer.=' by '.$home;
 1707:     }
 1708:     return $answer;
 1709: }
 1710:     
 1711: # -------------------------------------------------------------- Replicate file
 1712: 
 1713: sub repcopy {
 1714:     my $filename=shift;
 1715:     $filename=~s/\/+/\//g;
 1716:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1717:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1718:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1719: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1720: 	return &repcopy_userfile($filename);
 1721:     }
 1722:     $filename=~s/[\n\r]//g;
 1723:     my $transname="$filename.in.transfer";
 1724: # FIXME: this should flock
 1725:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1726:     my $remoteurl=subscribe($filename);
 1727:     if ($remoteurl =~ /^con_lost by/) {
 1728: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1729:            return 'unavailable';
 1730:     } elsif ($remoteurl eq 'not_found') {
 1731: 	   #&logthis("Subscribe returned not_found: $filename");
 1732: 	   return 'not_found';
 1733:     } elsif ($remoteurl =~ /^rejected by/) {
 1734: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1735:            return 'forbidden';
 1736:     } elsif ($remoteurl eq 'directory') {
 1737:            return 'ok';
 1738:     } else {
 1739:         my $author=$filename;
 1740:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1741:         my ($udom,$uname)=split(/\//,$author);
 1742:         my $home=homeserver($uname,$udom);
 1743:         unless ($home eq $perlvar{'lonHostID'}) {
 1744:            my @parts=split(/\//,$filename);
 1745:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1746:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1747:                &logthis("Malconfiguration for replication: $filename");
 1748: 	       return 'bad_request';
 1749:            }
 1750:            my $count;
 1751:            for ($count=5;$count<$#parts;$count++) {
 1752:                $path.="/$parts[$count]";
 1753:                if ((-e $path)!=1) {
 1754: 		   mkdir($path,0777);
 1755:                }
 1756:            }
 1757:            my $ua=new LWP::UserAgent;
 1758:            my $request=new HTTP::Request('GET',"$remoteurl");
 1759:            my $response=$ua->request($request,$transname);
 1760:            if ($response->is_error()) {
 1761: 	       unlink($transname);
 1762:                my $message=$response->status_line;
 1763:                &logthis("<font color=\"blue\">WARNING:"
 1764:                        ." LWP get: $message: $filename</font>");
 1765:                return 'unavailable';
 1766:            } else {
 1767: 	       if ($remoteurl!~/\.meta$/) {
 1768:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1769:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1770:                   if ($mresponse->is_error()) {
 1771: 		      unlink($filename.'.meta');
 1772:                       &logthis(
 1773:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1774:                   }
 1775: 	       }
 1776:                rename($transname,$filename);
 1777:                return 'ok';
 1778:            }
 1779:        }
 1780:     }
 1781: }
 1782: 
 1783: # ------------------------------------------------ Get server side include body
 1784: sub ssi_body {
 1785:     my ($filelink,%form)=@_;
 1786:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1787:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1788:     }
 1789:     my $output='';
 1790:     my $response;
 1791:     if ($filelink=~/^https?\:/) {
 1792:        ($output,$response)=&externalssi($filelink);
 1793:     } else {
 1794:        ($output,$response)=&ssi($filelink,%form);
 1795:     }
 1796:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1797:     $output=~s/^.*?\<body[^\>]*\>//si;
 1798:     $output=~s/\<\/body\s*\>.*?$//si;
 1799:     if (wantarray) {
 1800:         return ($output, $response);
 1801:     } else {
 1802:         return $output;
 1803:     }
 1804: }
 1805: 
 1806: # --------------------------------------------------------- Server Side Include
 1807: 
 1808: sub absolute_url {
 1809:     my ($host_name) = @_;
 1810:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1811:     if ($host_name eq '') {
 1812: 	$host_name = $ENV{'SERVER_NAME'};
 1813:     }
 1814:     return $protocol.$host_name;
 1815: }
 1816: 
 1817: #
 1818: #   Server side include.
 1819: # Parameters:
 1820: #  fn     Possibly encrypted resource name/id.
 1821: #  form   Hash that describes how the rendering should be done
 1822: #         and other things.
 1823: # Returns:
 1824: #   Scalar context: The content of the response.
 1825: #   Array context:  2 element list of the content and the full response object.
 1826: #     
 1827: sub ssi {
 1828: 
 1829:     my ($fn,%form)=@_;
 1830:     my $ua=new LWP::UserAgent;
 1831:     my $request;
 1832: 
 1833:     $form{'no_update_last_known'}=1;
 1834:     &Apache::lonenc::check_encrypt(\$fn);
 1835:     if (%form) {
 1836:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1837:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1838:     } else {
 1839:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1840:     }
 1841: 
 1842:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1843:     my $response=$ua->request($request);
 1844: 
 1845:     if (wantarray) {
 1846: 	return ($response->content, $response);
 1847:     } else {
 1848: 	return $response->content;
 1849:     }
 1850: }
 1851: 
 1852: sub externalssi {
 1853:     my ($url)=@_;
 1854:     my $ua=new LWP::UserAgent;
 1855:     my $request=new HTTP::Request('GET',$url);
 1856:     my $response=$ua->request($request);
 1857:     if (wantarray) {
 1858:         return ($response->content, $response);
 1859:     } else {
 1860:         return $response->content;
 1861:     }
 1862: }
 1863: 
 1864: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1865: 
 1866: sub allowuploaded {
 1867:     my ($srcurl,$url)=@_;
 1868:     $url=&clutter(&declutter($url));
 1869:     my $dir=$url;
 1870:     $dir=~s/\/[^\/]+$//;
 1871:     my %httpref=();
 1872:     my $httpurl=&hreflocation('',$url);
 1873:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1874:     &Apache::lonnet::appenv(\%httpref);
 1875: }
 1876: 
 1877: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1878: # input: action, courseID, current domain, intended
 1879: #        path to file, source of file, instruction to parse file for objects,
 1880: #        ref to hash for embedded objects,
 1881: #        ref to hash for codebase of java objects.
 1882: #
 1883: # output: url to file (if action was uploaddoc), 
 1884: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1885: #
 1886: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1887: # course.
 1888: #
 1889: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1890: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1891: #          course's home server.
 1892: #
 1893: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1894: #          be copied from $source (current location) to 
 1895: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1896: #         and will then be copied to
 1897: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1898: #         course's home server.
 1899: #
 1900: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1901: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1902: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1903: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1904: #         in course's home server.
 1905: #
 1906: 
 1907: sub process_coursefile {
 1908:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1909:     my $fetchresult;
 1910:     my $home=&homeserver($docuname,$docudom);
 1911:     if ($action eq 'propagate') {
 1912:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1913: 			     $home);
 1914:     } else {
 1915:         my $fpath = '';
 1916:         my $fname = $file;
 1917:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1918:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1919:         my $filepath = &build_filepath($fpath);
 1920:         if ($action eq 'copy') {
 1921:             if ($source eq '') {
 1922:                 $fetchresult = 'no source file';
 1923:                 return $fetchresult;
 1924:             } else {
 1925:                 my $destination = $filepath.'/'.$fname;
 1926:                 rename($source,$destination);
 1927:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1928:                                  $home);
 1929:             }
 1930:         } elsif ($action eq 'uploaddoc') {
 1931:             open(my $fh,'>'.$filepath.'/'.$fname);
 1932:             print $fh $env{'form.'.$source};
 1933:             close($fh);
 1934:             if ($parser eq 'parse') {
 1935:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1936:                 unless ($parse_result eq 'ok') {
 1937:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1938:                 }
 1939:             }
 1940:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1941:                                  $home);
 1942:             if ($fetchresult eq 'ok') {
 1943:                 return '/uploaded/'.$fpath.'/'.$fname;
 1944:             } else {
 1945:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1946:                         ' to host '.$home.': '.$fetchresult);
 1947:                 return '/adm/notfound.html';
 1948:             }
 1949:         }
 1950:     }
 1951:     unless ( $fetchresult eq 'ok') {
 1952:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1953:              ' to host '.$home.': '.$fetchresult);
 1954:     }
 1955:     return $fetchresult;
 1956: }
 1957: 
 1958: sub build_filepath {
 1959:     my ($fpath) = @_;
 1960:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1961:     unless ($fpath eq '') {
 1962:         my @parts=split('/',$fpath);
 1963:         foreach my $part (@parts) {
 1964:             $filepath.= '/'.$part;
 1965:             if ((-e $filepath)!=1) {
 1966:                 mkdir($filepath,0777);
 1967:             }
 1968:         }
 1969:     }
 1970:     return $filepath;
 1971: }
 1972: 
 1973: sub store_edited_file {
 1974:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1975:     my $file = $primary_url;
 1976:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1977:     my $fpath = '';
 1978:     my $fname = $file;
 1979:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1980:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1981:     my $filepath = &build_filepath($fpath);
 1982:     open(my $fh,'>'.$filepath.'/'.$fname);
 1983:     print $fh $content;
 1984:     close($fh);
 1985:     my $home=&homeserver($docuname,$docudom);
 1986:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1987: 			  $home);
 1988:     if ($$fetchresult eq 'ok') {
 1989:         return '/uploaded/'.$fpath.'/'.$fname;
 1990:     } else {
 1991:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1992: 		 ' to host '.$home.': '.$$fetchresult);
 1993:         return '/adm/notfound.html';
 1994:     }
 1995: }
 1996: 
 1997: sub clean_filename {
 1998:     my ($fname,$args)=@_;
 1999: # Replace Windows backslashes by forward slashes
 2000:     $fname=~s/\\/\//g;
 2001:     if (!$args->{'keep_path'}) {
 2002:         # Get rid of everything but the actual filename
 2003: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2004:     }
 2005: # Replace spaces by underscores
 2006:     $fname=~s/\s+/\_/g;
 2007: # Replace all other weird characters by nothing
 2008:     $fname=~s{[^/\w\.\-]}{}g;
 2009: # Replace all .\d. sequences with _\d. so they no longer look like version
 2010: # numbers
 2011:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2012:     return $fname;
 2013: }
 2014: 
 2015: # --------------- Take an uploaded file and put it into the userfiles directory
 2016: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2017: #                    the desired filenam is in $env{"form.$formname.filename"}
 2018: #        $coursedoc - if true up to the current course
 2019: #                     if false
 2020: #        $subdir - directory in userfile to store the file into
 2021: #        $parser - instruction to parse file for objects ($parser = parse)    
 2022: #        $allfiles - reference to hash for embedded objects
 2023: #        $codebase - reference to hash for codebase of java objects
 2024: #        $desuname - username for permanent storage of uploaded file
 2025: #        $dsetudom - domain for permanaent storage of uploaded file
 2026: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2027: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2028: # 
 2029: # output: url of file in userspace, or error: <message> 
 2030: #             or /adm/notfound.html if failure to upload occurse
 2031: 
 2032: 
 2033: sub userfileupload {
 2034:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2035:         $destudom,$thumbwidth,$thumbheight)=@_;
 2036:     if (!defined($subdir)) { $subdir='unknown'; }
 2037:     my $fname=$env{'form.'.$formname.'.filename'};
 2038:     $fname=&clean_filename($fname);
 2039: # See if there is anything left
 2040:     unless ($fname) { return 'error: no uploaded file'; }
 2041:     chop($env{'form.'.$formname});
 2042:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2043:         my $now = time;
 2044:         my $filepath = 'tmp/helprequests/'.$now;
 2045:         my @parts=split(/\//,$filepath);
 2046:         my $fullpath = $perlvar{'lonDaemons'};
 2047:         for (my $i=0;$i<@parts;$i++) {
 2048:             $fullpath .= '/'.$parts[$i];
 2049:             if ((-e $fullpath)!=1) {
 2050:                 mkdir($fullpath,0777);
 2051:             }
 2052:         }
 2053:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2054:         print $fh $env{'form.'.$formname};
 2055:         close($fh);
 2056:         return $fullpath.'/'.$fname;
 2057:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2058:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2059:                        '_'.$env{'user.domain'}.'/pending';
 2060:         my @parts=split(/\//,$filepath);
 2061:         my $fullpath = $perlvar{'lonDaemons'};
 2062:         for (my $i=0;$i<@parts;$i++) {
 2063:             $fullpath .= '/'.$parts[$i];
 2064:             if ((-e $fullpath)!=1) {
 2065:                 mkdir($fullpath,0777);
 2066:             }
 2067:         }
 2068:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2069:         print $fh $env{'form.'.$formname};
 2070:         close($fh);
 2071:         return $fullpath.'/'.$fname;
 2072:     }
 2073:     
 2074: # Create the directory if not present
 2075:     $fname="$subdir/$fname";
 2076:     if ($coursedoc) {
 2077: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2078: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2079:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2080:             return &finishuserfileupload($docuname,$docudom,
 2081: 					 $formname,$fname,$parser,$allfiles,
 2082: 					 $codebase,$thumbwidth,$thumbheight);
 2083:         } else {
 2084:             $fname=$env{'form.folder'}.'/'.$fname;
 2085:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2086: 				       $fname,$formname,$parser,
 2087: 				       $allfiles,$codebase);
 2088:         }
 2089:     } elsif (defined($destuname)) {
 2090:         my $docuname=$destuname;
 2091:         my $docudom=$destudom;
 2092: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2093: 				     $parser,$allfiles,$codebase,
 2094:                                      $thumbwidth,$thumbheight);
 2095:         
 2096:     } else {
 2097:         my $docuname=$env{'user.name'};
 2098:         my $docudom=$env{'user.domain'};
 2099:         if (exists($env{'form.group'})) {
 2100:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2101:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2102:         }
 2103: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2104: 				     $parser,$allfiles,$codebase,
 2105:                                      $thumbwidth,$thumbheight);
 2106:     }
 2107: }
 2108: 
 2109: sub finishuserfileupload {
 2110:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2111:         $thumbwidth,$thumbheight) = @_;
 2112:     my $path=$docudom.'/'.$docuname.'/';
 2113:     my $filepath=$perlvar{'lonDocRoot'};
 2114:     my ($fnamepath,$file,$fetchthumb);
 2115:     $file=$fname;
 2116:     if ($fname=~m|/|) {
 2117:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2118: 	$path.=$fnamepath.'/';
 2119:     }
 2120:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2121:     my $count;
 2122:     for ($count=4;$count<=$#parts;$count++) {
 2123:         $filepath.="/$parts[$count]";
 2124:         if ((-e $filepath)!=1) {
 2125: 	    mkdir($filepath,0777);
 2126:         }
 2127:     }
 2128: # Save the file
 2129:     {
 2130: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2131: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2132: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2133: 	    return '/adm/notfound.html';
 2134: 	}
 2135: 	if (!print FH ($env{'form.'.$formname})) {
 2136: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2137: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2138: 	    return '/adm/notfound.html';
 2139: 	}
 2140: 	close(FH);
 2141:     }
 2142:     if ($parser eq 'parse') {
 2143:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2144: 						   $codebase);
 2145:         unless ($parse_result eq 'ok') {
 2146:             &logthis('Failed to parse '.$filepath.$file.
 2147: 		     ' for embedded media: '.$parse_result); 
 2148:         }
 2149:     }
 2150:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2151:         my $input = $filepath.'/'.$file;
 2152:         my $output = $filepath.'/'.'tn-'.$file;
 2153:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2154:         system("convert -sample $thumbsize $input $output");
 2155:         if (-e $filepath.'/'.'tn-'.$file) {
 2156:             $fetchthumb  = 1; 
 2157:         }
 2158:     }
 2159:  
 2160: # Notify homeserver to grep it
 2161: #
 2162:     my $docuhome=&homeserver($docuname,$docudom);
 2163:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2164:     if ($fetchresult eq 'ok') {
 2165:         if ($fetchthumb) {
 2166:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2167:             if ($thumbresult ne 'ok') {
 2168:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2169:                          $docuhome.': '.$thumbresult);
 2170:             }
 2171:         }
 2172: #
 2173: # Return the URL to it
 2174:         return '/uploaded/'.$path.$file;
 2175:     } else {
 2176:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2177: 		 ': '.$fetchresult);
 2178:         return '/adm/notfound.html';
 2179:     }
 2180: }
 2181: 
 2182: sub extract_embedded_items {
 2183:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2184:     my @state = ();
 2185:     my %javafiles = (
 2186:                       codebase => '',
 2187:                       code => '',
 2188:                       archive => ''
 2189:                     );
 2190:     my %mediafiles = (
 2191:                       src => '',
 2192:                       movie => '',
 2193:                      );
 2194:     my $p;
 2195:     if ($content) {
 2196:         $p = HTML::LCParser->new($content);
 2197:     } else {
 2198:         $p = HTML::LCParser->new($fullpath);
 2199:     }
 2200:     while (my $t=$p->get_token()) {
 2201: 	if ($t->[0] eq 'S') {
 2202: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2203: 	    push(@state, $tagname);
 2204:             if (lc($tagname) eq 'allow') {
 2205:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2206:             }
 2207: 	    if (lc($tagname) eq 'img') {
 2208: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2209: 	    }
 2210: 	    if (lc($tagname) eq 'a') {
 2211: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2212: 	    }
 2213:             if (lc($tagname) eq 'script') {
 2214:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2215:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2216:                 } else {
 2217:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2218:                 }
 2219:             }
 2220:             if (lc($tagname) eq 'link') {
 2221:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2222:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2223:                 }
 2224:             }
 2225: 	    if (lc($tagname) eq 'object' ||
 2226: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2227: 		foreach my $item (keys(%javafiles)) {
 2228: 		    $javafiles{$item} = '';
 2229: 		}
 2230: 	    }
 2231: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2232: 		my $name = lc($attr->{'name'});
 2233: 		foreach my $item (keys(%javafiles)) {
 2234: 		    if ($name eq $item) {
 2235: 			$javafiles{$item} = $attr->{'value'};
 2236: 			last;
 2237: 		    }
 2238: 		}
 2239: 		foreach my $item (keys(%mediafiles)) {
 2240: 		    if ($name eq $item) {
 2241: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2242: 			last;
 2243: 		    }
 2244: 		}
 2245: 	    }
 2246: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2247: 		foreach my $item (keys(%javafiles)) {
 2248: 		    if ($attr->{$item}) {
 2249: 			$javafiles{$item} = $attr->{$item};
 2250: 			last;
 2251: 		    }
 2252: 		}
 2253: 		foreach my $item (keys(%mediafiles)) {
 2254: 		    if ($attr->{$item}) {
 2255: 			&add_filetype($allfiles,$attr->{$item},$item);
 2256: 			last;
 2257: 		    }
 2258: 		}
 2259: 	    }
 2260: 	} elsif ($t->[0] eq 'E') {
 2261: 	    my ($tagname) = ($t->[1]);
 2262: 	    if ($javafiles{'codebase'} ne '') {
 2263: 		$javafiles{'codebase'} .= '/';
 2264: 	    }  
 2265: 	    if (lc($tagname) eq 'applet' ||
 2266: 		lc($tagname) eq 'object' ||
 2267: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2268: 		) {
 2269: 		foreach my $item (keys(%javafiles)) {
 2270: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2271: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2272: 			&add_filetype($allfiles,$file,$item);
 2273: 		    }
 2274: 		}
 2275: 	    } 
 2276: 	    pop @state;
 2277: 	}
 2278:     }
 2279:     return 'ok';
 2280: }
 2281: 
 2282: sub add_filetype {
 2283:     my ($allfiles,$file,$type)=@_;
 2284:     if (exists($allfiles->{$file})) {
 2285: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2286: 	    push(@{$allfiles->{$file}}, &escape($type));
 2287: 	}
 2288:     } else {
 2289: 	@{$allfiles->{$file}} = (&escape($type));
 2290:     }
 2291: }
 2292: 
 2293: sub removeuploadedurl {
 2294:     my ($url)=@_;
 2295:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2296:     return &removeuserfile($uname,$udom,$fname);
 2297: }
 2298: 
 2299: sub removeuserfile {
 2300:     my ($docuname,$docudom,$fname)=@_;
 2301:     my $home=&homeserver($docuname,$docudom);
 2302:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2303:     if ($result eq 'ok') {
 2304:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2305:             my $metafile = $fname.'.meta';
 2306:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2307: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2308:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2309:             my $sqlresult = 
 2310:                 &update_portfolio_table($docuname,$docudom,$file,
 2311:                                         'portfolio_metadata',$group,
 2312:                                         'delete');
 2313:         }
 2314:     }
 2315:     return $result;
 2316: }
 2317: 
 2318: sub mkdiruserfile {
 2319:     my ($docuname,$docudom,$dir)=@_;
 2320:     my $home=&homeserver($docuname,$docudom);
 2321:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2322: }
 2323: 
 2324: sub renameuserfile {
 2325:     my ($docuname,$docudom,$old,$new)=@_;
 2326:     my $home=&homeserver($docuname,$docudom);
 2327:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2328:                         &escape("$old").':'.&escape("$new"),$home);
 2329:     if ($result eq 'ok') {
 2330:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2331:             my $oldmeta = $old.'.meta';
 2332:             my $newmeta = $new.'.meta';
 2333:             my $metaresult = 
 2334:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2335: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2336:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2337:             my $sqlresult = 
 2338:                 &update_portfolio_table($docuname,$docudom,$file,
 2339:                                         'portfolio_metadata',$group,
 2340:                                         'delete');
 2341:         }
 2342:     }
 2343:     return $result;
 2344: }
 2345: 
 2346: # ------------------------------------------------------------------------- Log
 2347: 
 2348: sub log {
 2349:     my ($dom,$nam,$hom,$what)=@_;
 2350:     return critical("log:$dom:$nam:$what",$hom);
 2351: }
 2352: 
 2353: # ------------------------------------------------------------------ Course Log
 2354: #
 2355: # This routine flushes several buffers of non-mission-critical nature
 2356: #
 2357: 
 2358: sub flushcourselogs {
 2359:     &logthis('Flushing log buffers');
 2360: #
 2361: # course logs
 2362: # This is a log of all transactions in a course, which can be used
 2363: # for data mining purposes
 2364: #
 2365: # It also collects the courseid database, which lists last transaction
 2366: # times and course titles for all courseids
 2367: #
 2368:     my %courseidbuffer=();
 2369:     foreach my $crsid (keys(%courselogs)) {
 2370:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2371: 		          &escape($courselogs{$crsid}),
 2372: 		          $coursehombuf{$crsid}) eq 'ok') {
 2373: 	    delete $courselogs{$crsid};
 2374:         } else {
 2375:             &logthis('Failed to flush log buffer for '.$crsid);
 2376:             if (length($courselogs{$crsid})>40000) {
 2377:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2378:                         " exceeded maximum size, deleting.</font>");
 2379:                delete $courselogs{$crsid};
 2380:             }
 2381:         }
 2382:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2383:             'description' => $coursedescrbuf{$crsid},
 2384:             'inst_code'    => $courseinstcodebuf{$crsid},
 2385:             'type'        => $coursetypebuf{$crsid},
 2386:             'owner'       => $courseownerbuf{$crsid},
 2387:         };
 2388:     }
 2389: #
 2390: # Write course id database (reverse lookup) to homeserver of courses 
 2391: # Is used in pickcourse
 2392: #
 2393:     foreach my $crs_home (keys(%courseidbuffer)) {
 2394:         my $response = &courseidput(&host_domain($crs_home),
 2395:                                     $courseidbuffer{$crs_home},
 2396:                                     $crs_home,'timeonly');
 2397:     }
 2398: #
 2399: # File accesses
 2400: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2401: #
 2402:     foreach my $entry (keys(%accesshash)) {
 2403:         if ($entry =~ /___count$/) {
 2404:             my ($dom,$name);
 2405:             ($dom,$name,undef)=
 2406: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2407:             if (! defined($dom) || $dom eq '' || 
 2408:                 ! defined($name) || $name eq '') {
 2409:                 my $cid = $env{'request.course.id'};
 2410:                 $dom  = $env{'request.'.$cid.'.domain'};
 2411:                 $name = $env{'request.'.$cid.'.num'};
 2412:             }
 2413:             my $value = $accesshash{$entry};
 2414:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2415:             my %temphash=($url => $value);
 2416:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2417:             if ($result eq 'ok') {
 2418:                 delete $accesshash{$entry};
 2419:             } elsif ($result eq 'unknown_cmd') {
 2420:                 # Target server has old code running on it.
 2421:                 my %temphash=($entry => $value);
 2422:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2423:                     delete $accesshash{$entry};
 2424:                 }
 2425:             }
 2426:         } else {
 2427:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2428:             my %temphash=($entry => $accesshash{$entry});
 2429:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2430:                 delete $accesshash{$entry};
 2431:             }
 2432:         }
 2433:     }
 2434: #
 2435: # Roles
 2436: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2437: #
 2438:     foreach my $entry (keys(%userrolehash)) {
 2439:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2440: 	    split(/\:/,$entry);
 2441:         if (&Apache::lonnet::put('nohist_userroles',
 2442:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2443:                 $rudom,$runame) eq 'ok') {
 2444: 	    delete $userrolehash{$entry};
 2445:         }
 2446:     }
 2447: #
 2448: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2449: #
 2450:     my %domrolebuffer = ();
 2451:     foreach my $entry (keys %domainrolehash) {
 2452:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2453:         if ($domrolebuffer{$rudom}) {
 2454:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2455:                       '='.&escape($domainrolehash{$entry});
 2456:         } else {
 2457:             $domrolebuffer{$rudom}.=&escape($entry).
 2458:                       '='.&escape($domainrolehash{$entry});
 2459:         }
 2460:         delete $domainrolehash{$entry};
 2461:     }
 2462:     foreach my $dom (keys(%domrolebuffer)) {
 2463: 	my %servers = &get_servers($dom,'library');
 2464: 	foreach my $tryserver (keys(%servers)) {
 2465: 	    unless (&reply('domroleput:'.$dom.':'.
 2466: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2467: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2468: 	    }
 2469:         }
 2470:     }
 2471:     $dumpcount++;
 2472: }
 2473: 
 2474: sub courselog {
 2475:     my $what=shift;
 2476:     $what=time.':'.$what;
 2477:     unless ($env{'request.course.id'}) { return ''; }
 2478:     $coursedombuf{$env{'request.course.id'}}=
 2479:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2480:     $coursenumbuf{$env{'request.course.id'}}=
 2481:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2482:     $coursehombuf{$env{'request.course.id'}}=
 2483:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2484:     $coursedescrbuf{$env{'request.course.id'}}=
 2485:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2486:     $courseinstcodebuf{$env{'request.course.id'}}=
 2487:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2488:     $courseownerbuf{$env{'request.course.id'}}=
 2489:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2490:     $coursetypebuf{$env{'request.course.id'}}=
 2491:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2492:     if (defined $courselogs{$env{'request.course.id'}}) {
 2493: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2494:     } else {
 2495: 	$courselogs{$env{'request.course.id'}}.=$what;
 2496:     }
 2497:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2498: 	&flushcourselogs();
 2499:     }
 2500: }
 2501: 
 2502: sub courseacclog {
 2503:     my $fnsymb=shift;
 2504:     unless ($env{'request.course.id'}) { return ''; }
 2505:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2506:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2507:         $what.=':POST';
 2508:         # FIXME: Probably ought to escape things....
 2509: 	foreach my $key (keys(%env)) {
 2510:             if ($key=~/^form\.(.*)/) {
 2511:                 my $formitem = $1;
 2512:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2513:                     $what.=':'.$formitem.'='.$env{$key};
 2514:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2515:                     $what.=':'.$formitem.'='.$env{$key};
 2516:                 }
 2517:             }
 2518:         }
 2519:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2520:         # FIXME: We should not be depending on a form parameter that someone
 2521:         # editing lonsearchcat.pm might change in the future.
 2522:         if ($env{'form.phase'} eq 'course_search') {
 2523:             $what.= ':POST';
 2524:             # FIXME: Probably ought to escape things....
 2525:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2526:                                  'crsdiscuss') {
 2527:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2528:             }
 2529:         }
 2530:     }
 2531:     &courselog($what);
 2532: }
 2533: 
 2534: sub countacc {
 2535:     my $url=&declutter(shift);
 2536:     return if (! defined($url) || $url eq '');
 2537:     unless ($env{'request.course.id'}) { return ''; }
 2538:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2539:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2540:     $accesshash{$key}++;
 2541: }
 2542: 
 2543: sub linklog {
 2544:     my ($from,$to)=@_;
 2545:     $from=&declutter($from);
 2546:     $to=&declutter($to);
 2547:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2548:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2549: }
 2550:   
 2551: sub userrolelog {
 2552:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2553:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2554:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2555:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2556:         ($trole=~/^ta/)) {
 2557:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2558:        $userrolehash
 2559:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2560:                     =$tend.':'.$tstart;
 2561:     }
 2562:     if (($env{'request.role'} =~ /dc\./) &&
 2563: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2564: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2565: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2566:        $userrolehash
 2567:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2568:                     =$tend.':'.$tstart;
 2569:     }
 2570:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2571:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2572:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2573:         ($trole=~/^sc/)) {
 2574:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2575:        $domainrolehash
 2576:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2577:                     = $tend.':'.$tstart;
 2578:     }
 2579: }
 2580: 
 2581: sub courserolelog {
 2582:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2583:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2584:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2585:         ($trole eq 'ta') || ($trole eq 'st') ||
 2586:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2587:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2588:             my $cdom = $1;
 2589:             my $cnum = $2;
 2590:             my $sec = $3;
 2591:             my $namespace = 'rolelog';
 2592:             my %storehash = (
 2593:                                role    => $trole,
 2594:                                start   => $tstart,
 2595:                                end     => $tend,
 2596:                                selfenroll => $selfenroll,
 2597:                                context    => $context,
 2598:                             );
 2599:             if ($trole eq 'gr') {
 2600:                 $namespace = 'groupslog';
 2601:                 $storehash{'group'} = $sec;
 2602:             } else {
 2603:                 $storehash{'section'} = $sec;
 2604:             }
 2605:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2606:         }
 2607:     }
 2608:     return;
 2609: }
 2610: 
 2611: sub get_course_adv_roles {
 2612:     my ($cid,$codes) = @_;
 2613:     $cid=$env{'request.course.id'} unless (defined($cid));
 2614:     my %coursehash=&coursedescription($cid);
 2615:     my %nothide=();
 2616:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2617:         if ($user !~ /:/) {
 2618: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2619:         } else {
 2620:             $nothide{$user}=1;
 2621:         }
 2622:     }
 2623:     my %returnhash=();
 2624:     my %dumphash=
 2625:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2626:     my $now=time;
 2627:     foreach my $entry (keys %dumphash) {
 2628: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2629:         if (($tstart) && ($tstart<0)) { next; }
 2630:         if (($tend) && ($tend<$now)) { next; }
 2631:         if (($tstart) && ($now<$tstart)) { next; }
 2632:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2633: 	if ($username eq '' || $domain eq '') { next; }
 2634: 	if ((&privileged($username,$domain)) && 
 2635: 	    (!$nothide{$username.':'.$domain})) { next; }
 2636: 	if ($role eq 'cr') { next; }
 2637:         if ($codes) {
 2638:             if ($section) { $role .= ':'.$section; }
 2639:             if ($returnhash{$role}) {
 2640:                 $returnhash{$role}.=','.$username.':'.$domain;
 2641:             } else {
 2642:                 $returnhash{$role}=$username.':'.$domain;
 2643:             }
 2644:         } else {
 2645:             my $key=&plaintext($role);
 2646:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2647:             if ($returnhash{$key}) {
 2648: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2649:             } else {
 2650:                 $returnhash{$key}=$username.':'.$domain;
 2651:             }
 2652:         }
 2653:     }
 2654:     return %returnhash;
 2655: }
 2656: 
 2657: sub get_my_roles {
 2658:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2659:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2660:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2661:     my (%dumphash,%nothide);
 2662:     if ($context eq 'userroles') { 
 2663:         %dumphash = &dump('roles',$udom,$uname);
 2664:     } else {
 2665:         %dumphash=
 2666:             &dump('nohist_userroles',$udom,$uname);
 2667:         if ($hidepriv) {
 2668:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2669:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2670:                 if ($user !~ /:/) {
 2671:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2672:                 } else {
 2673:                     $nothide{$user} = 1;
 2674:                 }
 2675:             }
 2676:         }
 2677:     }
 2678:     my %returnhash=();
 2679:     my $now=time;
 2680:     foreach my $entry (keys(%dumphash)) {
 2681:         my ($role,$tend,$tstart);
 2682:         if ($context eq 'userroles') {
 2683: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2684:         } else {
 2685:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2686:         }
 2687:         if (($tstart) && ($tstart<0)) { next; }
 2688:         my $status = 'active';
 2689:         if (($tend) && ($tend<=$now)) {
 2690:             $status = 'previous';
 2691:         } 
 2692:         if (($tstart) && ($now<$tstart)) {
 2693:             $status = 'future';
 2694:         }
 2695:         if (ref($types) eq 'ARRAY') {
 2696:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2697:                 next;
 2698:             } 
 2699:         } else {
 2700:             if ($status ne 'active') {
 2701:                 next;
 2702:             }
 2703:         }
 2704:         my ($rolecode,$username,$domain,$section,$area);
 2705:         if ($context eq 'userroles') {
 2706:             ($area,$rolecode) = split(/_/,$entry);
 2707:             (undef,$domain,$username,$section) = split(/\//,$area);
 2708:         } else {
 2709:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2710:         }
 2711:         if (ref($roledoms) eq 'ARRAY') {
 2712:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2713:                 next;
 2714:             }
 2715:         }
 2716:         if (ref($roles) eq 'ARRAY') {
 2717:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2718:                 if ($role =~ /^cr\//) {
 2719:                     if (!grep(/^cr$/,@{$roles})) {
 2720:                         next;
 2721:                     }
 2722:                 } else {
 2723:                     next;
 2724:                 }
 2725:             }
 2726:         }
 2727:         if ($hidepriv) {
 2728:             if ((&privileged($username,$domain)) &&
 2729:                 (!$nothide{$username.':'.$domain})) { 
 2730:                 next;
 2731:             }
 2732:         }
 2733:         if ($withsec) {
 2734:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2735:                 $tstart.':'.$tend;
 2736:         } else {
 2737:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2738:         }
 2739:     }
 2740:     return %returnhash;
 2741: }
 2742: 
 2743: # ----------------------------------------------------- Frontpage Announcements
 2744: #
 2745: #
 2746: 
 2747: sub postannounce {
 2748:     my ($server,$text)=@_;
 2749:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2750:     unless ($text=~/\w/) { $text=''; }
 2751:     return &reply('setannounce:'.&escape($text),$server);
 2752: }
 2753: 
 2754: sub getannounce {
 2755: 
 2756:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2757: 	my $announcement='';
 2758: 	while (my $line = <$fh>) { $announcement .= $line; }
 2759: 	close($fh);
 2760: 	if ($announcement=~/\w/) { 
 2761: 	    return 
 2762:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2763:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2764: 	} else {
 2765: 	    return '';
 2766: 	}
 2767:     } else {
 2768: 	return '';
 2769:     }
 2770: }
 2771: 
 2772: # ---------------------------------------------------------- Course ID routines
 2773: # Deal with domain's nohist_courseid.db files
 2774: #
 2775: 
 2776: sub courseidput {
 2777:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2778:     my $outcome;
 2779:     if ($caller eq 'timeonly') {
 2780:         my $cids = '';
 2781:         foreach my $item (keys(%$storehash)) {
 2782:             $cids.=&escape($item).'&';
 2783:         }
 2784:         $cids=~s/\&$//;
 2785:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2786:                           $coursehome);       
 2787:     } else {
 2788:         my $items = '';
 2789:         foreach my $item (keys(%$storehash)) {
 2790:             $items.= &escape($item).'='.
 2791:                      &freeze_escape($$storehash{$item}).'&';
 2792:         }
 2793:         $items=~s/\&$//;
 2794:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2795:                           $coursehome);
 2796:     }
 2797:     if ($outcome eq 'unknown_cmd') {
 2798:         my $what;
 2799:         foreach my $cid (keys(%$storehash)) {
 2800:             $what .= &escape($cid).'=';
 2801:             foreach my $item ('description','inst_code','owner','type') {
 2802:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2803:             }
 2804:             $what =~ s/\:$/&/;
 2805:         }
 2806:         $what =~ s/\&$//;  
 2807:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2808:     } else {
 2809:         return $outcome;
 2810:     }
 2811: }
 2812: 
 2813: sub courseiddump {
 2814:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2815:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2816:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2817:     my $as_hash = 1;
 2818:     my %returnhash;
 2819:     if (!$domfilter) { $domfilter=''; }
 2820:     my %libserv = &all_library();
 2821:     foreach my $tryserver (keys(%libserv)) {
 2822:         if ( (  $hostidflag == 1 
 2823: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2824: 	     || (!defined($hostidflag)) ) {
 2825: 
 2826: 	    if (($domfilter eq '') ||
 2827: 		(&host_domain($tryserver) eq $domfilter)) {
 2828:                 my $rep = 
 2829:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2830:                          $sincefilter.':'.&escape($descfilter).':'.
 2831:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2832:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2833:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2834:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2835:                          $showhidden.':'.$caller,$tryserver);
 2836:                 my @pairs=split(/\&/,$rep);
 2837:                 foreach my $item (@pairs) {
 2838:                     my ($key,$value)=split(/\=/,$item,2);
 2839:                     $key = &unescape($key);
 2840:                     next if ($key =~ /^error: 2 /);
 2841:                     my $result = &thaw_unescape($value);
 2842:                     if (ref($result) eq 'HASH') {
 2843:                         $returnhash{$key}=$result;
 2844:                     } else {
 2845:                         my @responses = split(/:/,$value);
 2846:                         my @items = ('description','inst_code','owner','type');
 2847:                         for (my $i=0; $i<@responses; $i++) {
 2848:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2849:                         }
 2850:                     } 
 2851:                 }
 2852:             }
 2853:         }
 2854:     }
 2855:     return %returnhash;
 2856: }
 2857: 
 2858: # ---------------------------------------------------------- DC e-mail
 2859: 
 2860: sub dcmailput {
 2861:     my ($domain,$msgid,$message,$server)=@_;
 2862:     my $status = &Apache::lonnet::critical(
 2863:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2864:        &escape($message),$server);
 2865:     return $status;
 2866: }
 2867: 
 2868: sub dcmaildump {
 2869:     my ($dom,$startdate,$enddate,$senders) = @_;
 2870:     my %returnhash=();
 2871: 
 2872:     if (defined(&domain($dom,'primary'))) {
 2873:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2874:                                                          &escape($enddate).':';
 2875: 	my @esc_senders=map { &escape($_)} @$senders;
 2876: 	$cmd.=&escape(join('&',@esc_senders));
 2877: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2878:             my ($key,$value) = split(/\=/,$line,2);
 2879:             if (($key) && ($value)) {
 2880:                 $returnhash{&unescape($key)} = &unescape($value);
 2881:             }
 2882:         }
 2883:     }
 2884:     return %returnhash;
 2885: }
 2886: # ---------------------------------------------------------- Domain roles
 2887: 
 2888: sub get_domain_roles {
 2889:     my ($dom,$roles,$startdate,$enddate)=@_;
 2890:     if (undef($startdate) || $startdate eq '') {
 2891:         $startdate = '.';
 2892:     }
 2893:     if (undef($enddate) || $enddate eq '') {
 2894:         $enddate = '.';
 2895:     }
 2896:     my $rolelist;
 2897:     if (ref($roles) eq 'ARRAY') {
 2898:         $rolelist = join(':',@{$roles});
 2899:     }
 2900:     my %personnel = ();
 2901: 
 2902:     my %servers = &get_servers($dom,'library');
 2903:     foreach my $tryserver (keys(%servers)) {
 2904: 	%{$personnel{$tryserver}}=();
 2905: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2906: 					    &escape($startdate).':'.
 2907: 					    &escape($enddate).':'.
 2908: 					    &escape($rolelist), $tryserver))) {
 2909: 	    my ($key,$value) = split(/\=/,$line,2);
 2910: 	    if (($key) && ($value)) {
 2911: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2912: 	    }
 2913: 	}
 2914:     }
 2915:     return %personnel;
 2916: }
 2917: 
 2918: # ----------------------------------------------------------- Check out an item
 2919: 
 2920: sub get_first_access {
 2921:     my ($type,$argsymb)=@_;
 2922:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2923:     if ($argsymb) { $symb=$argsymb; }
 2924:     my ($map,$id,$res)=&decode_symb($symb);
 2925:     if ($type eq 'course') {
 2926: 	$res='course';
 2927:     } elsif ($type eq 'map') {
 2928: 	$res=&symbread($map);
 2929:     } else {
 2930: 	$res=$symb;
 2931:     }
 2932:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2933:     return $times{"$courseid\0$res"};
 2934: }
 2935: 
 2936: sub set_first_access {
 2937:     my ($type)=@_;
 2938:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2939:     my ($map,$id,$res)=&decode_symb($symb);
 2940:     if ($type eq 'course') {
 2941: 	$res='course';
 2942:     } elsif ($type eq 'map') {
 2943: 	$res=&symbread($map);
 2944:     } else {
 2945: 	$res=$symb;
 2946:     }
 2947:     my $firstaccess=&get_first_access($type,$symb);
 2948:     if (!$firstaccess) {
 2949: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2950:     }
 2951:     return 'already_set';
 2952: }
 2953: 
 2954: sub checkout {
 2955:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2956:     my $now=time;
 2957:     my $lonhost=$perlvar{'lonHostID'};
 2958:     my $infostr=&escape(
 2959:                  'CHECKOUTTOKEN&'.
 2960:                  $tuname.'&'.
 2961:                  $tudom.'&'.
 2962:                  $tcrsid.'&'.
 2963:                  $symb.'&'.
 2964: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2965:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2966:     if ($token=~/^error\:/) { 
 2967:         &logthis("<font color=\"blue\">WARNING: ".
 2968:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2969:                  "</font>");
 2970:         return ''; 
 2971:     }
 2972: 
 2973:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2974:     $token=~tr/a-z/A-Z/;
 2975: 
 2976:     my %infohash=('resource.0.outtoken' => $token,
 2977:                   'resource.0.checkouttime' => $now,
 2978:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 2979: 
 2980:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 2981:        return '';
 2982:     } else {
 2983:         &logthis("<font color=\"blue\">WARNING: ".
 2984:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 2985:                  "</font>");
 2986:     }    
 2987: 
 2988:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 2989:                          &escape('Checkout '.$infostr.' - '.
 2990:                                                  $token)) ne 'ok') {
 2991: 	return '';
 2992:     } else {
 2993:         &logthis("<font color=\"blue\">WARNING: ".
 2994:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 2995:                  "</font>");
 2996:     }
 2997:     return $token;
 2998: }
 2999: 
 3000: # ------------------------------------------------------------ Check in an item
 3001: 
 3002: sub checkin {
 3003:     my $token=shift;
 3004:     my $now=time;
 3005:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3006:     $lonhost=~tr/A-Z/a-z/;
 3007:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3008:     $dtoken=~s/\W/\_/g;
 3009:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3010:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3011: 
 3012:     unless (($tuname) && ($tudom)) {
 3013:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3014:         return '';
 3015:     }
 3016:     
 3017:     unless (&allowed('mgr',$tcrsid)) {
 3018:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3019:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3020:         return '';
 3021:     }
 3022: 
 3023:     my %infohash=('resource.0.intoken' => $token,
 3024:                   'resource.0.checkintime' => $now,
 3025:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3026: 
 3027:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3028:        return '';
 3029:     }    
 3030: 
 3031:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3032:                          &escape('Checkin - '.$token)) ne 'ok') {
 3033: 	return '';
 3034:     }
 3035: 
 3036:     return ($symb,$tuname,$tudom,$tcrsid);    
 3037: }
 3038: 
 3039: # --------------------------------------------- Set Expire Date for Spreadsheet
 3040: 
 3041: sub expirespread {
 3042:     my ($uname,$udom,$stype,$usymb)=@_;
 3043:     my $cid=$env{'request.course.id'}; 
 3044:     if ($cid) {
 3045:        my $now=time;
 3046:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3047:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3048:                             $env{'course.'.$cid.'.num'}.
 3049: 	        	    ':nohist_expirationdates:'.
 3050:                             &escape($key).'='.$now,
 3051:                             $env{'course.'.$cid.'.home'})
 3052:     }
 3053:     return 'ok';
 3054: }
 3055: 
 3056: # ----------------------------------------------------- Devalidate Spreadsheets
 3057: 
 3058: sub devalidate {
 3059:     my ($symb,$uname,$udom)=@_;
 3060:     my $cid=$env{'request.course.id'}; 
 3061:     if ($cid) {
 3062:         # delete the stored spreadsheets for
 3063:         # - the student level sheet of this user in course's homespace
 3064:         # - the assessment level sheet for this resource 
 3065:         #   for this user in user's homespace
 3066: 	# - current conditional state info
 3067: 	my $key=$uname.':'.$udom.':';
 3068:         my $status=
 3069: 	    &del('nohist_calculatedsheets',
 3070: 		 [$key.'studentcalc:'],
 3071: 		 $env{'course.'.$cid.'.domain'},
 3072: 		 $env{'course.'.$cid.'.num'})
 3073: 		.' '.
 3074: 	    &del('nohist_calculatedsheets_'.$cid,
 3075: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3076:         unless ($status eq 'ok ok') {
 3077:            &logthis('Could not devalidate spreadsheet '.
 3078:                     $uname.' at '.$udom.' for '.
 3079: 		    $symb.': '.$status);
 3080:         }
 3081: 	&delenv('user.state.'.$cid);
 3082:     }
 3083: }
 3084: 
 3085: sub get_scalar {
 3086:     my ($string,$end) = @_;
 3087:     my $value;
 3088:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3089: 	$value = $1;
 3090:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3091: 	$value = $1;
 3092:     }
 3093:     return &unescape($value);
 3094: }
 3095: 
 3096: sub array2str {
 3097:   my (@array) = @_;
 3098:   my $result=&arrayref2str(\@array);
 3099:   $result=~s/^__ARRAY_REF__//;
 3100:   $result=~s/__END_ARRAY_REF__$//;
 3101:   return $result;
 3102: }
 3103: 
 3104: sub arrayref2str {
 3105:   my ($arrayref) = @_;
 3106:   my $result='__ARRAY_REF__';
 3107:   foreach my $elem (@$arrayref) {
 3108:     if(ref($elem) eq 'ARRAY') {
 3109:       $result.=&arrayref2str($elem).'&';
 3110:     } elsif(ref($elem) eq 'HASH') {
 3111:       $result.=&hashref2str($elem).'&';
 3112:     } elsif(ref($elem)) {
 3113:       #print("Got a ref of ".(ref($elem))." skipping.");
 3114:     } else {
 3115:       $result.=&escape($elem).'&';
 3116:     }
 3117:   }
 3118:   $result=~s/\&$//;
 3119:   $result .= '__END_ARRAY_REF__';
 3120:   return $result;
 3121: }
 3122: 
 3123: sub hash2str {
 3124:   my (%hash) = @_;
 3125:   my $result=&hashref2str(\%hash);
 3126:   $result=~s/^__HASH_REF__//;
 3127:   $result=~s/__END_HASH_REF__$//;
 3128:   return $result;
 3129: }
 3130: 
 3131: sub hashref2str {
 3132:   my ($hashref)=@_;
 3133:   my $result='__HASH_REF__';
 3134:   foreach my $key (sort(keys(%$hashref))) {
 3135:     if (ref($key) eq 'ARRAY') {
 3136:       $result.=&arrayref2str($key).'=';
 3137:     } elsif (ref($key) eq 'HASH') {
 3138:       $result.=&hashref2str($key).'=';
 3139:     } elsif (ref($key)) {
 3140:       $result.='=';
 3141:       #print("Got a ref of ".(ref($key))." skipping.");
 3142:     } else {
 3143: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3144:     }
 3145: 
 3146:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3147:       $result.=&arrayref2str($hashref->{$key}).'&';
 3148:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3149:       $result.=&hashref2str($hashref->{$key}).'&';
 3150:     } elsif(ref($hashref->{$key})) {
 3151:        $result.='&';
 3152:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3153:     } else {
 3154:       $result.=&escape($hashref->{$key}).'&';
 3155:     }
 3156:   }
 3157:   $result=~s/\&$//;
 3158:   $result .= '__END_HASH_REF__';
 3159:   return $result;
 3160: }
 3161: 
 3162: sub str2hash {
 3163:     my ($string)=@_;
 3164:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3165:     return %$hash;
 3166: }
 3167: 
 3168: sub str2hashref {
 3169:   my ($string) = @_;
 3170: 
 3171:   my %hash;
 3172: 
 3173:   if($string !~ /^__HASH_REF__/) {
 3174:       if (! ($string eq '' || !defined($string))) {
 3175: 	  $hash{'error'}='Not hash reference';
 3176:       }
 3177:       return (\%hash, $string);
 3178:   }
 3179: 
 3180:   $string =~ s/^__HASH_REF__//;
 3181: 
 3182:   while($string !~ /^__END_HASH_REF__/) {
 3183:       #key
 3184:       my $key='';
 3185:       if($string =~ /^__HASH_REF__/) {
 3186:           ($key, $string)=&str2hashref($string);
 3187:           if(defined($key->{'error'})) {
 3188:               $hash{'error'}='Bad data';
 3189:               return (\%hash, $string);
 3190:           }
 3191:       } elsif($string =~ /^__ARRAY_REF__/) {
 3192:           ($key, $string)=&str2arrayref($string);
 3193:           if($key->[0] eq 'Array reference error') {
 3194:               $hash{'error'}='Bad data';
 3195:               return (\%hash, $string);
 3196:           }
 3197:       } else {
 3198:           $string =~ s/^(.*?)=//;
 3199: 	  $key=&unescape($1);
 3200:       }
 3201:       $string =~ s/^=//;
 3202: 
 3203:       #value
 3204:       my $value='';
 3205:       if($string =~ /^__HASH_REF__/) {
 3206:           ($value, $string)=&str2hashref($string);
 3207:           if(defined($value->{'error'})) {
 3208:               $hash{'error'}='Bad data';
 3209:               return (\%hash, $string);
 3210:           }
 3211:       } elsif($string =~ /^__ARRAY_REF__/) {
 3212:           ($value, $string)=&str2arrayref($string);
 3213:           if($value->[0] eq 'Array reference error') {
 3214:               $hash{'error'}='Bad data';
 3215:               return (\%hash, $string);
 3216:           }
 3217:       } else {
 3218: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3219:       }
 3220:       $string =~ s/^&//;
 3221: 
 3222:       $hash{$key}=$value;
 3223:   }
 3224: 
 3225:   $string =~ s/^__END_HASH_REF__//;
 3226: 
 3227:   return (\%hash, $string);
 3228: }
 3229: 
 3230: sub str2array {
 3231:     my ($string)=@_;
 3232:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3233:     return @$array;
 3234: }
 3235: 
 3236: sub str2arrayref {
 3237:   my ($string) = @_;
 3238:   my @array;
 3239: 
 3240:   if($string !~ /^__ARRAY_REF__/) {
 3241:       if (! ($string eq '' || !defined($string))) {
 3242: 	  $array[0]='Array reference error';
 3243:       }
 3244:       return (\@array, $string);
 3245:   }
 3246: 
 3247:   $string =~ s/^__ARRAY_REF__//;
 3248: 
 3249:   while($string !~ /^__END_ARRAY_REF__/) {
 3250:       my $value='';
 3251:       if($string =~ /^__HASH_REF__/) {
 3252:           ($value, $string)=&str2hashref($string);
 3253:           if(defined($value->{'error'})) {
 3254:               $array[0] ='Array reference error';
 3255:               return (\@array, $string);
 3256:           }
 3257:       } elsif($string =~ /^__ARRAY_REF__/) {
 3258:           ($value, $string)=&str2arrayref($string);
 3259:           if($value->[0] eq 'Array reference error') {
 3260:               $array[0] ='Array reference error';
 3261:               return (\@array, $string);
 3262:           }
 3263:       } else {
 3264: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3265:       }
 3266:       $string =~ s/^&//;
 3267: 
 3268:       push(@array, $value);
 3269:   }
 3270: 
 3271:   $string =~ s/^__END_ARRAY_REF__//;
 3272: 
 3273:   return (\@array, $string);
 3274: }
 3275: 
 3276: # -------------------------------------------------------------------Temp Store
 3277: 
 3278: sub tmpreset {
 3279:   my ($symb,$namespace,$domain,$stuname) = @_;
 3280:   if (!$symb) {
 3281:     $symb=&symbread();
 3282:     if (!$symb) { $symb= $env{'request.url'}; }
 3283:   }
 3284:   $symb=escape($symb);
 3285: 
 3286:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3287:   $namespace=~s/\//\_/g;
 3288:   $namespace=~s/\W//g;
 3289: 
 3290:   if (!$domain) { $domain=$env{'user.domain'}; }
 3291:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3292:   if ($domain eq 'public' && $stuname eq 'public') {
 3293:       $stuname=$ENV{'REMOTE_ADDR'};
 3294:   }
 3295:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3296:   my %hash;
 3297:   if (tie(%hash,'GDBM_File',
 3298: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3299: 	  &GDBM_WRCREAT(),0640)) {
 3300:     foreach my $key (keys %hash) {
 3301:       if ($key=~ /:$symb/) {
 3302: 	delete($hash{$key});
 3303:       }
 3304:     }
 3305:   }
 3306: }
 3307: 
 3308: sub tmpstore {
 3309:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3310: 
 3311:   if (!$symb) {
 3312:     $symb=&symbread();
 3313:     if (!$symb) { $symb= $env{'request.url'}; }
 3314:   }
 3315:   $symb=escape($symb);
 3316: 
 3317:   if (!$namespace) {
 3318:     # I don't think we would ever want to store this for a course.
 3319:     # it seems this will only be used if we don't have a course.
 3320:     #$namespace=$env{'request.course.id'};
 3321:     #if (!$namespace) {
 3322:       $namespace=$env{'request.state'};
 3323:     #}
 3324:   }
 3325:   $namespace=~s/\//\_/g;
 3326:   $namespace=~s/\W//g;
 3327:   if (!$domain) { $domain=$env{'user.domain'}; }
 3328:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3329:   if ($domain eq 'public' && $stuname eq 'public') {
 3330:       $stuname=$ENV{'REMOTE_ADDR'};
 3331:   }
 3332:   my $now=time;
 3333:   my %hash;
 3334:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3335:   if (tie(%hash,'GDBM_File',
 3336: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3337: 	  &GDBM_WRCREAT(),0640)) {
 3338:     $hash{"version:$symb"}++;
 3339:     my $version=$hash{"version:$symb"};
 3340:     my $allkeys=''; 
 3341:     foreach my $key (keys(%$storehash)) {
 3342:       $allkeys.=$key.':';
 3343:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3344:     }
 3345:     $hash{"$version:$symb:timestamp"}=$now;
 3346:     $allkeys.='timestamp';
 3347:     $hash{"$version:keys:$symb"}=$allkeys;
 3348:     if (untie(%hash)) {
 3349:       return 'ok';
 3350:     } else {
 3351:       return "error:$!";
 3352:     }
 3353:   } else {
 3354:     return "error:$!";
 3355:   }
 3356: }
 3357: 
 3358: # -----------------------------------------------------------------Temp Restore
 3359: 
 3360: sub tmprestore {
 3361:   my ($symb,$namespace,$domain,$stuname) = @_;
 3362: 
 3363:   if (!$symb) {
 3364:     $symb=&symbread();
 3365:     if (!$symb) { $symb= $env{'request.url'}; }
 3366:   }
 3367:   $symb=escape($symb);
 3368: 
 3369:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3370: 
 3371:   if (!$domain) { $domain=$env{'user.domain'}; }
 3372:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3373:   if ($domain eq 'public' && $stuname eq 'public') {
 3374:       $stuname=$ENV{'REMOTE_ADDR'};
 3375:   }
 3376:   my %returnhash;
 3377:   $namespace=~s/\//\_/g;
 3378:   $namespace=~s/\W//g;
 3379:   my %hash;
 3380:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3381:   if (tie(%hash,'GDBM_File',
 3382: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3383: 	  &GDBM_READER(),0640)) {
 3384:     my $version=$hash{"version:$symb"};
 3385:     $returnhash{'version'}=$version;
 3386:     my $scope;
 3387:     for ($scope=1;$scope<=$version;$scope++) {
 3388:       my $vkeys=$hash{"$scope:keys:$symb"};
 3389:       my @keys=split(/:/,$vkeys);
 3390:       my $key;
 3391:       $returnhash{"$scope:keys"}=$vkeys;
 3392:       foreach $key (@keys) {
 3393: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3394: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3395:       }
 3396:     }
 3397:     if (!(untie(%hash))) {
 3398:       return "error:$!";
 3399:     }
 3400:   } else {
 3401:     return "error:$!";
 3402:   }
 3403:   return %returnhash;
 3404: }
 3405: 
 3406: # ----------------------------------------------------------------------- Store
 3407: 
 3408: sub store {
 3409:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3410:     my $home='';
 3411: 
 3412:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3413: 
 3414:     $symb=&symbclean($symb);
 3415:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3416: 
 3417:     if (!$domain) { $domain=$env{'user.domain'}; }
 3418:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3419: 
 3420:     &devalidate($symb,$stuname,$domain);
 3421: 
 3422:     $symb=escape($symb);
 3423:     if (!$namespace) { 
 3424:        unless ($namespace=$env{'request.course.id'}) { 
 3425:           return ''; 
 3426:        } 
 3427:     }
 3428:     if (!$home) { $home=$env{'user.home'}; }
 3429: 
 3430:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3431:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3432: 
 3433:     my $namevalue='';
 3434:     foreach my $key (keys(%$storehash)) {
 3435:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3436:     }
 3437:     $namevalue=~s/\&$//;
 3438:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3439:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3440: }
 3441: 
 3442: # -------------------------------------------------------------- Critical Store
 3443: 
 3444: sub cstore {
 3445:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3446:     my $home='';
 3447: 
 3448:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3449: 
 3450:     $symb=&symbclean($symb);
 3451:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3452: 
 3453:     if (!$domain) { $domain=$env{'user.domain'}; }
 3454:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3455: 
 3456:     &devalidate($symb,$stuname,$domain);
 3457: 
 3458:     $symb=escape($symb);
 3459:     if (!$namespace) { 
 3460:        unless ($namespace=$env{'request.course.id'}) { 
 3461:           return ''; 
 3462:        } 
 3463:     }
 3464:     if (!$home) { $home=$env{'user.home'}; }
 3465: 
 3466:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3467:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3468: 
 3469:     my $namevalue='';
 3470:     foreach my $key (keys(%$storehash)) {
 3471:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3472:     }
 3473:     $namevalue=~s/\&$//;
 3474:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3475:     return critical
 3476:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3477: }
 3478: 
 3479: # --------------------------------------------------------------------- Restore
 3480: 
 3481: sub restore {
 3482:     my ($symb,$namespace,$domain,$stuname) = @_;
 3483:     my $home='';
 3484: 
 3485:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3486: 
 3487:     if (!$symb) {
 3488:       unless ($symb=escape(&symbread())) { return ''; }
 3489:     } else {
 3490:       $symb=&escape(&symbclean($symb));
 3491:     }
 3492:     if (!$namespace) { 
 3493:        unless ($namespace=$env{'request.course.id'}) { 
 3494:           return ''; 
 3495:        } 
 3496:     }
 3497:     if (!$domain) { $domain=$env{'user.domain'}; }
 3498:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3499:     if (!$home) { $home=$env{'user.home'}; }
 3500:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3501: 
 3502:     my %returnhash=();
 3503:     foreach my $line (split(/\&/,$answer)) {
 3504: 	my ($name,$value)=split(/\=/,$line);
 3505:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3506:     }
 3507:     my $version;
 3508:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3509:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3510:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3511:        }
 3512:     }
 3513:     return %returnhash;
 3514: }
 3515: 
 3516: # ---------------------------------------------------------- Course Description
 3517: 
 3518: sub coursedescription {
 3519:     my ($courseid,$args)=@_;
 3520:     $courseid=~s/^\///;
 3521:     $courseid=~s/\_/\//g;
 3522:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3523:     my $chome=&homeserver($cnum,$cdomain);
 3524:     my $normalid=$cdomain.'_'.$cnum;
 3525:     # need to always cache even if we get errors otherwise we keep 
 3526:     # trying and trying and trying to get the course description.
 3527:     my %envhash=();
 3528:     my %returnhash=();
 3529:     
 3530:     my $expiretime=600;
 3531:     if ($env{'request.course.id'} eq $normalid) {
 3532: 	$expiretime=120;
 3533:     }
 3534: 
 3535:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3536:     if (!$args->{'freshen_cache'}
 3537: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3538: 	foreach my $key (keys(%env)) {
 3539: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3540: 	    my ($setting) = $1;
 3541: 	    $returnhash{$setting} = $env{$key};
 3542: 	}
 3543: 	return %returnhash;
 3544:     }
 3545: 
 3546:     # get the data agin
 3547:     if (!$args->{'one_time'}) {
 3548: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3549:     }
 3550: 
 3551:     if ($chome ne 'no_host') {
 3552:        %returnhash=&dump('environment',$cdomain,$cnum);
 3553:        if (!exists($returnhash{'con_lost'})) {
 3554:            $returnhash{'home'}= $chome;
 3555: 	   $returnhash{'domain'} = $cdomain;
 3556: 	   $returnhash{'num'} = $cnum;
 3557:            if (!defined($returnhash{'type'})) {
 3558:                $returnhash{'type'} = 'Course';
 3559:            }
 3560:            while (my ($name,$value) = each %returnhash) {
 3561:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3562:            }
 3563:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3564:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3565: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3566:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3567:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3568:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3569:        }
 3570:     }
 3571:     if (!$args->{'one_time'}) {
 3572: 	&appenv(\%envhash);
 3573:     }
 3574:     return %returnhash;
 3575: }
 3576: 
 3577: # -------------------------------------------------See if a user is privileged
 3578: 
 3579: sub privileged {
 3580:     my ($username,$domain)=@_;
 3581:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3582: 			&homeserver($username,$domain));
 3583:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3584:     my $now=time;
 3585:     if ($rolesdump ne '') {
 3586:         foreach my $entry (split(/&/,$rolesdump)) {
 3587: 	    if ($entry!~/^rolesdef_/) {
 3588: 		my ($area,$role)=split(/=/,$entry);
 3589: 		$area=~s/\_\w\w$//;
 3590: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3591: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3592: 		    my $active=1;
 3593: 		    if ($tend) {
 3594: 			if ($tend<$now) { $active=0; }
 3595: 		    }
 3596: 		    if ($tstart) {
 3597: 			if ($tstart>$now) { $active=0; }
 3598: 		    }
 3599: 		    if ($active) { return 1; }
 3600: 		}
 3601: 	    }
 3602: 	}
 3603:     }
 3604:     return 0;
 3605: }
 3606: 
 3607: # -------------------------------------------------------- Get user privileges
 3608: 
 3609: sub rolesinit {
 3610:     my ($domain,$username,$authhost)=@_;
 3611:     my %userroles;
 3612:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3613:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3614:     my %allroles=();
 3615:     my %allgroups=();   
 3616:     my $now=time;
 3617:     %userroles = ('user.login.time' => $now);
 3618:     my $group_privs;
 3619: 
 3620:     if ($rolesdump ne '') {
 3621:         foreach my $entry (split(/&/,$rolesdump)) {
 3622: 	  if ($entry!~/^rolesdef_/) {
 3623:             my ($area,$role)=split(/=/,$entry);
 3624: 	    $area=~s/\_\w\w$//;
 3625:             my ($trole,$tend,$tstart,$group_privs);
 3626: 	    if ($role=~/^cr/) { 
 3627: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3628: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3629: 		    ($tend,$tstart)=split('_',$trest);
 3630: 		} else {
 3631: 		    $trole=$role;
 3632: 		}
 3633:             } elsif ($role =~ m|^gr/|) {
 3634:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3635:                 ($trole,$group_privs) = split(/\//,$trole);
 3636:                 $group_privs = &unescape($group_privs);
 3637: 	    } else {
 3638: 		($trole,$tend,$tstart)=split(/_/,$role);
 3639: 	    }
 3640: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3641: 					 $username);
 3642: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3643:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3644:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3645:             if (($area ne '') && ($trole ne '')) {
 3646: 		my $spec=$trole.'.'.$area;
 3647: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3648: 		if ($trole =~ /^cr\//) {
 3649:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3650:                 } elsif ($trole eq 'gr') {
 3651:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3652: 		} else {
 3653:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3654: 		}
 3655:             }
 3656:           }
 3657:         }
 3658:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3659:         $userroles{'user.adv'}    = $adv;
 3660: 	$userroles{'user.author'} = $author;
 3661:         $env{'user.adv'}=$adv;
 3662:     }
 3663:     return \%userroles;  
 3664: }
 3665: 
 3666: sub set_arearole {
 3667:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3668: # log the associated role with the area
 3669:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3670:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3671: }
 3672: 
 3673: sub custom_roleprivs {
 3674:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3675:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3676:     my $homsvr=homeserver($rauthor,$rdomain);
 3677:     if (&hostname($homsvr) ne '') {
 3678:         my ($rdummy,$roledef)=
 3679:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3680:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3681:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3682:             if (defined($syspriv)) {
 3683:                 $$allroles{'cm./'}.=':'.$syspriv;
 3684:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3685:             }
 3686:             if ($tdomain ne '') {
 3687:                 if (defined($dompriv)) {
 3688:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3689:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3690:                 }
 3691:                 if (($trest ne '') && (defined($coursepriv))) {
 3692:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3693:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3694:                 }
 3695:             }
 3696:         }
 3697:     }
 3698: }
 3699: 
 3700: sub group_roleprivs {
 3701:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3702:     my $access = 1;
 3703:     my $now = time;
 3704:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3705:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3706:     if ($access) {
 3707:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3708:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3709:     }
 3710: }
 3711: 
 3712: sub standard_roleprivs {
 3713:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3714:     if (defined($pr{$trole.':s'})) {
 3715:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3716:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3717:     }
 3718:     if ($tdomain ne '') {
 3719:         if (defined($pr{$trole.':d'})) {
 3720:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3721:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3722:         }
 3723:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3724:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3725:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3726:         }
 3727:     }
 3728: }
 3729: 
 3730: sub set_userprivs {
 3731:     my ($userroles,$allroles,$allgroups) = @_; 
 3732:     my $author=0;
 3733:     my $adv=0;
 3734:     my %grouproles = ();
 3735:     if (keys(%{$allgroups}) > 0) {
 3736:         foreach my $role (keys %{$allroles}) {
 3737:             my ($trole,$area,$sec,$extendedarea);
 3738:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3739:                 $trole = $1;
 3740:                 $area = $2;
 3741:                 $sec = $3;
 3742:                 $extendedarea = $area.$sec;
 3743:                 if (exists($$allgroups{$area})) {
 3744:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3745:                         my $spec = $trole.'.'.$extendedarea;
 3746:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3747:                                                 $$allgroups{$area}{$group};
 3748:                     }
 3749:                 }
 3750:             }
 3751:         }
 3752:     }
 3753:     foreach my $group (keys(%grouproles)) {
 3754:         $$allroles{$group} = $grouproles{$group};
 3755:     }
 3756:     foreach my $role (keys(%{$allroles})) {
 3757:         my %thesepriv;
 3758:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3759:         foreach my $item (split(/:/,$$allroles{$role})) {
 3760:             if ($item ne '') {
 3761:                 my ($privilege,$restrictions)=split(/&/,$item);
 3762:                 if ($restrictions eq '') {
 3763:                     $thesepriv{$privilege}='F';
 3764:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3765:                     $thesepriv{$privilege}.=$restrictions;
 3766:                 }
 3767:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3768:             }
 3769:         }
 3770:         my $thesestr='';
 3771:         foreach my $priv (keys(%thesepriv)) {
 3772: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3773: 	}
 3774:         $userroles->{'user.priv.'.$role} = $thesestr;
 3775:     }
 3776:     return ($author,$adv);
 3777: }
 3778: 
 3779: # --------------------------------------------------------------- get interface
 3780: 
 3781: sub get {
 3782:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3783:    my $items='';
 3784:    foreach my $item (@$storearr) {
 3785:        $items.=&escape($item).'&';
 3786:    }
 3787:    $items=~s/\&$//;
 3788:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3789:    if (!$uname) { $uname=$env{'user.name'}; }
 3790:    my $uhome=&homeserver($uname,$udomain);
 3791: 
 3792:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3793:    my @pairs=split(/\&/,$rep);
 3794:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3795:      return @pairs;
 3796:    }
 3797:    my %returnhash=();
 3798:    my $i=0;
 3799:    foreach my $item (@$storearr) {
 3800:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3801:       $i++;
 3802:    }
 3803:    return %returnhash;
 3804: }
 3805: 
 3806: # --------------------------------------------------------------- del interface
 3807: 
 3808: sub del {
 3809:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3810:    my $items='';
 3811:    foreach my $item (@$storearr) {
 3812:        $items.=&escape($item).'&';
 3813:    }
 3814:    $items=~s/\&$//;
 3815:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3816:    if (!$uname) { $uname=$env{'user.name'}; }
 3817:    my $uhome=&homeserver($uname,$udomain);
 3818: 
 3819:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3820: }
 3821: 
 3822: # -------------------------------------------------------------- dump interface
 3823: 
 3824: sub dump {
 3825:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3826:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3827:     if (!$uname) { $uname=$env{'user.name'}; }
 3828:     my $uhome=&homeserver($uname,$udomain);
 3829:     if ($regexp) {
 3830: 	$regexp=&escape($regexp);
 3831:     } else {
 3832: 	$regexp='.';
 3833:     }
 3834:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3835:     my @pairs=split(/\&/,$rep);
 3836:     my %returnhash=();
 3837:     foreach my $item (@pairs) {
 3838: 	my ($key,$value)=split(/=/,$item,2);
 3839: 	$key = &unescape($key);
 3840: 	next if ($key =~ /^error: 2 /);
 3841: 	$returnhash{$key}=&thaw_unescape($value);
 3842:     }
 3843:     return %returnhash;
 3844: }
 3845: 
 3846: # --------------------------------------------------------- dumpstore interface
 3847: 
 3848: sub dumpstore {
 3849:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3850:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3851:    if (!$uname) { $uname=$env{'user.name'}; }
 3852:    my $uhome=&homeserver($uname,$udomain);
 3853:    if ($regexp) {
 3854:        $regexp=&escape($regexp);
 3855:    } else {
 3856:        $regexp='.';
 3857:    }
 3858:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3859:    my @pairs=split(/\&/,$rep);
 3860:    my %returnhash=();
 3861:    foreach my $item (@pairs) {
 3862:        my ($key,$value)=split(/=/,$item,2);
 3863:        next if ($key =~ /^error: 2 /);
 3864:        $returnhash{$key}=&thaw_unescape($value);
 3865:    }
 3866:    return %returnhash;
 3867: }
 3868: 
 3869: # -------------------------------------------------------------- keys interface
 3870: 
 3871: sub getkeys {
 3872:    my ($namespace,$udomain,$uname)=@_;
 3873:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3874:    if (!$uname) { $uname=$env{'user.name'}; }
 3875:    my $uhome=&homeserver($uname,$udomain);
 3876:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3877:    my @keyarray=();
 3878:    foreach my $key (split(/\&/,$rep)) {
 3879:       next if ($key =~ /^error: 2 /);
 3880:       push(@keyarray,&unescape($key));
 3881:    }
 3882:    return @keyarray;
 3883: }
 3884: 
 3885: # --------------------------------------------------------------- currentdump
 3886: sub currentdump {
 3887:    my ($courseid,$sdom,$sname)=@_;
 3888:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3889:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3890:    $sname    = $env{'user.name'}         if (! defined($sname));
 3891:    my $uhome = &homeserver($sname,$sdom);
 3892:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3893:    return if ($rep =~ /^(error:|no_such_host)/);
 3894:    #
 3895:    my %returnhash=();
 3896:    #
 3897:    if ($rep eq "unknown_cmd") { 
 3898:        # an old lond will not know currentdump
 3899:        # Do a dump and make it look like a currentdump
 3900:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3901:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3902:        my %hash = @tmp;
 3903:        @tmp=();
 3904:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3905:    } else {
 3906:        my @pairs=split(/\&/,$rep);
 3907:        foreach my $pair (@pairs) {
 3908:            my ($key,$value)=split(/=/,$pair,2);
 3909:            my ($symb,$param) = split(/:/,$key);
 3910:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3911:                                                         &thaw_unescape($value);
 3912:        }
 3913:    }
 3914:    return %returnhash;
 3915: }
 3916: 
 3917: sub convert_dump_to_currentdump{
 3918:     my %hash = %{shift()};
 3919:     my %returnhash;
 3920:     # Code ripped from lond, essentially.  The only difference
 3921:     # here is the unescaping done by lonnet::dump().  Conceivably
 3922:     # we might run in to problems with parameter names =~ /^v\./
 3923:     while (my ($key,$value) = each(%hash)) {
 3924:         my ($v,$symb,$param) = split(/:/,$key);
 3925: 	$symb  = &unescape($symb);
 3926: 	$param = &unescape($param);
 3927:         next if ($v eq 'version' || $symb eq 'keys');
 3928:         next if (exists($returnhash{$symb}) &&
 3929:                  exists($returnhash{$symb}->{$param}) &&
 3930:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3931:         $returnhash{$symb}->{$param}=$value;
 3932:         $returnhash{$symb}->{'v.'.$param}=$v;
 3933:     }
 3934:     #
 3935:     # Remove all of the keys in the hashes which keep track of
 3936:     # the version of the parameter.
 3937:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3938:         # use a foreach because we are going to delete from the hash.
 3939:         foreach my $key (keys(%$param_hash)) {
 3940:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3941:         }
 3942:     }
 3943:     return \%returnhash;
 3944: }
 3945: 
 3946: # ------------------------------------------------------ critical inc interface
 3947: 
 3948: sub cinc {
 3949:     return &inc(@_,'critical');
 3950: }
 3951: 
 3952: # --------------------------------------------------------------- inc interface
 3953: 
 3954: sub inc {
 3955:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3956:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3957:     if (!$uname) { $uname=$env{'user.name'}; }
 3958:     my $uhome=&homeserver($uname,$udomain);
 3959:     my $items='';
 3960:     if (! ref($store)) {
 3961:         # got a single value, so use that instead
 3962:         $items = &escape($store).'=&';
 3963:     } elsif (ref($store) eq 'SCALAR') {
 3964:         $items = &escape($$store).'=&';        
 3965:     } elsif (ref($store) eq 'ARRAY') {
 3966:         $items = join('=&',map {&escape($_);} @{$store});
 3967:     } elsif (ref($store) eq 'HASH') {
 3968:         while (my($key,$value) = each(%{$store})) {
 3969:             $items.= &escape($key).'='.&escape($value).'&';
 3970:         }
 3971:     }
 3972:     $items=~s/\&$//;
 3973:     if ($critical) {
 3974: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3975:     } else {
 3976: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3977:     }
 3978: }
 3979: 
 3980: # --------------------------------------------------------------- put interface
 3981: 
 3982: sub put {
 3983:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3984:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3985:    if (!$uname) { $uname=$env{'user.name'}; }
 3986:    my $uhome=&homeserver($uname,$udomain);
 3987:    my $items='';
 3988:    foreach my $item (keys(%$storehash)) {
 3989:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 3990:    }
 3991:    $items=~s/\&$//;
 3992:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 3993: }
 3994: 
 3995: # ------------------------------------------------------------ newput interface
 3996: 
 3997: sub newput {
 3998:    my ($namespace,$storehash,$udomain,$uname)=@_;
 3999:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4000:    if (!$uname) { $uname=$env{'user.name'}; }
 4001:    my $uhome=&homeserver($uname,$udomain);
 4002:    my $items='';
 4003:    foreach my $key (keys(%$storehash)) {
 4004:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4005:    }
 4006:    $items=~s/\&$//;
 4007:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4008: }
 4009: 
 4010: # ---------------------------------------------------------  putstore interface
 4011: 
 4012: sub putstore {
 4013:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4014:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4015:    if (!$uname) { $uname=$env{'user.name'}; }
 4016:    my $uhome=&homeserver($uname,$udomain);
 4017:    my $items='';
 4018:    foreach my $key (keys(%$storehash)) {
 4019:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4020:    }
 4021:    $items=~s/\&$//;
 4022:    my $esc_symb=&escape($symb);
 4023:    my $esc_v=&escape($version);
 4024:    my $reply =
 4025:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4026: 	      $uhome);
 4027:    if ($reply eq 'unknown_cmd') {
 4028:        # gfall back to way things use to be done
 4029:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4030: 			    $uname);
 4031:    }
 4032:    return $reply;
 4033: }
 4034: 
 4035: sub old_putstore {
 4036:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4037:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4038:     if (!$uname) { $uname=$env{'user.name'}; }
 4039:     my $uhome=&homeserver($uname,$udomain);
 4040:     my %newstorehash;
 4041:     foreach my $item (keys(%$storehash)) {
 4042: 	my $key = $version.':'.&escape($symb).':'.$item;
 4043: 	$newstorehash{$key} = $storehash->{$item};
 4044:     }
 4045:     my $items='';
 4046:     my %allitems = ();
 4047:     foreach my $item (keys(%newstorehash)) {
 4048: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4049: 	    my $key = $1.':keys:'.$2;
 4050: 	    $allitems{$key} .= $3.':';
 4051: 	}
 4052: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4053:     }
 4054:     foreach my $item (keys(%allitems)) {
 4055: 	$allitems{$item} =~ s/\:$//;
 4056: 	$items.= $item.'='.$allitems{$item}.'&';
 4057:     }
 4058:     $items=~s/\&$//;
 4059:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4060: }
 4061: 
 4062: # ------------------------------------------------------ critical put interface
 4063: 
 4064: sub cput {
 4065:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4066:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4067:    if (!$uname) { $uname=$env{'user.name'}; }
 4068:    my $uhome=&homeserver($uname,$udomain);
 4069:    my $items='';
 4070:    foreach my $item (keys(%$storehash)) {
 4071:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4072:    }
 4073:    $items=~s/\&$//;
 4074:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4075: }
 4076: 
 4077: # -------------------------------------------------------------- eget interface
 4078: 
 4079: sub eget {
 4080:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4081:    my $items='';
 4082:    foreach my $item (@$storearr) {
 4083:        $items.=&escape($item).'&';
 4084:    }
 4085:    $items=~s/\&$//;
 4086:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4087:    if (!$uname) { $uname=$env{'user.name'}; }
 4088:    my $uhome=&homeserver($uname,$udomain);
 4089:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4090:    my @pairs=split(/\&/,$rep);
 4091:    my %returnhash=();
 4092:    my $i=0;
 4093:    foreach my $item (@$storearr) {
 4094:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4095:       $i++;
 4096:    }
 4097:    return %returnhash;
 4098: }
 4099: 
 4100: # ------------------------------------------------------------ tmpput interface
 4101: sub tmpput {
 4102:     my ($storehash,$server,$context)=@_;
 4103:     my $items='';
 4104:     foreach my $item (keys(%$storehash)) {
 4105: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4106:     }
 4107:     $items=~s/\&$//;
 4108:     if (defined($context)) {
 4109:         $items .= ':'.&escape($context);
 4110:     }
 4111:     return &reply("tmpput:$items",$server);
 4112: }
 4113: 
 4114: # ------------------------------------------------------------ tmpget interface
 4115: sub tmpget {
 4116:     my ($token,$server)=@_;
 4117:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4118:     my $rep=&reply("tmpget:$token",$server);
 4119:     my %returnhash;
 4120:     foreach my $item (split(/\&/,$rep)) {
 4121: 	my ($key,$value)=split(/=/,$item);
 4122:         next if ($key =~ /^error: 2 /);
 4123: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4124:     }
 4125:     return %returnhash;
 4126: }
 4127: 
 4128: # ------------------------------------------------------------ tmpget interface
 4129: sub tmpdel {
 4130:     my ($token,$server)=@_;
 4131:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4132:     return &reply("tmpdel:$token",$server);
 4133: }
 4134: 
 4135: # -------------------------------------------------- portfolio access checking
 4136: 
 4137: sub portfolio_access {
 4138:     my ($requrl) = @_;
 4139:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4140:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4141:     if ($result) {
 4142:         my %setters;
 4143:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4144:             my ($startblock,$endblock) =
 4145:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4146:             if ($startblock && $endblock) {
 4147:                 return 'B';
 4148:             }
 4149:         } else {
 4150:             my ($startblock,$endblock) =
 4151:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4152:             if ($startblock && $endblock) {
 4153:                 return 'B';
 4154:             }
 4155:         }
 4156:     }
 4157:     if ($result eq 'ok') {
 4158:        return 'F';
 4159:     } elsif ($result =~ /^[^:]+:guest_/) {
 4160:        return 'A';
 4161:     }
 4162:     return '';
 4163: }
 4164: 
 4165: sub get_portfolio_access {
 4166:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4167: 
 4168:     if (!ref($access_hash)) {
 4169: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4170: 	my %access_controls = &get_access_controls($current_perms,$group,
 4171: 						   $file_name);
 4172: 	$access_hash = $access_controls{$file_name};
 4173:     }
 4174: 
 4175:     my ($public,$guest,@domains,@users,@courses,@groups);
 4176:     my $now = time;
 4177:     if (ref($access_hash) eq 'HASH') {
 4178:         foreach my $key (keys(%{$access_hash})) {
 4179:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4180:             if ($start > $now) {
 4181:                 next;
 4182:             }
 4183:             if ($end && $end<$now) {
 4184:                 next;
 4185:             }
 4186:             if ($scope eq 'public') {
 4187:                 $public = $key;
 4188:                 last;
 4189:             } elsif ($scope eq 'guest') {
 4190:                 $guest = $key;
 4191:             } elsif ($scope eq 'domains') {
 4192:                 push(@domains,$key);
 4193:             } elsif ($scope eq 'users') {
 4194:                 push(@users,$key);
 4195:             } elsif ($scope eq 'course') {
 4196:                 push(@courses,$key);
 4197:             } elsif ($scope eq 'group') {
 4198:                 push(@groups,$key);
 4199:             }
 4200:         }
 4201:         if ($public) {
 4202:             return 'ok';
 4203:         }
 4204:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4205:             if ($guest) {
 4206:                 return $guest;
 4207:             }
 4208:         } else {
 4209:             if (@domains > 0) {
 4210:                 foreach my $domkey (@domains) {
 4211:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4212:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4213:                             return 'ok';
 4214:                         }
 4215:                     }
 4216:                 }
 4217:             }
 4218:             if (@users > 0) {
 4219:                 foreach my $userkey (@users) {
 4220:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4221:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4222:                             if (ref($item) eq 'HASH') {
 4223:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4224:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4225:                                     return 'ok';
 4226:                                 }
 4227:                             }
 4228:                         }
 4229:                     } 
 4230:                 }
 4231:             }
 4232:             my %roleshash;
 4233:             my @courses_and_groups = @courses;
 4234:             push(@courses_and_groups,@groups); 
 4235:             if (@courses_and_groups > 0) {
 4236:                 my (%allgroups,%allroles); 
 4237:                 my ($start,$end,$role,$sec,$group);
 4238:                 foreach my $envkey (%env) {
 4239:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4240:                         my $cid = $2.'_'.$3; 
 4241:                         if ($1 eq 'gr') {
 4242:                             $group = $4;
 4243:                             $allgroups{$cid}{$group} = $env{$envkey};
 4244:                         } else {
 4245:                             if ($4 eq '') {
 4246:                                 $sec = 'none';
 4247:                             } else {
 4248:                                 $sec = $4;
 4249:                             }
 4250:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4251:                         }
 4252:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4253:                         my $cid = $2.'_'.$3;
 4254:                         if ($4 eq '') {
 4255:                             $sec = 'none';
 4256:                         } else {
 4257:                             $sec = $4;
 4258:                         }
 4259:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4260:                     }
 4261:                 }
 4262:                 if (keys(%allroles) == 0) {
 4263:                     return;
 4264:                 }
 4265:                 foreach my $key (@courses_and_groups) {
 4266:                     my %content = %{$$access_hash{$key}};
 4267:                     my $cnum = $content{'number'};
 4268:                     my $cdom = $content{'domain'};
 4269:                     my $cid = $cdom.'_'.$cnum;
 4270:                     if (!exists($allroles{$cid})) {
 4271:                         next;
 4272:                     }    
 4273:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4274:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4275:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4276:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4277:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4278:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4279:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4280:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4281:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4282:                                         if (grep/^all$/,@sections) {
 4283:                                             return 'ok';
 4284:                                         } else {
 4285:                                             if (grep/^$sec$/,@sections) {
 4286:                                                 return 'ok';
 4287:                                             }
 4288:                                         }
 4289:                                     }
 4290:                                 }
 4291:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4292:                                     if (grep/^none$/,@groups) {
 4293:                                         return 'ok';
 4294:                                     }
 4295:                                 } else {
 4296:                                     if (grep/^all$/,@groups) {
 4297:                                         return 'ok';
 4298:                                     } 
 4299:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4300:                                         if (grep/^$group$/,@groups) {
 4301:                                             return 'ok';
 4302:                                         }
 4303:                                     }
 4304:                                 } 
 4305:                             }
 4306:                         }
 4307:                     }
 4308:                 }
 4309:             }
 4310:             if ($guest) {
 4311:                 return $guest;
 4312:             }
 4313:         }
 4314:     }
 4315:     return;
 4316: }
 4317: 
 4318: sub course_group_datechecker {
 4319:     my ($dates,$now,$status) = @_;
 4320:     my ($start,$end) = split(/\./,$dates);
 4321:     if (!$start && !$end) {
 4322:         return 'ok';
 4323:     }
 4324:     if (grep/^active$/,@{$status}) {
 4325:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4326:             return 'ok';
 4327:         }
 4328:     }
 4329:     if (grep/^previous$/,@{$status}) {
 4330:         if ($end > $now ) {
 4331:             return 'ok';
 4332:         }
 4333:     }
 4334:     if (grep/^future$/,@{$status}) {
 4335:         if ($start > $now) {
 4336:             return 'ok';
 4337:         }
 4338:     }
 4339:     return; 
 4340: }
 4341: 
 4342: sub parse_portfolio_url {
 4343:     my ($url) = @_;
 4344: 
 4345:     my ($type,$udom,$unum,$group,$file_name);
 4346:     
 4347:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4348: 	$type = 1;
 4349:         $udom = $1;
 4350:         $unum = $2;
 4351:         $file_name = $3;
 4352:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4353: 	$type = 2;
 4354:         $udom = $1;
 4355:         $unum = $2;
 4356:         $group = $3;
 4357:         $file_name = $3.'/'.$4;
 4358:     }
 4359:     if (wantarray) {
 4360: 	return ($type,$udom,$unum,$file_name,$group);
 4361:     }
 4362:     return $type;
 4363: }
 4364: 
 4365: sub is_portfolio_url {
 4366:     my ($url) = @_;
 4367:     return scalar(&parse_portfolio_url($url));
 4368: }
 4369: 
 4370: sub is_portfolio_file {
 4371:     my ($file) = @_;
 4372:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4373:         return 1;
 4374:     }
 4375:     return;
 4376: }
 4377: 
 4378: sub usertools_access {
 4379:     my ($uname,$udom,$tool,$action) = @_;
 4380:     my $access;
 4381:     my %tools = (
 4382:                   aboutme   => 1,
 4383:                   blog      => 1,
 4384:                   portfolio => 1,
 4385:                 );
 4386:     return if (!defined($tools{$tool}));
 4387: 
 4388:     if ((!defined($udom)) || (!defined($uname))) {
 4389:         $udom = $env{'user.domain'};
 4390:         $uname = $env{'user.name'};
 4391:     }
 4392: 
 4393:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4394:         if ($action ne 'reload') {
 4395:             return $env{'environment.availabletools.'.$tool};
 4396:         }
 4397:     }
 4398: 
 4399:     my ($toolstatus,$inststatus);
 4400: 
 4401:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4402:         $toolstatus = $env{'environment.tools.'.$tool};
 4403:         $inststatus = $env{'environment.inststatus'};
 4404:     } else {
 4405:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
 4406:         $toolstatus = $userenv{'tools.'.$tool};
 4407:         $inststatus = $userenv{'inststatus'};
 4408:     }
 4409: 
 4410:     if ($toolstatus ne '') {
 4411:         if ($toolstatus) {
 4412:             $access = 1;
 4413:         } else {
 4414:             $access = 0;
 4415:         }
 4416:         return $access;
 4417:     }
 4418: 
 4419:     my $is_adv = &is_advanced_user($udom,$uname);
 4420:     my %domdef = &get_domain_defaults($udom);
 4421:     if (ref($domdef{$tool}) eq 'HASH') {
 4422:         if ($is_adv) {
 4423:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4424:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4425:                     $access = 1;
 4426:                 } else {
 4427:                     $access = 0;
 4428:                 }
 4429:                 return $access;
 4430:             }
 4431:         }
 4432:         if ($inststatus ne '') {
 4433:             my ($hasaccess,$hasnoaccess);
 4434:             foreach my $affiliation (split(/:/,$inststatus)) {
 4435:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4436:                     if ($domdef{$tool}{$affiliation}) {
 4437:                         $hasaccess = 1;
 4438:                     } else {
 4439:                         $hasnoaccess = 1;
 4440:                     }
 4441:                 }
 4442:             }
 4443:             if ($hasaccess || $hasnoaccess) {
 4444:                 if ($hasaccess) {
 4445:                     $access = 1;
 4446:                 } elsif ($hasnoaccess) {
 4447:                     $access = 0; 
 4448:                 }
 4449:                 return $access;
 4450:             }
 4451:         } else {
 4452:             if ($domdef{$tool}{'default'} ne '') {
 4453:                 if ($domdef{$tool}{'default'}) {
 4454:                     $access = 1;
 4455:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4456:                     $access = 0;
 4457:                 }
 4458:                 return $access;
 4459:             }
 4460:         }
 4461:     } else {
 4462:         $access = 1;
 4463:         return $access;
 4464:     }
 4465: }
 4466: 
 4467: sub is_advanced_user {
 4468:     my ($udom,$uname) = @_;
 4469:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4470:     my %allroles;
 4471:     my $is_adv;
 4472:     foreach my $role (keys(%roleshash)) {
 4473:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4474:         my $area = '/'.$tdomain.'/'.$trest;
 4475:         if ($sec ne '') {
 4476:             $area .= '/'.$sec;
 4477:         }
 4478:         if (($area ne '') && ($trole ne '')) {
 4479:             my $spec=$trole.'.'.$area;
 4480:             if ($trole =~ /^cr\//) {
 4481:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4482:             } elsif ($trole ne 'gr') {
 4483:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4484:             }
 4485:         }
 4486:     }
 4487:     foreach my $role (keys(%allroles)) {
 4488:         last if ($is_adv);
 4489:         foreach my $item (split(/:/,$allroles{$role})) {
 4490:             if ($item ne '') {
 4491:                 my ($privilege,$restrictions)=split(/&/,$item);
 4492:                 if ($privilege eq 'adv') {
 4493:                     $is_adv = 1;
 4494:                     last;
 4495:                 }
 4496:             }
 4497:         }
 4498:     }
 4499:     return $is_adv;
 4500: }
 4501: 
 4502: # ---------------------------------------------- Custom access rule evaluation
 4503: 
 4504: sub customaccess {
 4505:     my ($priv,$uri)=@_;
 4506:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4507:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4508:     $udom = &LONCAPA::clean_domain($udom);
 4509:     $ucrs = &LONCAPA::clean_username($ucrs);
 4510:     my $access=0;
 4511:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4512: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4513: 	if ($type eq 'user') {
 4514: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4515: 		my ($tdom,$tuname)=split(m{/},$scope);
 4516: 		if ($tdom) {
 4517: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4518: 		}
 4519: 		if ($tuname) {
 4520: 		    if ($tuname ne $env{'user.name'}) { next; }
 4521: 		}
 4522: 		$access=($effect eq 'allow');
 4523: 		last;
 4524: 	    }
 4525: 	} else {
 4526: 	    if ($role) {
 4527: 		if ($role ne $urole) { next; }
 4528: 	    }
 4529: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4530: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4531: 		if ($tdom) {
 4532: 		    if ($tdom ne $udom) { next; }
 4533: 		}
 4534: 		if ($tcrs) {
 4535: 		    if ($tcrs ne $ucrs) { next; }
 4536: 		}
 4537: 		if ($tsec) {
 4538: 		    if ($tsec ne $usec) { next; }
 4539: 		}
 4540: 		$access=($effect eq 'allow');
 4541: 		last;
 4542: 	    }
 4543: 	    if ($realm eq '' && $role eq '') {
 4544: 		$access=($effect eq 'allow');
 4545: 	    }
 4546: 	}
 4547:     }
 4548:     return $access;
 4549: }
 4550: 
 4551: # ------------------------------------------------- Check for a user privilege
 4552: 
 4553: sub allowed {
 4554:     my ($priv,$uri,$symb,$role)=@_;
 4555:     my $ver_orguri=$uri;
 4556:     $uri=&deversion($uri);
 4557:     my $orguri=$uri;
 4558:     $uri=&declutter($uri);
 4559: 
 4560:     if ($priv eq 'evb') {
 4561: # Evade communication block restrictions for specified role in a course
 4562:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4563:             return $1;
 4564:         } else {
 4565:             return;
 4566:         }
 4567:     }
 4568: 
 4569:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4570: # Free bre access to adm and meta resources
 4571:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4572: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4573: 	&& ($priv eq 'bre')) {
 4574: 	return 'F';
 4575:     }
 4576: 
 4577: # Free bre access to user's own portfolio contents
 4578:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4579:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4580: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4581:         my %setters;
 4582:         my ($startblock,$endblock) = 
 4583:             &Apache::loncommon::blockcheck(\%setters,'port');
 4584:         if ($startblock && $endblock) {
 4585:             return 'B';
 4586:         } else {
 4587:             return 'F';
 4588:         }
 4589:     }
 4590: 
 4591: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4592:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4593:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4594:         if (exists($env{'request.course.id'})) {
 4595:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4596:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4597:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4598:                 my $courseprivid=$env{'request.course.id'};
 4599:                 $courseprivid=~s/\_/\//;
 4600:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4601:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4602:                     return $1; 
 4603:                 } else {
 4604:                     if ($env{'request.course.sec'}) {
 4605:                         $courseprivid.='/'.$env{'request.course.sec'};
 4606:                     }
 4607:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4608:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4609:                         return $2;
 4610:                     }
 4611:                 }
 4612:             }
 4613:         }
 4614:     }
 4615: 
 4616: # Free bre to public access
 4617: 
 4618:     if ($priv eq 'bre') {
 4619:         my $copyright=&metadata($uri,'copyright');
 4620: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4621:            return 'F'; 
 4622:         }
 4623:         if ($copyright eq 'priv') {
 4624:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4625: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4626: 		return '';
 4627:             }
 4628:         }
 4629:         if ($copyright eq 'domain') {
 4630:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4631: 	    unless (($env{'user.domain'} eq $1) ||
 4632:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4633: 		return '';
 4634:             }
 4635:         }
 4636:         if ($env{'request.role'}=~ /li\.\//) {
 4637:             # Library role, so allow browsing of resources in this domain.
 4638:             return 'F';
 4639:         }
 4640:         if ($copyright eq 'custom') {
 4641: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4642:         }
 4643:     }
 4644:     # Domain coordinator is trying to create a course
 4645:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4646:         # uri is the requested domain in this case.
 4647:         # comparison to 'request.role.domain' shows if the user has selected
 4648:         # a role of dc for the domain in question.
 4649:         return 'F' if ($uri eq $env{'request.role.domain'});
 4650:     }
 4651: 
 4652:     my $thisallowed='';
 4653:     my $statecond=0;
 4654:     my $courseprivid='';
 4655: 
 4656: # Course
 4657: 
 4658:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4659:        $thisallowed.=$1;
 4660:     }
 4661: 
 4662: # Domain
 4663: 
 4664:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4665:        =~/\Q$priv\E\&([^\:]*)/) {
 4666:        $thisallowed.=$1;
 4667:     }
 4668: 
 4669: # Course: uri itself is a course
 4670:     my $courseuri=$uri;
 4671:     $courseuri=~s/\_(\d)/\/$1/;
 4672:     $courseuri=~s/^([^\/])/\/$1/;
 4673: 
 4674:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4675:        =~/\Q$priv\E\&([^\:]*)/) {
 4676:        $thisallowed.=$1;
 4677:     }
 4678: 
 4679: # URI is an uploaded document for this course, default permissions don't matter
 4680: # not allowing 'edit' access (editupload) to uploaded course docs
 4681:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4682: 	$thisallowed='';
 4683:         my ($match)=&is_on_map($uri);
 4684:         if ($match) {
 4685:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4686:                   =~/\Q$priv\E\&([^\:]*)/) {
 4687:                 $thisallowed.=$1;
 4688:             }
 4689:         } else {
 4690:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4691:             if ($refuri) {
 4692:                 if ($refuri =~ m|^/adm/|) {
 4693:                     $thisallowed='F';
 4694:                 } else {
 4695:                     $refuri=&declutter($refuri);
 4696:                     my ($match) = &is_on_map($refuri);
 4697:                     if ($match) {
 4698:                         $thisallowed='F';
 4699:                     }
 4700:                 }
 4701:             }
 4702:         }
 4703:     }
 4704: 
 4705:     if ($priv eq 'bre'
 4706: 	&& $thisallowed ne 'F' 
 4707: 	&& $thisallowed ne '2'
 4708: 	&& &is_portfolio_url($uri)) {
 4709: 	$thisallowed = &portfolio_access($uri);
 4710:     }
 4711:     
 4712: # Full access at system, domain or course-wide level? Exit.
 4713:     if ($thisallowed=~/F/) {
 4714: 	return 'F';
 4715:     }
 4716: 
 4717: # If this is generating or modifying users, exit with special codes
 4718: 
 4719:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4720: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4721: 	    my ($audom,$auname)=split('/',$uri);
 4722: # no author name given, so this just checks on the general right to make a co-author in this domain
 4723: 	    unless ($auname) { return $thisallowed; }
 4724: # an author name is given, so we are about to actually make a co-author for a certain account
 4725: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4726: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4727: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4728: 	}
 4729: 	return $thisallowed;
 4730:     }
 4731: #
 4732: # Gathered so far: system, domain and course wide privileges
 4733: #
 4734: # Course: See if uri or referer is an individual resource that is part of 
 4735: # the course
 4736: 
 4737:     if ($env{'request.course.id'}) {
 4738: 
 4739:        $courseprivid=$env{'request.course.id'};
 4740:        if ($env{'request.course.sec'}) {
 4741:           $courseprivid.='/'.$env{'request.course.sec'};
 4742:        }
 4743:        $courseprivid=~s/\_/\//;
 4744:        my $checkreferer=1;
 4745:        my ($match,$cond)=&is_on_map($uri);
 4746:        if ($match) {
 4747:            $statecond=$cond;
 4748:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4749:                =~/\Q$priv\E\&([^\:]*)/) {
 4750:                $thisallowed.=$1;
 4751:                $checkreferer=0;
 4752:            }
 4753:        }
 4754:        
 4755:        if ($checkreferer) {
 4756: 	  my $refuri=$env{'httpref.'.$orguri};
 4757:             unless ($refuri) {
 4758:                 foreach my $key (keys(%env)) {
 4759: 		    if ($key=~/^httpref\..*\*/) {
 4760: 			my $pattern=$key;
 4761:                         $pattern=~s/^httpref\.\/res\///;
 4762:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4763:                         $pattern=~s/\//\\\//g;
 4764:                         if ($orguri=~/$pattern/) {
 4765: 			    $refuri=$env{$key};
 4766:                         }
 4767:                     }
 4768:                 }
 4769:             }
 4770: 
 4771:          if ($refuri) { 
 4772: 	  $refuri=&declutter($refuri);
 4773:           my ($match,$cond)=&is_on_map($refuri);
 4774:             if ($match) {
 4775:               my $refstatecond=$cond;
 4776:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4777:                   =~/\Q$priv\E\&([^\:]*)/) {
 4778:                   $thisallowed.=$1;
 4779:                   $uri=$refuri;
 4780:                   $statecond=$refstatecond;
 4781:               }
 4782:           }
 4783:         }
 4784:        }
 4785:    }
 4786: 
 4787: #
 4788: # Gathered now: all privileges that could apply, and condition number
 4789: # 
 4790: #
 4791: # Full or no access?
 4792: #
 4793: 
 4794:     if ($thisallowed=~/F/) {
 4795: 	return 'F';
 4796:     }
 4797: 
 4798:     unless ($thisallowed) {
 4799:         return '';
 4800:     }
 4801: 
 4802: # Restrictions exist, deal with them
 4803: #
 4804: #   C:according to course preferences
 4805: #   R:according to resource settings
 4806: #   L:unless locked
 4807: #   X:according to user session state
 4808: #
 4809: 
 4810: # Possibly locked functionality, check all courses
 4811: # Locks might take effect only after 10 minutes cache expiration for other
 4812: # courses, and 2 minutes for current course
 4813: 
 4814:     my $envkey;
 4815:     if ($thisallowed=~/L/) {
 4816:         foreach $envkey (keys %env) {
 4817:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4818:                my $courseid=$2;
 4819:                my $roleid=$1.'.'.$2;
 4820:                $courseid=~s/^\///;
 4821:                my $expiretime=600;
 4822:                if ($env{'request.role'} eq $roleid) {
 4823: 		  $expiretime=120;
 4824:                }
 4825: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4826:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4827:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4828: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4829:                }
 4830:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4831:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4832: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4833:                        &log($env{'user.domain'},$env{'user.name'},
 4834:                             $env{'user.home'},
 4835:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4836:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4837:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4838: 		       return '';
 4839:                    }
 4840:                }
 4841:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4842:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4843: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4844:                        &log($env{'user.domain'},$env{'user.name'},
 4845:                             $env{'user.home'},
 4846:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4847:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4848:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4849: 		       return '';
 4850:                    }
 4851:                }
 4852: 	   }
 4853:        }
 4854:     }
 4855:    
 4856: #
 4857: # Rest of the restrictions depend on selected course
 4858: #
 4859: 
 4860:     unless ($env{'request.course.id'}) {
 4861: 	if ($thisallowed eq 'A') {
 4862: 	    return 'A';
 4863:         } elsif ($thisallowed eq 'B') {
 4864:             return 'B';
 4865: 	} else {
 4866: 	    return '1';
 4867: 	}
 4868:     }
 4869: 
 4870: #
 4871: # Now user is definitely in a course
 4872: #
 4873: 
 4874: 
 4875: # Course preferences
 4876: 
 4877:    if ($thisallowed=~/C/) {
 4878:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4879:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4880:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4881: 	   =~/\Q$rolecode\E/) {
 4882: 	   if ($priv ne 'pch') { 
 4883: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4884: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4885: 			$env{'request.course.id'});
 4886: 	   }
 4887:            return '';
 4888:        }
 4889: 
 4890:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4891: 	   =~/\Q$unamedom\E/) {
 4892: 	   if ($priv ne 'pch') { 
 4893: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4894: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4895: 			$env{'request.course.id'});
 4896: 	   }
 4897:            return '';
 4898:        }
 4899:    }
 4900: 
 4901: # Resource preferences
 4902: 
 4903:    if ($thisallowed=~/R/) {
 4904:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4905:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4906: 	   if ($priv ne 'pch') { 
 4907: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4908: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4909: 	   }
 4910: 	   return '';
 4911:        }
 4912:    }
 4913: 
 4914: # Restricted by state or randomout?
 4915: 
 4916:    if ($thisallowed=~/X/) {
 4917:       if ($env{'acc.randomout'}) {
 4918: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4919:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4920:             return ''; 
 4921:          }
 4922:       }
 4923:       if (&condval($statecond)) {
 4924: 	 return '2';
 4925:       } else {
 4926:          return '';
 4927:       }
 4928:    }
 4929: 
 4930:     if ($thisallowed eq 'A') {
 4931: 	return 'A';
 4932:     } elsif ($thisallowed eq 'B') {
 4933:         return 'B';
 4934:     }
 4935:    return 'F';
 4936: }
 4937: 
 4938: sub split_uri_for_cond {
 4939:     my $uri=&deversion(&declutter(shift));
 4940:     my @uriparts=split(/\//,$uri);
 4941:     my $filename=pop(@uriparts);
 4942:     my $pathname=join('/',@uriparts);
 4943:     return ($pathname,$filename);
 4944: }
 4945: # --------------------------------------------------- Is a resource on the map?
 4946: 
 4947: sub is_on_map {
 4948:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4949:     #Trying to find the conditional for the file
 4950:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4951: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4952:     if ($match) {
 4953: 	return (1,$1);
 4954:     } else {
 4955: 	return (0,0);
 4956:     }
 4957: }
 4958: 
 4959: # --------------------------------------------------------- Get symb from alias
 4960: 
 4961: sub get_symb_from_alias {
 4962:     my $symb=shift;
 4963:     my ($map,$resid,$url)=&decode_symb($symb);
 4964: # Already is a symb
 4965:     if ($url) { return $symb; }
 4966: # Must be an alias
 4967:     my $aliassymb='';
 4968:     my %bighash;
 4969:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4970:                             &GDBM_READER(),0640)) {
 4971:         my $rid=$bighash{'mapalias_'.$symb};
 4972: 	if ($rid) {
 4973: 	    my ($mapid,$resid)=split(/\./,$rid);
 4974: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4975: 				    $resid,$bighash{'src_'.$rid});
 4976: 	}
 4977:         untie %bighash;
 4978:     }
 4979:     return $aliassymb;
 4980: }
 4981: 
 4982: # ----------------------------------------------------------------- Define Role
 4983: 
 4984: sub definerole {
 4985:   if (allowed('mcr','/')) {
 4986:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 4987:     foreach my $role (split(':',$sysrole)) {
 4988: 	my ($crole,$cqual)=split(/\&/,$role);
 4989:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 4990:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 4991: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 4992:                return "refused:s:$crole&$cqual"; 
 4993:             }
 4994:         }
 4995:     }
 4996:     foreach my $role (split(':',$domrole)) {
 4997: 	my ($crole,$cqual)=split(/\&/,$role);
 4998:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 4999:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5000: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5001:                return "refused:d:$crole&$cqual"; 
 5002:             }
 5003:         }
 5004:     }
 5005:     foreach my $role (split(':',$courole)) {
 5006: 	my ($crole,$cqual)=split(/\&/,$role);
 5007:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5008:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5009: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5010:                return "refused:c:$crole&$cqual"; 
 5011:             }
 5012:         }
 5013:     }
 5014:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5015:                 "$env{'user.domain'}:$env{'user.name'}:".
 5016: 	        "rolesdef_$rolename=".
 5017:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5018:     return reply($command,$env{'user.home'});
 5019:   } else {
 5020:     return 'refused';
 5021:   }
 5022: }
 5023: 
 5024: # ---------------- Make a metadata query against the network of library servers
 5025: 
 5026: sub metadata_query {
 5027:     my ($query,$custom,$customshow,$server_array)=@_;
 5028:     my %rhash;
 5029:     my %libserv = &all_library();
 5030:     my @server_list = (defined($server_array) ? @$server_array
 5031:                                               : keys(%libserv) );
 5032:     for my $server (@server_list) {
 5033: 	unless ($custom or $customshow) {
 5034: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5035: 	    $rhash{$server}=$reply;
 5036: 	}
 5037: 	else {
 5038: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5039: 			     &escape($custom).':'.&escape($customshow),
 5040: 			     $server);
 5041: 	    $rhash{$server}=$reply;
 5042: 	}
 5043:     }
 5044:     return \%rhash;
 5045: }
 5046: 
 5047: # ----------------------------------------- Send log queries and wait for reply
 5048: 
 5049: sub log_query {
 5050:     my ($uname,$udom,$query,%filters)=@_;
 5051:     my $uhome=&homeserver($uname,$udom);
 5052:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5053:     my $uhost=&hostname($uhome);
 5054:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5055:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5056:                        $uhome);
 5057:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5058:     return get_query_reply($queryid);
 5059: }
 5060: 
 5061: # -------------------------- Update MySQL table for portfolio file
 5062: 
 5063: sub update_portfolio_table {
 5064:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5065:     if ($group ne '') {
 5066:         $file_name =~s /^\Q$group\E//;
 5067:     }
 5068:     my $homeserver = &homeserver($uname,$udom);
 5069:     my $queryid=
 5070:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5071:                ':'.&escape($file_name).':'.$action,$homeserver);
 5072:     my $reply = &get_query_reply($queryid);
 5073:     return $reply;
 5074: }
 5075: 
 5076: # -------------------------- Update MySQL allusers table
 5077: 
 5078: sub update_allusers_table {
 5079:     my ($uname,$udom,$names) = @_;
 5080:     my $homeserver = &homeserver($uname,$udom);
 5081:     my $queryid=
 5082:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5083:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5084:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5085:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5086:                'generation='.&escape($names->{'generation'}).'%%'.
 5087:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5088:                'id='.&escape($names->{'id'}),$homeserver);
 5089:     my $reply = &get_query_reply($queryid);
 5090:     return $reply;
 5091: }
 5092: 
 5093: # ------- Request retrieval of institutional classlists for course(s)
 5094: 
 5095: sub fetch_enrollment_query {
 5096:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5097:     my $homeserver;
 5098:     my $maxtries = 1;
 5099:     if ($context eq 'automated') {
 5100:         $homeserver = $perlvar{'lonHostID'};
 5101:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5102:     } else {
 5103:         $homeserver = &homeserver($cnum,$dom);
 5104:     }
 5105:     my $host=&hostname($homeserver);
 5106:     my $cmd = '';
 5107:     foreach my $affiliate (keys %{$affiliatesref}) {
 5108:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5109:     }
 5110:     $cmd =~ s/%%$//;
 5111:     $cmd = &escape($cmd);
 5112:     my $query = 'fetchenrollment';
 5113:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5114:     unless ($queryid=~/^\Q$host\E\_/) { 
 5115:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5116:         return 'error: '.$queryid;
 5117:     }
 5118:     my $reply = &get_query_reply($queryid);
 5119:     my $tries = 1;
 5120:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5121:         $reply = &get_query_reply($queryid);
 5122:         $tries ++;
 5123:     }
 5124:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5125:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5126:     } else {
 5127:         my @responses = split(/:/,$reply);
 5128:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5129:             foreach my $line (@responses) {
 5130:                 my ($key,$value) = split(/=/,$line,2);
 5131:                 $$replyref{$key} = $value;
 5132:             }
 5133:         } else {
 5134:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5135:             foreach my $line (@responses) {
 5136:                 my ($key,$value) = split(/=/,$line);
 5137:                 $$replyref{$key} = $value;
 5138:                 if ($value > 0) {
 5139:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5140:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5141:                         my $destname = $pathname.'/'.$filename;
 5142:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5143:                         if ($xml_classlist =~ /^error/) {
 5144:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5145:                         } else {
 5146:                             if ( open(FILE,">$destname") ) {
 5147:                                 print FILE &unescape($xml_classlist);
 5148:                                 close(FILE);
 5149:                             } else {
 5150:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5151:                             }
 5152:                         }
 5153:                     }
 5154:                 }
 5155:             }
 5156:         }
 5157:         return 'ok';
 5158:     }
 5159:     return 'error';
 5160: }
 5161: 
 5162: sub get_query_reply {
 5163:     my $queryid=shift;
 5164:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5165:     my $reply='';
 5166:     for (1..100) {
 5167: 	sleep 2;
 5168:         if (-e $replyfile.'.end') {
 5169: 	    if (open(my $fh,$replyfile)) {
 5170: 		$reply = join('',<$fh>);
 5171: 		close($fh);
 5172: 	   } else { return 'error: reply_file_error'; }
 5173:            return &unescape($reply);
 5174: 	}
 5175:     }
 5176:     return 'timeout:'.$queryid;
 5177: }
 5178: 
 5179: sub courselog_query {
 5180: #
 5181: # possible filters:
 5182: # url: url or symb
 5183: # username
 5184: # domain
 5185: # action: view, submit, grade
 5186: # start: timestamp
 5187: # end: timestamp
 5188: #
 5189:     my (%filters)=@_;
 5190:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5191:     if ($filters{'url'}) {
 5192: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5193:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5194:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5195:     }
 5196:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5197:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5198:     return &log_query($cname,$cdom,'courselog',%filters);
 5199: }
 5200: 
 5201: sub userlog_query {
 5202: #
 5203: # possible filters:
 5204: # action: log check role
 5205: # start: timestamp
 5206: # end: timestamp
 5207: #
 5208:     my ($uname,$udom,%filters)=@_;
 5209:     return &log_query($uname,$udom,'userlog',%filters);
 5210: }
 5211: 
 5212: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5213: 
 5214: sub auto_run {
 5215:     my ($cnum,$cdom) = @_;
 5216:     my $response = 0;
 5217:     my $settings;
 5218:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5219:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5220:         $settings = $domconfig{'autoenroll'};
 5221:         if ($settings->{'run'} eq '1') {
 5222:             $response = 1;
 5223:         }
 5224:     } else {
 5225:         my $homeserver;
 5226:         if (&is_course($cdom,$cnum)) {
 5227:             $homeserver = &homeserver($cnum,$cdom);
 5228:         } else {
 5229:             $homeserver = &domain($cdom,'primary');
 5230:         }
 5231:         if ($homeserver ne 'no_host') {
 5232:             $response = &reply('autorun:'.$cdom,$homeserver);
 5233:         }
 5234:     }
 5235:     return $response;
 5236: }
 5237: 
 5238: sub auto_get_sections {
 5239:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5240:     my $homeserver = &homeserver($cnum,$cdom);
 5241:     my @secs = ();
 5242:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5243:     unless ($response eq 'refused') {
 5244:         @secs = split(/:/,$response);
 5245:     }
 5246:     return @secs;
 5247: }
 5248: 
 5249: sub auto_new_course {
 5250:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5251:     my $homeserver = &homeserver($cnum,$cdom);
 5252:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5253:     return $response;
 5254: }
 5255: 
 5256: sub auto_validate_courseID {
 5257:     my ($cnum,$cdom,$inst_course_id) = @_;
 5258:     my $homeserver = &homeserver($cnum,$cdom);
 5259:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5260:     return $response;
 5261: }
 5262: 
 5263: sub auto_create_password {
 5264:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5265:     my ($homeserver,$response);
 5266:     my $create_passwd = 0;
 5267:     my $authchk = '';
 5268:     if ($udom =~ /^$match_domain$/) {
 5269:         $homeserver = &domain($udom,'primary');
 5270:     }
 5271:     if ($homeserver eq '') {
 5272:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5273:             $homeserver = &homeserver($cnum,$cdom);
 5274:         }
 5275:     }
 5276:     if ($homeserver eq '') {
 5277:         $authchk = 'nodomain';
 5278:     } else {
 5279:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5280:         if ($response eq 'refused') {
 5281:             $authchk = 'refused';
 5282:         } else {
 5283:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5284:         }
 5285:     }
 5286:     return ($authparam,$create_passwd,$authchk);
 5287: }
 5288: 
 5289: sub auto_photo_permission {
 5290:     my ($cnum,$cdom,$students) = @_;
 5291:     my $homeserver = &homeserver($cnum,$cdom);
 5292:     my ($outcome,$perm_reqd,$conditions) = 
 5293: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5294:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5295: 	return (undef,undef);
 5296:     }
 5297:     return ($outcome,$perm_reqd,$conditions);
 5298: }
 5299: 
 5300: sub auto_checkphotos {
 5301:     my ($uname,$udom,$pid) = @_;
 5302:     my $homeserver = &homeserver($uname,$udom);
 5303:     my ($result,$resulttype);
 5304:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5305: 				   &escape($uname).':'.&escape($pid),
 5306: 				   $homeserver));
 5307:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5308: 	return (undef,undef);
 5309:     }
 5310:     if ($outcome) {
 5311:         ($result,$resulttype) = split(/:/,$outcome);
 5312:     } 
 5313:     return ($result,$resulttype);
 5314: }
 5315: 
 5316: sub auto_photochoice {
 5317:     my ($cnum,$cdom) = @_;
 5318:     my $homeserver = &homeserver($cnum,$cdom);
 5319:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5320: 						       &escape($cdom),
 5321: 						       $homeserver)));
 5322:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5323: 	return (undef,undef);
 5324:     }
 5325:     return ($update,$comment);
 5326: }
 5327: 
 5328: sub auto_photoupdate {
 5329:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5330:     my $homeserver = &homeserver($cnum,$dom);
 5331:     my $host=&hostname($homeserver);
 5332:     my $cmd = '';
 5333:     my $maxtries = 1;
 5334:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5335:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5336:     }
 5337:     $cmd =~ s/%%$//;
 5338:     $cmd = &escape($cmd);
 5339:     my $query = 'institutionalphotos';
 5340:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5341:     unless ($queryid=~/^\Q$host\E\_/) {
 5342:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5343:         return 'error: '.$queryid;
 5344:     }
 5345:     my $reply = &get_query_reply($queryid);
 5346:     my $tries = 1;
 5347:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5348:         $reply = &get_query_reply($queryid);
 5349:         $tries ++;
 5350:     }
 5351:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5352:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5353:     } else {
 5354:         my @responses = split(/:/,$reply);
 5355:         my $outcome = shift(@responses); 
 5356:         foreach my $item (@responses) {
 5357:             my ($key,$value) = split(/=/,$item);
 5358:             $$photo{$key} = $value;
 5359:         }
 5360:         return $outcome;
 5361:     }
 5362:     return 'error';
 5363: }
 5364: 
 5365: sub auto_instcode_format {
 5366:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5367: 	$cat_order) = @_;
 5368:     my $courses = '';
 5369:     my @homeservers;
 5370:     if ($caller eq 'global') {
 5371: 	my %servers = &get_servers($codedom,'library');
 5372: 	foreach my $tryserver (keys(%servers)) {
 5373: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5374: 		push(@homeservers,$tryserver);
 5375: 	    }
 5376:         }
 5377:     } else {
 5378:         push(@homeservers,&homeserver($caller,$codedom));
 5379:     }
 5380:     foreach my $code (keys(%{$instcodes})) {
 5381:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5382:     }
 5383:     chop($courses);
 5384:     my $ok_response = 0;
 5385:     my $response;
 5386:     while (@homeservers > 0 && $ok_response == 0) {
 5387:         my $server = shift(@homeservers); 
 5388:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5389:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5390:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5391: 		split(/:/,$response);
 5392:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5393:             push(@{$codetitles},&str2array($codetitles_str));
 5394:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5395:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5396:             $ok_response = 1;
 5397:         }
 5398:     }
 5399:     if ($ok_response) {
 5400:         return 'ok';
 5401:     } else {
 5402:         return $response;
 5403:     }
 5404: }
 5405: 
 5406: sub auto_instcode_defaults {
 5407:     my ($domain,$returnhash,$code_order) = @_;
 5408:     my @homeservers;
 5409: 
 5410:     my %servers = &get_servers($domain,'library');
 5411:     foreach my $tryserver (keys(%servers)) {
 5412: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5413: 	    push(@homeservers,$tryserver);
 5414: 	}
 5415:     }
 5416: 
 5417:     my $response;
 5418:     foreach my $server (@homeservers) {
 5419:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5420:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5421: 	
 5422: 	foreach my $pair (split(/\&/,$response)) {
 5423: 	    my ($name,$value)=split(/\=/,$pair);
 5424: 	    if ($name eq 'code_order') {
 5425: 		@{$code_order} = split(/\&/,&unescape($value));
 5426: 	    } else {
 5427: 		$returnhash->{&unescape($name)}=&unescape($value);
 5428: 	    }
 5429: 	}
 5430: 	return 'ok';
 5431:     }
 5432: 
 5433:     return $response;
 5434: } 
 5435: 
 5436: sub auto_validate_class_sec {
 5437:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5438:     my $homeserver = &homeserver($cnum,$cdom);
 5439:     my $ownerlist;
 5440:     if (ref($owners) eq 'ARRAY') {
 5441:         $ownerlist = join(',',@{$owners});
 5442:     } else {
 5443:         $ownerlist = $owners;
 5444:     }
 5445:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5446:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5447:     return $response;
 5448: }
 5449: 
 5450: # ------------------------------------------------------- Course Group routines
 5451: 
 5452: sub get_coursegroups {
 5453:     my ($cdom,$cnum,$group,$namespace) = @_;
 5454:     return(&dump($namespace,$cdom,$cnum,$group));
 5455: }
 5456: 
 5457: sub modify_coursegroup {
 5458:     my ($cdom,$cnum,$groupsettings) = @_;
 5459:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5460: }
 5461: 
 5462: sub toggle_coursegroup_status {
 5463:     my ($cdom,$cnum,$group,$action) = @_;
 5464:     my ($from_namespace,$to_namespace);
 5465:     if ($action eq 'delete') {
 5466:         $from_namespace = 'coursegroups';
 5467:         $to_namespace = 'deleted_groups';
 5468:     } else {
 5469:         $from_namespace = 'deleted_groups';
 5470:         $to_namespace = 'coursegroups';
 5471:     }
 5472:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5473:     if (my $tmp = &error(%curr_group)) {
 5474:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5475:         return ('read error',$tmp);
 5476:     } else {
 5477:         my %savedsettings = %curr_group; 
 5478:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5479:         my $deloutcome;
 5480:         if ($result eq 'ok') {
 5481:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5482:         } else {
 5483:             return ('write error',$result);
 5484:         }
 5485:         if ($deloutcome eq 'ok') {
 5486:             return 'ok';
 5487:         } else {
 5488:             return ('delete error',$deloutcome);
 5489:         }
 5490:     }
 5491: }
 5492: 
 5493: sub modify_group_roles {
 5494:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5495:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5496:     my $role = 'gr/'.&escape($userprivs);
 5497:     my ($uname,$udom) = split(/:/,$user);
 5498:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5499:     if ($result eq 'ok') {
 5500:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5501:     }
 5502:     return $result;
 5503: }
 5504: 
 5505: sub modify_coursegroup_membership {
 5506:     my ($cdom,$cnum,$membership) = @_;
 5507:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5508:     return $result;
 5509: }
 5510: 
 5511: sub get_active_groups {
 5512:     my ($udom,$uname,$cdom,$cnum) = @_;
 5513:     my $now = time;
 5514:     my %groups = ();
 5515:     foreach my $key (keys(%env)) {
 5516:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5517:             my ($start,$end) = split(/\./,$env{$key});
 5518:             if (($end!=0) && ($end<$now)) { next; }
 5519:             if (($start!=0) && ($start>$now)) { next; }
 5520:             if ($1 eq $cdom && $2 eq $cnum) {
 5521:                 $groups{$3} = $env{$key} ;
 5522:             }
 5523:         }
 5524:     }
 5525:     return %groups;
 5526: }
 5527: 
 5528: sub get_group_membership {
 5529:     my ($cdom,$cnum,$group) = @_;
 5530:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5531: }
 5532: 
 5533: sub get_users_groups {
 5534:     my ($udom,$uname,$courseid) = @_;
 5535:     my @usersgroups;
 5536:     my $cachetime=1800;
 5537: 
 5538:     my $hashid="$udom:$uname:$courseid";
 5539:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5540:     if (defined($cached)) {
 5541:         @usersgroups = split(/:/,$grouplist);
 5542:     } else {  
 5543:         $grouplist = '';
 5544:         my $courseurl = &courseid_to_courseurl($courseid);
 5545:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5546:         my $access_end = $env{'course.'.$courseid.
 5547:                               '.default_enrollment_end_date'};
 5548:         my $now = time;
 5549:         foreach my $key (keys(%roleshash)) {
 5550:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5551:                 my $group = $1;
 5552:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5553:                     my $start = $2;
 5554:                     my $end = $1;
 5555:                     if ($start == -1) { next; } # deleted from group
 5556:                     if (($start!=0) && ($start>$now)) { next; }
 5557:                     if (($end!=0) && ($end<$now)) {
 5558:                         if ($access_end && $access_end < $now) {
 5559:                             if ($access_end - $end < 86400) {
 5560:                                 push(@usersgroups,$group);
 5561:                             }
 5562:                         }
 5563:                         next;
 5564:                     }
 5565:                     push(@usersgroups,$group);
 5566:                 }
 5567:             }
 5568:         }
 5569:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5570:         $grouplist = join(':',@usersgroups);
 5571:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5572:     }
 5573:     return @usersgroups;
 5574: }
 5575: 
 5576: sub devalidate_getgroups_cache {
 5577:     my ($udom,$uname,$cdom,$cnum)=@_;
 5578:     my $courseid = $cdom.'_'.$cnum;
 5579: 
 5580:     my $hashid="$udom:$uname:$courseid";
 5581:     &devalidate_cache_new('getgroups',$hashid);
 5582: }
 5583: 
 5584: # ------------------------------------------------------------------ Plain Text
 5585: 
 5586: sub plaintext {
 5587:     my ($short,$type,$cid) = @_;
 5588:     if ($short =~ /^cr/) {
 5589: 	return (split('/',$short))[-1];
 5590:     }
 5591:     if (!defined($cid)) {
 5592:         $cid = $env{'request.course.id'};
 5593:     }
 5594:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5595:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5596:                                           '.plaintext'});
 5597:     }
 5598:     my %rolenames = (
 5599:                       Course => 'std',
 5600:                       Group => 'alt1',
 5601:                     );
 5602:     if (defined($type) && 
 5603:          defined($rolenames{$type}) && 
 5604:          defined($prp{$short}{$rolenames{$type}})) {
 5605:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5606:     } else {
 5607:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5608:     }
 5609: }
 5610: 
 5611: # ----------------------------------------------------------------- Assign Role
 5612: 
 5613: sub assignrole {
 5614:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5615:         $context)=@_;
 5616:     my $mrole;
 5617:     if ($role =~ /^cr\//) {
 5618:         my $cwosec=$url;
 5619:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5620: 	unless (&allowed('ccr',$cwosec)) {
 5621:            &logthis('Refused custom assignrole: '.
 5622:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5623: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5624:            return 'refused'; 
 5625:         }
 5626:         $mrole='cr';
 5627:     } elsif ($role =~ /^gr\//) {
 5628:         my $cwogrp=$url;
 5629:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5630:         unless (&allowed('mdg',$cwogrp)) {
 5631:             &logthis('Refused group assignrole: '.
 5632:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5633:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5634:             return 'refused';
 5635:         }
 5636:         $mrole='gr';
 5637:     } else {
 5638:         my $cwosec=$url;
 5639:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5640:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5641:             my $refused;
 5642:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5643:                 if (!(&allowed('c'.$role,$url))) {
 5644:                     $refused = 1;
 5645:                 }
 5646:             } else {
 5647:                 $refused = 1;
 5648:             }
 5649:             if ($refused) {
 5650:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5651:                     $refused = '';
 5652:                 } else {
 5653:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5654:                              ' '.$role.' '.$end.' '.$start.' by '.
 5655: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5656:                     return 'refused';
 5657:                 }
 5658:             }
 5659:         }
 5660:         $mrole=$role;
 5661:     }
 5662:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5663:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5664:     if ($end) { $command.='_'.$end; }
 5665:     if ($start) {
 5666: 	if ($end) { 
 5667:            $command.='_'.$start; 
 5668:         } else {
 5669:            $command.='_0_'.$start;
 5670:         }
 5671:     }
 5672:     my $origstart = $start;
 5673:     my $origend = $end;
 5674:     my $delflag;
 5675: # actually delete
 5676:     if ($deleteflag) {
 5677: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5678: # modify command to delete the role
 5679:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5680:                 "$udom:$uname:$url".'_'."$mrole";
 5681: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5682: # set start and finish to negative values for userrolelog
 5683:            $start=-1;
 5684:            $end=-1;
 5685:            $delflag = 1;
 5686:         }
 5687:     }
 5688: # send command
 5689:     my $answer=&reply($command,&homeserver($uname,$udom));
 5690: # log new user role if status is ok
 5691:     if ($answer eq 'ok') {
 5692: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5693: # for course roles, perform group memberships changes triggered by role change.
 5694:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5695:         unless ($role =~ /^gr/) {
 5696:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5697:                                              $origstart,$selfenroll,$context);
 5698:         }
 5699:     }
 5700:     return $answer;
 5701: }
 5702: 
 5703: # -------------------------------------------------- Modify user authentication
 5704: # Overrides without validation
 5705: 
 5706: sub modifyuserauth {
 5707:     my ($udom,$uname,$umode,$upass)=@_;
 5708:     my $uhome=&homeserver($uname,$udom);
 5709:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5710:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5711:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5712:              ' in domain '.$env{'request.role.domain'});  
 5713:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5714: 		     &escape($upass),$uhome);
 5715:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5716:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5717:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5718:     &log($udom,,$uname,$uhome,
 5719:         'Authentication changed by '.$env{'user.domain'}.', '.
 5720:                                      $env{'user.name'}.', '.$umode.
 5721:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5722:     unless ($reply eq 'ok') {
 5723:         &logthis('Authentication mode error: '.$reply);
 5724: 	return 'error: '.$reply;
 5725:     }   
 5726:     return 'ok';
 5727: }
 5728: 
 5729: # --------------------------------------------------------------- Modify a user
 5730: 
 5731: sub modifyuser {
 5732:     my ($udom,    $uname, $uid,
 5733:         $umode,   $upass, $first,
 5734:         $middle,  $last,  $gene,
 5735:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5736:     $udom= &LONCAPA::clean_domain($udom);
 5737:     $uname=&LONCAPA::clean_username($uname);
 5738:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5739:              $umode.', '.$first.', '.$middle.', '.
 5740: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5741:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5742:                                      ' desiredhome not specified'). 
 5743:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5744:              ' in domain '.$env{'request.role.domain'});
 5745:     my $uhome=&homeserver($uname,$udom,'true');
 5746: # ----------------------------------------------------------------- Create User
 5747:     if (($uhome eq 'no_host') && 
 5748: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5749:         my $unhome='';
 5750:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5751:             $unhome = $desiredhome;
 5752: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5753: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5754:         } else { # load balancing routine for determining $unhome
 5755:             my $loadm=10000000;
 5756: 	    my %servers = &get_servers($udom,'library');
 5757: 	    foreach my $tryserver (keys(%servers)) {
 5758: 		my $answer=reply('load',$tryserver);
 5759: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5760: 		    $loadm=$answer;
 5761: 		    $unhome=$tryserver;
 5762: 		}
 5763: 	    }
 5764:         }
 5765:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5766: 	    return 'error: unable to find a home server for '.$uname.
 5767:                    ' in domain '.$udom;
 5768:         }
 5769:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5770:                          &escape($upass),$unhome);
 5771: 	unless ($reply eq 'ok') {
 5772:             return 'error: '.$reply;
 5773:         }   
 5774:         $uhome=&homeserver($uname,$udom,'true');
 5775:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5776: 	    return 'error: unable verify users home machine.';
 5777:         }
 5778:     }   # End of creation of new user
 5779: # ---------------------------------------------------------------------- Add ID
 5780:     if ($uid) {
 5781:        $uid=~tr/A-Z/a-z/;
 5782:        my %uidhash=&idrget($udom,$uname);
 5783:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5784:          && (!$forceid)) {
 5785: 	  unless ($uid eq $uidhash{$uname}) {
 5786: 	      return 'error: user id "'.$uid.'" does not match '.
 5787:                   'current user id "'.$uidhash{$uname}.'".';
 5788:           }
 5789:        } else {
 5790: 	  &idput($udom,($uname => $uid));
 5791:        }
 5792:     }
 5793: # -------------------------------------------------------------- Add names, etc
 5794:     my @tmp=&get('environment',
 5795: 		   ['firstname','middlename','lastname','generation','id',
 5796:                     'permanentemail','inststatus'],
 5797: 		   $udom,$uname);
 5798:     my %names;
 5799:     if ($tmp[0] =~ m/^error:.*/) { 
 5800:         %names=(); 
 5801:     } else {
 5802:         %names = @tmp;
 5803:     }
 5804: #
 5805: # Make sure to not trash student environment if instructor does not bother
 5806: # to supply name and email information
 5807: #
 5808:     if ($first)  { $names{'firstname'}  = $first; }
 5809:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5810:     if ($last)   { $names{'lastname'}   = $last; }
 5811:     if (defined($gene))   { $names{'generation'} = $gene; }
 5812:     if ($email) {
 5813:        $email=~s/[^\w\@\.\-\,]//gs;
 5814:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5815:     }
 5816:     if ($uid) { $names{'id'}  = $uid; }
 5817:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
 5818:     my $reply = &put('environment', \%names, $udom,$uname);
 5819:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5820:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5821:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5822:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5823:                  $umode.', '.$first.', '.$middle.', '.
 5824: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5825:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5826:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5827:     } else {
 5828:         $logmsg .= ' during self creation';
 5829:     }
 5830:     &logthis($logmsg);
 5831:     return 'ok';
 5832: }
 5833: 
 5834: # -------------------------------------------------------------- Modify student
 5835: 
 5836: sub modifystudent {
 5837:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5838:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5839:         $selfenroll,$context)=@_;
 5840:     if (!$cid) {
 5841: 	unless ($cid=$env{'request.course.id'}) {
 5842: 	    return 'not_in_class';
 5843: 	}
 5844:     }
 5845: # --------------------------------------------------------------- Make the user
 5846:     my $reply=&modifyuser
 5847: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5848:          $desiredhome,$email);
 5849:     unless ($reply eq 'ok') { return $reply; }
 5850:     # This will cause &modify_student_enrollment to get the uid from the
 5851:     # students environment
 5852:     $uid = undef if (!$forceid);
 5853:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5854: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5855:     return $reply;
 5856: }
 5857: 
 5858: sub modify_student_enrollment {
 5859:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5860:     my ($cdom,$cnum,$chome);
 5861:     if (!$cid) {
 5862: 	unless ($cid=$env{'request.course.id'}) {
 5863: 	    return 'not_in_class';
 5864: 	}
 5865: 	$cdom=$env{'course.'.$cid.'.domain'};
 5866: 	$cnum=$env{'course.'.$cid.'.num'};
 5867:     } else {
 5868: 	($cdom,$cnum)=split(/_/,$cid);
 5869:     }
 5870:     $chome=$env{'course.'.$cid.'.home'};
 5871:     if (!$chome) {
 5872: 	$chome=&homeserver($cnum,$cdom);
 5873:     }
 5874:     if (!$chome) { return 'unknown_course'; }
 5875:     # Make sure the user exists
 5876:     my $uhome=&homeserver($uname,$udom);
 5877:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5878: 	return 'error: no such user';
 5879:     }
 5880:     # Get student data if we were not given enough information
 5881:     if (!defined($first)  || $first  eq '' || 
 5882:         !defined($last)   || $last   eq '' || 
 5883:         !defined($uid)    || $uid    eq '' || 
 5884:         !defined($middle) || $middle eq '' || 
 5885:         !defined($gene)   || $gene   eq '') {
 5886:         # They did not supply us with enough data to enroll the student, so
 5887:         # we need to pick up more information.
 5888:         my %tmp = &get('environment',
 5889:                        ['firstname','middlename','lastname', 'generation','id']
 5890:                        ,$udom,$uname);
 5891: 
 5892:         #foreach my $key (keys(%tmp)) {
 5893:         #    &logthis("key $key = ".$tmp{$key});
 5894:         #}
 5895:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5896:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5897:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5898:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5899:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5900:     }
 5901:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5902:     my $reply=cput('classlist',
 5903: 		   {"$uname:$udom" => 
 5904: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5905: 		   $cdom,$cnum);
 5906:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5907: 	return 'error: '.$reply;
 5908:     } else {
 5909: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5910:     }
 5911:     # Add student role to user
 5912:     my $uurl='/'.$cid;
 5913:     $uurl=~s/\_/\//g;
 5914:     if ($usec) {
 5915: 	$uurl.='/'.$usec;
 5916:     }
 5917:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 5918: }
 5919: 
 5920: sub format_name {
 5921:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5922:     my $name;
 5923:     if ($first ne 'lastname') {
 5924: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5925:     } else {
 5926: 	if ($lastname=~/\S/) {
 5927: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5928: 	    $name=~s/\s+,/,/;
 5929: 	} else {
 5930: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5931: 	}
 5932:     }
 5933:     $name=~s/^\s+//;
 5934:     $name=~s/\s+$//;
 5935:     $name=~s/\s+/ /g;
 5936:     return $name;
 5937: }
 5938: 
 5939: # ------------------------------------------------- Write to course preferences
 5940: 
 5941: sub writecoursepref {
 5942:     my ($courseid,%prefs)=@_;
 5943:     $courseid=~s/^\///;
 5944:     $courseid=~s/\_/\//g;
 5945:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5946:     my $chome=homeserver($cnum,$cdomain);
 5947:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5948: 	return 'error: no such course';
 5949:     }
 5950:     my $cstring='';
 5951:     foreach my $pref (keys(%prefs)) {
 5952: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5953:     }
 5954:     $cstring=~s/\&$//;
 5955:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5956: }
 5957: 
 5958: # ---------------------------------------------------------- Make/modify course
 5959: 
 5960: sub createcourse {
 5961:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5962:         $course_owner,$crstype)=@_;
 5963:     $url=&declutter($url);
 5964:     my $cid='';
 5965:     unless (&allowed('ccc',$udom)) {
 5966:         return 'refused';
 5967:     }
 5968: # ------------------------------------------------------------------- Create ID
 5969:    my $uname=int(1+rand(9)).
 5970:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5971:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5972:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5973: # ----------------------------------------------- Make sure that does not exist
 5974:    my $uhome=&homeserver($uname,$udom,'true');
 5975:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5976:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5977:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5978:        $uhome=&homeserver($uname,$udom,'true');       
 5979:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5980:            return 'error: unable to generate unique course-ID';
 5981:        } 
 5982:    }
 5983: # ------------------------------------------------ Check supplied server name
 5984:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 5985:     if (! &is_library($course_server)) {
 5986:         return 'error:bad server name '.$course_server;
 5987:     }
 5988: # ------------------------------------------------------------- Make the course
 5989:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 5990:                       $course_server);
 5991:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 5992:     $uhome=&homeserver($uname,$udom,'true');
 5993:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5994: 	return 'error: no such course';
 5995:     }
 5996: # ----------------------------------------------------------------- Course made
 5997: # log existence
 5998:     my $newcourse = {
 5999:                     $udom.'_'.$uname => {
 6000:                                      description => $description,
 6001:                                      inst_code   => $inst_code,
 6002:                                      owner       => $course_owner,
 6003:                                      type        => $crstype,
 6004:                                                 },
 6005:                     };
 6006:     &courseidput($udom,$newcourse,$uhome,'notime');
 6007: # set toplevel url
 6008:     my $topurl=$url;
 6009:     unless ($nonstandard) {
 6010: # ------------------------------------------ For standard courses, make top url
 6011:         my $mapurl=&clutter($url);
 6012:         if ($mapurl eq '/res/') { $mapurl=''; }
 6013:         $env{'form.initmap'}=(<<ENDINITMAP);
 6014: <map>
 6015: <resource id="1" type="start"></resource>
 6016: <resource id="2" src="$mapurl"></resource>
 6017: <resource id="3" type="finish"></resource>
 6018: <link index="1" from="1" to="2"></link>
 6019: <link index="2" from="2" to="3"></link>
 6020: </map>
 6021: ENDINITMAP
 6022:         $topurl=&declutter(
 6023:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6024:                           );
 6025:     }
 6026: # ----------------------------------------------------------- Write preferences
 6027:     &writecoursepref($udom.'_'.$uname,
 6028:                      ('description' => $description,
 6029:                       'url'         => $topurl));
 6030:     return '/'.$udom.'/'.$uname;
 6031: }
 6032: 
 6033: sub is_course {
 6034:     my ($cdom,$cnum) = @_;
 6035:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6036: 				undef,'.');
 6037:     if (exists($courses{$cdom.'_'.$cnum})) {
 6038:         return 1;
 6039:     }
 6040:     return 0;
 6041: }
 6042: 
 6043: # ---------------------------------------------------------- Assign Custom Role
 6044: 
 6045: sub assigncustomrole {
 6046:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6047:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6048:                        $end,$start,$deleteflag,$selfenroll,$context);
 6049: }
 6050: 
 6051: # ----------------------------------------------------------------- Revoke Role
 6052: 
 6053: sub revokerole {
 6054:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6055:     my $now=time;
 6056:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6057: }
 6058: 
 6059: # ---------------------------------------------------------- Revoke Custom Role
 6060: 
 6061: sub revokecustomrole {
 6062:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6063:     my $now=time;
 6064:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6065:            $deleteflag,$selfenroll,$context);
 6066: }
 6067: 
 6068: # ------------------------------------------------------------ Disk usage
 6069: sub diskusage {
 6070:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6071:     $directorypath =~ s/\/$//;
 6072:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6073:                        .&escape($getpropath).':'.&escape($uname).':'
 6074:                        .&escape($udom),homeserver($uname,$udom));
 6075:     if ($listing eq 'unknown_cmd') {
 6076:         if ($getpropath) {
 6077:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6078:         }
 6079:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6080:     }
 6081:     return $listing;
 6082: }
 6083: 
 6084: sub is_locked {
 6085:     my ($file_name, $domain, $user) = @_;
 6086:     my @check;
 6087:     my $is_locked;
 6088:     push @check, $file_name;
 6089:     my %locked = &get('file_permissions',\@check,
 6090: 		      $env{'user.domain'},$env{'user.name'});
 6091:     my ($tmp)=keys(%locked);
 6092:     if ($tmp=~/^error:/) { undef(%locked); }
 6093:     
 6094:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6095:         $is_locked = 'false';
 6096:         foreach my $entry (@{$locked{$file_name}}) {
 6097:            if (ref($entry) eq 'ARRAY') { 
 6098:                $is_locked = 'true';
 6099:                last;
 6100:            }
 6101:        }
 6102:     } else {
 6103:         $is_locked = 'false';
 6104:     }
 6105: }
 6106: 
 6107: sub declutter_portfile {
 6108:     my ($file) = @_;
 6109:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6110:     return $file;
 6111: }
 6112: 
 6113: # ------------------------------------------------------------- Mark as Read Only
 6114: 
 6115: sub mark_as_readonly {
 6116:     my ($domain,$user,$files,$what) = @_;
 6117:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6118:     my ($tmp)=keys(%current_permissions);
 6119:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6120:     foreach my $file (@{$files}) {
 6121: 	$file = &declutter_portfile($file);
 6122:         push(@{$current_permissions{$file}},$what);
 6123:     }
 6124:     &put('file_permissions',\%current_permissions,$domain,$user);
 6125:     return;
 6126: }
 6127: 
 6128: # ------------------------------------------------------------Save Selected Files
 6129: 
 6130: sub save_selected_files {
 6131:     my ($user, $path, @files) = @_;
 6132:     my $filename = $user."savedfiles";
 6133:     my @other_files = &files_not_in_path($user, $path);
 6134:     open (OUT, '>'.$tmpdir.$filename);
 6135:     foreach my $file (@files) {
 6136:         print (OUT $env{'form.currentpath'}.$file."\n");
 6137:     }
 6138:     foreach my $file (@other_files) {
 6139:         print (OUT $file."\n");
 6140:     }
 6141:     close (OUT);
 6142:     return 'ok';
 6143: }
 6144: 
 6145: sub clear_selected_files {
 6146:     my ($user) = @_;
 6147:     my $filename = $user."savedfiles";
 6148:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6149:     print (OUT undef);
 6150:     close (OUT);
 6151:     return ("ok");    
 6152: }
 6153: 
 6154: sub files_in_path {
 6155:     my ($user, $path) = @_;
 6156:     my $filename = $user."savedfiles";
 6157:     my %return_files;
 6158:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6159:     while (my $line_in = <IN>) {
 6160:         chomp ($line_in);
 6161:         my @paths_and_file = split (m!/!, $line_in);
 6162:         my $file_part = pop (@paths_and_file);
 6163:         my $path_part = join ('/', @paths_and_file);
 6164:         $path_part.='/';
 6165:         my $path_and_file = $path_part.$file_part;
 6166:         if ($path_part eq $path) {
 6167:             $return_files{$file_part}= 'selected';
 6168:         }
 6169:     }
 6170:     close (IN);
 6171:     return (\%return_files);
 6172: }
 6173: 
 6174: # called in portfolio select mode, to show files selected NOT in current directory
 6175: sub files_not_in_path {
 6176:     my ($user, $path) = @_;
 6177:     my $filename = $user."savedfiles";
 6178:     my @return_files;
 6179:     my $path_part;
 6180:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6181:     while (my $line = <IN>) {
 6182:         #ok, I know it's clunky, but I want it to work
 6183:         my @paths_and_file = split(m|/|, $line);
 6184:         my $file_part = pop(@paths_and_file);
 6185:         chomp($file_part);
 6186:         my $path_part = join('/', @paths_and_file);
 6187:         $path_part .= '/';
 6188:         my $path_and_file = $path_part.$file_part;
 6189:         if ($path_part ne $path) {
 6190:             push(@return_files, ($path_and_file));
 6191:         }
 6192:     }
 6193:     close(OUT);
 6194:     return (@return_files);
 6195: }
 6196: 
 6197: #----------------------------------------------Get portfolio file permissions
 6198: 
 6199: sub get_portfile_permissions {
 6200:     my ($domain,$user) = @_;
 6201:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6202:     my ($tmp)=keys(%current_permissions);
 6203:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6204:     return \%current_permissions;
 6205: }
 6206: 
 6207: #---------------------------------------------Get portfolio file access controls
 6208: 
 6209: sub get_access_controls {
 6210:     my ($current_permissions,$group,$file) = @_;
 6211:     my %access;
 6212:     my $real_file = $file;
 6213:     $file =~ s/\.meta$//;
 6214:     if (defined($file)) {
 6215:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6216:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6217:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6218:             }
 6219:         }
 6220:     } else {
 6221:         foreach my $key (keys(%{$current_permissions})) {
 6222:             if ($key =~ /\0accesscontrol$/) {
 6223:                 if (defined($group)) {
 6224:                     if ($key !~ m-^\Q$group\E/-) {
 6225:                         next;
 6226:                     }
 6227:                 }
 6228:                 my ($fullpath) = split(/\0/,$key);
 6229:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6230:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6231:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6232:                     }
 6233:                 }
 6234:             }
 6235:         }
 6236:     }
 6237:     return %access;
 6238: }
 6239: 
 6240: sub modify_access_controls {
 6241:     my ($file_name,$changes,$domain,$user)=@_;
 6242:     my ($outcome,$deloutcome);
 6243:     my %store_permissions;
 6244:     my %new_values;
 6245:     my %new_control;
 6246:     my %translation;
 6247:     my @deletions = ();
 6248:     my $now = time;
 6249:     if (exists($$changes{'activate'})) {
 6250:         if (ref($$changes{'activate'}) eq 'HASH') {
 6251:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6252:             my $numnew = scalar(@newitems);
 6253:             for (my $i=0; $i<$numnew; $i++) {
 6254:                 my $newkey = $newitems[$i];
 6255:                 my $newid = &Apache::loncommon::get_cgi_id();
 6256:                 if ($newkey =~ /^\d+:/) { 
 6257:                     $newkey =~ s/^(\d+)/$newid/;
 6258:                     $translation{$1} = $newid;
 6259:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6260:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6261:                     $translation{$1} = $newid;
 6262:                 }
 6263:                 $new_values{$file_name."\0".$newkey} = 
 6264:                                           $$changes{'activate'}{$newitems[$i]};
 6265:                 $new_control{$newkey} = $now;
 6266:             }
 6267:         }
 6268:     }
 6269:     my %todelete;
 6270:     my %changed_items;
 6271:     foreach my $action ('delete','update') {
 6272:         if (exists($$changes{$action})) {
 6273:             if (ref($$changes{$action}) eq 'HASH') {
 6274:                 foreach my $key (keys(%{$$changes{$action}})) {
 6275:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6276:                     if ($action eq 'delete') { 
 6277:                         $todelete{$itemnum} = 1;
 6278:                     } else {
 6279:                         $changed_items{$itemnum} = $key;
 6280:                     }
 6281:                 }
 6282:             }
 6283:         }
 6284:     }
 6285:     # get lock on access controls for file.
 6286:     my $lockhash = {
 6287:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6288:                                                        ':'.$env{'user.domain'},
 6289:                    }; 
 6290:     my $tries = 0;
 6291:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6292:    
 6293:     while (($gotlock ne 'ok') && $tries <3) {
 6294:         $tries ++;
 6295:         sleep 1;
 6296:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6297:     }
 6298:     if ($gotlock eq 'ok') {
 6299:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6300:         my ($tmp)=keys(%curr_permissions);
 6301:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6302:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6303:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6304:             if (ref($curr_controls) eq 'HASH') {
 6305:                 foreach my $control_item (keys(%{$curr_controls})) {
 6306:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6307:                     if (defined($todelete{$itemnum})) {
 6308:                         push(@deletions,$file_name."\0".$control_item);
 6309:                     } else {
 6310:                         if (defined($changed_items{$itemnum})) {
 6311:                             $new_control{$changed_items{$itemnum}} = $now;
 6312:                             push(@deletions,$file_name."\0".$control_item);
 6313:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6314:                         } else {
 6315:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6316:                         }
 6317:                     }
 6318:                 }
 6319:             }
 6320:         }
 6321:         my ($group);
 6322:         if (&is_course($domain,$user)) {
 6323:             ($group,my $file) = split(/\//,$file_name,2);
 6324:         }
 6325:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6326:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6327:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6328:         #  remove lock
 6329:         my @del_lock = ($file_name."\0".'locked_access_records');
 6330:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6331:         my $sqlresult =
 6332:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6333:                                     $group);
 6334:     } else {
 6335:         $outcome = "error: could not obtain lockfile\n";  
 6336:     }
 6337:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6338: }
 6339: 
 6340: sub make_public_indefinitely {
 6341:     my ($requrl) = @_;
 6342:     my $now = time;
 6343:     my $action = 'activate';
 6344:     my $aclnum = 0;
 6345:     if (&is_portfolio_url($requrl)) {
 6346:         my (undef,$udom,$unum,$file_name,$group) =
 6347:             &parse_portfolio_url($requrl);
 6348:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6349:         my %access_controls = &get_access_controls($current_perms,
 6350:                                                    $group,$file_name);
 6351:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6352:             my ($num,$scope,$end,$start) = 
 6353:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6354:             if ($scope eq 'public') {
 6355:                 if ($start <= $now && $end == 0) {
 6356:                     $action = 'none';
 6357:                 } else {
 6358:                     $action = 'update';
 6359:                     $aclnum = $num;
 6360:                 }
 6361:                 last;
 6362:             }
 6363:         }
 6364:         if ($action eq 'none') {
 6365:              return 'ok';
 6366:         } else {
 6367:             my %changes;
 6368:             my $newend = 0;
 6369:             my $newstart = $now;
 6370:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6371:             $changes{$action}{$newkey} = {
 6372:                 type => 'public',
 6373:                 time => {
 6374:                     start => $newstart,
 6375:                     end   => $newend,
 6376:                 },
 6377:             };
 6378:             my ($outcome,$deloutcome,$new_values,$translation) =
 6379:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6380:             return $outcome;
 6381:         }
 6382:     } else {
 6383:         return 'invalid';
 6384:     }
 6385: }
 6386: 
 6387: #------------------------------------------------------Get Marked as Read Only
 6388: 
 6389: sub get_marked_as_readonly {
 6390:     my ($domain,$user,$what,$group) = @_;
 6391:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6392:     my @readonly_files;
 6393:     my $cmp1=$what;
 6394:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6395:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6396:         if (defined($group)) {
 6397:             if ($file_name !~ m-^\Q$group\E/-) {
 6398:                 next;
 6399:             }
 6400:         }
 6401:         if (ref($value) eq "ARRAY"){
 6402:             foreach my $stored_what (@{$value}) {
 6403:                 my $cmp2=$stored_what;
 6404:                 if (ref($stored_what) eq 'ARRAY') {
 6405:                     $cmp2=join('',@{$stored_what});
 6406:                 }
 6407:                 if ($cmp1 eq $cmp2) {
 6408:                     push(@readonly_files, $file_name);
 6409:                     last;
 6410:                 } elsif (!defined($what)) {
 6411:                     push(@readonly_files, $file_name);
 6412:                     last;
 6413:                 }
 6414:             }
 6415:         }
 6416:     }
 6417:     return @readonly_files;
 6418: }
 6419: #-----------------------------------------------------------Get Marked as Read Only Hash
 6420: 
 6421: sub get_marked_as_readonly_hash {
 6422:     my ($current_permissions,$group,$what) = @_;
 6423:     my %readonly_files;
 6424:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6425:         if (defined($group)) {
 6426:             if ($file_name !~ m-^\Q$group\E/-) {
 6427:                 next;
 6428:             }
 6429:         }
 6430:         if (ref($value) eq "ARRAY"){
 6431:             foreach my $stored_what (@{$value}) {
 6432:                 if (ref($stored_what) eq 'ARRAY') {
 6433:                     foreach my $lock_descriptor(@{$stored_what}) {
 6434:                         if ($lock_descriptor eq 'graded') {
 6435:                             $readonly_files{$file_name} = 'graded';
 6436:                         } elsif ($lock_descriptor eq 'handback') {
 6437:                             $readonly_files{$file_name} = 'handback';
 6438:                         } else {
 6439:                             if (!exists($readonly_files{$file_name})) {
 6440:                                 $readonly_files{$file_name} = 'locked';
 6441:                             }
 6442:                         }
 6443:                     }
 6444:                 } 
 6445:             }
 6446:         } 
 6447:     }
 6448:     return %readonly_files;
 6449: }
 6450: # ------------------------------------------------------------ Unmark as Read Only
 6451: 
 6452: sub unmark_as_readonly {
 6453:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6454:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6455:     my ($domain,$user,$what,$file_name,$group) = @_;
 6456:     $file_name = &declutter_portfile($file_name);
 6457:     my $symb_crs = $what;
 6458:     if (ref($what)) { $symb_crs=join('',@$what); }
 6459:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6460:     my ($tmp)=keys(%current_permissions);
 6461:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6462:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6463:     foreach my $file (@readonly_files) {
 6464: 	my $clean_file = &declutter_portfile($file);
 6465: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6466: 	my $current_locks = $current_permissions{$file};
 6467:         my @new_locks;
 6468:         my @del_keys;
 6469:         if (ref($current_locks) eq "ARRAY"){
 6470:             foreach my $locker (@{$current_locks}) {
 6471:                 my $compare=$locker;
 6472:                 if (ref($locker) eq 'ARRAY') {
 6473:                     $compare=join('',@{$locker});
 6474:                     if ($compare ne $symb_crs) {
 6475:                         push(@new_locks, $locker);
 6476:                     }
 6477:                 }
 6478:             }
 6479:             if (scalar(@new_locks) > 0) {
 6480:                 $current_permissions{$file} = \@new_locks;
 6481:             } else {
 6482:                 push(@del_keys, $file);
 6483:                 &del('file_permissions',\@del_keys, $domain, $user);
 6484:                 delete($current_permissions{$file});
 6485:             }
 6486:         }
 6487:     }
 6488:     &put('file_permissions',\%current_permissions,$domain,$user);
 6489:     return;
 6490: }
 6491: 
 6492: # ------------------------------------------------------------ Directory lister
 6493: 
 6494: sub dirlist {
 6495:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6496:     $uri=~s/^\///;
 6497:     $uri=~s/\/$//;
 6498:     my ($udom, $uname);
 6499:     if ($getuserdir) {
 6500:         $udom = $userdomain;
 6501:         $uname = $username;
 6502:     } else {
 6503:         (undef,$udom,$uname)=split(/\//,$uri);
 6504:         if(defined($userdomain)) {
 6505:             $udom = $userdomain;
 6506:         }
 6507:         if(defined($username)) {
 6508:             $uname = $username;
 6509:         }
 6510:     }
 6511:     my ($dirRoot,$listing,@listing_results);
 6512: 
 6513:     $dirRoot = $perlvar{'lonDocRoot'};
 6514:     if (defined($getpropath)) {
 6515:         $dirRoot = &propath($udom,$uname);
 6516:         $dirRoot =~ s/\/$//;
 6517:     } elsif (defined($getuserdir)) {
 6518:         my $subdir=$uname.'__';
 6519:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6520:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6521:                    ."/$udom/$subdir/$uname";
 6522:     } elsif (defined($alternateRoot)) {
 6523:         $dirRoot = $alternateRoot;
 6524:     }
 6525: 
 6526:     if($udom) {
 6527:         if($uname) {
 6528:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6529:                               .$getuserdir.':'.&escape($dirRoot)
 6530:                               .':'.&escape($uname).':'.&escape($udom),
 6531:                               &homeserver($uname,$udom));
 6532:             if ($listing eq 'unknown_cmd') {
 6533:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6534:                                   &homeserver($uname,$udom));
 6535:             } else {
 6536:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6537:             }
 6538:             if ($listing eq 'unknown_cmd') {
 6539:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6540: 				  &homeserver($uname,$udom));
 6541:                 @listing_results = split(/:/,$listing);
 6542:             } else {
 6543:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6544:             }
 6545:             return @listing_results;
 6546:         } elsif(!$alternateRoot) {
 6547:             my %allusers;
 6548: 	    my %servers = &get_servers($udom,'library');
 6549:  	    foreach my $tryserver (keys(%servers)) {
 6550:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6551:                                   &escape($udom),$tryserver);
 6552:                 if ($listing eq 'unknown_cmd') {
 6553: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6554: 				      $udom, $tryserver);
 6555:                 } else {
 6556:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6557:                 }
 6558: 		if ($listing eq 'unknown_cmd') {
 6559: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6560: 				      $udom, $tryserver);
 6561: 		    @listing_results = split(/:/,$listing);
 6562: 		} else {
 6563: 		    @listing_results =
 6564: 			map { &unescape($_); } split(/:/,$listing);
 6565: 		}
 6566: 		if ($listing_results[0] ne 'no_such_dir' && 
 6567: 		    $listing_results[0] ne 'empty'       &&
 6568: 		    $listing_results[0] ne 'con_lost') {
 6569: 		    foreach my $line (@listing_results) {
 6570: 			my ($entry) = split(/&/,$line,2);
 6571: 			$allusers{$entry} = 1;
 6572: 		    }
 6573: 		}
 6574:             }
 6575:             my $alluserstr='';
 6576:             foreach my $user (sort(keys(%allusers))) {
 6577:                 $alluserstr.=$user.'&user:';
 6578:             }
 6579:             $alluserstr=~s/:$//;
 6580:             return split(/:/,$alluserstr);
 6581:         } else {
 6582:             return ('missing user name');
 6583:         }
 6584:     } elsif(!defined($getpropath)) {
 6585:         my @all_domains = sort(&all_domains());
 6586:         foreach my $domain (@all_domains) {
 6587:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6588:         }
 6589:         return @all_domains;
 6590:     } else {
 6591:         return ('missing domain');
 6592:     }
 6593: }
 6594: 
 6595: # --------------------------------------------- GetFileTimestamp
 6596: # This function utilizes dirlist and returns the date stamp for
 6597: # when it was last modified.  It will also return an error of -1
 6598: # if an error occurs
 6599: 
 6600: sub GetFileTimestamp {
 6601:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6602:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6603:     $studentName   = &LONCAPA::clean_username($studentName);
 6604:     my ($fileStat) = 
 6605:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6606:                                  undef,$getuserdir);
 6607:     my @stats = split('&', $fileStat);
 6608:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6609:         # @stats contains first the filename, then the stat output
 6610:         return $stats[10]; # so this is 10 instead of 9.
 6611:     } else {
 6612:         return -1;
 6613:     }
 6614: }
 6615: 
 6616: sub stat_file {
 6617:     my ($uri) = @_;
 6618:     $uri = &clutter_with_no_wrapper($uri);
 6619: 
 6620:     my ($udom,$uname,$file);
 6621:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6622: 	($udom,$uname,$file) =
 6623: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6624: 	$file = 'userfiles/'.$file;
 6625:     }
 6626:     if ($uri =~ m-^/res/-) {
 6627: 	($udom,$uname) = 
 6628: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6629: 	$file = $uri;
 6630:     }
 6631: 
 6632:     if (!$udom || !$uname || !$file) {
 6633: 	# unable to handle the uri
 6634: 	return ();
 6635:     }
 6636:     my $getpropath;
 6637:     if ($file =~ /^userfiles\//) {
 6638:         $getpropath = 1;
 6639:     }
 6640:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6641:     my @stats = split('&', $result);
 6642:     
 6643:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6644: 	shift(@stats); #filename is first
 6645: 	return @stats;
 6646:     }
 6647:     return ();
 6648: }
 6649: 
 6650: # -------------------------------------------------------- Value of a Condition
 6651: 
 6652: # gets the value of a specific preevaluated condition
 6653: #    stored in the string  $env{user.state.<cid>}
 6654: # or looks up a condition reference in the bighash and if if hasn't
 6655: # already been evaluated recurses into docondval to get the value of
 6656: # the condition, then memoizing it to 
 6657: #   $env{user.state.<cid>.<condition>}
 6658: sub directcondval {
 6659:     my $number=shift;
 6660:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6661: 	&Apache::lonuserstate::evalstate();
 6662:     }
 6663:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6664: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6665:     } elsif ($number =~ /^_/) {
 6666: 	my $sub_condition;
 6667: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6668: 		&GDBM_READER(),0640)) {
 6669: 	    $sub_condition=$bighash{'conditions'.$number};
 6670: 	    untie(%bighash);
 6671: 	}
 6672: 	my $value = &docondval($sub_condition);
 6673: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6674: 	return $value;
 6675:     }
 6676:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6677:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6678:     } else {
 6679:        return 2;
 6680:     }
 6681: }
 6682: 
 6683: # get the collection of conditions for this resource
 6684: sub condval {
 6685:     my $condidx=shift;
 6686:     my $allpathcond='';
 6687:     foreach my $cond (split(/\|/,$condidx)) {
 6688: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6689: 	    $allpathcond.=
 6690: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6691: 	}
 6692:     }
 6693:     $allpathcond=~s/\|$//;
 6694:     return &docondval($allpathcond);
 6695: }
 6696: 
 6697: #evaluates an expression of conditions
 6698: sub docondval {
 6699:     my ($allpathcond) = @_;
 6700:     my $result=0;
 6701:     if ($env{'request.course.id'}
 6702: 	&& defined($allpathcond)) {
 6703: 	my $operand='|';
 6704: 	my @stack;
 6705: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6706: 	    if ($chunk eq '(') {
 6707: 		push @stack,($operand,$result);
 6708: 	    } elsif ($chunk eq ')') {
 6709: 		my $before=pop @stack;
 6710: 		if (pop @stack eq '&') {
 6711: 		    $result=$result>$before?$before:$result;
 6712: 		} else {
 6713: 		    $result=$result>$before?$result:$before;
 6714: 		}
 6715: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6716: 		$operand=$chunk;
 6717: 	    } else {
 6718: 		my $new=directcondval($chunk);
 6719: 		if ($operand eq '&') {
 6720: 		    $result=$result>$new?$new:$result;
 6721: 		} else {
 6722: 		    $result=$result>$new?$result:$new;
 6723: 		}
 6724: 	    }
 6725: 	}
 6726:     }
 6727:     return $result;
 6728: }
 6729: 
 6730: # ---------------------------------------------------- Devalidate courseresdata
 6731: 
 6732: sub devalidatecourseresdata {
 6733:     my ($coursenum,$coursedomain)=@_;
 6734:     my $hashid=$coursenum.':'.$coursedomain;
 6735:     &devalidate_cache_new('courseres',$hashid);
 6736: }
 6737: 
 6738: 
 6739: # --------------------------------------------------- Course Resourcedata Query
 6740: #
 6741: #  Parameters:
 6742: #      $coursenum    - Number of the course.
 6743: #      $coursedomain - Domain at which the course was created.
 6744: #  Returns:
 6745: #     A hash of the course parameters along (I think) with timestamps
 6746: #     and version info.
 6747: 
 6748: sub get_courseresdata {
 6749:     my ($coursenum,$coursedomain)=@_;
 6750:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6751:     my $hashid=$coursenum.':'.$coursedomain;
 6752:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6753:     my %dumpreply;
 6754:     unless (defined($cached)) {
 6755: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6756: 	$result=\%dumpreply;
 6757: 	my ($tmp) = keys(%dumpreply);
 6758: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6759: 	    &do_cache_new('courseres',$hashid,$result,600);
 6760: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6761: 	    return $tmp;
 6762: 	} elsif ($tmp =~ /^(error)/) {
 6763: 	    $result=undef;
 6764: 	    &do_cache_new('courseres',$hashid,$result,600);
 6765: 	}
 6766:     }
 6767:     return $result;
 6768: }
 6769: 
 6770: sub devalidateuserresdata {
 6771:     my ($uname,$udom)=@_;
 6772:     my $hashid="$udom:$uname";
 6773:     &devalidate_cache_new('userres',$hashid);
 6774: }
 6775: 
 6776: sub get_userresdata {
 6777:     my ($uname,$udom)=@_;
 6778:     #most student don\'t have any data set, check if there is some data
 6779:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6780: 
 6781:     my $hashid="$udom:$uname";
 6782:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6783:     if (!defined($cached)) {
 6784: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6785: 	$result=\%resourcedata;
 6786: 	&do_cache_new('userres',$hashid,$result,600);
 6787:     }
 6788:     my ($tmp)=keys(%$result);
 6789:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6790: 	return $result;
 6791:     }
 6792:     #error 2 occurs when the .db doesn't exist
 6793:     if ($tmp!~/error: 2 /) {
 6794: 	&logthis("<font color=\"blue\">WARNING:".
 6795: 		 " Trying to get resource data for ".
 6796: 		 $uname." at ".$udom.": ".
 6797: 		 $tmp."</font>");
 6798:     } elsif ($tmp=~/error: 2 /) {
 6799: 	#&EXT_cache_set($udom,$uname);
 6800: 	&do_cache_new('userres',$hashid,undef,600);
 6801: 	undef($tmp); # not really an error so don't send it back
 6802:     }
 6803:     return $tmp;
 6804: }
 6805: #----------------------------------------------- resdata - return resource data
 6806: #  Purpose:
 6807: #    Return resource data for either users or for a course.
 6808: #  Parameters:
 6809: #     $name      - Course/user name.
 6810: #     $domain    - Name of the domain the user/course is registered on.
 6811: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6812: #     @which     - Array of names of resources desired.
 6813: #  Returns:
 6814: #     The value of the first reasource in @which that is found in the
 6815: #     resource hash.
 6816: #  Exceptional Conditions:
 6817: #     If the $type passed in is not valid (not the string 'course' or 
 6818: #     'user', an undefined  reference is returned.
 6819: #     If none of the resources are found, an undef is returned
 6820: sub resdata {
 6821:     my ($name,$domain,$type,@which)=@_;
 6822:     my $result;
 6823:     if ($type eq 'course') {
 6824: 	$result=&get_courseresdata($name,$domain);
 6825:     } elsif ($type eq 'user') {
 6826: 	$result=&get_userresdata($name,$domain);
 6827:     }
 6828:     if (!ref($result)) { return $result; }    
 6829:     foreach my $item (@which) {
 6830: 	if (defined($result->{$item->[0]})) {
 6831: 	    return [$result->{$item->[0]},$item->[1]];
 6832: 	}
 6833:     }
 6834:     return undef;
 6835: }
 6836: 
 6837: #
 6838: # EXT resource caching routines
 6839: #
 6840: 
 6841: sub clear_EXT_cache_status {
 6842:     &delenv('cache.EXT.');
 6843: }
 6844: 
 6845: sub EXT_cache_status {
 6846:     my ($target_domain,$target_user) = @_;
 6847:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6848:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6849:         # We know already the user has no data
 6850:         return 1;
 6851:     } else {
 6852:         return 0;
 6853:     }
 6854: }
 6855: 
 6856: sub EXT_cache_set {
 6857:     my ($target_domain,$target_user) = @_;
 6858:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6859:     #&appenv({$cachename => time});
 6860: }
 6861: 
 6862: # --------------------------------------------------------- Value of a Variable
 6863: sub EXT {
 6864: 
 6865:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6866:     unless ($varname) { return ''; }
 6867:     #get real user name/domain, courseid and symb
 6868:     my $courseid;
 6869:     my $publicuser;
 6870:     if ($symbparm) {
 6871: 	$symbparm=&get_symb_from_alias($symbparm);
 6872:     }
 6873:     if (!($uname && $udom)) {
 6874:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6875:       if (!$symbparm) {	$symbparm=$cursymb; }
 6876:     } else {
 6877: 	$courseid=$env{'request.course.id'};
 6878:     }
 6879:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6880:     my $rest;
 6881:     if (defined($therest[0])) {
 6882:        $rest=join('.',@therest);
 6883:     } else {
 6884:        $rest='';
 6885:     }
 6886: 
 6887:     my $qualifierrest=$qualifier;
 6888:     if ($rest) { $qualifierrest.='.'.$rest; }
 6889:     my $spacequalifierrest=$space;
 6890:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6891:     if ($realm eq 'user') {
 6892: # --------------------------------------------------------------- user.resource
 6893: 	if ($space eq 'resource') {
 6894: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6895: 		  || defined($Apache::lonhomework::parsing_a_task))
 6896: 		 &&
 6897: 		 ($symbparm eq &symbread()) ) {	
 6898: 		# if we are in the middle of processing the resource the
 6899: 		# get the value we are planning on committing
 6900:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6901:                     return $Apache::lonhomework::results{$qualifierrest};
 6902:                 } else {
 6903:                     return $Apache::lonhomework::history{$qualifierrest};
 6904:                 }
 6905: 	    } else {
 6906: 		my %restored;
 6907: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6908: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6909: 		} else {
 6910: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6911: 		}
 6912: 		return $restored{$qualifierrest};
 6913: 	    }
 6914: # ----------------------------------------------------------------- user.access
 6915:         } elsif ($space eq 'access') {
 6916: 	    # FIXME - not supporting calls for a specific user
 6917:             return &allowed($qualifier,$rest);
 6918: # ------------------------------------------ user.preferences, user.environment
 6919:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6920: 	    if (($uname eq $env{'user.name'}) &&
 6921: 		($udom eq $env{'user.domain'})) {
 6922: 		return $env{join('.',('environment',$qualifierrest))};
 6923: 	    } else {
 6924: 		my %returnhash;
 6925: 		if (!$publicuser) {
 6926: 		    %returnhash=&userenvironment($udom,$uname,
 6927: 						 $qualifierrest);
 6928: 		}
 6929: 		return $returnhash{$qualifierrest};
 6930: 	    }
 6931: # ----------------------------------------------------------------- user.course
 6932:         } elsif ($space eq 'course') {
 6933: 	    # FIXME - not supporting calls for a specific user
 6934:             return $env{join('.',('request.course',$qualifier))};
 6935: # ------------------------------------------------------------------- user.role
 6936:         } elsif ($space eq 'role') {
 6937: 	    # FIXME - not supporting calls for a specific user
 6938:             my ($role,$where)=split(/\./,$env{'request.role'});
 6939:             if ($qualifier eq 'value') {
 6940: 		return $role;
 6941:             } elsif ($qualifier eq 'extent') {
 6942:                 return $where;
 6943:             }
 6944: # ----------------------------------------------------------------- user.domain
 6945:         } elsif ($space eq 'domain') {
 6946:             return $udom;
 6947: # ------------------------------------------------------------------- user.name
 6948:         } elsif ($space eq 'name') {
 6949:             return $uname;
 6950: # ---------------------------------------------------- Any other user namespace
 6951:         } else {
 6952: 	    my %reply;
 6953: 	    if (!$publicuser) {
 6954: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6955: 	    }
 6956: 	    return $reply{$qualifierrest};
 6957:         }
 6958:     } elsif ($realm eq 'query') {
 6959: # ---------------------------------------------- pull stuff out of query string
 6960:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6961: 						[$spacequalifierrest]);
 6962: 	return $env{'form.'.$spacequalifierrest}; 
 6963:    } elsif ($realm eq 'request') {
 6964: # ------------------------------------------------------------- request.browser
 6965:         if ($space eq 'browser') {
 6966: 	    if ($qualifier eq 'textremote') {
 6967: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6968: 		    return 1;
 6969: 		} else {
 6970: 		    return 0;
 6971: 		}
 6972: 	    } else {
 6973: 		return $env{'browser.'.$qualifier};
 6974: 	    }
 6975: # ------------------------------------------------------------ request.filename
 6976:         } else {
 6977:             return $env{'request.'.$spacequalifierrest};
 6978:         }
 6979:     } elsif ($realm eq 'course') {
 6980: # ---------------------------------------------------------- course.description
 6981:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 6982:     } elsif ($realm eq 'resource') {
 6983: 
 6984: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 6985: 	    if (!$symbparm) { $symbparm=&symbread(); }
 6986: 	}
 6987: 
 6988: 	if ($space eq 'title') {
 6989: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 6990: 	    return &gettitle($symbparm);
 6991: 	}
 6992: 	
 6993: 	if ($space eq 'map') {
 6994: 	    my ($map) = &decode_symb($symbparm);
 6995: 	    return &symbread($map);
 6996: 	}
 6997: 	if ($space eq 'filename') {
 6998: 	    if ($symbparm) {
 6999: 		return &clutter((&decode_symb($symbparm))[2]);
 7000: 	    }
 7001: 	    return &hreflocation('',$env{'request.filename'});
 7002: 	}
 7003: 
 7004: 	my ($section, $group, @groups);
 7005: 	my ($courselevelm,$courselevel);
 7006: 	if ($symbparm && defined($courseid) && 
 7007: 	    $courseid eq $env{'request.course.id'}) {
 7008: 
 7009: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7010: 
 7011: # ----------------------------------------------------- Cascading lookup scheme
 7012: 	    my $symbp=$symbparm;
 7013: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7014: 
 7015: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7016: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7017: 
 7018: 	    if (($env{'user.name'} eq $uname) &&
 7019: 		($env{'user.domain'} eq $udom)) {
 7020: 		$section=$env{'request.course.sec'};
 7021:                 @groups = split(/:/,$env{'request.course.groups'});  
 7022:                 @groups=&sort_course_groups($courseid,@groups); 
 7023: 	    } else {
 7024: 		if (! defined($usection)) {
 7025: 		    $section=&getsection($udom,$uname,$courseid);
 7026: 		} else {
 7027: 		    $section = $usection;
 7028: 		}
 7029:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7030: 	    }
 7031: 
 7032: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7033: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7034: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7035: 
 7036: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7037: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7038: 	    $courselevelm=$courseid.'.'.$mapparm;
 7039: 
 7040: # ----------------------------------------------------------- first, check user
 7041: 
 7042: 	    my $userreply=&resdata($uname,$udom,'user',
 7043: 				       ([$courselevelr,'resource'],
 7044: 					[$courselevelm,'map'     ],
 7045: 					[$courselevel, 'course'  ]));
 7046: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7047: 
 7048: # ------------------------------------------------ second, check some of course
 7049:             my $coursereply;
 7050:             if (@groups > 0) {
 7051:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7052:                                        $mapparm,$spacequalifierrest);
 7053:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7054:             }
 7055: 
 7056: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7057: 				  $env{'course.'.$courseid.'.domain'},
 7058: 				  'course',
 7059: 				  ([$seclevelr,   'resource'],
 7060: 				   [$seclevelm,   'map'     ],
 7061: 				   [$seclevel,    'course'  ],
 7062: 				   [$courselevelr,'resource']));
 7063: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7064: 
 7065: # ------------------------------------------------------ third, check map parms
 7066: 	    my %parmhash=();
 7067: 	    my $thisparm='';
 7068: 	    if (tie(%parmhash,'GDBM_File',
 7069: 		    $env{'request.course.fn'}.'_parms.db',
 7070: 		    &GDBM_READER(),0640)) {
 7071: 		$thisparm=$parmhash{$symbparm};
 7072: 		untie(%parmhash);
 7073: 	    }
 7074: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7075: 	}
 7076: # ------------------------------------------ fourth, look in resource metadata
 7077: 
 7078: 	$spacequalifierrest=~s/\./\_/;
 7079: 	my $filename;
 7080: 	if (!$symbparm) { $symbparm=&symbread(); }
 7081: 	if ($symbparm) {
 7082: 	    $filename=(&decode_symb($symbparm))[2];
 7083: 	} else {
 7084: 	    $filename=$env{'request.filename'};
 7085: 	}
 7086: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7087: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7088: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7089: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7090: 
 7091: # ---------------------------------------------- fourth, look in rest of course
 7092: 	if ($symbparm && defined($courseid) && 
 7093: 	    $courseid eq $env{'request.course.id'}) {
 7094: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7095: 				     $env{'course.'.$courseid.'.domain'},
 7096: 				     'course',
 7097: 				     ([$courselevelm,'map'   ],
 7098: 				      [$courselevel, 'course']));
 7099: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7100: 	}
 7101: # ------------------------------------------------------------------ Cascade up
 7102: 	unless ($space eq '0') {
 7103: 	    my @parts=split(/_/,$space);
 7104: 	    my $id=pop(@parts);
 7105: 	    my $part=join('_',@parts);
 7106: 	    if ($part eq '') { $part='0'; }
 7107: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7108: 				 $symbparm,$udom,$uname,$section,1);
 7109: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7110: 	}
 7111: 	if ($recurse) { return undef; }
 7112: 	my $pack_def=&packages_tab_default($filename,$varname);
 7113: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7114: # ---------------------------------------------------- Any other user namespace
 7115:     } elsif ($realm eq 'environment') {
 7116: # ----------------------------------------------------------------- environment
 7117: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7118: 	    return $env{'environment.'.$spacequalifierrest};
 7119: 	} else {
 7120: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7121: 		return '';
 7122: 	    }
 7123: 	    my %returnhash=&userenvironment($udom,$uname,
 7124: 					    $spacequalifierrest);
 7125: 	    return $returnhash{$spacequalifierrest};
 7126: 	}
 7127:     } elsif ($realm eq 'system') {
 7128: # ----------------------------------------------------------------- system.time
 7129: 	if ($space eq 'time') {
 7130: 	    return time;
 7131:         }
 7132:     } elsif ($realm eq 'server') {
 7133: # ----------------------------------------------------------------- system.time
 7134: 	if ($space eq 'name') {
 7135: 	    return $ENV{'SERVER_NAME'};
 7136:         }
 7137:     }
 7138:     return '';
 7139: }
 7140: 
 7141: sub get_reply {
 7142:     my ($reply_value) = @_;
 7143:     if (ref($reply_value) eq 'ARRAY') {
 7144:         if (wantarray) {
 7145: 	    return @$reply_value;
 7146:         }
 7147:         return $reply_value->[0];
 7148:     } else {
 7149:         return $reply_value;
 7150:     }
 7151: }
 7152: 
 7153: sub check_group_parms {
 7154:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7155:     my @groupitems = ();
 7156:     my $resultitem;
 7157:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7158:     foreach my $group (@{$groups}) {
 7159:         foreach my $level (@levels) {
 7160:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7161:              push(@groupitems,[$item,$level->[1]]);
 7162:         }
 7163:     }
 7164:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7165:                             $env{'course.'.$courseid.'.domain'},
 7166:                                      'course',@groupitems);
 7167:     return $coursereply;
 7168: }
 7169: 
 7170: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7171:     my ($courseid,@groups) = @_;
 7172:     @groups = sort(@groups);
 7173:     return @groups;
 7174: }
 7175: 
 7176: sub packages_tab_default {
 7177:     my ($uri,$varname)=@_;
 7178:     my (undef,$part,$name)=split(/\./,$varname);
 7179: 
 7180:     my (@extension,@specifics,$do_default);
 7181:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7182: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7183: 	if ($pack_type eq 'default') {
 7184: 	    $do_default=1;
 7185: 	} elsif ($pack_type eq 'extension') {
 7186: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7187: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7188: 	    # only look at packages defaults for packages that this id is
 7189: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7190: 	}
 7191:     }
 7192:     # first look for a package that matches the requested part id
 7193:     foreach my $package (@specifics) {
 7194: 	my (undef,$pack_type,$pack_part)=@{$package};
 7195: 	next if ($pack_part ne $part);
 7196: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7197: 	    return $packagetab{"$pack_type&$name&default"};
 7198: 	}
 7199:     }
 7200:     # look for any possible matching non extension_ package
 7201:     foreach my $package (@specifics) {
 7202: 	my (undef,$pack_type,$pack_part)=@{$package};
 7203: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7204: 	    return $packagetab{"$pack_type&$name&default"};
 7205: 	}
 7206: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7207: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7208: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7209: 	}
 7210:     }
 7211:     # look for any posible extension_ match
 7212:     foreach my $package (@extension) {
 7213: 	my ($package,$pack_type)=@{$package};
 7214: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7215: 	    return $packagetab{"$pack_type&$name&default"};
 7216: 	}
 7217: 	if (defined($packagetab{$package."&$name&default"})) {
 7218: 	    return $packagetab{$package."&$name&default"};
 7219: 	}
 7220:     }
 7221:     # look for a global default setting
 7222:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7223: 	return $packagetab{"default&$name&default"};
 7224:     }
 7225:     return undef;
 7226: }
 7227: 
 7228: sub add_prefix_and_part {
 7229:     my ($prefix,$part)=@_;
 7230:     my $keyroot;
 7231:     if (defined($prefix) && $prefix !~ /^__/) {
 7232: 	# prefix that has a part already
 7233: 	$keyroot=$prefix;
 7234:     } elsif (defined($prefix)) {
 7235: 	# prefix that is missing a part
 7236: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7237:     } else {
 7238: 	# no prefix at all
 7239: 	if (defined($part)) { $keyroot='_'.$part; }
 7240:     }
 7241:     return $keyroot;
 7242: }
 7243: 
 7244: # ---------------------------------------------------------------- Get metadata
 7245: 
 7246: my %metaentry;
 7247: sub metadata {
 7248:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7249:     $uri=&declutter($uri);
 7250:     # if it is a non metadata possible uri return quickly
 7251:     if (($uri eq '') || 
 7252: 	(($uri =~ m|^/*adm/|) && 
 7253: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7254:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7255: 	return undef;
 7256:     }
 7257:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7258: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7259: 	return undef;
 7260:     }
 7261:     my $filename=$uri;
 7262:     $uri=~s/\.meta$//;
 7263: #
 7264: # Is the metadata already cached?
 7265: # Look at timestamp of caching
 7266: # Everything is cached by the main uri, libraries are never directly cached
 7267: #
 7268:     if (!defined($liburi)) {
 7269: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7270: 	if (defined($cached)) { return $result->{':'.$what}; }
 7271:     }
 7272:     {
 7273: #
 7274: # Is this a recursive call for a library?
 7275: #
 7276: #	if (! exists($metacache{$uri})) {
 7277: #	    $metacache{$uri}={};
 7278: #	}
 7279: 	my $cachetime = 60*60;
 7280:         if ($liburi) {
 7281: 	    $liburi=&declutter($liburi);
 7282:             $filename=$liburi;
 7283:         } else {
 7284: 	    &devalidate_cache_new('meta',$uri);
 7285: 	    undef(%metaentry);
 7286: 	}
 7287:         my %metathesekeys=();
 7288:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7289: 	my $metastring;
 7290: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7291: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7292: 	    $metastring = 
 7293: 		&Apache::lonnet::ssi_body($which,
 7294: 					  ('grade_target' => 'meta'));
 7295: 	    $cachetime = 1; # only want this cached in the child not long term
 7296: 	} elsif ($uri !~ m -^(editupload)/-) {
 7297: 	    my $file=&filelocation('',&clutter($filename));
 7298: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7299: 	    $metastring=&getfile($file);
 7300: 	}
 7301:         my $parser=HTML::LCParser->new(\$metastring);
 7302:         my $token;
 7303:         undef %metathesekeys;
 7304:         while ($token=$parser->get_token) {
 7305: 	    if ($token->[0] eq 'S') {
 7306: 		if (defined($token->[2]->{'package'})) {
 7307: #
 7308: # This is a package - get package info
 7309: #
 7310: 		    my $package=$token->[2]->{'package'};
 7311: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7312: 		    if (defined($token->[2]->{'id'})) { 
 7313: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7314: 		    }
 7315: 		    if ($metaentry{':packages'}) {
 7316: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7317: 		    } else {
 7318: 			$metaentry{':packages'}=$package.$keyroot;
 7319: 		    }
 7320: 		    foreach my $pack_entry (keys(%packagetab)) {
 7321: 			my $part=$keyroot;
 7322: 			$part=~s/^\_//;
 7323: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7324: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7325: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7326: 			    # ignore package.tab specified default values
 7327:                             # here &package_tab_default() will fetch those
 7328: 			    if ($subp eq 'default') { next; }
 7329: 			    my $value=$packagetab{$pack_entry};
 7330: 			    my $unikey;
 7331: 			    if ($pack =~ /_0$/) {
 7332: 				$unikey='parameter_0_'.$name;
 7333: 				$part=0;
 7334: 			    } else {
 7335: 				$unikey='parameter'.$keyroot.'_'.$name;
 7336: 			    }
 7337: 			    if ($subp eq 'display') {
 7338: 				$value.=' [Part: '.$part.']';
 7339: 			    }
 7340: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7341: 			    $metathesekeys{$unikey}=1;
 7342: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7343: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7344: 			    }
 7345: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7346: 				$metaentry{':'.$unikey}=
 7347: 				    $metaentry{':'.$unikey.'.default'};
 7348: 			    }
 7349: 			}
 7350: 		    }
 7351: 		} else {
 7352: #
 7353: # This is not a package - some other kind of start tag
 7354: #
 7355: 		    my $entry=$token->[1];
 7356: 		    my $unikey;
 7357: 		    if ($entry eq 'import') {
 7358: 			$unikey='';
 7359: 		    } else {
 7360: 			$unikey=$entry;
 7361: 		    }
 7362: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7363: 
 7364: 		    if (defined($token->[2]->{'id'})) { 
 7365: 			$unikey.='_'.$token->[2]->{'id'}; 
 7366: 		    }
 7367: 
 7368: 		    if ($entry eq 'import') {
 7369: #
 7370: # Importing a library here
 7371: #
 7372: 			if ($depthcount<20) {
 7373: 			    my $location=$parser->get_text('/import');
 7374: 			    my $dir=$filename;
 7375: 			    $dir=~s|[^/]*$||;
 7376: 			    $location=&filelocation($dir,$location);
 7377: 			    my $metadata = 
 7378: 				&metadata($uri,'keys', $location,$unikey,
 7379: 					  $depthcount+1);
 7380: 			    foreach my $meta (split(',',$metadata)) {
 7381: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7382: 				$metathesekeys{$meta}=1;
 7383: 			    }
 7384: 			}
 7385: 		    } else { 
 7386: 			
 7387: 			if (defined($token->[2]->{'name'})) { 
 7388: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7389: 			}
 7390: 			$metathesekeys{$unikey}=1;
 7391: 			foreach my $param (@{$token->[3]}) {
 7392: 			    $metaentry{':'.$unikey.'.'.$param} =
 7393: 				$token->[2]->{$param};
 7394: 			}
 7395: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7396: 			my $default=$metaentry{':'.$unikey.'.default'};
 7397: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7398: 		 # only ws inside the tag, and not in default, so use default
 7399: 		 # as value
 7400: 			    $metaentry{':'.$unikey}=$default;
 7401: 			} elsif ( $internaltext =~ /\S/ ) {
 7402: 		  # something interesting inside the tag
 7403: 			    $metaentry{':'.$unikey}=$internaltext;
 7404: 			} else {
 7405: 		  # no interesting values, don't set a default
 7406: 			}
 7407: # end of not-a-package not-a-library import
 7408: 		    }
 7409: # end of not-a-package start tag
 7410: 		}
 7411: # the next is the end of "start tag"
 7412: 	    }
 7413: 	}
 7414: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7415: 	$extension = lc($extension);
 7416: 	if ($extension eq 'htm') { $extension='html'; }
 7417: 
 7418: 	foreach my $key (keys(%packagetab)) {
 7419: 	    #no specific packages #how's our extension
 7420: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7421: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7422: 					 \%metathesekeys);
 7423: 	}
 7424: 
 7425: 	if (!exists($metaentry{':packages'})
 7426: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7427: 	    foreach my $key (keys(%packagetab)) {
 7428: 		#no specific packages well let's get default then
 7429: 		if ($key!~/^default&/) { next; }
 7430: 		&metadata_create_package_def($uri,$key,'default',
 7431: 					     \%metathesekeys);
 7432: 	    }
 7433: 	}
 7434: # are there custom rights to evaluate
 7435: 	if ($metaentry{':copyright'} eq 'custom') {
 7436: 
 7437:     #
 7438:     # Importing a rights file here
 7439:     #
 7440: 	    unless ($depthcount) {
 7441: 		my $location=$metaentry{':customdistributionfile'};
 7442: 		my $dir=$filename;
 7443: 		$dir=~s|[^/]*$||;
 7444: 		$location=&filelocation($dir,$location);
 7445: 		my $rights_metadata =
 7446: 		    &metadata($uri,'keys',$location,'_rights',
 7447: 			      $depthcount+1);
 7448: 		foreach my $rights (split(',',$rights_metadata)) {
 7449: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7450: 		    $metathesekeys{$rights}=1;
 7451: 		}
 7452: 	    }
 7453: 	}
 7454: 	# uniqifiy package listing
 7455: 	my %seen;
 7456: 	my @uniq_packages =
 7457: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7458: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7459: 
 7460: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7461: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7462: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7463: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7464: # this is the end of "was not already recently cached
 7465:     }
 7466:     return $metaentry{':'.$what};
 7467: }
 7468: 
 7469: sub metadata_create_package_def {
 7470:     my ($uri,$key,$package,$metathesekeys)=@_;
 7471:     my ($pack,$name,$subp)=split(/\&/,$key);
 7472:     if ($subp eq 'default') { next; }
 7473:     
 7474:     if (defined($metaentry{':packages'})) {
 7475: 	$metaentry{':packages'}.=','.$package;
 7476:     } else {
 7477: 	$metaentry{':packages'}=$package;
 7478:     }
 7479:     my $value=$packagetab{$key};
 7480:     my $unikey;
 7481:     $unikey='parameter_0_'.$name;
 7482:     $metaentry{':'.$unikey.'.part'}=0;
 7483:     $$metathesekeys{$unikey}=1;
 7484:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7485: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7486:     }
 7487:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7488: 	$metaentry{':'.$unikey}=
 7489: 	    $metaentry{':'.$unikey.'.default'};
 7490:     }
 7491: }
 7492: 
 7493: sub metadata_generate_part0 {
 7494:     my ($metadata,$metacache,$uri) = @_;
 7495:     my %allnames;
 7496:     foreach my $metakey (keys(%$metadata)) {
 7497: 	if ($metakey=~/^parameter\_(.*)/) {
 7498: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7499: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7500: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7501: 	    $allnames{$name}=$part;
 7502: 	  }
 7503: 	}
 7504:     }
 7505:     foreach my $name (keys(%allnames)) {
 7506:       $$metadata{"parameter_0_$name"}=1;
 7507:       my $key=":parameter_0_$name";
 7508:       $$metacache{"$key.part"}='0';
 7509:       $$metacache{"$key.name"}=$name;
 7510:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7511: 					   $allnames{$name}.'_'.$name.
 7512: 					   '.type'};
 7513:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7514: 			     '.display'};
 7515:       my $expr='[Part: '.$allnames{$name}.']';
 7516:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7517:       $$metacache{"$key.display"}=$olddis;
 7518:     }
 7519: }
 7520: 
 7521: # ------------------------------------------------------ Devalidate title cache
 7522: 
 7523: sub devalidate_title_cache {
 7524:     my ($url)=@_;
 7525:     if (!$env{'request.course.id'}) { return; }
 7526:     my $symb=&symbread($url);
 7527:     if (!$symb) { return; }
 7528:     my $key=$env{'request.course.id'}."\0".$symb;
 7529:     &devalidate_cache_new('title',$key);
 7530: }
 7531: 
 7532: # ------------------------------------------------- Get the title of a resource
 7533: 
 7534: sub gettitle {
 7535:     my $urlsymb=shift;
 7536:     my $symb=&symbread($urlsymb);
 7537:     if ($symb) {
 7538: 	my $key=$env{'request.course.id'}."\0".$symb;
 7539: 	my ($result,$cached)=&is_cached_new('title',$key);
 7540: 	if (defined($cached)) { 
 7541: 	    return $result;
 7542: 	}
 7543: 	my ($map,$resid,$url)=&decode_symb($symb);
 7544: 	my $title='';
 7545: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7546: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7547: 	} else {
 7548: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7549: 		    &GDBM_READER(),0640)) {
 7550: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7551: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7552: 		untie(%bighash);
 7553: 	    }
 7554: 	}
 7555: 	$title=~s/\&colon\;/\:/gs;
 7556: 	if ($title) {
 7557: 	    return &do_cache_new('title',$key,$title,600);
 7558: 	}
 7559: 	$urlsymb=$url;
 7560:     }
 7561:     my $title=&metadata($urlsymb,'title');
 7562:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7563:     return $title;
 7564: }
 7565: 
 7566: sub get_slot {
 7567:     my ($which,$cnum,$cdom)=@_;
 7568:     if (!$cnum || !$cdom) {
 7569: 	(undef,my $courseid)=&whichuser();
 7570: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7571: 	$cnum=$env{'course.'.$courseid.'.num'};
 7572:     }
 7573:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7574:     my %slotinfo;
 7575:     if (exists($remembered{$key})) {
 7576: 	$slotinfo{$which} = $remembered{$key};
 7577:     } else {
 7578: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7579: 	&Apache::lonhomework::showhash(%slotinfo);
 7580: 	my ($tmp)=keys(%slotinfo);
 7581: 	if ($tmp=~/^error:/) { return (); }
 7582: 	$remembered{$key} = $slotinfo{$which};
 7583:     }
 7584:     if (ref($slotinfo{$which}) eq 'HASH') {
 7585: 	return %{$slotinfo{$which}};
 7586:     }
 7587:     return $slotinfo{$which};
 7588: }
 7589: # ------------------------------------------------- Update symbolic store links
 7590: 
 7591: sub symblist {
 7592:     my ($mapname,%newhash)=@_;
 7593:     $mapname=&deversion(&declutter($mapname));
 7594:     my %hash;
 7595:     if (($env{'request.course.fn'}) && (%newhash)) {
 7596:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7597:                       &GDBM_WRCREAT(),0640)) {
 7598: 	    foreach my $url (keys %newhash) {
 7599: 		next if ($url eq 'last_known'
 7600: 			 && $env{'form.no_update_last_known'});
 7601: 		$hash{declutter($url)}=&encode_symb($mapname,
 7602: 						    $newhash{$url}->[1],
 7603: 						    $newhash{$url}->[0]);
 7604:             }
 7605:             if (untie(%hash)) {
 7606: 		return 'ok';
 7607:             }
 7608:         }
 7609:     }
 7610:     return 'error';
 7611: }
 7612: 
 7613: # --------------------------------------------------------------- Verify a symb
 7614: 
 7615: sub symbverify {
 7616:     my ($symb,$thisurl)=@_;
 7617:     my $thisfn=$thisurl;
 7618:     $thisfn=&declutter($thisfn);
 7619: # direct jump to resource in page or to a sequence - will construct own symbs
 7620:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7621: # check URL part
 7622:     my ($map,$resid,$url)=&decode_symb($symb);
 7623: 
 7624:     unless ($url eq $thisfn) { return 0; }
 7625: 
 7626:     $symb=&symbclean($symb);
 7627:     $thisurl=&deversion($thisurl);
 7628:     $thisfn=&deversion($thisfn);
 7629: 
 7630:     my %bighash;
 7631:     my $okay=0;
 7632: 
 7633:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7634:                             &GDBM_READER(),0640)) {
 7635:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7636:         unless ($ids) { 
 7637:            $ids=$bighash{'ids_/'.$thisurl};
 7638:         }
 7639:         if ($ids) {
 7640: # ------------------------------------------------------------------- Has ID(s)
 7641: 	    foreach my $id (split(/\,/,$ids)) {
 7642: 	       my ($mapid,$resid)=split(/\./,$id);
 7643:                if (
 7644:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7645:    eq $symb) { 
 7646: 		   if (($env{'request.role.adv'}) ||
 7647: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7648: 		       $okay=1; 
 7649: 		   }
 7650: 	       }
 7651: 	   }
 7652:         }
 7653: 	untie(%bighash);
 7654:     }
 7655:     return $okay;
 7656: }
 7657: 
 7658: # --------------------------------------------------------------- Clean-up symb
 7659: 
 7660: sub symbclean {
 7661:     my $symb=shift;
 7662:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7663: # remove version from map
 7664:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7665: 
 7666: # remove version from URL
 7667:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7668: 
 7669: # remove wrapper
 7670: 
 7671:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7672:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7673:     return $symb;
 7674: }
 7675: 
 7676: # ---------------------------------------------- Split symb to find map and url
 7677: 
 7678: sub encode_symb {
 7679:     my ($map,$resid,$url)=@_;
 7680:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7681: }
 7682: 
 7683: sub decode_symb {
 7684:     my $symb=shift;
 7685:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7686:     my ($map,$resid,$url)=split(/___/,$symb);
 7687:     return (&fixversion($map),$resid,&fixversion($url));
 7688: }
 7689: 
 7690: sub fixversion {
 7691:     my $fn=shift;
 7692:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7693:     my %bighash;
 7694:     my $uri=&clutter($fn);
 7695:     my $key=$env{'request.course.id'}.'_'.$uri;
 7696: # is this cached?
 7697:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7698:     if (defined($cached)) { return $result; }
 7699: # unfortunately not cached, or expired
 7700:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7701: 	    &GDBM_READER(),0640)) {
 7702:  	if ($bighash{'version_'.$uri}) {
 7703:  	    my $version=$bighash{'version_'.$uri};
 7704:  	    unless (($version eq 'mostrecent') || 
 7705: 		    ($version==&getversion($uri))) {
 7706:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7707:  	    }
 7708:  	}
 7709:  	untie %bighash;
 7710:     }
 7711:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7712: }
 7713: 
 7714: sub deversion {
 7715:     my $url=shift;
 7716:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7717:     return $url;
 7718: }
 7719: 
 7720: # ------------------------------------------------------ Return symb list entry
 7721: 
 7722: sub symbread {
 7723:     my ($thisfn,$donotrecurse)=@_;
 7724:     my $cache_str='request.symbread.cached.'.$thisfn;
 7725:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7726: # no filename provided? try from environment
 7727:     unless ($thisfn) {
 7728:         if ($env{'request.symb'}) {
 7729: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7730: 	}
 7731: 	$thisfn=$env{'request.filename'};
 7732:     }
 7733:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7734: # is that filename actually a symb? Verify, clean, and return
 7735:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7736: 	if (&symbverify($thisfn,$1)) {
 7737: 	    return $env{$cache_str}=&symbclean($thisfn);
 7738: 	}
 7739:     }
 7740:     $thisfn=declutter($thisfn);
 7741:     my %hash;
 7742:     my %bighash;
 7743:     my $syval='';
 7744:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7745:         my $targetfn = $thisfn;
 7746:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7747:             $targetfn = 'adm/wrapper/'.$thisfn;
 7748:         }
 7749: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7750: 	    $targetfn=$1;
 7751: 	}
 7752:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7753:                       &GDBM_READER(),0640)) {
 7754: 	    $syval=$hash{$targetfn};
 7755:             untie(%hash);
 7756:         }
 7757: # ---------------------------------------------------------- There was an entry
 7758:         if ($syval) {
 7759: 	    #unless ($syval=~/\_\d+$/) {
 7760: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7761: 		    #&appenv({'request.ambiguous' => $thisfn});
 7762: 		    #return $env{$cache_str}='';
 7763: 		#}    
 7764: 		#$syval.=$1;
 7765: 	    #}
 7766:         } else {
 7767: # ------------------------------------------------------- Was not in symb table
 7768:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7769:                             &GDBM_READER(),0640)) {
 7770: # ---------------------------------------------- Get ID(s) for current resource
 7771:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7772:               unless ($ids) { 
 7773:                  $ids=$bighash{'ids_/'.$thisfn};
 7774:               }
 7775:               unless ($ids) {
 7776: # alias?
 7777: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7778:               }
 7779:               if ($ids) {
 7780: # ------------------------------------------------------------------- Has ID(s)
 7781:                  my @possibilities=split(/\,/,$ids);
 7782:                  if ($#possibilities==0) {
 7783: # ----------------------------------------------- There is only one possibility
 7784: 		     my ($mapid,$resid)=split(/\./,$ids);
 7785: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7786: 						    $resid,$thisfn);
 7787:                  } elsif (!$donotrecurse) {
 7788: # ------------------------------------------ There is more than one possibility
 7789:                      my $realpossible=0;
 7790:                      foreach my $id (@possibilities) {
 7791: 			 my $file=$bighash{'src_'.$id};
 7792:                          if (&allowed('bre',$file)) {
 7793:          		    my ($mapid,$resid)=split(/\./,$id);
 7794:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7795: 				$realpossible++;
 7796:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7797: 						    $resid,$thisfn);
 7798:                             }
 7799: 			 }
 7800:                      }
 7801: 		     if ($realpossible!=1) { $syval=''; }
 7802:                  } else {
 7803:                      $syval='';
 7804:                  }
 7805: 	      }
 7806:               untie(%bighash)
 7807:            }
 7808:         }
 7809:         if ($syval) {
 7810: 	    return $env{$cache_str}=$syval;
 7811:         }
 7812:     }
 7813:     &appenv({'request.ambiguous' => $thisfn});
 7814:     return $env{$cache_str}='';
 7815: }
 7816: 
 7817: # ---------------------------------------------------------- Return random seed
 7818: 
 7819: sub numval {
 7820:     my $txt=shift;
 7821:     $txt=~tr/A-J/0-9/;
 7822:     $txt=~tr/a-j/0-9/;
 7823:     $txt=~tr/K-T/0-9/;
 7824:     $txt=~tr/k-t/0-9/;
 7825:     $txt=~tr/U-Z/0-5/;
 7826:     $txt=~tr/u-z/0-5/;
 7827:     $txt=~s/\D//g;
 7828:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7829:     return int($txt);
 7830: }
 7831: 
 7832: sub numval2 {
 7833:     my $txt=shift;
 7834:     $txt=~tr/A-J/0-9/;
 7835:     $txt=~tr/a-j/0-9/;
 7836:     $txt=~tr/K-T/0-9/;
 7837:     $txt=~tr/k-t/0-9/;
 7838:     $txt=~tr/U-Z/0-5/;
 7839:     $txt=~tr/u-z/0-5/;
 7840:     $txt=~s/\D//g;
 7841:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7842:     my $total;
 7843:     foreach my $val (@txts) { $total+=$val; }
 7844:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7845:     return int($total);
 7846: }
 7847: 
 7848: sub numval3 {
 7849:     use integer;
 7850:     my $txt=shift;
 7851:     $txt=~tr/A-J/0-9/;
 7852:     $txt=~tr/a-j/0-9/;
 7853:     $txt=~tr/K-T/0-9/;
 7854:     $txt=~tr/k-t/0-9/;
 7855:     $txt=~tr/U-Z/0-5/;
 7856:     $txt=~tr/u-z/0-5/;
 7857:     $txt=~s/\D//g;
 7858:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7859:     my $total;
 7860:     foreach my $val (@txts) { $total+=$val; }
 7861:     if ($_64bit) { $total=(($total<<32)>>32); }
 7862:     return $total;
 7863: }
 7864: 
 7865: sub digest {
 7866:     my ($data)=@_;
 7867:     my $digest=&Digest::MD5::md5($data);
 7868:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7869:     my ($e,$f);
 7870:     {
 7871:         use integer;
 7872:         $e=($a+$b);
 7873:         $f=($c+$d);
 7874:         if ($_64bit) {
 7875:             $e=(($e<<32)>>32);
 7876:             $f=(($f<<32)>>32);
 7877:         }
 7878:     }
 7879:     if (wantarray) {
 7880: 	return ($e,$f);
 7881:     } else {
 7882: 	my $g;
 7883: 	{
 7884: 	    use integer;
 7885: 	    $g=($e+$f);
 7886: 	    if ($_64bit) {
 7887: 		$g=(($g<<32)>>32);
 7888: 	    }
 7889: 	}
 7890: 	return $g;
 7891:     }
 7892: }
 7893: 
 7894: sub latest_rnd_algorithm_id {
 7895:     return '64bit5';
 7896: }
 7897: 
 7898: sub get_rand_alg {
 7899:     my ($courseid)=@_;
 7900:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7901:     if ($courseid) {
 7902: 	return $env{"course.$courseid.rndseed"};
 7903:     }
 7904:     return &latest_rnd_algorithm_id();
 7905: }
 7906: 
 7907: sub validCODE {
 7908:     my ($CODE)=@_;
 7909:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7910:     return 0;
 7911: }
 7912: 
 7913: sub getCODE {
 7914:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7915:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7916: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7917: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7918: 	return $Apache::lonhomework::history{'resource.CODE'};
 7919:     }
 7920:     return undef;
 7921: }
 7922: 
 7923: sub rndseed {
 7924:     my ($symb,$courseid,$domain,$username)=@_;
 7925:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7926:     if (!defined($symb)) {
 7927: 	unless ($symb=$wsymb) { return time; }
 7928:     }
 7929:     if (!$courseid) { $courseid=$wcourseid; }
 7930:     if (!$domain) { $domain=$wdomain; }
 7931:     if (!$username) { $username=$wusername }
 7932:     my $which=&get_rand_alg();
 7933: 
 7934:     if (defined(&getCODE())) {
 7935: 	if ($which eq '64bit5') {
 7936: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7937: 	} elsif ($which eq '64bit4') {
 7938: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7939: 	} else {
 7940: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7941: 	}
 7942:     } elsif ($which eq '64bit5') {
 7943: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7944:     } elsif ($which eq '64bit4') {
 7945: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7946:     } elsif ($which eq '64bit3') {
 7947: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7948:     } elsif ($which eq '64bit2') {
 7949: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7950:     } elsif ($which eq '64bit') {
 7951: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7952:     }
 7953:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7954: }
 7955: 
 7956: sub rndseed_32bit {
 7957:     my ($symb,$courseid,$domain,$username)=@_;
 7958:     {
 7959: 	use integer;
 7960: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7961: 	my $symbseed=numval($symb) << 22;
 7962: 	my $namechck=unpack("%32C*",$username) << 17;
 7963: 	my $nameseed=numval($username) << 12;
 7964: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7965: 	my $courseseed=unpack("%32C*",$courseid);
 7966: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7967: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7968: 	#&logthis("rndseed :$num:$symb");
 7969: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7970: 	return $num;
 7971:     }
 7972: }
 7973: 
 7974: sub rndseed_64bit {
 7975:     my ($symb,$courseid,$domain,$username)=@_;
 7976:     {
 7977: 	use integer;
 7978: 	my $symbchck=unpack("%32S*",$symb) << 21;
 7979: 	my $symbseed=numval($symb) << 10;
 7980: 	my $namechck=unpack("%32S*",$username);
 7981: 	
 7982: 	my $nameseed=numval($username) << 21;
 7983: 	my $domainseed=unpack("%32S*",$domain) << 10;
 7984: 	my $courseseed=unpack("%32S*",$courseid);
 7985: 	
 7986: 	my $num1=$symbchck+$symbseed+$namechck;
 7987: 	my $num2=$nameseed+$domainseed+$courseseed;
 7988: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7989: 	#&logthis("rndseed :$num:$symb");
 7990: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 7991: 	return "$num1,$num2";
 7992:     }
 7993: }
 7994: 
 7995: sub rndseed_64bit2 {
 7996:     my ($symb,$courseid,$domain,$username)=@_;
 7997:     {
 7998: 	use integer;
 7999: 	# strings need to be an even # of cahracters long, it it is odd the
 8000:         # last characters gets thrown away
 8001: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8002: 	my $symbseed=numval($symb) << 10;
 8003: 	my $namechck=unpack("%32S*",$username.' ');
 8004: 	
 8005: 	my $nameseed=numval($username) << 21;
 8006: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8007: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8008: 	
 8009: 	my $num1=$symbchck+$symbseed+$namechck;
 8010: 	my $num2=$nameseed+$domainseed+$courseseed;
 8011: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8012: 	#&logthis("rndseed :$num:$symb");
 8013: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8014: 	return "$num1,$num2";
 8015:     }
 8016: }
 8017: 
 8018: sub rndseed_64bit3 {
 8019:     my ($symb,$courseid,$domain,$username)=@_;
 8020:     {
 8021: 	use integer;
 8022: 	# strings need to be an even # of cahracters long, it it is odd the
 8023:         # last characters gets thrown away
 8024: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8025: 	my $symbseed=numval2($symb) << 10;
 8026: 	my $namechck=unpack("%32S*",$username.' ');
 8027: 	
 8028: 	my $nameseed=numval2($username) << 21;
 8029: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8030: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8031: 	
 8032: 	my $num1=$symbchck+$symbseed+$namechck;
 8033: 	my $num2=$nameseed+$domainseed+$courseseed;
 8034: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8035: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8036: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8037: 	
 8038: 	return "$num1:$num2";
 8039:     }
 8040: }
 8041: 
 8042: sub rndseed_64bit4 {
 8043:     my ($symb,$courseid,$domain,$username)=@_;
 8044:     {
 8045: 	use integer;
 8046: 	# strings need to be an even # of cahracters long, it it is odd the
 8047:         # last characters gets thrown away
 8048: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8049: 	my $symbseed=numval3($symb) << 10;
 8050: 	my $namechck=unpack("%32S*",$username.' ');
 8051: 	
 8052: 	my $nameseed=numval3($username) << 21;
 8053: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8054: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8055: 	
 8056: 	my $num1=$symbchck+$symbseed+$namechck;
 8057: 	my $num2=$nameseed+$domainseed+$courseseed;
 8058: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8059: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8060: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8061: 	
 8062: 	return "$num1:$num2";
 8063:     }
 8064: }
 8065: 
 8066: sub rndseed_64bit5 {
 8067:     my ($symb,$courseid,$domain,$username)=@_;
 8068:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8069:     return "$num1:$num2";
 8070: }
 8071: 
 8072: sub rndseed_CODE_64bit {
 8073:     my ($symb,$courseid,$domain,$username)=@_;
 8074:     {
 8075: 	use integer;
 8076: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8077: 	my $symbseed=numval2($symb);
 8078: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8079: 	my $CODEseed=numval(&getCODE());
 8080: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8081: 	my $num1=$symbseed+$CODEchck;
 8082: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8083: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8084: 	#&logthis("rndseed :$num1:$num2:$symb");
 8085: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8086: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8087: 	return "$num1:$num2";
 8088:     }
 8089: }
 8090: 
 8091: sub rndseed_CODE_64bit4 {
 8092:     my ($symb,$courseid,$domain,$username)=@_;
 8093:     {
 8094: 	use integer;
 8095: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8096: 	my $symbseed=numval3($symb);
 8097: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8098: 	my $CODEseed=numval3(&getCODE());
 8099: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8100: 	my $num1=$symbseed+$CODEchck;
 8101: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8102: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8103: 	#&logthis("rndseed :$num1:$num2:$symb");
 8104: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8105: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8106: 	return "$num1:$num2";
 8107:     }
 8108: }
 8109: 
 8110: sub rndseed_CODE_64bit5 {
 8111:     my ($symb,$courseid,$domain,$username)=@_;
 8112:     my $code = &getCODE();
 8113:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8114:     return "$num1:$num2";
 8115: }
 8116: 
 8117: sub setup_random_from_rndseed {
 8118:     my ($rndseed)=@_;
 8119:     if ($rndseed =~/([,:])/) {
 8120: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8121: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8122:     } else {
 8123: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8124:     }
 8125: }
 8126: 
 8127: sub latest_receipt_algorithm_id {
 8128:     return 'receipt3';
 8129: }
 8130: 
 8131: sub recunique {
 8132:     my $fucourseid=shift;
 8133:     my $unique;
 8134:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8135: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8136: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8137:     } else {
 8138: 	$unique=$perlvar{'lonReceipt'};
 8139:     }
 8140:     return unpack("%32C*",$unique);
 8141: }
 8142: 
 8143: sub recprefix {
 8144:     my $fucourseid=shift;
 8145:     my $prefix;
 8146:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8147: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8148: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8149:     } else {
 8150: 	$prefix=$perlvar{'lonHostID'};
 8151:     }
 8152:     return unpack("%32C*",$prefix);
 8153: }
 8154: 
 8155: sub ireceipt {
 8156:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8157: 
 8158:     my $return =&recprefix($fucourseid).'-';
 8159: 
 8160:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8161: 	$env{'request.state'} eq 'construct') {
 8162: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8163: 	return $return;
 8164:     }
 8165: 
 8166:     my $cuname=unpack("%32C*",$funame);
 8167:     my $cudom=unpack("%32C*",$fudom);
 8168:     my $cucourseid=unpack("%32C*",$fucourseid);
 8169:     my $cusymb=unpack("%32C*",$fusymb);
 8170:     my $cunique=&recunique($fucourseid);
 8171:     my $cpart=unpack("%32S*",$part);
 8172:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8173: 
 8174: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8175: 			       
 8176: 	$return.= ($cunique%$cuname+
 8177: 		   $cunique%$cudom+
 8178: 		   $cusymb%$cuname+
 8179: 		   $cusymb%$cudom+
 8180: 		   $cucourseid%$cuname+
 8181: 		   $cucourseid%$cudom+
 8182: 		   $cpart%$cuname+
 8183: 		   $cpart%$cudom);
 8184:     } else {
 8185: 	$return.= ($cunique%$cuname+
 8186: 		   $cunique%$cudom+
 8187: 		   $cusymb%$cuname+
 8188: 		   $cusymb%$cudom+
 8189: 		   $cucourseid%$cuname+
 8190: 		   $cucourseid%$cudom);
 8191:     }
 8192:     return $return;
 8193: }
 8194: 
 8195: sub receipt {
 8196:     my ($part)=@_;
 8197:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8198:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8199: }
 8200: 
 8201: sub whichuser {
 8202:     my ($passedsymb)=@_;
 8203:     my ($symb,$courseid,$domain,$name,$publicuser);
 8204:     if (defined($env{'form.grade_symb'})) {
 8205: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8206: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8207: 	if (!$allowed &&
 8208: 	    exists($env{'request.course.sec'}) &&
 8209: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8210: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8211: 			      '/'.$env{'request.course.sec'});
 8212: 	}
 8213: 	if ($allowed) {
 8214: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8215: 	    $courseid=$tmp_courseid;
 8216: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8217: 	    ($name)=&get_env_multiple('form.grade_username');
 8218: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8219: 	}
 8220:     }
 8221:     if (!$passedsymb) {
 8222: 	$symb=&symbread();
 8223:     } else {
 8224: 	$symb=$passedsymb;
 8225:     }
 8226:     $courseid=$env{'request.course.id'};
 8227:     $domain=$env{'user.domain'};
 8228:     $name=$env{'user.name'};
 8229:     if ($name eq 'public' && $domain eq 'public') {
 8230: 	if (!defined($env{'form.username'})) {
 8231: 	    $env{'form.username'}.=time.rand(10000000);
 8232: 	}
 8233: 	$name.=$env{'form.username'};
 8234:     }
 8235:     return ($symb,$courseid,$domain,$name,$publicuser);
 8236: 
 8237: }
 8238: 
 8239: # ------------------------------------------------------------ Serves up a file
 8240: # returns either the contents of the file or 
 8241: # -1 if the file doesn't exist
 8242: #
 8243: # if the target is a file that was uploaded via DOCS, 
 8244: # a check will be made to see if a current copy exists on the local server,
 8245: # if it does this will be served, otherwise a copy will be retrieved from
 8246: # the home server for the course and stored in /home/httpd/html/userfiles on
 8247: # the local server.   
 8248: 
 8249: sub getfile {
 8250:     my ($file) = @_;
 8251:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8252:     &repcopy($file);
 8253:     return &readfile($file);
 8254: }
 8255: 
 8256: sub repcopy_userfile {
 8257:     my ($file)=@_;
 8258:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8259:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8260:     my ($cdom,$cnum,$filename) = 
 8261: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8262:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8263:     if (-e "$file") {
 8264: # we already have a local copy, check it out
 8265: 	my @fileinfo = stat($file);
 8266: 	my $rtncode;
 8267: 	my $info;
 8268: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8269: 	if ($lwpresp ne 'ok') {
 8270: # there is no such file anymore, even though we had a local copy
 8271: 	    if ($rtncode eq '404') {
 8272: 		unlink($file);
 8273: 	    }
 8274: 	    return -1;
 8275: 	}
 8276: 	if ($info < $fileinfo[9]) {
 8277: # nice, the file we have is up-to-date, just say okay
 8278: 	    return 'ok';
 8279: 	} else {
 8280: # the file is outdated, get rid of it
 8281: 	    unlink($file);
 8282: 	}
 8283:     }
 8284: # one way or the other, at this point, we don't have the file
 8285: # construct the correct path for the file
 8286:     my @parts = ($cdom,$cnum); 
 8287:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8288: 	push @parts, split(/\//,$1);
 8289:     }
 8290:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8291:     foreach my $part (@parts) {
 8292: 	$path .= '/'.$part;
 8293: 	if (!-e $path) {
 8294: 	    mkdir($path,0770);
 8295: 	}
 8296:     }
 8297: # now the path exists for sure
 8298: # get a user agent
 8299:     my $ua=new LWP::UserAgent;
 8300:     my $transferfile=$file.'.in.transfer';
 8301: # FIXME: this should flock
 8302:     if (-e $transferfile) { return 'ok'; }
 8303:     my $request;
 8304:     $uri=~s/^\///;
 8305:     my $homeserver = &homeserver($cnum,$cdom);
 8306:     my $protocol = $protocol{$homeserver};
 8307:     $protocol = 'http' if ($protocol ne 'https');
 8308:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8309:     my $response=$ua->request($request,$transferfile);
 8310: # did it work?
 8311:     if ($response->is_error()) {
 8312: 	unlink($transferfile);
 8313: 	&logthis("Userfile repcopy failed for $uri");
 8314: 	return -1;
 8315:     }
 8316: # worked, rename the transfer file
 8317:     rename($transferfile,$file);
 8318:     return 'ok';
 8319: }
 8320: 
 8321: sub tokenwrapper {
 8322:     my $uri=shift;
 8323:     $uri=~s|^https?\://([^/]+)||;
 8324:     $uri=~s|^/||;
 8325:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8326:     my $token=$1;
 8327:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8328:     if ($udom && $uname && $file) {
 8329: 	$file=~s|(\?\.*)*$||;
 8330:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8331:         my $homeserver = &homeserver($uname,$udom);
 8332:         my $protocol = $protocol{$homeserver};
 8333:         $protocol = 'http' if ($protocol ne 'https');
 8334:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8335:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8336:                                '&tokenissued='.$perlvar{'lonHostID'};
 8337:     } else {
 8338:         return '/adm/notfound.html';
 8339:     }
 8340: }
 8341: 
 8342: # call with reqtype HEAD: get last modification time
 8343: # call with reqtype GET: get the file contents
 8344: # Do not call this with reqtype GET for large files! It loads everything into memory
 8345: #
 8346: sub getuploaded {
 8347:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8348:     $uri=~s/^\///;
 8349:     my $homeserver = &homeserver($cnum,$cdom);
 8350:     my $protocol = $protocol{$homeserver};
 8351:     $protocol = 'http' if ($protocol ne 'https');
 8352:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8353:     my $ua=new LWP::UserAgent;
 8354:     my $request=new HTTP::Request($reqtype,$uri);
 8355:     my $response=$ua->request($request);
 8356:     $$rtncode = $response->code;
 8357:     if (! $response->is_success()) {
 8358: 	return 'failed';
 8359:     }      
 8360:     if ($reqtype eq 'HEAD') {
 8361: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8362:     } elsif ($reqtype eq 'GET') {
 8363: 	$$info = $response->content;
 8364:     }
 8365:     return 'ok';
 8366: }
 8367: 
 8368: sub readfile {
 8369:     my $file = shift;
 8370:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8371:     my $fh;
 8372:     open($fh,"<$file");
 8373:     my $a='';
 8374:     while (my $line = <$fh>) { $a .= $line; }
 8375:     return $a;
 8376: }
 8377: 
 8378: sub filelocation {
 8379:     my ($dir,$file) = @_;
 8380:     my $location;
 8381:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8382: 
 8383:     if ($file =~ m-^/adm/-) {
 8384: 	$file=~s-^/adm/wrapper/-/-;
 8385: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8386:     }
 8387: 
 8388:     if ($file=~m:^/~:) { # is a contruction space reference
 8389:         $location = $file;
 8390:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8391:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8392: 	# is a correct contruction space reference
 8393:         $location = $file;
 8394:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8395:         $location = $file;
 8396:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8397:         my ($udom,$uname,$filename)=
 8398:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8399:         my $home=&homeserver($uname,$udom);
 8400:         my $is_me=0;
 8401:         my @ids=&current_machine_ids();
 8402:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8403:         if ($is_me) {
 8404:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8405:         } else {
 8406:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8407:   	      $udom.'/'.$uname.'/'.$filename;
 8408:         }
 8409:     } elsif ($file =~ m-^/adm/-) {
 8410: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8411:     } else {
 8412:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8413:         $file=~s:^/res/:/:;
 8414:         if ( !( $file =~ m:^/:) ) {
 8415:             $location = $dir. '/'.$file;
 8416:         } else {
 8417:             $location = '/home/httpd/html/res'.$file;
 8418:         }
 8419:     }
 8420:     $location=~s://+:/:g; # remove duplicate /
 8421:     while ($location=~m{/\.\./}) {
 8422: 	if ($location =~ m{/[^/]+/\.\./}) {
 8423: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8424: 	} else {
 8425: 	    $location=~ s{/\.\./}{/}g;
 8426: 	}
 8427:     } #remove dir/..
 8428:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8429:     return $location;
 8430: }
 8431: 
 8432: sub hreflocation {
 8433:     my ($dir,$file)=@_;
 8434:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8435: 	$file=filelocation($dir,$file);
 8436:     } elsif ($file=~m-^/adm/-) {
 8437: 	$file=~s-^/adm/wrapper/-/-;
 8438: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8439:     }
 8440:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8441: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8442:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8443: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8444:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8445: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8446: 	    -/uploaded/$1/$2/-x;
 8447:     }
 8448:     if ($file=~ m{^/userfiles/}) {
 8449: 	$file =~ s{^/userfiles/}{/uploaded/};
 8450:     }
 8451:     return $file;
 8452: }
 8453: 
 8454: sub current_machine_domains {
 8455:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8456: }
 8457: 
 8458: sub machine_domains {
 8459:     my ($hostname) = @_;
 8460:     my @domains;
 8461:     my %hostname = &all_hostnames();
 8462:     while( my($id, $name) = each(%hostname)) {
 8463: #	&logthis("-$id-$name-$hostname-");
 8464: 	if ($hostname eq $name) {
 8465: 	    push(@domains,&host_domain($id));
 8466: 	}
 8467:     }
 8468:     return @domains;
 8469: }
 8470: 
 8471: sub current_machine_ids {
 8472:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8473: }
 8474: 
 8475: sub machine_ids {
 8476:     my ($hostname) = @_;
 8477:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8478:     my @ids;
 8479:     my %name_to_host = &all_names();
 8480:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8481: 	return @{ $name_to_host{$hostname} };
 8482:     }
 8483:     return;
 8484: }
 8485: 
 8486: sub additional_machine_domains {
 8487:     my @domains;
 8488:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8489:     while( my $line = <$fh>) {
 8490:         $line =~ s/\s//g;
 8491:         push(@domains,$line);
 8492:     }
 8493:     return @domains;
 8494: }
 8495: 
 8496: sub default_login_domain {
 8497:     my $domain = $perlvar{'lonDefDomain'};
 8498:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8499:     foreach my $posdom (&current_machine_domains(),
 8500:                         &additional_machine_domains()) {
 8501:         if (lc($posdom) eq lc($testdomain)) {
 8502:             $domain=$posdom;
 8503:             last;
 8504:         }
 8505:     }
 8506:     return $domain;
 8507: }
 8508: 
 8509: # ------------------------------------------------------------- Declutters URLs
 8510: 
 8511: sub declutter {
 8512:     my $thisfn=shift;
 8513:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8514:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8515:     $thisfn=~s/^\///;
 8516:     $thisfn=~s|^adm/wrapper/||;
 8517:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8518:     $thisfn=~s/^res\///;
 8519:     $thisfn=~s/\?.+$//;
 8520:     return $thisfn;
 8521: }
 8522: 
 8523: # ------------------------------------------------------------- Clutter up URLs
 8524: 
 8525: sub clutter {
 8526:     my $thisfn='/'.&declutter(shift);
 8527:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8528: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8529:        $thisfn='/res'.$thisfn; 
 8530:     }
 8531:     if ($thisfn !~m|/adm|) {
 8532: 	if ($thisfn =~ m|/ext/|) {
 8533: 	    $thisfn='/adm/wrapper'.$thisfn;
 8534: 	} else {
 8535: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8536: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8537: 	    if ($embstyle eq 'ssi'
 8538: 		|| ($embstyle eq 'hdn')
 8539: 		|| ($embstyle eq 'rat')
 8540: 		|| ($embstyle eq 'prv')
 8541: 		|| ($embstyle eq 'ign')) {
 8542: 		#do nothing with these
 8543: 	    } elsif (($embstyle eq 'img') 
 8544: 		|| ($embstyle eq 'emb')
 8545: 		|| ($embstyle eq 'wrp')) {
 8546: 		$thisfn='/adm/wrapper'.$thisfn;
 8547: 	    } elsif ($embstyle eq 'unk'
 8548: 		     && $thisfn!~/\.(sequence|page)$/) {
 8549: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8550: 	    } else {
 8551: #		&logthis("Got a blank emb style");
 8552: 	    }
 8553: 	}
 8554:     }
 8555:     return $thisfn;
 8556: }
 8557: 
 8558: sub clutter_with_no_wrapper {
 8559:     my $uri = &clutter(shift);
 8560:     if ($uri =~ m-^/adm/-) {
 8561: 	$uri =~ s-^/adm/wrapper/-/-;
 8562: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8563:     }
 8564:     return $uri;
 8565: }
 8566: 
 8567: sub freeze_escape {
 8568:     my ($value)=@_;
 8569:     if (ref($value)) {
 8570: 	$value=&nfreeze($value);
 8571: 	return '__FROZEN__'.&escape($value);
 8572:     }
 8573:     return &escape($value);
 8574: }
 8575: 
 8576: 
 8577: sub thaw_unescape {
 8578:     my ($value)=@_;
 8579:     if ($value =~ /^__FROZEN__/) {
 8580: 	substr($value,0,10,undef);
 8581: 	$value=&unescape($value);
 8582: 	return &thaw($value);
 8583:     }
 8584:     return &unescape($value);
 8585: }
 8586: 
 8587: sub correct_line_ends {
 8588:     my ($result)=@_;
 8589:     $$result =~s/\r\n/\n/mg;
 8590:     $$result =~s/\r/\n/mg;
 8591: }
 8592: # ================================================================ Main Program
 8593: 
 8594: sub goodbye {
 8595:    &logthis("Starting Shut down");
 8596: #not converted to using infrastruture and probably shouldn't be
 8597:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8598: #converted
 8599: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8600:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8601: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8602: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8603: #1.1 only
 8604: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8605: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8606: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8607: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8608:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8609:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8610:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8611:    &flushcourselogs();
 8612:    &logthis("Shutting down");
 8613: }
 8614: 
 8615: sub get_dns {
 8616:     my ($url,$func,$ignore_cache) = @_;
 8617:     if (!$ignore_cache) {
 8618: 	my ($content,$cached)=
 8619: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8620: 	if ($cached) {
 8621: 	    &$func($content);
 8622: 	    return;
 8623: 	}
 8624:     }
 8625: 
 8626:     my %alldns;
 8627:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8628:     foreach my $dns (<$config>) {
 8629: 	next if ($dns !~ /^\^(\S*)/x);
 8630:         my $line = $1;
 8631:         my ($host,$protocol) = split(/:/,$line);
 8632:         if ($protocol ne 'https') {
 8633:             $protocol = 'http';
 8634:         }
 8635: 	$alldns{$host} = $protocol;
 8636:     }
 8637:     while (%alldns) {
 8638: 	my ($dns) = keys(%alldns);
 8639: 	my $ua=new LWP::UserAgent;
 8640: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8641: 	my $response=$ua->request($request);
 8642:         delete($alldns{$dns});
 8643: 	next if ($response->is_error());
 8644: 	my @content = split("\n",$response->content);
 8645: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8646: 	&$func(\@content);
 8647: 	return;
 8648:     }
 8649:     close($config);
 8650:     my $which = (split('/',$url))[3];
 8651:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8652:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8653:     my @content = <$config>;
 8654:     &$func(\@content);
 8655:     return;
 8656: }
 8657: # ------------------------------------------------------------ Read domain file
 8658: {
 8659:     my $loaded;
 8660:     my %domain;
 8661: 
 8662:     sub parse_domain_tab {
 8663: 	my ($lines) = @_;
 8664: 	foreach my $line (@$lines) {
 8665: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8666: 
 8667: 	    chomp($line);
 8668: 	    my ($name,@elements) = split(/:/,$line,9);
 8669: 	    my %this_domain;
 8670: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8671: 			       'lang_def', 'city', 'longi', 'lati',
 8672: 			       'primary') {
 8673: 		$this_domain{$field} = shift(@elements);
 8674: 	    }
 8675: 	    $domain{$name} = \%this_domain;
 8676: 	}
 8677:     }
 8678: 
 8679:     sub reset_domain_info {
 8680: 	undef($loaded);
 8681: 	undef(%domain);
 8682:     }
 8683: 
 8684:     sub load_domain_tab {
 8685: 	my ($ignore_cache) = @_;
 8686: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8687: 	my $fh;
 8688: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8689: 	    my @lines = <$fh>;
 8690: 	    &parse_domain_tab(\@lines);
 8691: 	}
 8692: 	close($fh);
 8693: 	$loaded = 1;
 8694:     }
 8695: 
 8696:     sub domain {
 8697: 	&load_domain_tab() if (!$loaded);
 8698: 
 8699: 	my ($name,$what) = @_;
 8700: 	return if ( !exists($domain{$name}) );
 8701: 
 8702: 	if (!$what) {
 8703: 	    return $domain{$name}{'description'};
 8704: 	}
 8705: 	return $domain{$name}{$what};
 8706:     }
 8707: 
 8708:     sub domain_info {
 8709:         &load_domain_tab() if (!$loaded);
 8710:         return %domain;
 8711:     }
 8712: 
 8713: }
 8714: 
 8715: 
 8716: # ------------------------------------------------------------- Read hosts file
 8717: {
 8718:     my %hostname;
 8719:     my %hostdom;
 8720:     my %libserv;
 8721:     my $loaded;
 8722:     my %name_to_host;
 8723: 
 8724:     sub parse_hosts_tab {
 8725: 	my ($file) = @_;
 8726: 	foreach my $configline (@$file) {
 8727: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8728: 	    next if ($configline =~ /^\^/);
 8729: 	    chomp($configline);
 8730: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8731: 	    $name=~s/\s//g;
 8732: 	    if ($id && $domain && $role && $name) {
 8733: 		$hostname{$id}=$name;
 8734: 		push(@{$name_to_host{$name}}, $id);
 8735: 		$hostdom{$id}=$domain;
 8736: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8737:                 if (defined($protocol)) {
 8738:                     if ($protocol eq 'https') {
 8739:                         $protocol{$id} = $protocol;
 8740:                     } else {
 8741:                         $protocol{$id} = 'http'; 
 8742:                     }
 8743:                 } else {
 8744:                     $protocol{$id} = 'http';
 8745:                 }
 8746: 	    }
 8747: 	}
 8748:     }
 8749:     
 8750:     sub reset_hosts_info {
 8751: 	&purge_remembered();
 8752: 	&reset_domain_info();
 8753: 	&reset_hosts_ip_info();
 8754: 	undef(%name_to_host);
 8755: 	undef(%hostname);
 8756: 	undef(%hostdom);
 8757: 	undef(%libserv);
 8758: 	undef($loaded);
 8759:     }
 8760: 
 8761:     sub load_hosts_tab {
 8762: 	my ($ignore_cache) = @_;
 8763: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8764: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8765: 	my @config = <$config>;
 8766: 	&parse_hosts_tab(\@config);
 8767: 	close($config);
 8768: 	$loaded=1;
 8769:     }
 8770: 
 8771:     sub hostname {
 8772: 	&load_hosts_tab() if (!$loaded);
 8773: 
 8774: 	my ($lonid) = @_;
 8775: 	return $hostname{$lonid};
 8776:     }
 8777: 
 8778:     sub all_hostnames {
 8779: 	&load_hosts_tab() if (!$loaded);
 8780: 
 8781: 	return %hostname;
 8782:     }
 8783: 
 8784:     sub all_names {
 8785: 	&load_hosts_tab() if (!$loaded);
 8786: 
 8787: 	return %name_to_host;
 8788:     }
 8789: 
 8790:     sub all_host_domain {
 8791:         &load_hosts_tab() if (!$loaded);
 8792:         return %hostdom;
 8793:     }
 8794: 
 8795:     sub is_library {
 8796: 	&load_hosts_tab() if (!$loaded);
 8797: 
 8798: 	return exists($libserv{$_[0]});
 8799:     }
 8800: 
 8801:     sub all_library {
 8802: 	&load_hosts_tab() if (!$loaded);
 8803: 
 8804: 	return %libserv;
 8805:     }
 8806: 
 8807:     sub get_servers {
 8808: 	&load_hosts_tab() if (!$loaded);
 8809: 
 8810: 	my ($domain,$type) = @_;
 8811: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8812: 	                                          : %hostname;
 8813: 	my %result;
 8814: 	if (ref($domain) eq 'ARRAY') {
 8815: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8816: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8817: 		    $result{$host} = $hostname;
 8818: 		}
 8819: 	    }
 8820: 	} else {
 8821: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8822: 		if ($hostdom{$host} eq $domain) {
 8823: 		    $result{$host} = $hostname;
 8824: 		}
 8825: 	    }
 8826: 	}
 8827: 	return %result;
 8828:     }
 8829: 
 8830:     sub host_domain {
 8831: 	&load_hosts_tab() if (!$loaded);
 8832: 
 8833: 	my ($lonid) = @_;
 8834: 	return $hostdom{$lonid};
 8835:     }
 8836: 
 8837:     sub all_domains {
 8838: 	&load_hosts_tab() if (!$loaded);
 8839: 
 8840: 	my %seen;
 8841: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8842: 	return @uniq;
 8843:     }
 8844: }
 8845: 
 8846: { 
 8847:     my %iphost;
 8848:     my %name_to_ip;
 8849:     my %lonid_to_ip;
 8850: 
 8851:     sub get_hosts_from_ip {
 8852: 	my ($ip) = @_;
 8853: 	my %iphosts = &get_iphost();
 8854: 	if (ref($iphosts{$ip})) {
 8855: 	    return @{$iphosts{$ip}};
 8856: 	}
 8857: 	return;
 8858:     }
 8859:     
 8860:     sub reset_hosts_ip_info {
 8861: 	undef(%iphost);
 8862: 	undef(%name_to_ip);
 8863: 	undef(%lonid_to_ip);
 8864:     }
 8865: 
 8866:     sub get_host_ip {
 8867: 	my ($lonid) = @_;
 8868: 	if (exists($lonid_to_ip{$lonid})) {
 8869: 	    return $lonid_to_ip{$lonid};
 8870: 	}
 8871: 	my $name=&hostname($lonid);
 8872:    	my $ip = gethostbyname($name);
 8873: 	return if (!$ip || length($ip) ne 4);
 8874: 	$ip=inet_ntoa($ip);
 8875: 	$name_to_ip{$name}   = $ip;
 8876: 	$lonid_to_ip{$lonid} = $ip;
 8877: 	return $ip;
 8878:     }
 8879:     
 8880:     sub get_iphost {
 8881: 	my ($ignore_cache) = @_;
 8882: 
 8883: 	if (!$ignore_cache) {
 8884: 	    if (%iphost) {
 8885: 		return %iphost;
 8886: 	    }
 8887: 	    my ($ip_info,$cached)=
 8888: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8889: 	    if ($cached) {
 8890: 		%iphost      = %{$ip_info->[0]};
 8891: 		%name_to_ip  = %{$ip_info->[1]};
 8892: 		%lonid_to_ip = %{$ip_info->[2]};
 8893: 		return %iphost;
 8894: 	    }
 8895: 	}
 8896: 
 8897: 	# get yesterday's info for fallback
 8898: 	my %old_name_to_ip;
 8899: 	my ($ip_info,$cached)=
 8900: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8901: 	if ($cached) {
 8902: 	    %old_name_to_ip = %{$ip_info->[1]};
 8903: 	}
 8904: 
 8905: 	my %name_to_host = &all_names();
 8906: 	foreach my $name (keys(%name_to_host)) {
 8907: 	    my $ip;
 8908: 	    if (!exists($name_to_ip{$name})) {
 8909: 		$ip = gethostbyname($name);
 8910: 		if (!$ip || length($ip) ne 4) {
 8911: 		    if (defined($old_name_to_ip{$name})) {
 8912: 			$ip = $old_name_to_ip{$name};
 8913: 			&logthis("Can't find $name defaulting to old $ip");
 8914: 		    } else {
 8915: 			&logthis("Name $name no IP found");
 8916: 			next;
 8917: 		    }
 8918: 		} else {
 8919: 		    $ip=inet_ntoa($ip);
 8920: 		}
 8921: 		$name_to_ip{$name} = $ip;
 8922: 	    } else {
 8923: 		$ip = $name_to_ip{$name};
 8924: 	    }
 8925: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8926: 		$lonid_to_ip{$id} = $ip;
 8927: 	    }
 8928: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8929: 	}
 8930: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8931: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8932: 				      48*60*60);
 8933: 
 8934: 	return %iphost;
 8935:     }
 8936: }
 8937: 
 8938: BEGIN {
 8939: 
 8940: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8941:     unless ($readit) {
 8942: {
 8943:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8944:     %perlvar = (%perlvar,%{$configvars});
 8945: }
 8946: 
 8947: 
 8948: # ------------------------------------------------------ Read spare server file
 8949: {
 8950:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8951: 
 8952:     while (my $configline=<$config>) {
 8953:        chomp($configline);
 8954:        if ($configline) {
 8955: 	   my ($host,$type) = split(':',$configline,2);
 8956: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8957: 	   push(@{ $spareid{$type} }, $host);
 8958:        }
 8959:     }
 8960:     close($config);
 8961: }
 8962: # ------------------------------------------------------------ Read permissions
 8963: {
 8964:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8965: 
 8966:     while (my $configline=<$config>) {
 8967: 	chomp($configline);
 8968: 	if ($configline) {
 8969: 	    my ($role,$perm)=split(/ /,$configline);
 8970: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8971: 	}
 8972:     }
 8973:     close($config);
 8974: }
 8975: 
 8976: # -------------------------------------------- Read plain texts for permissions
 8977: {
 8978:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 8979: 
 8980:     while (my $configline=<$config>) {
 8981: 	chomp($configline);
 8982: 	if ($configline) {
 8983: 	    my ($short,@plain)=split(/:/,$configline);
 8984:             %{$prp{$short}} = ();
 8985: 	    if (@plain > 0) {
 8986:                 $prp{$short}{'std'} = $plain[0];
 8987:                 for (my $i=1; $i<@plain; $i++) {
 8988:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 8989:                 }
 8990:             }
 8991: 	}
 8992:     }
 8993:     close($config);
 8994: }
 8995: 
 8996: # ---------------------------------------------------------- Read package table
 8997: {
 8998:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 8999: 
 9000:     while (my $configline=<$config>) {
 9001: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9002: 	chomp($configline);
 9003: 	my ($short,$plain)=split(/:/,$configline);
 9004: 	my ($pack,$name)=split(/\&/,$short);
 9005: 	if ($plain ne '') {
 9006: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9007: 	    $packagetab{$short}=$plain; 
 9008: 	}
 9009:     }
 9010:     close($config);
 9011: }
 9012: 
 9013: # ------------- set up temporary directory
 9014: {
 9015:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9016: 
 9017: }
 9018: 
 9019: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9020: 				'compress_threshold'=> 20_000,
 9021:  			        });
 9022: 
 9023: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9024: $dumpcount=0;
 9025: $locknum=0;
 9026: 
 9027: &logtouch();
 9028: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9029: $readit=1;
 9030:     {
 9031: 	use integer;
 9032: 	my $test=(2**32)+1;
 9033: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9034: 	&logthis(" Detected 64bit platform ($_64bit)");
 9035:     }
 9036: }
 9037: }
 9038: 
 9039: 1;
 9040: __END__
 9041: 
 9042: =pod
 9043: 
 9044: =head1 NAME
 9045: 
 9046: Apache::lonnet - Subroutines to ask questions about things in the network.
 9047: 
 9048: =head1 SYNOPSIS
 9049: 
 9050: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9051: 
 9052:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9053: 
 9054: Common parameters:
 9055: 
 9056: =over 4
 9057: 
 9058: =item *
 9059: 
 9060: $uname : an internal username (if $cname expecting a course Id specifically)
 9061: 
 9062: =item *
 9063: 
 9064: $udom : a domain (if $cdom expecting a course's domain specifically)
 9065: 
 9066: =item *
 9067: 
 9068: $symb : a resource instance identifier
 9069: 
 9070: =item *
 9071: 
 9072: $namespace : the name of a .db file that contains the data needed or
 9073: being set.
 9074: 
 9075: =back
 9076: 
 9077: =head1 OVERVIEW
 9078: 
 9079: lonnet provides subroutines which interact with the
 9080: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9081: about classes, users, and resources.
 9082: 
 9083: For many of these objects you can also use this to store data about
 9084: them or modify them in various ways.
 9085: 
 9086: =head2 Symbs
 9087: 
 9088: To identify a specific instance of a resource, LON-CAPA uses symbols
 9089: or "symbs"X<symb>. These identifiers are built from the URL of the
 9090: map, the resource number of the resource in the map, and the URL of
 9091: the resource itself. The latter is somewhat redundant, but might help
 9092: if maps change.
 9093: 
 9094: An example is
 9095: 
 9096:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9097: 
 9098: The respective map entry is
 9099: 
 9100:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9101:   title="Problem 2">
 9102:  </resource>
 9103: 
 9104: Symbs are used by the random number generator, as well as to store and
 9105: restore data specific to a certain instance of for example a problem.
 9106: 
 9107: =head2 Storing And Retrieving Data
 9108: 
 9109: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9110: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9111: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9112: is is the non-critical message twin of cstore. These functions are for
 9113: handlers to store a perl hash to a user's permanent data space in an
 9114: easy manner, and to retrieve it again on another call. It is expected
 9115: that a handler would use this once at the beginning to retrieve data,
 9116: and then again once at the end to send only the new data back.
 9117: 
 9118: The data is stored in the user's data directory on the user's
 9119: homeserver under the ID of the course.
 9120: 
 9121: The hash that is returned by restore will have all of the previous
 9122: value for all of the elements of the hash.
 9123: 
 9124: Example:
 9125: 
 9126:  #creating a hash
 9127:  my %hash;
 9128:  $hash{'foo'}='bar';
 9129: 
 9130:  #storing it
 9131:  &Apache::lonnet::cstore(\%hash);
 9132: 
 9133:  #changing a value
 9134:  $hash{'foo'}='notbar';
 9135: 
 9136:  #adding a new value
 9137:  $hash{'bar'}='foo';
 9138:  &Apache::lonnet::cstore(\%hash);
 9139: 
 9140:  #retrieving the hash
 9141:  my %history=&Apache::lonnet::restore();
 9142: 
 9143:  #print the hash
 9144:  foreach my $key (sort(keys(%history))) {
 9145:    print("\%history{$key} = $history{$key}");
 9146:  }
 9147: 
 9148: Will print out:
 9149: 
 9150:  %history{1:foo} = bar
 9151:  %history{1:keys} = foo:timestamp
 9152:  %history{1:timestamp} = 990455579
 9153:  %history{2:bar} = foo
 9154:  %history{2:foo} = notbar
 9155:  %history{2:keys} = foo:bar:timestamp
 9156:  %history{2:timestamp} = 990455580
 9157:  %history{bar} = foo
 9158:  %history{foo} = notbar
 9159:  %history{timestamp} = 990455580
 9160:  %history{version} = 2
 9161: 
 9162: Note that the special hash entries C<keys>, C<version> and
 9163: C<timestamp> were added to the hash. C<version> will be equal to the
 9164: total number of versions of the data that have been stored. The
 9165: C<timestamp> attribute will be the UNIX time the hash was
 9166: stored. C<keys> is available in every historical section to list which
 9167: keys were added or changed at a specific historical revision of a
 9168: hash.
 9169: 
 9170: B<Warning>: do not store the hash that restore returns directly. This
 9171: will cause a mess since it will restore the historical keys as if the
 9172: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9173: 
 9174: Calling convention:
 9175: 
 9176:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9177:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9178: 
 9179: For more detailed information, see lonnet specific documentation.
 9180: 
 9181: =head1 RETURN MESSAGES
 9182: 
 9183: =over 4
 9184: 
 9185: =item * B<con_lost>: unable to contact remote host
 9186: 
 9187: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9188: when the connection is brought back up
 9189: 
 9190: =item * B<con_failed>: unable to contact remote host and unable to save message
 9191: for later delivery
 9192: 
 9193: =item * B<error:>: an error a occurred, a description of the error follows the :
 9194: 
 9195: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9196: that was requested
 9197: 
 9198: =back
 9199: 
 9200: =head1 PUBLIC SUBROUTINES
 9201: 
 9202: =head2 Session Environment Functions
 9203: 
 9204: =over 4
 9205: 
 9206: =item * 
 9207: X<appenv()>
 9208: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9209: the user envirnoment file, and will be restored for each access this
 9210: user makes during this session, also modifies the %env for the current
 9211: process. Optional rolesarrayref - if defined contains a reference to an array
 9212: of roles which are exempt from the restriction on modifying user.role entries 
 9213: in the user's environment.db and in %env.    
 9214: 
 9215: =item *
 9216: X<delenv()>
 9217: B<delenv($regexp)>: removes all items from the session
 9218: environment file that matches the regular expression in $regexp. The
 9219: values are also delted from the current processes %env.
 9220: 
 9221: =item * get_env_multiple($name) 
 9222: 
 9223: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9224: values may be defined and end up as an array ref.
 9225: 
 9226: returns an array of values
 9227: 
 9228: =back
 9229: 
 9230: =head2 User Information
 9231: 
 9232: =over 4
 9233: 
 9234: =item *
 9235: X<queryauthenticate()>
 9236: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9237: authentication scheme
 9238: 
 9239: =item *
 9240: X<authenticate()>
 9241: B<authenticate($uname,$upass,$udom)>: try to
 9242: authenticate user from domain's lib servers (first use the current
 9243: one). C<$upass> should be the users password.
 9244: 
 9245: =item *
 9246: X<homeserver()>
 9247: B<homeserver($uname,$udom)>: find the server which has
 9248: the user's directory and files (there must be only one), this caches
 9249: the answer, and also caches if there is a borken connection.
 9250: 
 9251: =item *
 9252: X<idget()>
 9253: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9254: (IDs are a unique resource in a domain, there must be only 1 ID per
 9255: username, and only 1 username per ID in a specific domain) (returns
 9256: hash: id=>name,id=>name)
 9257: 
 9258: =item *
 9259: X<idrget()>
 9260: B<idrget($udom,@unames)>: find the IDs behind a list of
 9261: usernames (returns hash: name=>id,name=>id)
 9262: 
 9263: =item *
 9264: X<idput()>
 9265: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9266: 
 9267: =item *
 9268: X<rolesinit()>
 9269: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9270: 
 9271: =item *
 9272: X<getsection()>
 9273: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9274: course $cname, return section name/number or '' for "not in course"
 9275: and '-1' for "no section"
 9276: 
 9277: =item *
 9278: X<userenvironment()>
 9279: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9280: passed in @what from the requested user's environment, returns a hash
 9281: 
 9282: =item * 
 9283: X<userlog_query()>
 9284: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9285: activity.log file. %filters defines filters applied when parsing the
 9286: log file. These can be start or end timestamps, or the type of action
 9287: - log to look for Login or Logout events, check for Checkin or
 9288: Checkout, role for role selection. The response is in the form
 9289: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9290: escaped strings of the action recorded in the activity.log file.
 9291: 
 9292: =back
 9293: 
 9294: =head2 User Roles
 9295: 
 9296: =over 4
 9297: 
 9298: =item *
 9299: 
 9300: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9301:  F: full access
 9302:  U,I,K: authentication modes (cxx only)
 9303:  '': forbidden
 9304:  1: user needs to choose course
 9305:  2: browse allowed
 9306:  A: passphrase authentication needed
 9307: 
 9308: =item *
 9309: 
 9310: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9311: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9312: and course level
 9313: 
 9314: =item *
 9315: 
 9316: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 9317: explanation of a user role term
 9318: 
 9319: =item *
 9320: 
 9321: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9322: All arguments are optional. Returns a hash of a roles, either for
 9323: co-author/assistant author roles for a user's Construction Space
 9324: (default), or if $context is 'userroles', roles for the user himself,
 9325: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9326: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9327: For each key, value is set to colon-separated start and end times for
 9328: the role.  If no username and domain are specified, will default to
 9329: current user/domain. Types, roles, and roledoms are references to arrays
 9330: of role statuses (active, future or previous), roles 
 9331: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9332: to restrict the list of roles reported. If no array ref is 
 9333: provided for types, will default to return only active roles.
 9334: 
 9335: =back
 9336: 
 9337: =head2 User Modification
 9338: 
 9339: =over 4
 9340: 
 9341: =item *
 9342: 
 9343: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9344: user for the level given by URL.  Optional start and end dates (leave empty
 9345: string or zero for "no date")
 9346: 
 9347: =item *
 9348: 
 9349: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9350: change a users, password, possible return values are: ok,
 9351: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9352: refused
 9353: 
 9354: =item *
 9355: 
 9356: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9357: 
 9358: =item *
 9359: 
 9360: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9361:            $forceid,$desiredhome,$email,$inststatus) : 
 9362: modify user
 9363: 
 9364: =item *
 9365: 
 9366: modifystudent
 9367: 
 9368: modify a student's enrollment and identification information.
 9369: The course id is resolved based on the current users environment.  
 9370: This means the envoking user must be a course coordinator or otherwise
 9371: associated with a course.
 9372: 
 9373: This call is essentially a wrapper for lonnet::modifyuser and
 9374: lonnet::modify_student_enrollment
 9375: 
 9376: Inputs: 
 9377: 
 9378: =over 4
 9379: 
 9380: =item B<$udom> Student's loncapa domain
 9381: 
 9382: =item B<$uname> Student's loncapa login name
 9383: 
 9384: =item B<$uid> Student/Employee ID
 9385: 
 9386: =item B<$umode> Student's authentication mode
 9387: 
 9388: =item B<$upass> Student's password
 9389: 
 9390: =item B<$first> Student's first name
 9391: 
 9392: =item B<$middle> Student's middle name
 9393: 
 9394: =item B<$last> Student's last name
 9395: 
 9396: =item B<$gene> Student's generation
 9397: 
 9398: =item B<$usec> Student's section in course
 9399: 
 9400: =item B<$end> Unix time of the roles expiration
 9401: 
 9402: =item B<$start> Unix time of the roles start date
 9403: 
 9404: =item B<$forceid> If defined, allow $uid to be changed
 9405: 
 9406: =item B<$desiredhome> server to use as home server for student
 9407: 
 9408: =item B<$email> Student's permanent e-mail address
 9409: 
 9410: =item B<$type> Type of enrollment (auto or manual)
 9411: 
 9412: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9413: 
 9414: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9415: 
 9416: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9417: 
 9418: =item B<$context> role change context (shown in User Management Logs display in a course)
 9419: 
 9420: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9421: 
 9422: =back
 9423: 
 9424: =item *
 9425: 
 9426: modify_student_enrollment
 9427: 
 9428: Change a students enrollment status in a class.  The environment variable
 9429: 'role.request.course' must be defined for this function to proceed.
 9430: 
 9431: Inputs:
 9432: 
 9433: =over 4
 9434: 
 9435: =item $udom, students domain
 9436: 
 9437: =item $uname, students name
 9438: 
 9439: =item $uid, students user id
 9440: 
 9441: =item $first, students first name
 9442: 
 9443: =item $middle
 9444: 
 9445: =item $last
 9446: 
 9447: =item $gene
 9448: 
 9449: =item $usec
 9450: 
 9451: =item $end
 9452: 
 9453: =item $start
 9454: 
 9455: =item $type
 9456: 
 9457: =item $locktype
 9458: 
 9459: =item $cid
 9460: 
 9461: =item $selfenroll
 9462: 
 9463: =item $context
 9464: 
 9465: =back
 9466: 
 9467: 
 9468: =item *
 9469: 
 9470: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9471: custom role; give a custom role to a user for the level given by URL.  Specify
 9472: name and domain of role author, and role name
 9473: 
 9474: =item *
 9475: 
 9476: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9477: 
 9478: =item *
 9479: 
 9480: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9481: 
 9482: =back
 9483: 
 9484: =head2 Course Infomation
 9485: 
 9486: =over 4
 9487: 
 9488: =item *
 9489: 
 9490: coursedescription($courseid) : returns a hash of information about the
 9491: specified course id, including all environment settings for the
 9492: course, the description of the course will be in the hash under the
 9493: key 'description'
 9494: 
 9495: =item *
 9496: 
 9497: resdata($name,$domain,$type,@which) : request for current parameter
 9498: setting for a specific $type, where $type is either 'course' or 'user',
 9499: @what should be a list of parameters to ask about. This routine caches
 9500: answers for 5 minutes.
 9501: 
 9502: =item *
 9503: 
 9504: get_courseresdata($courseid, $domain) : dump the entire course resource
 9505: data base, returning a hash that is keyed by the resource name and has
 9506: values that are the resource value.  I believe that the timestamps and
 9507: versions are also returned.
 9508: 
 9509: 
 9510: =back
 9511: 
 9512: =head2 Course Modification
 9513: 
 9514: =over 4
 9515: 
 9516: =item *
 9517: 
 9518: writecoursepref($courseid,%prefs) : write preferences (environment
 9519: database) for a course
 9520: 
 9521: =item *
 9522: 
 9523: createcourse($udom,$description,$url) : make/modify course
 9524: 
 9525: =back
 9526: 
 9527: =head2 Resource Subroutines
 9528: 
 9529: =over 4
 9530: 
 9531: =item *
 9532: 
 9533: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9534: 
 9535: =item *
 9536: 
 9537: repcopy($filename) : subscribes to the requested file, and attempts to
 9538: replicate from the owning library server, Might return
 9539: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9540: 'bad_request', also attempts to grab the metadata for the
 9541: resource. Expects the local filesystem pathname
 9542: (/home/httpd/html/res/....)
 9543: 
 9544: =back
 9545: 
 9546: =head2 Resource Information
 9547: 
 9548: =over 4
 9549: 
 9550: =item *
 9551: 
 9552: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9553: a vairety of different possible values, $varname should be a request
 9554: string, and the other parameters can be used to specify who and what
 9555: one is asking about.
 9556: 
 9557: Possible values for $varname are environment.lastname (or other item
 9558: from the envirnment hash), user.name (or someother aspect about the
 9559: user), resource.0.maxtries (or some other part and parameter of a
 9560: resource)
 9561: 
 9562: =item *
 9563: 
 9564: directcondval($number) : get current value of a condition; reads from a state
 9565: string
 9566: 
 9567: =item *
 9568: 
 9569: condval($condidx) : value of condition index based on state
 9570: 
 9571: =item *
 9572: 
 9573: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9574: resource's metadata, $what should be either a specific key, or either
 9575: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9576: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9577: 
 9578: this function automatically caches all requests
 9579: 
 9580: =item *
 9581: 
 9582: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9583: network of library servers; returns file handle of where SQL and regex results
 9584: will be stored for query
 9585: 
 9586: =item *
 9587: 
 9588: symbread($filename) : return symbolic list entry (filename argument optional);
 9589: returns the data handle
 9590: 
 9591: =item *
 9592: 
 9593: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9594: a possible symb for the URL in $thisfn, and if is an encryypted
 9595: resource that the user accessed using /enc/ returns a 1 on success, 0
 9596: on failure, user must be in a course, as it assumes the existance of
 9597: the course initial hash, and uses $env('request.course.id'}
 9598: 
 9599: 
 9600: =item *
 9601: 
 9602: symbclean($symb) : removes versions numbers from a symb, returns the
 9603: cleaned symb
 9604: 
 9605: =item *
 9606: 
 9607: is_on_map($uri) : checks if the $uri is somewhere on the current
 9608: course map, user must be in a course for it to work.
 9609: 
 9610: =item *
 9611: 
 9612: numval($salt) : return random seed value (addend for rndseed)
 9613: 
 9614: =item *
 9615: 
 9616: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9617: a random seed, all arguments are optional, if they aren't sent it uses the
 9618: environment to derive them. Note: if symb isn't sent and it can't get one
 9619: from &symbread it will use the current time as its return value
 9620: 
 9621: =item *
 9622: 
 9623: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9624: unfakeable, receipt
 9625: 
 9626: =item *
 9627: 
 9628: receipt() : API to ireceipt working off of env values; given out to users
 9629: 
 9630: =item *
 9631: 
 9632: countacc($url) : count the number of accesses to a given URL
 9633: 
 9634: =item *
 9635: 
 9636: 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
 9637: 
 9638: =item *
 9639: 
 9640: 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)
 9641: 
 9642: =item *
 9643: 
 9644: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9645: 
 9646: =item *
 9647: 
 9648: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9649: forcing spreadsheet to reevaluate the resource scores next time.
 9650: 
 9651: =back
 9652: 
 9653: =head2 Storing/Retreiving Data
 9654: 
 9655: =over 4
 9656: 
 9657: =item *
 9658: 
 9659: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9660: for this url; hashref needs to be given and should be a \%hashname; the
 9661: remaining args aren't required and if they aren't passed or are '' they will
 9662: be derived from the env
 9663: 
 9664: =item *
 9665: 
 9666: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9667: uses critical subroutine
 9668: 
 9669: =item *
 9670: 
 9671: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9672: all args are optional
 9673: 
 9674: =item *
 9675: 
 9676: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9677: dumps the complete (or key matching regexp) namespace into a hash
 9678: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9679: normally &store()ed into
 9680: 
 9681: $range should be either an integer '100' (give me the first 100
 9682:                                            matching records)
 9683:               or be  two integers sperated by a - with no spaces
 9684:                  '30-50' (give me the 30th through the 50th matching
 9685:                           records)
 9686: 
 9687: 
 9688: =item *
 9689: 
 9690: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9691: replaces a &store() version of data with a replacement set of data
 9692: for a particular resource in a namespace passed in the $storehash hash 
 9693: reference
 9694: 
 9695: =item *
 9696: 
 9697: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9698: works very similar to store/cstore, but all data is stored in a
 9699: temporary location and can be reset using tmpreset, $storehash should
 9700: be a hash reference, returns nothing on success
 9701: 
 9702: =item *
 9703: 
 9704: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9705: similar to restore, but all data is stored in a temporary location and
 9706: can be reset using tmpreset. Returns a hash of values on success,
 9707: error string otherwise.
 9708: 
 9709: =item *
 9710: 
 9711: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9712: deltes all keys for $symb form the temporary storage hash.
 9713: 
 9714: =item *
 9715: 
 9716: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9717: reference filled in from namesp ($udom and $uname are optional)
 9718: 
 9719: =item *
 9720: 
 9721: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9722: namesp ($udom and $uname are optional)
 9723: 
 9724: =item *
 9725: 
 9726: dump($namespace,$udom,$uname,$regexp,$range) : 
 9727: dumps the complete (or key matching regexp) namespace into a hash
 9728: ($udom, $uname, $regexp, $range are optional)
 9729: 
 9730: $range should be either an integer '100' (give me the first 100
 9731:                                            matching records)
 9732:               or be  two integers sperated by a - with no spaces
 9733:                  '30-50' (give me the 30th through the 50th matching
 9734:                           records)
 9735: =item *
 9736: 
 9737: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9738: $store can be a scalar, an array reference, or if the amount to be 
 9739: incremented is > 1, a hash reference.
 9740: 
 9741: ($udom and $uname are optional)
 9742: 
 9743: =item *
 9744: 
 9745: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9746: ($udom and $uname are optional)
 9747: 
 9748: =item *
 9749: 
 9750: cput($namespace,$storehash,$udom,$uname) : critical put
 9751: ($udom and $uname are optional)
 9752: 
 9753: =item *
 9754: 
 9755: newput($namespace,$storehash,$udom,$uname) :
 9756: 
 9757: Attempts to store the items in the $storehash, but only if they don't
 9758: currently exist, if this succeeds you can be certain that you have 
 9759: successfully created a new key value pair in the $namespace db.
 9760: 
 9761: 
 9762: Args:
 9763:  $namespace: name of database to store values to
 9764:  $storehash: hashref to store to the db
 9765:  $udom: (optional) domain of user containing the db
 9766:  $uname: (optional) name of user caontaining the db
 9767: 
 9768: Returns:
 9769:  'ok' -> succeeded in storing all keys of $storehash
 9770:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9771:                         least <key> already existed in the db (other
 9772:                         requested keys may also already exist)
 9773:  'error: <msg>' -> unable to tie the DB or other error occurred
 9774:  'con_lost' -> unable to contact request server
 9775:  'refused' -> action was not allowed by remote machine
 9776: 
 9777: 
 9778: =item *
 9779: 
 9780: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9781: reference filled in from namesp (encrypts the return communication)
 9782: ($udom and $uname are optional)
 9783: 
 9784: =item *
 9785: 
 9786: log($udom,$name,$home,$message) : write to permanent log for user; use
 9787: critical subroutine
 9788: 
 9789: =item *
 9790: 
 9791: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9792: array reference filled in from namespace found in domain level on either
 9793: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9794: 
 9795: =item *
 9796: 
 9797: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9798: domain level either on specified domain server ($uhome) or primary domain 
 9799: server ($udom and $uhome are optional)
 9800: 
 9801: =item * 
 9802: 
 9803: get_domain_defaults($target_domain) : returns hash with defaults for
 9804: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9805: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9806: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9807: Values are retrieved from cache (if current), or from domain's configuration.db
 9808: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9809: or lonTabs/domain.tab. 
 9810: 
 9811: %domdefaults = &get_auth_defaults($target_domain);
 9812: 
 9813: =back
 9814: 
 9815: =head2 Network Status Functions
 9816: 
 9817: =over 4
 9818: 
 9819: =item *
 9820: 
 9821: dirlist($uri) : return directory list based on URI
 9822: 
 9823: =item *
 9824: 
 9825: spareserver() : find server with least workload from spare.tab
 9826: 
 9827: =back
 9828: 
 9829: =head2 Apache Request
 9830: 
 9831: =over 4
 9832: 
 9833: =item *
 9834: 
 9835: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9836: localhost, posts hash
 9837: 
 9838: =back
 9839: 
 9840: =head2 Data to String to Data
 9841: 
 9842: =over 4
 9843: 
 9844: =item *
 9845: 
 9846: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9847: and '&' separators, supports elements that are arrayrefs and hashrefs
 9848: 
 9849: =item *
 9850: 
 9851: hashref2str($hashref) : convert a hashref into a string complete with
 9852: escaping and '=' and '&' separators, supports elements that are
 9853: arrayrefs and hashrefs
 9854: 
 9855: =item *
 9856: 
 9857: arrayref2str($arrayref) : convert an arrayref into a string complete
 9858: with escaping and '&' separators, supports elements that are arrayrefs
 9859: and hashrefs
 9860: 
 9861: =item *
 9862: 
 9863: str2hash($string) : convert string to hash using unescaping and
 9864: splitting on '=' and '&', supports elements that are arrayrefs and
 9865: hashrefs
 9866: 
 9867: =item *
 9868: 
 9869: str2array($string) : convert string to hash using unescaping and
 9870: splitting on '&', supports elements that are arrayrefs and hashrefs
 9871: 
 9872: =back
 9873: 
 9874: =head2 Logging Routines
 9875: 
 9876: =over 4
 9877: 
 9878: These routines allow one to make log messages in the lonnet.log and
 9879: lonnet.perm logfiles.
 9880: 
 9881: =item *
 9882: 
 9883: logtouch() : make sure the logfile, lonnet.log, exists
 9884: 
 9885: =item *
 9886: 
 9887: logthis() : append message to the normal lonnet.log file, it gets
 9888: preiodically rolled over and deleted.
 9889: 
 9890: =item *
 9891: 
 9892: logperm() : append a permanent message to lonnet.perm.log, this log
 9893: file never gets deleted by any automated portion of the system, only
 9894: messages of critical importance should go in here.
 9895: 
 9896: =back
 9897: 
 9898: =head2 General File Helper Routines
 9899: 
 9900: =over 4
 9901: 
 9902: =item *
 9903: 
 9904: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9905: (a) files in /uploaded
 9906:   (i) If a local copy of the file exists - 
 9907:       compares modification date of local copy with last-modified date for 
 9908:       definitive version stored on home server for course. If local copy is 
 9909:       stale, requests a new version from the home server and stores it. 
 9910:       If the original has been removed from the home server, then local copy 
 9911:       is unlinked.
 9912:   (ii) If local copy does not exist -
 9913:       requests the file from the home server and stores it. 
 9914:   
 9915:   If $caller is 'uploadrep':  
 9916:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9917:     for request for files originally uploaded via DOCS. 
 9918:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9919:   
 9920:   Otherwise:
 9921:      This indicates a call from the content generation phase of the request.
 9922:      -  returns the entire contents of the file or -1.
 9923:      
 9924: (b) files in /res
 9925:    - returns the entire contents of a file or -1; 
 9926:    it properly subscribes to and replicates the file if neccessary.
 9927: 
 9928: 
 9929: =item *
 9930: 
 9931: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9932:                   reference
 9933: 
 9934: returns either a stat() list of data about the file or an empty list
 9935: if the file doesn't exist or couldn't find out about it (connection
 9936: problems or user unknown)
 9937: 
 9938: =item *
 9939: 
 9940: filelocation($dir,$file) : returns file system location of a file
 9941: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9942: directory that relative $file lookups are to looked in ($dir of /a/dir
 9943: and a file of ../bob will become /a/bob)
 9944: 
 9945: =item *
 9946: 
 9947: hreflocation($dir,$file) : returns file system location or a URL; same as
 9948: filelocation except for hrefs
 9949: 
 9950: =item *
 9951: 
 9952: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9953: 
 9954: =back
 9955: 
 9956: =head2 Usererfile file routines (/uploaded*)
 9957: 
 9958: =over 4
 9959: 
 9960: =item *
 9961: 
 9962: userfileupload(): main rotine for putting a file in a user or course's
 9963:                   filespace, arguments are,
 9964: 
 9965:  formname - required - this is the name of the element in $env where the
 9966:            filename, and the contents of the file to create/modifed exist
 9967:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9968:            contents of the file is located in $env{'form.'.$formname}
 9969:  coursedoc - if true, store the file in the course of the active role
 9970:              of the current user
 9971:  subdir - required - subdirectory to put the file in under ../userfiles/
 9972:          if undefined, it will be placed in "unknown"
 9973: 
 9974:  (This routine calls clean_filename() to remove any dangerous
 9975:  characters from the filename, and then calls finuserfileupload() to
 9976:  complete the transaction)
 9977: 
 9978:  returns either the url of the uploaded file (/uploaded/....) if successful
 9979:  and /adm/notfound.html if unsuccessful
 9980: 
 9981: =item *
 9982: 
 9983: clean_filename(): routine for cleaing a filename up for storage in
 9984:                  userfile space, argument is:
 9985: 
 9986:  filename - proposed filename
 9987: 
 9988: returns: the new clean filename
 9989: 
 9990: =item *
 9991: 
 9992: finishuserfileupload(): routine that creaes and sends the file to
 9993: userspace, probably shouldn't be called directly
 9994: 
 9995:   docuname: username or courseid of destination for the file
 9996:   docudom: domain of user/course of destination for the file
 9997:   formname: same as for userfileupload()
 9998:   fname: filename (inculding subdirectories) for the file
 9999: 
10000:  returns either the url of the uploaded file (/uploaded/....) if successful
10001:  and /adm/notfound.html if unsuccessful
10002: 
10003: =item *
10004: 
10005: renameuserfile(): renames an existing userfile to a new name
10006: 
10007:   Args:
10008:    docuname: username or courseid of destination for the file
10009:    docudom: domain of user/course of destination for the file
10010:    old: current file name (including any subdirs under userfiles)
10011:    new: desired file name (including any subdirs under userfiles)
10012: 
10013: =item *
10014: 
10015: mkdiruserfile(): creates a directory is a userfiles dir
10016: 
10017:   Args:
10018:    docuname: username or courseid of destination for the file
10019:    docudom: domain of user/course of destination for the file
10020:    dir: dir to create (including any subdirs under userfiles)
10021: 
10022: =item *
10023: 
10024: removeuserfile(): removes a file that exists in userfiles
10025: 
10026:   Args:
10027:    docuname: username or courseid of destination for the file
10028:    docudom: domain of user/course of destination for the file
10029:    fname: filname to delete (including any subdirs under userfiles)
10030: 
10031: =item *
10032: 
10033: removeuploadedurl(): convience function for removeuserfile()
10034: 
10035:   Args:
10036:    url:  a full /uploaded/... url to delete
10037: 
10038: =item * 
10039: 
10040: get_portfile_permissions():
10041:   Args:
10042:     domain: domain of user or course contain the portfolio files
10043:     user: name of user or num of course contain the portfolio files
10044:   Returns:
10045:     hashref of a dump of the proper file_permissions.db
10046:    
10047: 
10048: =item * 
10049: 
10050: get_access_controls():
10051: 
10052: Args:
10053:   current_permissions: the hash ref returned from get_portfile_permissions()
10054:   group: (optional) the group you want the files associated with
10055:   file: (optional) the file you want access info on
10056: 
10057: Returns:
10058:     a hash (keys are file names) of hashes containing
10059:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10060:         values are XML containing access control settings (see below) 
10061: 
10062: Internal notes:
10063: 
10064:  access controls are stored in file_permissions.db as key=value pairs.
10065:     key -> path to file/file_name\0uniqueID:scope_end_start
10066:         where scope -> public,guest,course,group,domains or users.
10067:               end -> UNIX time for end of access (0 -> no end date)
10068:               start -> UNIX time for start of access
10069: 
10070:     value -> XML description of access control
10071:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10072:             <start></start>
10073:             <end></end>
10074: 
10075:             <password></password>  for scope type = guest
10076: 
10077:             <domain></domain>     for scope type = course or group
10078:             <number></number>
10079:             <roles id="">
10080:              <role></role>
10081:              <access></access>
10082:              <section></section>
10083:              <group></group>
10084:             </roles>
10085: 
10086:             <dom></dom>         for scope type = domains
10087: 
10088:             <users>             for scope type = users
10089:              <user>
10090:               <uname></uname>
10091:               <udom></udom>
10092:              </user>
10093:             </users>
10094:            </scope> 
10095:               
10096:  Access data is also aggregated for each file in an additional key=value pair:
10097:  key -> path to file/file_name\0accesscontrol 
10098:  value -> reference to hash
10099:           hash contains key = value pairs
10100:           where key = uniqueID:scope_end_start
10101:                 value = UNIX time record was last updated
10102: 
10103:           Used to improve speed of look-ups of access controls for each file.  
10104:  
10105:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10106: 
10107: modify_access_controls():
10108: 
10109: Modifies access controls for a portfolio file
10110: Args
10111: 1. file name
10112: 2. reference to hash of required changes,
10113: 3. domain
10114: 4. username
10115:   where domain,username are the domain of the portfolio owner 
10116:   (either a user or a course) 
10117: 
10118: Returns:
10119: 1. result of additions or updates ('ok' or 'error', with error message). 
10120: 2. result of deletions ('ok' or 'error', with error message).
10121: 3. reference to hash of any new or updated access controls.
10122: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10123:    key = integer (inbound ID)
10124:    value = uniqueID  
10125: 
10126: =back
10127: 
10128: =head2 HTTP Helper Routines
10129: 
10130: =over 4
10131: 
10132: =item *
10133: 
10134: escape() : unpack non-word characters into CGI-compatible hex codes
10135: 
10136: =item *
10137: 
10138: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10139: 
10140: =back
10141: 
10142: =head1 PRIVATE SUBROUTINES
10143: 
10144: =head2 Underlying communication routines (Shouldn't call)
10145: 
10146: =over 4
10147: 
10148: =item *
10149: 
10150: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10151: 
10152: =item *
10153: 
10154: reply() : uses subreply to send a message to remote machine, logs all failures
10155: 
10156: =item *
10157: 
10158: critical() : passes a critical message to another server; if cannot
10159: get through then place message in connection buffer directory and
10160: returns con_delayed, if incapable of saving message, returns
10161: con_failed
10162: 
10163: =item *
10164: 
10165: reconlonc() : tries to reconnect lonc client processes.
10166: 
10167: =back
10168: 
10169: =head2 Resource Access Logging
10170: 
10171: =over 4
10172: 
10173: =item *
10174: 
10175: flushcourselogs() : flush (save) buffer logs and access logs
10176: 
10177: =item *
10178: 
10179: courselog($what) : save message for course in hash
10180: 
10181: =item *
10182: 
10183: courseacclog($what) : save message for course using &courselog().  Perform
10184: special processing for specific resource types (problems, exams, quizzes, etc).
10185: 
10186: =item *
10187: 
10188: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10189: as a PerlChildExitHandler
10190: 
10191: =back
10192: 
10193: =head2 Other
10194: 
10195: =over 4
10196: 
10197: =item *
10198: 
10199: symblist($mapname,%newhash) : update symbolic storage links
10200: 
10201: =back
10202: 
10203: =cut
10204: 

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