File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.981: download - view: text, annotated - select for diffs
Sun Dec 21 19:03:10 2008 UTC (15 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- \Q escape to avoid interpolating contents of $delthis as special characters in regexp.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.981 2008/12/21 19:03:10 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 Image::Magick;
   77: 
   78: # use Date::Parse;
   79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   80:             $_64bit %env %protocol);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use LONCAPA qw(:DEFAULT :match);
   97: use LONCAPA::Configuration;
   98: 
   99: my $readit;
  100: my $max_connection_retries = 10;     # Or some such value.
  101: 
  102: my $upload_photo_form = 0; #Variable to check  when user upload a photo 0=not 1=true
  103: 
  104: require Exporter;
  105: 
  106: our @ISA = qw (Exporter);
  107: our @EXPORT = qw(%env);
  108: 
  109: 
  110: # --------------------------------------------------------------------- Logging
  111: {
  112:     my $logid;
  113:     sub instructor_log {
  114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  115:         if (($cnum eq '') || ($cdom eq '')) {
  116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  118:         }
  119: 	$logid++;
  120:         my $now = time();
  121: 	my $id=$now.'00000'.$$.'00000'.$logid;
  122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  123: 				    { $id => {
  124: 					'exe_uname' => $env{'user.name'},
  125: 					'exe_udom'  => $env{'user.domain'},
  126: 					'exe_time'  => $now,
  127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  128: 					'delflag'   => $delflag,
  129: 					'logentry'  => $storehash,
  130: 					'uname'     => $uname,
  131: 					'udom'      => $udom,
  132: 				    }
  133: 				  },$cdom,$cnum);
  134:     }
  135: }
  136: 
  137: sub logtouch {
  138:     my $execdir=$perlvar{'lonDaemons'};
  139:     unless (-e "$execdir/logs/lonnet.log") {	
  140: 	open(my $fh,">>$execdir/logs/lonnet.log");
  141: 	close $fh;
  142:     }
  143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  145: }
  146: 
  147: sub logthis {
  148:     my $message=shift;
  149:     my $execdir=$perlvar{'lonDaemons'};
  150:     my $now=time;
  151:     my $local=localtime($now);
  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  153: 	print $fh "$local ($$): $message\n";
  154: 	close($fh);
  155:     }
  156:     return 1;
  157: }
  158: 
  159: sub logperm {
  160:     my $message=shift;
  161:     my $execdir=$perlvar{'lonDaemons'};
  162:     my $now=time;
  163:     my $local=localtime($now);
  164:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  165: 	print $fh "$now:$message:$local\n";
  166: 	close($fh);
  167:     }
  168:     return 1;
  169: }
  170: 
  171: sub create_connection {
  172:     my ($hostname,$lonid) = @_;
  173:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  174: 				     Type    => SOCK_STREAM,
  175: 				     Timeout => 10);
  176:     return 0 if (!$client);
  177:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  178:     my $result = <$client>;
  179:     chomp($result);
  180:     return 1 if ($result eq 'done');
  181:     return 0;
  182: }
  183: 
  184: 
  185: # -------------------------------------------------- Non-critical communication
  186: sub subreply {
  187:     my ($cmd,$server)=@_;
  188:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  189:     #
  190:     #  With loncnew process trimming, there's a timing hole between lonc server
  191:     #  process exit and the master server picking up the listen on the AF_UNIX
  192:     #  socket.  In that time interval, a lock file will exist:
  193: 
  194:     my $lockfile=$peerfile.".lock";
  195:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  196: 	sleep(1);
  197:     }
  198:     # At this point, either a loncnew parent is listening or an old lonc
  199:     # or loncnew child is listening so we can connect or everything's dead.
  200:     #
  201:     #   We'll give the connection a few tries before abandoning it.  If
  202:     #   connection is not possible, we'll con_lost back to the client.
  203:     #   
  204:     my $client;
  205:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  206: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  207: 				      Type    => SOCK_STREAM,
  208: 				      Timeout => 10);
  209: 	if ($client) {
  210: 	    last;		# Connected!
  211: 	} else {
  212: 	    &create_connection(&hostname($server),$server);
  213: 	}
  214:         sleep(1);		# Try again later if failed connection.
  215:     }
  216:     my $answer;
  217:     if ($client) {
  218: 	print $client "sethost:$server:$cmd\n";
  219: 	$answer=<$client>;
  220: 	if (!$answer) { $answer="con_lost"; }
  221: 	chomp($answer);
  222:     } else {
  223: 	$answer = 'con_lost';	# Failed connection.
  224:     }
  225:     return $answer;
  226: }
  227: 
  228: sub reply {
  229:     my ($cmd,$server)=@_;
  230:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  231:     my $answer=subreply($cmd,$server);
  232:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  233:        &logthis("<font color=\"blue\">WARNING:".
  234:                 " $cmd to $server returned $answer</font>");
  235:     }
  236:     return $answer;
  237: }
  238: 
  239: # ----------------------------------------------------------- Send USR1 to lonc
  240: 
  241: sub reconlonc {
  242:     my ($lonid) = @_;
  243:     my $hostname = &hostname($lonid);
  244:     if ($lonid) {
  245: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  246: 	if ($hostname && -e $peerfile) {
  247: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  248: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  249: 					     Type    => SOCK_STREAM,
  250: 					     Timeout => 10);
  251: 	    if ($client) {
  252: 		print $client ("reset_retries\n");
  253: 		my $answer=<$client>;
  254: 		#reset just this one.
  255: 	    }
  256: 	}
  257: 	return;
  258:     }
  259: 
  260:     &logthis("Trying to reconnect lonc");
  261:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  262:     if (open(my $fh,"<$loncfile")) {
  263: 	my $loncpid=<$fh>;
  264:         chomp($loncpid);
  265:         if (kill 0 => $loncpid) {
  266: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  267:             kill USR1 => $loncpid;
  268:             sleep 1;
  269:          } else {
  270: 	    &logthis(
  271:                "<font color=\"blue\">WARNING:".
  272:                " lonc at pid $loncpid not responding, giving up</font>");
  273:         }
  274:     } else {
  275: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  276:     }
  277: }
  278: 
  279: # ------------------------------------------------------ Critical communication
  280: 
  281: sub critical {
  282:     my ($cmd,$server)=@_;
  283:     unless (&hostname($server)) {
  284:         &logthis("<font color=\"blue\">WARNING:".
  285:                " Critical message to unknown server ($server)</font>");
  286:         return 'no_such_host';
  287:     }
  288:     my $answer=reply($cmd,$server);
  289:     if ($answer eq 'con_lost') {
  290: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  291: 	my $answer=reply($cmd,$server);
  292:         if ($answer eq 'con_lost') {
  293:             my $now=time;
  294:             my $middlename=$cmd;
  295:             $middlename=substr($middlename,0,16);
  296:             $middlename=~s/\W//g;
  297:             my $dfilename=
  298:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  299:             $dumpcount++;
  300:             {
  301: 		my $dfh;
  302: 		if (open($dfh,">$dfilename")) {
  303: 		    print $dfh "$cmd\n"; 
  304: 		    close($dfh);
  305: 		}
  306:             }
  307:             sleep 2;
  308:             my $wcmd='';
  309:             {
  310: 		my $dfh;
  311: 		if (open($dfh,"<$dfilename")) {
  312: 		    $wcmd=<$dfh>; 
  313: 		    close($dfh);
  314: 		}
  315:             }
  316:             chomp($wcmd);
  317:             if ($wcmd eq $cmd) {
  318: 		&logthis("<font color=\"blue\">WARNING: ".
  319:                          "Connection buffer $dfilename: $cmd</font>");
  320:                 &logperm("D:$server:$cmd");
  321: 	        return 'con_delayed';
  322:             } else {
  323:                 &logthis("<font color=\"red\">CRITICAL:"
  324:                         ." Critical connection failed: $server $cmd</font>");
  325:                 &logperm("F:$server:$cmd");
  326:                 return 'con_failed';
  327:             }
  328:         }
  329:     }
  330:     return $answer;
  331: }
  332: 
  333: # ------------------------------------------- check if return value is an error
  334: 
  335: sub error {
  336:     my ($result) = @_;
  337:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  338: 	if ($2 == 2) { return undef; }
  339: 	return $1;
  340:     }
  341:     return undef;
  342: }
  343: 
  344: sub convert_and_load_session_env {
  345:     my ($lonidsdir,$handle)=@_;
  346:     my @profile;
  347:     {
  348: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  349: 	if (!$opened) {
  350: 	    return 0;
  351: 	}
  352: 	flock($idf,LOCK_SH);
  353: 	@profile=<$idf>;
  354: 	close($idf);
  355:     }
  356:     my %temp_env;
  357:     foreach my $line (@profile) {
  358: 	if ($line !~ m/=/) {
  359: 	    return 0;
  360: 	}
  361: 	chomp($line);
  362: 	my ($envname,$envvalue)=split(/=/,$line,2);
  363: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  364:     }
  365:     unlink("$lonidsdir/$handle.id");
  366:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  367: 	    0640)) {
  368: 	%disk_env = %temp_env;
  369: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  370: 	untie(%disk_env);
  371:     }
  372:     return 1;
  373: }
  374: 
  375: # ------------------------------------------- Transfer profile into environment
  376: my $env_loaded;
  377: sub transfer_profile_to_env {
  378:     my ($lonidsdir,$handle,$force_transfer) = @_;
  379:     if (!$force_transfer && $env_loaded) { return; } 
  380: 
  381:     if (!defined($lonidsdir)) {
  382: 	$lonidsdir = $perlvar{'lonIDsDir'};
  383:     }
  384:     if (!defined($handle)) {
  385:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  386:     }
  387: 
  388:     my $convert;
  389:     {
  390:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  391: 	if (!$opened) {
  392: 	    return;
  393: 	}
  394: 	flock($idf,LOCK_SH);
  395: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  396: 		&GDBM_READER(),0640)) {
  397: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  398: 	    untie(%disk_env);
  399: 	} else {
  400: 	    $convert = 1;
  401: 	}
  402:     }
  403:     if ($convert) {
  404: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  405: 	    &logthis("Failed to load session, or convert session.");
  406: 	}
  407:     }
  408: 
  409:     my %remove;
  410:     while ( my $envname = each(%env) ) {
  411:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  412:             if ($time < time-300) {
  413:                 $remove{$key}++;
  414:             }
  415:         }
  416:     }
  417: 
  418:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  419:     $env_loaded=1;
  420:     foreach my $expired_key (keys(%remove)) {
  421:         &delenv($expired_key);
  422:     }
  423: }
  424: 
  425: # ---------------------------------------------------- Check for valid session 
  426: sub check_for_valid_session {
  427:     my ($r) = @_;
  428:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  429:     my $lonid=$cookies{'lonID'};
  430:     return undef if (!$lonid);
  431: 
  432:     my $handle=&LONCAPA::clean_handle($lonid->value);
  433:     my $lonidsdir=$r->dir_config('lonIDsDir');
  434:     return undef if (!-e "$lonidsdir/$handle.id");
  435: 
  436:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  437:     return undef if (!$opened);
  438: 
  439:     flock($idf,LOCK_SH);
  440:     my %disk_env;
  441:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  442: 	    &GDBM_READER(),0640)) {
  443: 	return undef;	
  444:     }
  445: 
  446:     if (!defined($disk_env{'user.name'})
  447: 	|| !defined($disk_env{'user.domain'})) {
  448: 	return undef;
  449:     }
  450:     return $handle;
  451: }
  452: 
  453: sub timed_flock {
  454:     my ($file,$lock_type) = @_;
  455:     my $failed=0;
  456:     eval {
  457: 	local $SIG{__DIE__}='DEFAULT';
  458: 	local $SIG{ALRM}=sub {
  459: 	    $failed=1;
  460: 	    die("failed lock");
  461: 	};
  462: 	alarm(13);
  463: 	flock($file,$lock_type);
  464: 	alarm(0);
  465:     };
  466:     if ($failed) {
  467: 	return undef;
  468:     } else {
  469: 	return 1;
  470:     }
  471: }
  472: 
  473: # ---------------------------------------------------------- Append Environment
  474: 
  475: sub appenv {
  476:     my ($newenv,$roles) = @_;
  477:     if (ref($newenv) eq 'HASH') {
  478:         foreach my $key (keys(%{$newenv})) {
  479:             my $refused = 0;
  480: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  481:                 $refused = 1;
  482:                 if (ref($roles) eq 'ARRAY') {
  483:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  484:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  485:                         $refused = 0;
  486:                     }
  487:                 }
  488:             }
  489:             if ($refused) {
  490:                 &logthis("<font color=\"blue\">WARNING: ".
  491:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  492:                          .'</font>');
  493: 	        delete($newenv->{$key});
  494:             } else {
  495:                 $env{$key}=$newenv->{$key};
  496:             }
  497:         }
  498:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  499:         if ($opened
  500: 	    && &timed_flock($env_file,LOCK_EX)
  501: 	    &&
  502: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  503: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  504: 	    while (my ($key,$value) = each(%{$newenv})) {
  505: 	        $disk_env{$key} = $value;
  506: 	    }
  507: 	    untie(%disk_env);
  508:         }
  509:     }
  510:     return 'ok';
  511: }
  512: # ----------------------------------------------------- Delete from Environment
  513: 
  514: sub delenv {
  515:     my $delthis=shift;
  516:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  517:         &logthis("<font color=\"blue\">WARNING: ".
  518:                 "Attempt to delete from environment ".$delthis);
  519:         return 'error';
  520:     }
  521:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  522:     if ($opened
  523: 	&& &timed_flock($env_file,LOCK_EX)
  524: 	&&
  525: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  526: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  527: 	foreach my $key (keys(%disk_env)) {
  528: 	    if ($key=~/^\Q$delthis\E/) { 
  529: 		delete($env{$key});
  530: 		delete($disk_env{$key});
  531: 	    }
  532: 	}
  533: 	untie(%disk_env);
  534:     }
  535:     return 'ok';
  536: }
  537: 
  538: sub get_env_multiple {
  539:     my ($name) = @_;
  540:     my @values;
  541:     if (defined($env{$name})) {
  542:         # exists is it an array
  543:         if (ref($env{$name})) {
  544:             @values=@{ $env{$name} };
  545:         } else {
  546:             $values[0]=$env{$name};
  547:         }
  548:     }
  549:     return(@values);
  550: }
  551: 
  552: # ------------------------------------------------------------------- Locking
  553: 
  554: sub set_lock {
  555:     my ($text)=@_;
  556:     $locknum++;
  557:     my $id=$$.'-'.$locknum;
  558:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  559:              'session.lock.'.$id => $text});
  560:     return $id;
  561: }
  562: 
  563: sub get_locks {
  564:     my $num=0;
  565:     my %texts=();
  566:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  567:        if ($lock=~/\w/) {
  568:           $num++;
  569:           $texts{$lock}=$env{'session.lock.'.$lock};
  570:        }
  571:    }
  572:    return ($num,%texts);
  573: }
  574: 
  575: sub remove_lock {
  576:     my ($id)=@_;
  577:     my $newlocks='';
  578:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  579:        if (($lock=~/\w/) && ($lock ne $id)) {
  580:           $newlocks.=','.$lock;
  581:        }
  582:     }
  583:     &appenv({'session.locks' => $newlocks});
  584:     &delenv('session.lock.'.$id);
  585: }
  586: 
  587: sub remove_all_locks {
  588:     my $activelocks=$env{'session.locks'};
  589:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  590:        if ($lock=~/\w/) {
  591:           &remove_lock($lock);
  592:        }
  593:     }
  594: }
  595: 
  596: 
  597: # ------------------------------------------ Find out current server userload
  598: sub userload {
  599:     my $numusers=0;
  600:     {
  601: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  602: 	my $filename;
  603: 	my $curtime=time;
  604: 	while ($filename=readdir(LONIDS)) {
  605: 	    next if ($filename eq '.' || $filename eq '..');
  606: 	    next if ($filename =~ /publicuser_\d+\.id/);
  607: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  608: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  609: 	}
  610: 	closedir(LONIDS);
  611:     }
  612:     my $userloadpercent=0;
  613:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  614:     if ($maxuserload) {
  615: 	$userloadpercent=100*$numusers/$maxuserload;
  616:     }
  617:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  618:     return $userloadpercent;
  619: }
  620: 
  621: # ------------------------------------------ Fight off request when overloaded
  622: 
  623: sub overloaderror {
  624:     my ($r,$checkserver)=@_;
  625:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  626:     my $loadavg;
  627:     if ($checkserver eq $perlvar{'lonHostID'}) {
  628:        open(my $loadfile,'/proc/loadavg');
  629:        $loadavg=<$loadfile>;
  630:        $loadavg =~ s/\s.*//g;
  631:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  632:        close($loadfile);
  633:     } else {
  634:        $loadavg=&reply('load',$checkserver);
  635:     }
  636:     my $overload=$loadavg-100;
  637:     if ($overload>0) {
  638: 	$r->err_headers_out->{'Retry-After'}=$overload;
  639:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  640:         return 413;
  641:     }    
  642:     return '';
  643: }
  644: 
  645: # ------------------------------ Find server with least workload from spare.tab
  646: 
  647: sub spareserver {
  648:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  649:     my $spare_server;
  650:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  651:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  652:                                                      :  $userloadpercent;
  653:     
  654:     foreach my $try_server (@{ $spareid{'primary'} }) {
  655: 	($spare_server, $lowest_load) =
  656: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  657:     }
  658: 
  659:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  660: 
  661:     if (!$found_server) {
  662: 	foreach my $try_server (@{ $spareid{'default'} }) {
  663: 	    ($spare_server, $lowest_load) =
  664: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  665: 	}
  666:     }
  667: 
  668:     if (!$want_server_name) {
  669:         my $protocol = 'http';
  670:         if ($protocol{$spare_server} eq 'https') {
  671:             $protocol = $protocol{$spare_server};
  672:         }
  673: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  674:     }
  675:     return $spare_server;
  676: }
  677: 
  678: sub compare_server_load {
  679:     my ($try_server, $spare_server, $lowest_load) = @_;
  680: 
  681:     my $loadans     = &reply('load',    $try_server);
  682:     my $userloadans = &reply('userload',$try_server);
  683: 
  684:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  685: 	next; #didn't get a number from the server
  686:     }
  687: 
  688:     my $load;
  689:     if ($loadans =~ /\d/) {
  690: 	if ($userloadans =~ /\d/) {
  691: 	    #both are numbers, pick the bigger one
  692: 	    $load = ($loadans > $userloadans) ? $loadans 
  693: 		                              : $userloadans;
  694: 	} else {
  695: 	    $load = $loadans;
  696: 	}
  697:     } else {
  698: 	$load = $userloadans;
  699:     }
  700: 
  701:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  702: 	$spare_server = $try_server;
  703: 	$lowest_load  = $load;
  704:     }
  705:     return ($spare_server,$lowest_load);
  706: }
  707: 
  708: # --------------------------- ask offload servers if user already has a session
  709: sub find_existing_session {
  710:     my ($udom,$uname) = @_;
  711:     foreach my $try_server (@{ $spareid{'primary'} },
  712: 			    @{ $spareid{'default'} }) {
  713: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  714:     }
  715:     return;
  716: }
  717: 
  718: # -------------------------------- ask if server already has a session for user
  719: sub has_user_session {
  720:     my ($lonid,$udom,$uname) = @_;
  721:     my $result = &reply(join(':','userhassession',
  722: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  723:     return 1 if ($result eq 'ok');
  724: 
  725:     return 0;
  726: }
  727: 
  728: # --------------------------------------------- Try to change a user's password
  729: 
  730: sub changepass {
  731:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  732:     $currentpass = &escape($currentpass);
  733:     $newpass     = &escape($newpass);
  734:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  735: 		       $server);
  736:     if (! $answer) {
  737: 	&logthis("No reply on password change request to $server ".
  738: 		 "by $uname in domain $udom.");
  739:     } elsif ($answer =~ "^ok") {
  740:         &logthis("$uname in $udom successfully changed their password ".
  741: 		 "on $server.");
  742:     } elsif ($answer =~ "^pwchange_failure") {
  743: 	&logthis("$uname in $udom was unable to change their password ".
  744: 		 "on $server.  The action was blocked by either lcpasswd ".
  745: 		 "or pwchange");
  746:     } elsif ($answer =~ "^non_authorized") {
  747:         &logthis("$uname in $udom did not get their password correct when ".
  748: 		 "attempting to change it on $server.");
  749:     } elsif ($answer =~ "^auth_mode_error") {
  750:         &logthis("$uname in $udom attempted to change their password despite ".
  751: 		 "not being locally or internally authenticated on $server.");
  752:     } elsif ($answer =~ "^unknown_user") {
  753:         &logthis("$uname in $udom attempted to change their password ".
  754: 		 "on $server but were unable to because $server is not ".
  755: 		 "their home server.");
  756:     } elsif ($answer =~ "^refused") {
  757: 	&logthis("$server refused to change $uname in $udom password because ".
  758: 		 "it was sent an unencrypted request to change the password.");
  759:     }
  760:     return $answer;
  761: }
  762: 
  763: # ----------------------- Try to determine user's current authentication scheme
  764: 
  765: sub queryauthenticate {
  766:     my ($uname,$udom)=@_;
  767:     my $uhome=&homeserver($uname,$udom);
  768:     if (!$uhome) {
  769: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  770: 	return 'no_host';
  771:     }
  772:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  773:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  774: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  775:     }
  776:     return $answer;
  777: }
  778: 
  779: # --------- Try to authenticate user from domain's lib servers (first this one)
  780: 
  781: sub authenticate {
  782:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  783:     $upass=&escape($upass);
  784:     $uname= &LONCAPA::clean_username($uname);
  785:     my $uhome=&homeserver($uname,$udom,1);
  786:     my $newhome;
  787:     if ((!$uhome) || ($uhome eq 'no_host')) {
  788: # Maybe the machine was offline and only re-appeared again recently?
  789:         &reconlonc();
  790: # One more
  791: 	$uhome=&homeserver($uname,$udom,1);
  792:         if (($uhome eq 'no_host') && $checkdefauth) {
  793:             if (defined(&domain($udom,'primary'))) {
  794:                 $newhome=&domain($udom,'primary');
  795:             }
  796:             if ($newhome ne '') {
  797:                 $uhome = $newhome;
  798:             }
  799:         }
  800: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  801: 	    &logthis("User $uname at $udom is unknown in authenticate");
  802: 	    return 'no_host';
  803:         }
  804:     }
  805:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  806:     if ($answer eq 'authorized') {
  807:         if ($newhome) {
  808:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  809:             return 'no_account_on_host'; 
  810:         } else {
  811:             &logthis("User $uname at $udom authorized by $uhome");
  812:             return $uhome;
  813:         }
  814:     }
  815:     if ($answer eq 'non_authorized') {
  816: 	&logthis("User $uname at $udom rejected by $uhome");
  817: 	return 'no_host'; 
  818:     }
  819:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  820:     return 'no_host';
  821: }
  822: 
  823: # ---------------------- Find the homebase for a user from domain's lib servers
  824: 
  825: my %homecache;
  826: sub homeserver {
  827:     my ($uname,$udom,$ignoreBadCache)=@_;
  828:     my $index="$uname:$udom";
  829: 
  830:     if (exists($homecache{$index})) { return $homecache{$index}; }
  831: 
  832:     my %servers = &get_servers($udom,'library');
  833:     foreach my $tryserver (keys(%servers)) {
  834:         next if ($ignoreBadCache ne 'true' && 
  835: 		 exists($badServerCache{$tryserver}));
  836: 
  837: 	my $answer=reply("home:$udom:$uname",$tryserver);
  838: 	if ($answer eq 'found') {
  839: 	    delete($badServerCache{$tryserver}); 
  840: 	    return $homecache{$index}=$tryserver;
  841: 	} elsif ($answer eq 'no_host') {
  842: 	    $badServerCache{$tryserver}=1;
  843: 	}
  844:     }    
  845:     return 'no_host';
  846: }
  847: 
  848: # ------------------------------------- Find the usernames behind a list of IDs
  849: 
  850: sub idget {
  851:     my ($udom,@ids)=@_;
  852:     my %returnhash=();
  853:     
  854:     my %servers = &get_servers($udom,'library');
  855:     foreach my $tryserver (keys(%servers)) {
  856: 	my $idlist=join('&',@ids);
  857: 	$idlist=~tr/A-Z/a-z/; 
  858: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  859: 	my @answer=();
  860: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  861: 	    @answer=split(/\&/,$reply);
  862: 	}                    ;
  863: 	my $i;
  864: 	for ($i=0;$i<=$#ids;$i++) {
  865: 	    if ($answer[$i]) {
  866: 		$returnhash{$ids[$i]}=$answer[$i];
  867: 	    } 
  868: 	}
  869:     } 
  870:     return %returnhash;
  871: }
  872: 
  873: # ------------------------------------- Find the IDs behind a list of usernames
  874: 
  875: sub idrget {
  876:     my ($udom,@unames)=@_;
  877:     my %returnhash=();
  878:     foreach my $uname (@unames) {
  879:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  880:     }
  881:     return %returnhash;
  882: }
  883: 
  884: # ------------------------------- Store away a list of names and associated IDs
  885: 
  886: sub idput {
  887:     my ($udom,%ids)=@_;
  888:     my %servers=();
  889:     foreach my $uname (keys(%ids)) {
  890: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  891:         my $uhom=&homeserver($uname,$udom);
  892:         if ($uhom ne 'no_host') {
  893:             my $id=&escape($ids{$uname});
  894:             $id=~tr/A-Z/a-z/;
  895:             my $esc_unam=&escape($uname);
  896: 	    if ($servers{$uhom}) {
  897: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  898:             } else {
  899:                 $servers{$uhom}=$id.'='.$esc_unam;
  900:             }
  901:         }
  902:     }
  903:     foreach my $server (keys(%servers)) {
  904:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  905:     }
  906: }
  907: 
  908: # ------------------------------------------- get items from domain db files   
  909: 
  910: sub get_dom {
  911:     my ($namespace,$storearr,$udom,$uhome)=@_;
  912:     my $items='';
  913:     foreach my $item (@$storearr) {
  914:         $items.=&escape($item).'&';
  915:     }
  916:     $items=~s/\&$//;
  917:     if (!$udom) {
  918:         $udom=$env{'user.domain'};
  919:         if (defined(&domain($udom,'primary'))) {
  920:             $uhome=&domain($udom,'primary');
  921:         } else {
  922:             undef($uhome);
  923:         }
  924:     } else {
  925:         if (!$uhome) {
  926:             if (defined(&domain($udom,'primary'))) {
  927:                 $uhome=&domain($udom,'primary');
  928:             }
  929:         }
  930:     }
  931:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  932:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  933:         my %returnhash;
  934:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  935:             return %returnhash;
  936:         }
  937:         my @pairs=split(/\&/,$rep);
  938:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  939:             return @pairs;
  940:         }
  941:         my $i=0;
  942:         foreach my $item (@$storearr) {
  943:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  944:             $i++;
  945:         }
  946:         return %returnhash;
  947:     } else {
  948:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  949:     }
  950: }
  951: 
  952: # -------------------------------------------- put items in domain db files 
  953: 
  954: sub put_dom {
  955:     my ($namespace,$storehash,$udom,$uhome)=@_;
  956:     if (!$udom) {
  957:         $udom=$env{'user.domain'};
  958:         if (defined(&domain($udom,'primary'))) {
  959:             $uhome=&domain($udom,'primary');
  960:         } else {
  961:             undef($uhome);
  962:         }
  963:     } else {
  964:         if (!$uhome) {
  965:             if (defined(&domain($udom,'primary'))) {
  966:                 $uhome=&domain($udom,'primary');
  967:             }
  968:         }
  969:     } 
  970:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  971:         my $items='';
  972:         foreach my $item (keys(%$storehash)) {
  973:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  974:         }
  975:         $items=~s/\&$//;
  976:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  977:     } else {
  978:         &logthis("put_dom failed - no homeserver and/or domain");
  979:     }
  980: }
  981: 
  982: sub retrieve_inst_usertypes {
  983:     my ($udom) = @_;
  984:     my (%returnhash,@order);
  985:     if (defined(&domain($udom,'primary'))) {
  986:         my $uhome=&domain($udom,'primary');
  987:         my $rep=&reply("inst_usertypes:$udom",$uhome);
  988:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
  989:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
  990:             return (\%returnhash,\@order);
  991:         }
  992:         my ($hashitems,$orderitems) = split(/:/,$rep); 
  993:         my @pairs=split(/\&/,$hashitems);
  994:         foreach my $item (@pairs) {
  995:             my ($key,$value)=split(/=/,$item,2);
  996:             $key = &unescape($key);
  997:             next if ($key =~ /^error: 2 /);
  998:             $returnhash{$key}=&thaw_unescape($value);
  999:         }
 1000:         my @esc_order = split(/\&/,$orderitems);
 1001:         foreach my $item (@esc_order) {
 1002:             push(@order,&unescape($item));
 1003:         }
 1004:     } else {
 1005:         &logthis("get_dom failed - no primary domain server for $udom");
 1006:     }
 1007:     return (\%returnhash,\@order);
 1008: }
 1009: 
 1010: sub is_domainimage {
 1011:     my ($url) = @_;
 1012:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1013:         if (&domain($1) ne '') {
 1014:             return '1';
 1015:         }
 1016:     }
 1017:     return;
 1018: }
 1019: 
 1020: sub inst_directory_query {
 1021:     my ($srch) = @_;
 1022:     my $udom = $srch->{'srchdomain'};
 1023:     my %results;
 1024:     my $homeserver = &domain($udom,'primary');
 1025:     my $outcome;
 1026:     if ($homeserver ne '') {
 1027: 	my $queryid=&reply("querysend:instdirsearch:".
 1028: 			   &escape($srch->{'srchby'}).':'.
 1029: 			   &escape($srch->{'srchterm'}).':'.
 1030: 			   &escape($srch->{'srchtype'}),$homeserver);
 1031: 	my $host=&hostname($homeserver);
 1032: 	if ($queryid !~/^\Q$host\E\_/) {
 1033: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1034: 	    return;
 1035: 	}
 1036: 	my $response = &get_query_reply($queryid);
 1037: 	my $maxtries = 5;
 1038: 	my $tries = 1;
 1039: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1040: 	    $response = &get_query_reply($queryid);
 1041: 	    $tries ++;
 1042: 	}
 1043: 
 1044:         if (!&error($response) && $response ne 'refused') {
 1045:             if ($response eq 'unavailable') {
 1046:                 $outcome = $response;
 1047:             } else {
 1048:                 $outcome = 'ok';
 1049:                 my @matches = split(/\n/,$response);
 1050:                 foreach my $match (@matches) {
 1051:                     my ($key,$value) = split(/=/,$match);
 1052:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1053:                 }
 1054:             }
 1055:         }
 1056:     }
 1057:     return ($outcome,%results);
 1058: }
 1059: 
 1060: sub usersearch {
 1061:     my ($srch) = @_;
 1062:     my $dom = $srch->{'srchdomain'};
 1063:     my %results;
 1064:     my %libserv = &all_library();
 1065:     my $query = 'usersearch';
 1066:     foreach my $tryserver (keys(%libserv)) {
 1067:         if (&host_domain($tryserver) eq $dom) {
 1068:             my $host=&hostname($tryserver);
 1069:             my $queryid=
 1070:                 &reply("querysend:".&escape($query).':'.
 1071:                        &escape($srch->{'srchby'}).':'.
 1072:                        &escape($srch->{'srchtype'}).':'.
 1073:                        &escape($srch->{'srchterm'}),$tryserver);
 1074:             if ($queryid !~/^\Q$host\E\_/) {
 1075:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1076:                 next;
 1077:             }
 1078:             my $reply = &get_query_reply($queryid);
 1079:             my $maxtries = 1;
 1080:             my $tries = 1;
 1081:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1082:                 $reply = &get_query_reply($queryid);
 1083:                 $tries ++;
 1084:             }
 1085:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1086:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1087:             } else {
 1088:                 my @matches;
 1089:                 if ($reply =~ /\n/) {
 1090:                     @matches = split(/\n/,$reply);
 1091:                 } else {
 1092:                     @matches = split(/\&/,$reply);
 1093:                 }
 1094:                 foreach my $match (@matches) {
 1095:                     my ($uname,$udom,%userhash);
 1096:                     foreach my $entry (split(/:/,$match)) {
 1097:                         my ($key,$value) =
 1098:                             map {&unescape($_);} split(/=/,$entry);
 1099:                         $userhash{$key} = $value;
 1100:                         if ($key eq 'username') {
 1101:                             $uname = $value;
 1102:                         } elsif ($key eq 'domain') {
 1103:                             $udom = $value;
 1104:                         }
 1105:                     }
 1106:                     $results{$uname.':'.$udom} = \%userhash;
 1107:                 }
 1108:             }
 1109:         }
 1110:     }
 1111:     return %results;
 1112: }
 1113: 
 1114: sub get_instuser {
 1115:     my ($udom,$uname,$id) = @_;
 1116:     my $homeserver = &domain($udom,'primary');
 1117:     my ($outcome,%results);
 1118:     if ($homeserver ne '') {
 1119:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1120:                            &escape($id).':'.&escape($udom),$homeserver);
 1121:         my $host=&hostname($homeserver);
 1122:         if ($queryid !~/^\Q$host\E\_/) {
 1123:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1124:             return;
 1125:         }
 1126:         my $response = &get_query_reply($queryid);
 1127:         my $maxtries = 5;
 1128:         my $tries = 1;
 1129:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1130:             $response = &get_query_reply($queryid);
 1131:             $tries ++;
 1132:         }
 1133:         if (!&error($response) && $response ne 'refused') {
 1134:             if ($response eq 'unavailable') {
 1135:                 $outcome = $response;
 1136:             } else {
 1137:                 $outcome = 'ok';
 1138:                 my @matches = split(/\n/,$response);
 1139:                 foreach my $match (@matches) {
 1140:                     my ($key,$value) = split(/=/,$match);
 1141:                     $results{&unescape($key)} = &thaw_unescape($value);
 1142:                 }
 1143:             }
 1144:         }
 1145:     }
 1146:     my %userinfo;
 1147:     if (ref($results{$uname}) eq 'HASH') {
 1148:         %userinfo = %{$results{$uname}};
 1149:     } 
 1150:     return ($outcome,%userinfo);
 1151: }
 1152: 
 1153: sub inst_rulecheck {
 1154:     my ($udom,$uname,$id,$item,$rules) = @_;
 1155:     my %returnhash;
 1156:     if ($udom ne '') {
 1157:         if (ref($rules) eq 'ARRAY') {
 1158:             @{$rules} = map {&escape($_);} (@{$rules});
 1159:             my $rulestr = join(':',@{$rules});
 1160:             my $homeserver=&domain($udom,'primary');
 1161:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1162:                 my $response;
 1163:                 if ($item eq 'username') {                
 1164:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1165:                                               ':'.&escape($uname).':'.$rulestr,
 1166:                                               $homeserver));
 1167:                 } elsif ($item eq 'id') {
 1168:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1169:                                               ':'.&escape($id).':'.$rulestr,
 1170:                                               $homeserver));
 1171:                 } elsif ($item eq 'selfcreate') {
 1172:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1173:                                                &escape($udom).':'.&escape($uname).
 1174:                                               ':'.$rulestr,$homeserver));
 1175:                 }
 1176:                 if ($response ne 'refused') {
 1177:                     my @pairs=split(/\&/,$response);
 1178:                     foreach my $item (@pairs) {
 1179:                         my ($key,$value)=split(/=/,$item,2);
 1180:                         $key = &unescape($key);
 1181:                         next if ($key =~ /^error: 2 /);
 1182:                         $returnhash{$key}=&thaw_unescape($value);
 1183:                     }
 1184:                 }
 1185:             }
 1186:         }
 1187:     }
 1188:     return %returnhash;
 1189: }
 1190: 
 1191: sub inst_userrules {
 1192:     my ($udom,$check) = @_;
 1193:     my (%ruleshash,@ruleorder);
 1194:     if ($udom ne '') {
 1195:         my $homeserver=&domain($udom,'primary');
 1196:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1197:             my $response;
 1198:             if ($check eq 'id') {
 1199:                 $response=&reply('instidrules:'.&escape($udom),
 1200:                                  $homeserver);
 1201:             } elsif ($check eq 'email') {
 1202:                 $response=&reply('instemailrules:'.&escape($udom),
 1203:                                  $homeserver);
 1204:             } else {
 1205:                 $response=&reply('instuserrules:'.&escape($udom),
 1206:                                  $homeserver);
 1207:             }
 1208:             if (($response ne 'refused') && ($response ne 'error') && 
 1209:                 ($response ne 'unknown_cmd') && 
 1210:                 ($response ne 'no_such_host')) {
 1211:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1212:                 my @pairs=split(/\&/,$hashitems);
 1213:                 foreach my $item (@pairs) {
 1214:                     my ($key,$value)=split(/=/,$item,2);
 1215:                     $key = &unescape($key);
 1216:                     next if ($key =~ /^error: 2 /);
 1217:                     $ruleshash{$key}=&thaw_unescape($value);
 1218:                 }
 1219:                 my @esc_order = split(/\&/,$orderitems);
 1220:                 foreach my $item (@esc_order) {
 1221:                     push(@ruleorder,&unescape($item));
 1222:                 }
 1223:             }
 1224:         }
 1225:     }
 1226:     return (\%ruleshash,\@ruleorder);
 1227: }
 1228: 
 1229: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1230: 
 1231: sub get_domain_defaults {
 1232:     my ($domain) = @_;
 1233:     my $cachetime = 60*60*24;
 1234:     my ($defauthtype,$defautharg,$deflang,%deftools);
 1235:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1236:     if (defined($cached)) {
 1237:         if (ref($result) eq 'HASH') {
 1238:             return %{$result};
 1239:         }
 1240:     }
 1241:     my %domdefaults;
 1242:     my %domconfig =
 1243:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
 1244:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1245:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1246:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1247:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1248:     } else {
 1249:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1250:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1251:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1252:     }
 1253:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1254:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1255:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1256:         } else {
 1257:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1258:         } 
 1259:         my @usertools = ('aboutme','blog','portfolio');
 1260:         foreach my $item (@usertools) {
 1261:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1262:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1263:             }
 1264:         }
 1265:     }
 1266:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1267:                                   $cachetime);
 1268:     return %domdefaults;
 1269: }
 1270: 
 1271: # --------------------------------------------------- Assign a key to a student
 1272: 
 1273: sub assign_access_key {
 1274: #
 1275: # a valid key looks like uname:udom#comments
 1276: # comments are being appended
 1277: #
 1278:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1279:     $kdom=
 1280:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1281:     $knum=
 1282:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1283:     $cdom=
 1284:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1285:     $cnum=
 1286:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1287:     $udom=$env{'user.name'} unless (defined($udom));
 1288:     $uname=$env{'user.domain'} unless (defined($uname));
 1289:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1290:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1291:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1292:                                                   # assigned to this person
 1293:                                                   # - this should not happen,
 1294:                                                   # unless something went wrong
 1295:                                                   # the first time around
 1296: # ready to assign
 1297:         $logentry=$1.'; '.$logentry;
 1298:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1299:                                                  $kdom,$knum) eq 'ok') {
 1300: # key now belongs to user
 1301: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1302:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1303:                 &appenv({'environment.'.$envkey => $ckey});
 1304:                 return 'ok';
 1305:             } else {
 1306:                 return 
 1307:   'error: Count not permanently assign key, will need to be re-entered later.';
 1308: 	    }
 1309:         } else {
 1310:             return 'error: Could not assign key, try again later.';
 1311:         }
 1312:     } elsif (!$existing{$ckey}) {
 1313: # the key does not exist
 1314: 	return 'error: The key does not exist';
 1315:     } else {
 1316: # the key is somebody else's
 1317: 	return 'error: The key is already in use';
 1318:     }
 1319: }
 1320: 
 1321: # ------------------------------------------ put an additional comment on a key
 1322: 
 1323: sub comment_access_key {
 1324: #
 1325: # a valid key looks like uname:udom#comments
 1326: # comments are being appended
 1327: #
 1328:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1329:     $cdom=
 1330:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1331:     $cnum=
 1332:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1333:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1334:     if ($existing{$ckey}) {
 1335:         $existing{$ckey}.='; '.$logentry;
 1336: # ready to assign
 1337:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1338:                                                  $cdom,$cnum) eq 'ok') {
 1339: 	    return 'ok';
 1340:         } else {
 1341: 	    return 'error: Count not store comment.';
 1342:         }
 1343:     } else {
 1344: # the key does not exist
 1345: 	return 'error: The key does not exist';
 1346:     }
 1347: }
 1348: 
 1349: # ------------------------------------------------------ Generate a set of keys
 1350: 
 1351: sub generate_access_keys {
 1352:     my ($number,$cdom,$cnum,$logentry)=@_;
 1353:     $cdom=
 1354:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1355:     $cnum=
 1356:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1357:     unless (&allowed('mky',$cdom)) { return 0; }
 1358:     unless (($cdom) && ($cnum)) { return 0; }
 1359:     if ($number>10000) { return 0; }
 1360:     sleep(2); # make sure don't get same seed twice
 1361:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1362:     my $total=0;
 1363:     for (my $i=1;$i<=$number;$i++) {
 1364:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1365:                   sprintf("%lx",int(100000*rand)).'-'.
 1366:                   sprintf("%lx",int(100000*rand));
 1367:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1368:        $newkey=~s/0/h/g; # and also 0 and O
 1369:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1370:        if ($existing{$newkey}) {
 1371:            $i--;
 1372:        } else {
 1373: 	  if (&put('accesskeys',
 1374:               { $newkey => '# generated '.localtime().
 1375:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1376:                            '; '.$logentry },
 1377: 		   $cdom,$cnum) eq 'ok') {
 1378:               $total++;
 1379: 	  }
 1380:        }
 1381:     }
 1382:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1383:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1384:     return $total;
 1385: }
 1386: 
 1387: # ------------------------------------------------------- Validate an accesskey
 1388: 
 1389: sub validate_access_key {
 1390:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1391:     $cdom=
 1392:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1393:     $cnum=
 1394:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1395:     $udom=$env{'user.domain'} unless (defined($udom));
 1396:     $uname=$env{'user.name'} unless (defined($uname));
 1397:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1398:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1399: }
 1400: 
 1401: # ------------------------------------- Find the section of student in a course
 1402: sub devalidate_getsection_cache {
 1403:     my ($udom,$unam,$courseid)=@_;
 1404:     my $hashid="$udom:$unam:$courseid";
 1405:     &devalidate_cache_new('getsection',$hashid);
 1406: }
 1407: 
 1408: sub courseid_to_courseurl {
 1409:     my ($courseid) = @_;
 1410:     #already url style courseid
 1411:     return $courseid if ($courseid =~ m{^/});
 1412: 
 1413:     if (exists($env{'course.'.$courseid.'.num'})) {
 1414: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1415: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1416: 	return "/$cdom/$cnum";
 1417:     }
 1418: 
 1419:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1420:     if (exists($courseinfo{'num'})) {
 1421: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1422:     }
 1423: 
 1424:     return undef;
 1425: }
 1426: 
 1427: sub getsection {
 1428:     my ($udom,$unam,$courseid)=@_;
 1429:     my $cachetime=1800;
 1430: 
 1431:     my $hashid="$udom:$unam:$courseid";
 1432:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1433:     if (defined($cached)) { return $result; }
 1434: 
 1435:     my %Pending; 
 1436:     my %Expired;
 1437:     #
 1438:     # Each role can either have not started yet (pending), be active, 
 1439:     #    or have expired.
 1440:     #
 1441:     # If there is an active role, we are done.
 1442:     #
 1443:     # If there is more than one role which has not started yet, 
 1444:     #     choose the one which will start sooner
 1445:     # If there is one role which has not started yet, return it.
 1446:     #
 1447:     # If there is more than one expired role, choose the one which ended last.
 1448:     # If there is a role which has expired, return it.
 1449:     #
 1450:     $courseid = &courseid_to_courseurl($courseid);
 1451:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1452:     foreach my $key (keys(%roleshash)) {
 1453:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1454:         my $section=$1;
 1455:         if ($key eq $courseid.'_st') { $section=''; }
 1456:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1457:         my $now=time;
 1458:         if (defined($end) && $end && ($now > $end)) {
 1459:             $Expired{$end}=$section;
 1460:             next;
 1461:         }
 1462:         if (defined($start) && $start && ($now < $start)) {
 1463:             $Pending{$start}=$section;
 1464:             next;
 1465:         }
 1466:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1467:     }
 1468:     #
 1469:     # Presumedly there will be few matching roles from the above
 1470:     # loop and the sorting time will be negligible.
 1471:     if (scalar(keys(%Pending))) {
 1472:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1473:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1474:     } 
 1475:     if (scalar(keys(%Expired))) {
 1476:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1477:         my $time = pop(@sorted);
 1478:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1479:     }
 1480:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1481: }
 1482: 
 1483: sub save_cache {
 1484:     &purge_remembered();
 1485:     #&Apache::loncommon::validate_page();
 1486:     undef(%env);
 1487:     undef($env_loaded);
 1488: }
 1489: 
 1490: my $to_remember=-1;
 1491: my %remembered;
 1492: my %accessed;
 1493: my $kicks=0;
 1494: my $hits=0;
 1495: sub make_key {
 1496:     my ($name,$id) = @_;
 1497:     if (length($id) > 65 
 1498: 	&& length(&escape($id)) > 200) {
 1499: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1500:     }
 1501:     return &escape($name.':'.$id);
 1502: }
 1503: 
 1504: sub devalidate_cache_new {
 1505:     my ($name,$id,$debug) = @_;
 1506:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1507:     $id=&make_key($name,$id);
 1508:     $memcache->delete($id);
 1509:     delete($remembered{$id});
 1510:     delete($accessed{$id});
 1511: }
 1512: 
 1513: sub is_cached_new {
 1514:     my ($name,$id,$debug) = @_;
 1515:     $id=&make_key($name,$id);
 1516:     if (exists($remembered{$id})) {
 1517: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1518: 	$accessed{$id}=[&gettimeofday()];
 1519: 	$hits++;
 1520: 	return ($remembered{$id},1);
 1521:     }
 1522:     my $value = $memcache->get($id);
 1523:     if (!(defined($value))) {
 1524: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1525: 	return (undef,undef);
 1526:     }
 1527:     if ($value eq '__undef__') {
 1528: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1529: 	$value=undef;
 1530:     }
 1531:     &make_room($id,$value,$debug);
 1532:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1533:     return ($value,1);
 1534: }
 1535: 
 1536: sub do_cache_new {
 1537:     my ($name,$id,$value,$time,$debug) = @_;
 1538:     $id=&make_key($name,$id);
 1539:     my $setvalue=$value;
 1540:     if (!defined($setvalue)) {
 1541: 	$setvalue='__undef__';
 1542:     }
 1543:     if (!defined($time) ) {
 1544: 	$time=600;
 1545:     }
 1546:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1547:     my $result = $memcache->set($id,$setvalue,$time);
 1548:     if (! $result) {
 1549: 	&logthis("caching of id -> $id  failed");
 1550: 	$memcache->disconnect_all();
 1551:     }
 1552:     # need to make a copy of $value
 1553:     &make_room($id,$value,$debug);
 1554:     return $value;
 1555: }
 1556: 
 1557: sub make_room {
 1558:     my ($id,$value,$debug)=@_;
 1559: 
 1560:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1561:                                     : $value;
 1562:     if ($to_remember<0) { return; }
 1563:     $accessed{$id}=[&gettimeofday()];
 1564:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1565:     my $to_kick;
 1566:     my $max_time=0;
 1567:     foreach my $other (keys(%accessed)) {
 1568: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1569: 	    $to_kick=$other;
 1570: 	    $max_time=&tv_interval($accessed{$other});
 1571: 	}
 1572:     }
 1573:     delete($remembered{$to_kick});
 1574:     delete($accessed{$to_kick});
 1575:     $kicks++;
 1576:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1577:     return;
 1578: }
 1579: 
 1580: sub purge_remembered {
 1581:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1582:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1583:     undef(%remembered);
 1584:     undef(%accessed);
 1585: }
 1586: # ------------------------------------- Read an entry from a user's environment
 1587: 
 1588: sub userenvironment {
 1589:     my ($udom,$unam,@what)=@_;
 1590:     my $items;
 1591:     foreach my $item (@what) {
 1592:         $items.=&escape($item).'&';
 1593:     }
 1594:     $items=~s/\&$//;
 1595:     my %returnhash=();
 1596:     my @answer=split(/\&/,
 1597:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1598:                       &homeserver($unam,$udom)));
 1599:     my $i;
 1600:     for ($i=0;$i<=$#what;$i++) {
 1601: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1602:     }
 1603:     return %returnhash;
 1604: }
 1605: 
 1606: # ---------------------------------------------------------- Get a studentphoto
 1607: sub studentphoto {
 1608:     my ($udom,$unam,$ext) = @_;
 1609:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1610:     if (defined($env{'request.course.id'})) {
 1611:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1612:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1613:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1614:             } else {
 1615:                 my ($result,$perm_reqd)=
 1616: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1617:                 if ($result eq 'ok') {
 1618:                     if (!($perm_reqd eq 'yes')) {
 1619:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1620:                     }
 1621:                 }
 1622:             }
 1623:         }
 1624:     } else {
 1625:         my ($result,$perm_reqd) = 
 1626: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1627:         if ($result eq 'ok') {
 1628:             if (!($perm_reqd eq 'yes')) {
 1629:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1630:             }
 1631:         }
 1632:     }
 1633:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1634: }
 1635: 
 1636: sub retrievestudentphoto {
 1637:     my ($udom,$unam,$ext,$type) = @_;
 1638:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1639:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1640:     if ($ret eq 'ok') {
 1641:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1642:         if ($type eq 'thumbnail') {
 1643:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1644:         }
 1645:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1646:         return $tokenurl;
 1647:     } else {
 1648:         if ($type eq 'thumbnail') {
 1649:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1650:         } else { 
 1651:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1652:         }
 1653:     }
 1654: }
 1655: 
 1656: # -------------------------------------------------------------------- New chat
 1657: 
 1658: sub chatsend {
 1659:     my ($newentry,$anon,$group)=@_;
 1660:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1661:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1662:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1663:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1664: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1665: 		   &escape($newentry)).':'.$group,$chome);
 1666: }
 1667: 
 1668: # ------------------------------------------ Find current version of a resource
 1669: 
 1670: sub getversion {
 1671:     my $fname=&clutter(shift);
 1672:     unless ($fname=~/^\/res\//) { return -1; }
 1673:     return &currentversion(&filelocation('',$fname));
 1674: }
 1675: 
 1676: sub currentversion {
 1677:     my $fname=shift;
 1678:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1679:     if (defined($cached)) { return $result; }
 1680:     my $author=$fname;
 1681:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1682:     my ($udom,$uname)=split(/\//,$author);
 1683:     my $home=homeserver($uname,$udom);
 1684:     if ($home eq 'no_host') { 
 1685:         return -1; 
 1686:     }
 1687:     my $answer=reply("currentversion:$fname",$home);
 1688:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1689: 	return -1;
 1690:     }
 1691:     return &do_cache_new('resversion',$fname,$answer,600);
 1692: }
 1693: 
 1694: # ----------------------------- Subscribe to a resource, return URL if possible
 1695: 
 1696: sub subscribe {
 1697:     my $fname=shift;
 1698:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1699:     $fname=~s/[\n\r]//g;
 1700:     my $author=$fname;
 1701:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1702:     my ($udom,$uname)=split(/\//,$author);
 1703:     my $home=homeserver($uname,$udom);
 1704:     if ($home eq 'no_host') {
 1705:         return 'not_found';
 1706:     }
 1707:     my $answer=reply("sub:$fname",$home);
 1708:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1709: 	$answer.=' by '.$home;
 1710:     }
 1711:     return $answer;
 1712: }
 1713:     
 1714: # -------------------------------------------------------------- Replicate file
 1715: 
 1716: sub repcopy {
 1717:     my $filename=shift;
 1718:     $filename=~s/\/+/\//g;
 1719:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1720:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1721:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1722: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1723: 	return &repcopy_userfile($filename);
 1724:     }
 1725:     $filename=~s/[\n\r]//g;
 1726:     my $transname="$filename.in.transfer";
 1727: # FIXME: this should flock
 1728:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1729:     my $remoteurl=subscribe($filename);
 1730:     if ($remoteurl =~ /^con_lost by/) {
 1731: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1732:            return 'unavailable';
 1733:     } elsif ($remoteurl eq 'not_found') {
 1734: 	   #&logthis("Subscribe returned not_found: $filename");
 1735: 	   return 'not_found';
 1736:     } elsif ($remoteurl =~ /^rejected by/) {
 1737: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1738:            return 'forbidden';
 1739:     } elsif ($remoteurl eq 'directory') {
 1740:            return 'ok';
 1741:     } else {
 1742:         my $author=$filename;
 1743:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1744:         my ($udom,$uname)=split(/\//,$author);
 1745:         my $home=homeserver($uname,$udom);
 1746:         unless ($home eq $perlvar{'lonHostID'}) {
 1747:            my @parts=split(/\//,$filename);
 1748:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1749:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1750:                &logthis("Malconfiguration for replication: $filename");
 1751: 	       return 'bad_request';
 1752:            }
 1753:            my $count;
 1754:            for ($count=5;$count<$#parts;$count++) {
 1755:                $path.="/$parts[$count]";
 1756:                if ((-e $path)!=1) {
 1757: 		   mkdir($path,0777);
 1758:                }
 1759:            }
 1760:            my $ua=new LWP::UserAgent;
 1761:            my $request=new HTTP::Request('GET',"$remoteurl");
 1762:            my $response=$ua->request($request,$transname);
 1763:            if ($response->is_error()) {
 1764: 	       unlink($transname);
 1765:                my $message=$response->status_line;
 1766:                &logthis("<font color=\"blue\">WARNING:"
 1767:                        ." LWP get: $message: $filename</font>");
 1768:                return 'unavailable';
 1769:            } else {
 1770: 	       if ($remoteurl!~/\.meta$/) {
 1771:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1772:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1773:                   if ($mresponse->is_error()) {
 1774: 		      unlink($filename.'.meta');
 1775:                       &logthis(
 1776:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1777:                   }
 1778: 	       }
 1779:                rename($transname,$filename);
 1780:                return 'ok';
 1781:            }
 1782:        }
 1783:     }
 1784: }
 1785: 
 1786: # ------------------------------------------------ Get server side include body
 1787: sub ssi_body {
 1788:     my ($filelink,%form)=@_;
 1789:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1790:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1791:     }
 1792:     my $output='';
 1793:     my $response;
 1794:     if ($filelink=~/^https?\:/) {
 1795:        ($output,$response)=&externalssi($filelink);
 1796:     } else {
 1797:        ($output,$response)=&ssi($filelink,%form);
 1798:     }
 1799:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1800:     $output=~s/^.*?\<body[^\>]*\>//si;
 1801:     $output=~s/\<\/body\s*\>.*?$//si;
 1802:     if (wantarray) {
 1803:         return ($output, $response);
 1804:     } else {
 1805:         return $output;
 1806:     }
 1807: }
 1808: 
 1809: # --------------------------------------------------------- Server Side Include
 1810: 
 1811: sub absolute_url {
 1812:     my ($host_name) = @_;
 1813:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1814:     if ($host_name eq '') {
 1815: 	$host_name = $ENV{'SERVER_NAME'};
 1816:     }
 1817:     return $protocol.$host_name;
 1818: }
 1819: 
 1820: #
 1821: #   Server side include.
 1822: # Parameters:
 1823: #  fn     Possibly encrypted resource name/id.
 1824: #  form   Hash that describes how the rendering should be done
 1825: #         and other things.
 1826: # Returns:
 1827: #   Scalar context: The content of the response.
 1828: #   Array context:  2 element list of the content and the full response object.
 1829: #     
 1830: sub ssi {
 1831: 
 1832:     my ($fn,%form)=@_;
 1833:     my $ua=new LWP::UserAgent;
 1834:     my $request;
 1835: 
 1836:     $form{'no_update_last_known'}=1;
 1837:     &Apache::lonenc::check_encrypt(\$fn);
 1838:     if (%form) {
 1839:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1840:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1841:     } else {
 1842:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1843:     }
 1844: 
 1845:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1846:     my $response=$ua->request($request);
 1847: 
 1848:     if (wantarray) {
 1849: 	return ($response->content, $response);
 1850:     } else {
 1851: 	return $response->content;
 1852:     }
 1853: }
 1854: 
 1855: sub externalssi {
 1856:     my ($url)=@_;
 1857:     my $ua=new LWP::UserAgent;
 1858:     my $request=new HTTP::Request('GET',$url);
 1859:     my $response=$ua->request($request);
 1860:     if (wantarray) {
 1861:         return ($response->content, $response);
 1862:     } else {
 1863:         return $response->content;
 1864:     }
 1865: }
 1866: 
 1867: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1868: 
 1869: sub allowuploaded {
 1870:     my ($srcurl,$url)=@_;
 1871:     $url=&clutter(&declutter($url));
 1872:     my $dir=$url;
 1873:     $dir=~s/\/[^\/]+$//;
 1874:     my %httpref=();
 1875:     my $httpurl=&hreflocation('',$url);
 1876:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1877:     &Apache::lonnet::appenv(\%httpref);
 1878: }
 1879: 
 1880: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1881: # input: action, courseID, current domain, intended
 1882: #        path to file, source of file, instruction to parse file for objects,
 1883: #        ref to hash for embedded objects,
 1884: #        ref to hash for codebase of java objects.
 1885: #
 1886: # output: url to file (if action was uploaddoc), 
 1887: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1888: #
 1889: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1890: # course.
 1891: #
 1892: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1893: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1894: #          course's home server.
 1895: #
 1896: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1897: #          be copied from $source (current location) to 
 1898: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1899: #         and will then be copied to
 1900: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1901: #         course's home server.
 1902: #
 1903: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1904: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1905: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1906: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1907: #         in course's home server.
 1908: #
 1909: 
 1910: sub process_coursefile {
 1911:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1912:     my $fetchresult;
 1913:     my $home=&homeserver($docuname,$docudom);
 1914:     if ($action eq 'propagate') {
 1915:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1916: 			     $home);
 1917:     } else {
 1918:         my $fpath = '';
 1919:         my $fname = $file;
 1920:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1921:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1922:         my $filepath = &build_filepath($fpath);
 1923:         if ($action eq 'copy') {
 1924:             if ($source eq '') {
 1925:                 $fetchresult = 'no source file';
 1926:                 return $fetchresult;
 1927:             } else {
 1928:                 my $destination = $filepath.'/'.$fname;
 1929:                 rename($source,$destination);
 1930:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1931:                                  $home);
 1932:             }
 1933:         } elsif ($action eq 'uploaddoc') {
 1934:             open(my $fh,'>'.$filepath.'/'.$fname);
 1935:             print $fh $env{'form.'.$source};
 1936:             close($fh);
 1937:             if ($parser eq 'parse') {
 1938:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1939:                 unless ($parse_result eq 'ok') {
 1940:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1941:                 }
 1942:             }
 1943:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1944:                                  $home);
 1945:             if ($fetchresult eq 'ok') {
 1946:                 return '/uploaded/'.$fpath.'/'.$fname;
 1947:             } else {
 1948:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1949:                         ' to host '.$home.': '.$fetchresult);
 1950:                 return '/adm/notfound.html';
 1951:             }
 1952:         }
 1953:     }
 1954:     unless ( $fetchresult eq 'ok') {
 1955:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1956:              ' to host '.$home.': '.$fetchresult);
 1957:     }
 1958:     return $fetchresult;
 1959: }
 1960: 
 1961: sub build_filepath {
 1962:     my ($fpath) = @_;
 1963:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1964:     unless ($fpath eq '') {
 1965:         my @parts=split('/',$fpath);
 1966:         foreach my $part (@parts) {
 1967:             $filepath.= '/'.$part;
 1968:             if ((-e $filepath)!=1) {
 1969:                 mkdir($filepath,0777);
 1970:             }
 1971:         }
 1972:     }
 1973:     return $filepath;
 1974: }
 1975: 
 1976: sub store_edited_file {
 1977:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1978:     my $file = $primary_url;
 1979:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1980:     my $fpath = '';
 1981:     my $fname = $file;
 1982:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1983:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1984:     my $filepath = &build_filepath($fpath);
 1985:     open(my $fh,'>'.$filepath.'/'.$fname);
 1986:     print $fh $content;
 1987:     close($fh);
 1988:     my $home=&homeserver($docuname,$docudom);
 1989:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1990: 			  $home);
 1991:     if ($$fetchresult eq 'ok') {
 1992:         return '/uploaded/'.$fpath.'/'.$fname;
 1993:     } else {
 1994:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1995: 		 ' to host '.$home.': '.$$fetchresult);
 1996:         return '/adm/notfound.html';
 1997:     }
 1998: }
 1999: 
 2000: sub clean_filename {
 2001:     my ($fname,$args)=@_;
 2002: # Replace Windows backslashes by forward slashes
 2003:     $fname=~s/\\/\//g;
 2004:     if (!$args->{'keep_path'}) {
 2005:         # Get rid of everything but the actual filename
 2006: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2007:     }
 2008: # Replace spaces by underscores
 2009:     $fname=~s/\s+/\_/g;
 2010: # Replace all other weird characters by nothing
 2011:     $fname=~s{[^/\w\.\-]}{}g;
 2012: # Replace all .\d. sequences with _\d. so they no longer look like version
 2013: # numbers
 2014:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2015:     return $fname;
 2016: }
 2017: 
 2018: #Wrapper function for userphotoupload
 2019: sub userphotoupload
 2020: {
 2021: 	my($formname,$subdir) = @_;
 2022: 	$upload_photo_form = 1;
 2023: 	return &userfileupload($formname,undef,$subdir);
 2024: }
 2025: 
 2026: # --------------- Take an uploaded file and put it into the userfiles directory
 2027: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2028: #                    the desired filenam is in $env{"form.$formname.filename"}
 2029: #        $coursedoc - if true up to the current course
 2030: #                     if false
 2031: #        $subdir - directory in userfile to store the file into
 2032: #        $parser - instruction to parse file for objects ($parser = parse)    
 2033: #        $allfiles - reference to hash for embedded objects
 2034: #        $codebase - reference to hash for codebase of java objects
 2035: #        $desuname - username for permanent storage of uploaded file
 2036: #        $dsetudom - domain for permanaent storage of uploaded file
 2037: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2038: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2039: # 
 2040: # output: url of file in userspace, or error: <message> 
 2041: #             or /adm/notfound.html if failure to upload occurse
 2042: 
 2043: 
 2044: sub userfileupload {
 2045:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2046:         $destudom,$thumbwidth,$thumbheight)=@_;
 2047:     if (!defined($subdir)) { $subdir='unknown'; }
 2048:     my $fname=$env{'form.'.$formname.'.filename'};
 2049:     $fname=&clean_filename($fname);
 2050: # See if there is anything left
 2051:     unless ($fname) { return 'error: no uploaded file'; }
 2052:     chop($env{'form.'.$formname});
 2053:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2054:         my $now = time;
 2055:         my $filepath = 'tmp/helprequests/'.$now;
 2056:         my @parts=split(/\//,$filepath);
 2057:         my $fullpath = $perlvar{'lonDaemons'};
 2058:         for (my $i=0;$i<@parts;$i++) {
 2059:             $fullpath .= '/'.$parts[$i];
 2060:             if ((-e $fullpath)!=1) {
 2061:                 mkdir($fullpath,0777);
 2062:             }
 2063:         }
 2064:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2065:         print $fh $env{'form.'.$formname};
 2066:         close($fh);
 2067:         return $fullpath.'/'.$fname;
 2068:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2069:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2070:                        '_'.$env{'user.domain'}.'/pending';
 2071:         my @parts=split(/\//,$filepath);
 2072:         my $fullpath = $perlvar{'lonDaemons'};
 2073:         for (my $i=0;$i<@parts;$i++) {
 2074:             $fullpath .= '/'.$parts[$i];
 2075:             if ((-e $fullpath)!=1) {
 2076:                 mkdir($fullpath,0777);
 2077:             }
 2078:         }
 2079:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2080:         print $fh $env{'form.'.$formname};
 2081:         close($fh);
 2082:         return $fullpath.'/'.$fname;
 2083:     }
 2084:     
 2085: # Create the directory if not present
 2086:     $fname="$subdir/$fname";
 2087:     if ($coursedoc) {
 2088: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2089: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2090:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2091:             return &finishuserfileupload($docuname,$docudom,
 2092: 					 $formname,$fname,$parser,$allfiles,
 2093: 					 $codebase,$thumbwidth,$thumbheight);
 2094:         } else {
 2095:             $fname=$env{'form.folder'}.'/'.$fname;
 2096:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2097: 				       $fname,$formname,$parser,
 2098: 				       $allfiles,$codebase);
 2099:         }
 2100:     } elsif (defined($destuname)) {
 2101:         my $docuname=$destuname;
 2102:         my $docudom=$destudom;
 2103: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2104: 				     $parser,$allfiles,$codebase,
 2105:                                      $thumbwidth,$thumbheight);
 2106:         
 2107:     } else {
 2108:         my $docuname=$env{'user.name'};
 2109:         my $docudom=$env{'user.domain'};
 2110:         if (exists($env{'form.group'})) {
 2111:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2112:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2113:         }
 2114: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2115: 				     $parser,$allfiles,$codebase,
 2116:                                      $thumbwidth,$thumbheight);
 2117:     }
 2118: }
 2119: 
 2120: sub finishuserfileupload {
 2121:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2122:         $thumbwidth,$thumbheight) = @_;
 2123:     my $path=$docudom.'/'.$docuname.'/';
 2124:     my $filepath=$perlvar{'lonDocRoot'};
 2125:     my ($fnamepath,$file,$fetchthumb);
 2126:     $file=$fname;
 2127:     if ($fname=~m|/|) {
 2128:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2129: 	$path.=$fnamepath.'/';
 2130:     }
 2131:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2132:     my $count;
 2133:     for ($count=4;$count<=$#parts;$count++) {
 2134:         $filepath.="/$parts[$count]";
 2135:         if ((-e $filepath)!=1) {
 2136: 	    mkdir($filepath,0777);
 2137:         }
 2138:     }
 2139: # Save the file
 2140:     {
 2141: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2142: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2143: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2144: 	    return '/adm/notfound.html';
 2145: 	}
 2146: 	if (!print FH ($env{'form.'.$formname})) {
 2147: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2148: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2149: 	    return '/adm/notfound.html';
 2150: 	}
 2151: 	close(FH);
 2152: 	if($upload_photo_form==1)
 2153: 	{
 2154: 		my $ima = Image::Magick->new;                       
 2155:             	$ima->Read($filepath.'/'.$file);
 2156: 		if($ima->Get('width') > 300)
 2157: 		{
 2158: 			my $factor = $ima->Get('width')/300;
 2159:              		$ima->Scale( width=>300, height=>$ima->Get('height')/$factor );
 2160: 		}
 2161: 		if($ima->Get('height') > 400)
 2162:                 {
 2163:                         my $factor = $ima->Get('height')/400;
 2164:                         $ima->Scale( width=>$ima->Get('width')/$factor, height=>400);
 2165:                 }
 2166:  
 2167: 		
 2168: 		$ima->Write($filepath.'/'.$file);
 2169: 		$upload_photo_form = 0;
 2170: 	}
 2171:     }
 2172:     if ($parser eq 'parse') {
 2173:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2174: 						   $codebase);
 2175:         unless ($parse_result eq 'ok') {
 2176:             &logthis('Failed to parse '.$filepath.$file.
 2177: 		     ' for embedded media: '.$parse_result); 
 2178:         }
 2179:     }
 2180:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2181:         my $input = $filepath.'/'.$file;
 2182:         my $output = $filepath.'/'.'tn-'.$file;
 2183:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2184:         system("convert -sample $thumbsize $input $output");
 2185:         if (-e $filepath.'/'.'tn-'.$file) {
 2186:             $fetchthumb  = 1; 
 2187:         }
 2188:     }
 2189:  
 2190: # Notify homeserver to grep it
 2191: #
 2192:     my $docuhome=&homeserver($docuname,$docudom);
 2193:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2194:     if ($fetchresult eq 'ok') {
 2195:         if ($fetchthumb) {
 2196:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2197:             if ($thumbresult ne 'ok') {
 2198:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2199:                          $docuhome.': '.$thumbresult);
 2200:             }
 2201:         }
 2202: #
 2203: # Return the URL to it
 2204:         return '/uploaded/'.$path.$file;
 2205:     } else {
 2206:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2207: 		 ': '.$fetchresult);
 2208:         return '/adm/notfound.html';
 2209:     }
 2210: }
 2211: 
 2212: sub extract_embedded_items {
 2213:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2214:     my @state = ();
 2215:     my %javafiles = (
 2216:                       codebase => '',
 2217:                       code => '',
 2218:                       archive => ''
 2219:                     );
 2220:     my %mediafiles = (
 2221:                       src => '',
 2222:                       movie => '',
 2223:                      );
 2224:     my $p;
 2225:     if ($content) {
 2226:         $p = HTML::LCParser->new($content);
 2227:     } else {
 2228:         $p = HTML::LCParser->new($fullpath);
 2229:     }
 2230:     while (my $t=$p->get_token()) {
 2231: 	if ($t->[0] eq 'S') {
 2232: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2233: 	    push(@state, $tagname);
 2234:             if (lc($tagname) eq 'allow') {
 2235:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2236:             }
 2237: 	    if (lc($tagname) eq 'img') {
 2238: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2239: 	    }
 2240: 	    if (lc($tagname) eq 'a') {
 2241: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2242: 	    }
 2243:             if (lc($tagname) eq 'script') {
 2244:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2245:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2246:                 } else {
 2247:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2248:                 }
 2249:             }
 2250:             if (lc($tagname) eq 'link') {
 2251:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2252:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2253:                 }
 2254:             }
 2255: 	    if (lc($tagname) eq 'object' ||
 2256: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2257: 		foreach my $item (keys(%javafiles)) {
 2258: 		    $javafiles{$item} = '';
 2259: 		}
 2260: 	    }
 2261: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2262: 		my $name = lc($attr->{'name'});
 2263: 		foreach my $item (keys(%javafiles)) {
 2264: 		    if ($name eq $item) {
 2265: 			$javafiles{$item} = $attr->{'value'};
 2266: 			last;
 2267: 		    }
 2268: 		}
 2269: 		foreach my $item (keys(%mediafiles)) {
 2270: 		    if ($name eq $item) {
 2271: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2272: 			last;
 2273: 		    }
 2274: 		}
 2275: 	    }
 2276: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2277: 		foreach my $item (keys(%javafiles)) {
 2278: 		    if ($attr->{$item}) {
 2279: 			$javafiles{$item} = $attr->{$item};
 2280: 			last;
 2281: 		    }
 2282: 		}
 2283: 		foreach my $item (keys(%mediafiles)) {
 2284: 		    if ($attr->{$item}) {
 2285: 			&add_filetype($allfiles,$attr->{$item},$item);
 2286: 			last;
 2287: 		    }
 2288: 		}
 2289: 	    }
 2290: 	} elsif ($t->[0] eq 'E') {
 2291: 	    my ($tagname) = ($t->[1]);
 2292: 	    if ($javafiles{'codebase'} ne '') {
 2293: 		$javafiles{'codebase'} .= '/';
 2294: 	    }  
 2295: 	    if (lc($tagname) eq 'applet' ||
 2296: 		lc($tagname) eq 'object' ||
 2297: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2298: 		) {
 2299: 		foreach my $item (keys(%javafiles)) {
 2300: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2301: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2302: 			&add_filetype($allfiles,$file,$item);
 2303: 		    }
 2304: 		}
 2305: 	    } 
 2306: 	    pop @state;
 2307: 	}
 2308:     }
 2309:     return 'ok';
 2310: }
 2311: 
 2312: sub add_filetype {
 2313:     my ($allfiles,$file,$type)=@_;
 2314:     if (exists($allfiles->{$file})) {
 2315: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2316: 	    push(@{$allfiles->{$file}}, &escape($type));
 2317: 	}
 2318:     } else {
 2319: 	@{$allfiles->{$file}} = (&escape($type));
 2320:     }
 2321: }
 2322: 
 2323: sub removeuploadedurl {
 2324:     my ($url)=@_;
 2325:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2326:     return &removeuserfile($uname,$udom,$fname);
 2327: }
 2328: 
 2329: sub removeuserfile {
 2330:     my ($docuname,$docudom,$fname)=@_;
 2331:     my $home=&homeserver($docuname,$docudom);
 2332:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2333:     if ($result eq 'ok') {
 2334:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2335:             my $metafile = $fname.'.meta';
 2336:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2337: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2338:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2339:             my $sqlresult = 
 2340:                 &update_portfolio_table($docuname,$docudom,$file,
 2341:                                         'portfolio_metadata',$group,
 2342:                                         'delete');
 2343:         }
 2344:     }
 2345:     return $result;
 2346: }
 2347: 
 2348: sub mkdiruserfile {
 2349:     my ($docuname,$docudom,$dir)=@_;
 2350:     my $home=&homeserver($docuname,$docudom);
 2351:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2352: }
 2353: 
 2354: sub renameuserfile {
 2355:     my ($docuname,$docudom,$old,$new)=@_;
 2356:     my $home=&homeserver($docuname,$docudom);
 2357:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2358:                         &escape("$old").':'.&escape("$new"),$home);
 2359:     if ($result eq 'ok') {
 2360:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2361:             my $oldmeta = $old.'.meta';
 2362:             my $newmeta = $new.'.meta';
 2363:             my $metaresult = 
 2364:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2365: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2366:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2367:             my $sqlresult = 
 2368:                 &update_portfolio_table($docuname,$docudom,$file,
 2369:                                         'portfolio_metadata',$group,
 2370:                                         'delete');
 2371:         }
 2372:     }
 2373:     return $result;
 2374: }
 2375: 
 2376: # ------------------------------------------------------------------------- Log
 2377: 
 2378: sub log {
 2379:     my ($dom,$nam,$hom,$what)=@_;
 2380:     return critical("log:$dom:$nam:$what",$hom);
 2381: }
 2382: 
 2383: # ------------------------------------------------------------------ Course Log
 2384: #
 2385: # This routine flushes several buffers of non-mission-critical nature
 2386: #
 2387: 
 2388: sub flushcourselogs {
 2389:     &logthis('Flushing log buffers');
 2390: #
 2391: # course logs
 2392: # This is a log of all transactions in a course, which can be used
 2393: # for data mining purposes
 2394: #
 2395: # It also collects the courseid database, which lists last transaction
 2396: # times and course titles for all courseids
 2397: #
 2398:     my %courseidbuffer=();
 2399:     foreach my $crsid (keys(%courselogs)) {
 2400:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2401: 		          &escape($courselogs{$crsid}),
 2402: 		          $coursehombuf{$crsid}) eq 'ok') {
 2403: 	    delete $courselogs{$crsid};
 2404:         } else {
 2405:             &logthis('Failed to flush log buffer for '.$crsid);
 2406:             if (length($courselogs{$crsid})>40000) {
 2407:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2408:                         " exceeded maximum size, deleting.</font>");
 2409:                delete $courselogs{$crsid};
 2410:             }
 2411:         }
 2412:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2413:             'description' => $coursedescrbuf{$crsid},
 2414:             'inst_code'    => $courseinstcodebuf{$crsid},
 2415:             'type'        => $coursetypebuf{$crsid},
 2416:             'owner'       => $courseownerbuf{$crsid},
 2417:         };
 2418:     }
 2419: #
 2420: # Write course id database (reverse lookup) to homeserver of courses 
 2421: # Is used in pickcourse
 2422: #
 2423:     foreach my $crs_home (keys(%courseidbuffer)) {
 2424:         my $response = &courseidput(&host_domain($crs_home),
 2425:                                     $courseidbuffer{$crs_home},
 2426:                                     $crs_home,'timeonly');
 2427:     }
 2428: #
 2429: # File accesses
 2430: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2431: #
 2432:     foreach my $entry (keys(%accesshash)) {
 2433:         if ($entry =~ /___count$/) {
 2434:             my ($dom,$name);
 2435:             ($dom,$name,undef)=
 2436: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2437:             if (! defined($dom) || $dom eq '' || 
 2438:                 ! defined($name) || $name eq '') {
 2439:                 my $cid = $env{'request.course.id'};
 2440:                 $dom  = $env{'request.'.$cid.'.domain'};
 2441:                 $name = $env{'request.'.$cid.'.num'};
 2442:             }
 2443:             my $value = $accesshash{$entry};
 2444:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2445:             my %temphash=($url => $value);
 2446:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2447:             if ($result eq 'ok') {
 2448:                 delete $accesshash{$entry};
 2449:             } elsif ($result eq 'unknown_cmd') {
 2450:                 # Target server has old code running on it.
 2451:                 my %temphash=($entry => $value);
 2452:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2453:                     delete $accesshash{$entry};
 2454:                 }
 2455:             }
 2456:         } else {
 2457:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2458:             my %temphash=($entry => $accesshash{$entry});
 2459:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2460:                 delete $accesshash{$entry};
 2461:             }
 2462:         }
 2463:     }
 2464: #
 2465: # Roles
 2466: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2467: #
 2468:     foreach my $entry (keys(%userrolehash)) {
 2469:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2470: 	    split(/\:/,$entry);
 2471:         if (&Apache::lonnet::put('nohist_userroles',
 2472:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2473:                 $rudom,$runame) eq 'ok') {
 2474: 	    delete $userrolehash{$entry};
 2475:         }
 2476:     }
 2477: #
 2478: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2479: #
 2480:     my %domrolebuffer = ();
 2481:     foreach my $entry (keys %domainrolehash) {
 2482:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2483:         if ($domrolebuffer{$rudom}) {
 2484:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2485:                       '='.&escape($domainrolehash{$entry});
 2486:         } else {
 2487:             $domrolebuffer{$rudom}.=&escape($entry).
 2488:                       '='.&escape($domainrolehash{$entry});
 2489:         }
 2490:         delete $domainrolehash{$entry};
 2491:     }
 2492:     foreach my $dom (keys(%domrolebuffer)) {
 2493: 	my %servers = &get_servers($dom,'library');
 2494: 	foreach my $tryserver (keys(%servers)) {
 2495: 	    unless (&reply('domroleput:'.$dom.':'.
 2496: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2497: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2498: 	    }
 2499:         }
 2500:     }
 2501:     $dumpcount++;
 2502: }
 2503: 
 2504: sub courselog {
 2505:     my $what=shift;
 2506:     $what=time.':'.$what;
 2507:     unless ($env{'request.course.id'}) { return ''; }
 2508:     $coursedombuf{$env{'request.course.id'}}=
 2509:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2510:     $coursenumbuf{$env{'request.course.id'}}=
 2511:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2512:     $coursehombuf{$env{'request.course.id'}}=
 2513:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2514:     $coursedescrbuf{$env{'request.course.id'}}=
 2515:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2516:     $courseinstcodebuf{$env{'request.course.id'}}=
 2517:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2518:     $courseownerbuf{$env{'request.course.id'}}=
 2519:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2520:     $coursetypebuf{$env{'request.course.id'}}=
 2521:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2522:     if (defined $courselogs{$env{'request.course.id'}}) {
 2523: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2524:     } else {
 2525: 	$courselogs{$env{'request.course.id'}}.=$what;
 2526:     }
 2527:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2528: 	&flushcourselogs();
 2529:     }
 2530: }
 2531: 
 2532: sub courseacclog {
 2533:     my $fnsymb=shift;
 2534:     unless ($env{'request.course.id'}) { return ''; }
 2535:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2536:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2537:         $what.=':POST';
 2538:         # FIXME: Probably ought to escape things....
 2539: 	foreach my $key (keys(%env)) {
 2540:             if ($key=~/^form\.(.*)/) {
 2541:                 my $formitem = $1;
 2542:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2543:                     $what.=':'.$formitem.'='.$env{$key};
 2544:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2545:                     $what.=':'.$formitem.'='.$env{$key};
 2546:                 }
 2547:             }
 2548:         }
 2549:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2550:         # FIXME: We should not be depending on a form parameter that someone
 2551:         # editing lonsearchcat.pm might change in the future.
 2552:         if ($env{'form.phase'} eq 'course_search') {
 2553:             $what.= ':POST';
 2554:             # FIXME: Probably ought to escape things....
 2555:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2556:                                  'crsdiscuss') {
 2557:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2558:             }
 2559:         }
 2560:     }
 2561:     &courselog($what);
 2562: }
 2563: 
 2564: sub countacc {
 2565:     my $url=&declutter(shift);
 2566:     return if (! defined($url) || $url eq '');
 2567:     unless ($env{'request.course.id'}) { return ''; }
 2568:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2569:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2570:     $accesshash{$key}++;
 2571: }
 2572: 
 2573: sub linklog {
 2574:     my ($from,$to)=@_;
 2575:     $from=&declutter($from);
 2576:     $to=&declutter($to);
 2577:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2578:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2579: }
 2580:   
 2581: sub userrolelog {
 2582:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2583:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2584:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2585:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2586:         ($trole=~/^ta/)) {
 2587:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2588:        $userrolehash
 2589:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2590:                     =$tend.':'.$tstart;
 2591:     }
 2592:     if (($env{'request.role'} =~ /dc\./) &&
 2593: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2594: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2595: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2596:        $userrolehash
 2597:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2598:                     =$tend.':'.$tstart;
 2599:     }
 2600:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2601:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2602:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2603:         ($trole=~/^sc/)) {
 2604:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2605:        $domainrolehash
 2606:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2607:                     = $tend.':'.$tstart;
 2608:     }
 2609: }
 2610: 
 2611: sub courserolelog {
 2612:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2613:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2614:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2615:         ($trole eq 'ta') || ($trole eq 'st') ||
 2616:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2617:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2618:             my $cdom = $1;
 2619:             my $cnum = $2;
 2620:             my $sec = $3;
 2621:             my $namespace = 'rolelog';
 2622:             my %storehash = (
 2623:                                role    => $trole,
 2624:                                start   => $tstart,
 2625:                                end     => $tend,
 2626:                                selfenroll => $selfenroll,
 2627:                                context    => $context,
 2628:                             );
 2629:             if ($trole eq 'gr') {
 2630:                 $namespace = 'groupslog';
 2631:                 $storehash{'group'} = $sec;
 2632:             } else {
 2633:                 $storehash{'section'} = $sec;
 2634:             }
 2635:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2636:         }
 2637:     }
 2638:     return;
 2639: }
 2640: 
 2641: sub get_course_adv_roles {
 2642:     my ($cid,$codes) = @_;
 2643:     $cid=$env{'request.course.id'} unless (defined($cid));
 2644:     my %coursehash=&coursedescription($cid);
 2645:     my %nothide=();
 2646:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2647:         if ($user !~ /:/) {
 2648: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2649:         } else {
 2650:             $nothide{$user}=1;
 2651:         }
 2652:     }
 2653:     my %returnhash=();
 2654:     my %dumphash=
 2655:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2656:     my $now=time;
 2657:     foreach my $entry (keys %dumphash) {
 2658: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2659:         if (($tstart) && ($tstart<0)) { next; }
 2660:         if (($tend) && ($tend<$now)) { next; }
 2661:         if (($tstart) && ($now<$tstart)) { next; }
 2662:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2663: 	if ($username eq '' || $domain eq '') { next; }
 2664: 	if ((&privileged($username,$domain)) && 
 2665: 	    (!$nothide{$username.':'.$domain})) { next; }
 2666: 	if ($role eq 'cr') { next; }
 2667:         if ($codes) {
 2668:             if ($section) { $role .= ':'.$section; }
 2669:             if ($returnhash{$role}) {
 2670:                 $returnhash{$role}.=','.$username.':'.$domain;
 2671:             } else {
 2672:                 $returnhash{$role}=$username.':'.$domain;
 2673:             }
 2674:         } else {
 2675:             my $key=&plaintext($role);
 2676:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2677:             if ($returnhash{$key}) {
 2678: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2679:             } else {
 2680:                 $returnhash{$key}=$username.':'.$domain;
 2681:             }
 2682:         }
 2683:     }
 2684:     return %returnhash;
 2685: }
 2686: 
 2687: sub get_my_roles {
 2688:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2689:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2690:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2691:     my (%dumphash,%nothide);
 2692:     if ($context eq 'userroles') { 
 2693:         %dumphash = &dump('roles',$udom,$uname);
 2694:     } else {
 2695:         %dumphash=
 2696:             &dump('nohist_userroles',$udom,$uname);
 2697:         if ($hidepriv) {
 2698:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2699:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2700:                 if ($user !~ /:/) {
 2701:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2702:                 } else {
 2703:                     $nothide{$user} = 1;
 2704:                 }
 2705:             }
 2706:         }
 2707:     }
 2708:     my %returnhash=();
 2709:     my $now=time;
 2710:     foreach my $entry (keys(%dumphash)) {
 2711:         my ($role,$tend,$tstart);
 2712:         if ($context eq 'userroles') {
 2713: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2714:         } else {
 2715:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2716:         }
 2717:         if (($tstart) && ($tstart<0)) { next; }
 2718:         my $status = 'active';
 2719:         if (($tend) && ($tend<=$now)) {
 2720:             $status = 'previous';
 2721:         } 
 2722:         if (($tstart) && ($now<$tstart)) {
 2723:             $status = 'future';
 2724:         }
 2725:         if (ref($types) eq 'ARRAY') {
 2726:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2727:                 next;
 2728:             } 
 2729:         } else {
 2730:             if ($status ne 'active') {
 2731:                 next;
 2732:             }
 2733:         }
 2734:         my ($rolecode,$username,$domain,$section,$area);
 2735:         if ($context eq 'userroles') {
 2736:             ($area,$rolecode) = split(/_/,$entry);
 2737:             (undef,$domain,$username,$section) = split(/\//,$area);
 2738:         } else {
 2739:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2740:         }
 2741:         if (ref($roledoms) eq 'ARRAY') {
 2742:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2743:                 next;
 2744:             }
 2745:         }
 2746:         if (ref($roles) eq 'ARRAY') {
 2747:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2748:                 if ($role =~ /^cr\//) {
 2749:                     if (!grep(/^cr$/,@{$roles})) {
 2750:                         next;
 2751:                     }
 2752:                 } else {
 2753:                     next;
 2754:                 }
 2755:             }
 2756:         }
 2757:         if ($hidepriv) {
 2758:             if ((&privileged($username,$domain)) &&
 2759:                 (!$nothide{$username.':'.$domain})) { 
 2760:                 next;
 2761:             }
 2762:         }
 2763:         if ($withsec) {
 2764:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2765:                 $tstart.':'.$tend;
 2766:         } else {
 2767:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2768:         }
 2769:     }
 2770:     return %returnhash;
 2771: }
 2772: 
 2773: # ----------------------------------------------------- Frontpage Announcements
 2774: #
 2775: #
 2776: 
 2777: sub postannounce {
 2778:     my ($server,$text)=@_;
 2779:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2780:     unless ($text=~/\w/) { $text=''; }
 2781:     return &reply('setannounce:'.&escape($text),$server);
 2782: }
 2783: 
 2784: sub getannounce {
 2785: 
 2786:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2787: 	my $announcement='';
 2788: 	while (my $line = <$fh>) { $announcement .= $line; }
 2789: 	close($fh);
 2790: 	if ($announcement=~/\w/) { 
 2791: 	    return 
 2792:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2793:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2794: 	} else {
 2795: 	    return '';
 2796: 	}
 2797:     } else {
 2798: 	return '';
 2799:     }
 2800: }
 2801: 
 2802: # ---------------------------------------------------------- Course ID routines
 2803: # Deal with domain's nohist_courseid.db files
 2804: #
 2805: 
 2806: sub courseidput {
 2807:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2808:     my $outcome;
 2809:     if ($caller eq 'timeonly') {
 2810:         my $cids = '';
 2811:         foreach my $item (keys(%$storehash)) {
 2812:             $cids.=&escape($item).'&';
 2813:         }
 2814:         $cids=~s/\&$//;
 2815:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2816:                           $coursehome);       
 2817:     } else {
 2818:         my $items = '';
 2819:         foreach my $item (keys(%$storehash)) {
 2820:             $items.= &escape($item).'='.
 2821:                      &freeze_escape($$storehash{$item}).'&';
 2822:         }
 2823:         $items=~s/\&$//;
 2824:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2825:                           $coursehome);
 2826:     }
 2827:     if ($outcome eq 'unknown_cmd') {
 2828:         my $what;
 2829:         foreach my $cid (keys(%$storehash)) {
 2830:             $what .= &escape($cid).'=';
 2831:             foreach my $item ('description','inst_code','owner','type') {
 2832:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2833:             }
 2834:             $what =~ s/\:$/&/;
 2835:         }
 2836:         $what =~ s/\&$//;  
 2837:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2838:     } else {
 2839:         return $outcome;
 2840:     }
 2841: }
 2842: 
 2843: sub courseiddump {
 2844:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2845:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2846:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2847:     my $as_hash = 1;
 2848:     my %returnhash;
 2849:     if (!$domfilter) { $domfilter=''; }
 2850:     my %libserv = &all_library();
 2851:     foreach my $tryserver (keys(%libserv)) {
 2852:         if ( (  $hostidflag == 1 
 2853: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2854: 	     || (!defined($hostidflag)) ) {
 2855: 
 2856: 	    if (($domfilter eq '') ||
 2857: 		(&host_domain($tryserver) eq $domfilter)) {
 2858:                 my $rep = 
 2859:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2860:                          $sincefilter.':'.&escape($descfilter).':'.
 2861:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2862:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2863:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2864:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2865:                          $showhidden.':'.$caller,$tryserver);
 2866:                 my @pairs=split(/\&/,$rep);
 2867:                 foreach my $item (@pairs) {
 2868:                     my ($key,$value)=split(/\=/,$item,2);
 2869:                     $key = &unescape($key);
 2870:                     next if ($key =~ /^error: 2 /);
 2871:                     my $result = &thaw_unescape($value);
 2872:                     if (ref($result) eq 'HASH') {
 2873:                         $returnhash{$key}=$result;
 2874:                     } else {
 2875:                         my @responses = split(/:/,$value);
 2876:                         my @items = ('description','inst_code','owner','type');
 2877:                         for (my $i=0; $i<@responses; $i++) {
 2878:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2879:                         }
 2880:                     } 
 2881:                 }
 2882:             }
 2883:         }
 2884:     }
 2885:     return %returnhash;
 2886: }
 2887: 
 2888: # ---------------------------------------------------------- DC e-mail
 2889: 
 2890: sub dcmailput {
 2891:     my ($domain,$msgid,$message,$server)=@_;
 2892:     my $status = &Apache::lonnet::critical(
 2893:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2894:        &escape($message),$server);
 2895:     return $status;
 2896: }
 2897: 
 2898: sub dcmaildump {
 2899:     my ($dom,$startdate,$enddate,$senders) = @_;
 2900:     my %returnhash=();
 2901: 
 2902:     if (defined(&domain($dom,'primary'))) {
 2903:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2904:                                                          &escape($enddate).':';
 2905: 	my @esc_senders=map { &escape($_)} @$senders;
 2906: 	$cmd.=&escape(join('&',@esc_senders));
 2907: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2908:             my ($key,$value) = split(/\=/,$line,2);
 2909:             if (($key) && ($value)) {
 2910:                 $returnhash{&unescape($key)} = &unescape($value);
 2911:             }
 2912:         }
 2913:     }
 2914:     return %returnhash;
 2915: }
 2916: # ---------------------------------------------------------- Domain roles
 2917: 
 2918: sub get_domain_roles {
 2919:     my ($dom,$roles,$startdate,$enddate)=@_;
 2920:     if (undef($startdate) || $startdate eq '') {
 2921:         $startdate = '.';
 2922:     }
 2923:     if (undef($enddate) || $enddate eq '') {
 2924:         $enddate = '.';
 2925:     }
 2926:     my $rolelist;
 2927:     if (ref($roles) eq 'ARRAY') {
 2928:         $rolelist = join(':',@{$roles});
 2929:     }
 2930:     my %personnel = ();
 2931: 
 2932:     my %servers = &get_servers($dom,'library');
 2933:     foreach my $tryserver (keys(%servers)) {
 2934: 	%{$personnel{$tryserver}}=();
 2935: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2936: 					    &escape($startdate).':'.
 2937: 					    &escape($enddate).':'.
 2938: 					    &escape($rolelist), $tryserver))) {
 2939: 	    my ($key,$value) = split(/\=/,$line,2);
 2940: 	    if (($key) && ($value)) {
 2941: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2942: 	    }
 2943: 	}
 2944:     }
 2945:     return %personnel;
 2946: }
 2947: 
 2948: # ----------------------------------------------------------- Check out an item
 2949: 
 2950: sub get_first_access {
 2951:     my ($type,$argsymb)=@_;
 2952:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2953:     if ($argsymb) { $symb=$argsymb; }
 2954:     my ($map,$id,$res)=&decode_symb($symb);
 2955:     if ($type eq 'course') {
 2956: 	$res='course';
 2957:     } elsif ($type eq 'map') {
 2958: 	$res=&symbread($map);
 2959:     } else {
 2960: 	$res=$symb;
 2961:     }
 2962:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2963:     return $times{"$courseid\0$res"};
 2964: }
 2965: 
 2966: sub set_first_access {
 2967:     my ($type)=@_;
 2968:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2969:     my ($map,$id,$res)=&decode_symb($symb);
 2970:     if ($type eq 'course') {
 2971: 	$res='course';
 2972:     } elsif ($type eq 'map') {
 2973: 	$res=&symbread($map);
 2974:     } else {
 2975: 	$res=$symb;
 2976:     }
 2977:     my $firstaccess=&get_first_access($type,$symb);
 2978:     if (!$firstaccess) {
 2979: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2980:     }
 2981:     return 'already_set';
 2982: }
 2983: 
 2984: sub checkout {
 2985:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2986:     my $now=time;
 2987:     my $lonhost=$perlvar{'lonHostID'};
 2988:     my $infostr=&escape(
 2989:                  'CHECKOUTTOKEN&'.
 2990:                  $tuname.'&'.
 2991:                  $tudom.'&'.
 2992:                  $tcrsid.'&'.
 2993:                  $symb.'&'.
 2994: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2995:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2996:     if ($token=~/^error\:/) { 
 2997:         &logthis("<font color=\"blue\">WARNING: ".
 2998:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2999:                  "</font>");
 3000:         return ''; 
 3001:     }
 3002: 
 3003:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 3004:     $token=~tr/a-z/A-Z/;
 3005: 
 3006:     my %infohash=('resource.0.outtoken' => $token,
 3007:                   'resource.0.checkouttime' => $now,
 3008:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3009: 
 3010:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3011:        return '';
 3012:     } else {
 3013:         &logthis("<font color=\"blue\">WARNING: ".
 3014:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3015:                  "</font>");
 3016:     }    
 3017: 
 3018:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3019:                          &escape('Checkout '.$infostr.' - '.
 3020:                                                  $token)) ne 'ok') {
 3021: 	return '';
 3022:     } else {
 3023:         &logthis("<font color=\"blue\">WARNING: ".
 3024:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3025:                  "</font>");
 3026:     }
 3027:     return $token;
 3028: }
 3029: 
 3030: # ------------------------------------------------------------ Check in an item
 3031: 
 3032: sub checkin {
 3033:     my $token=shift;
 3034:     my $now=time;
 3035:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3036:     $lonhost=~tr/A-Z/a-z/;
 3037:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3038:     $dtoken=~s/\W/\_/g;
 3039:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3040:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3041: 
 3042:     unless (($tuname) && ($tudom)) {
 3043:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3044:         return '';
 3045:     }
 3046:     
 3047:     unless (&allowed('mgr',$tcrsid)) {
 3048:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3049:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3050:         return '';
 3051:     }
 3052: 
 3053:     my %infohash=('resource.0.intoken' => $token,
 3054:                   'resource.0.checkintime' => $now,
 3055:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3056: 
 3057:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3058:        return '';
 3059:     }    
 3060: 
 3061:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3062:                          &escape('Checkin - '.$token)) ne 'ok') {
 3063: 	return '';
 3064:     }
 3065: 
 3066:     return ($symb,$tuname,$tudom,$tcrsid);    
 3067: }
 3068: 
 3069: # --------------------------------------------- Set Expire Date for Spreadsheet
 3070: 
 3071: sub expirespread {
 3072:     my ($uname,$udom,$stype,$usymb)=@_;
 3073:     my $cid=$env{'request.course.id'}; 
 3074:     if ($cid) {
 3075:        my $now=time;
 3076:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3077:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3078:                             $env{'course.'.$cid.'.num'}.
 3079: 	        	    ':nohist_expirationdates:'.
 3080:                             &escape($key).'='.$now,
 3081:                             $env{'course.'.$cid.'.home'})
 3082:     }
 3083:     return 'ok';
 3084: }
 3085: 
 3086: # ----------------------------------------------------- Devalidate Spreadsheets
 3087: 
 3088: sub devalidate {
 3089:     my ($symb,$uname,$udom)=@_;
 3090:     my $cid=$env{'request.course.id'}; 
 3091:     if ($cid) {
 3092:         # delete the stored spreadsheets for
 3093:         # - the student level sheet of this user in course's homespace
 3094:         # - the assessment level sheet for this resource 
 3095:         #   for this user in user's homespace
 3096: 	# - current conditional state info
 3097: 	my $key=$uname.':'.$udom.':';
 3098:         my $status=
 3099: 	    &del('nohist_calculatedsheets',
 3100: 		 [$key.'studentcalc:'],
 3101: 		 $env{'course.'.$cid.'.domain'},
 3102: 		 $env{'course.'.$cid.'.num'})
 3103: 		.' '.
 3104: 	    &del('nohist_calculatedsheets_'.$cid,
 3105: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3106:         unless ($status eq 'ok ok') {
 3107:            &logthis('Could not devalidate spreadsheet '.
 3108:                     $uname.' at '.$udom.' for '.
 3109: 		    $symb.': '.$status);
 3110:         }
 3111: 	&delenv('user.state.'.$cid);
 3112:     }
 3113: }
 3114: 
 3115: sub get_scalar {
 3116:     my ($string,$end) = @_;
 3117:     my $value;
 3118:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3119: 	$value = $1;
 3120:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3121: 	$value = $1;
 3122:     }
 3123:     return &unescape($value);
 3124: }
 3125: 
 3126: sub array2str {
 3127:   my (@array) = @_;
 3128:   my $result=&arrayref2str(\@array);
 3129:   $result=~s/^__ARRAY_REF__//;
 3130:   $result=~s/__END_ARRAY_REF__$//;
 3131:   return $result;
 3132: }
 3133: 
 3134: sub arrayref2str {
 3135:   my ($arrayref) = @_;
 3136:   my $result='__ARRAY_REF__';
 3137:   foreach my $elem (@$arrayref) {
 3138:     if(ref($elem) eq 'ARRAY') {
 3139:       $result.=&arrayref2str($elem).'&';
 3140:     } elsif(ref($elem) eq 'HASH') {
 3141:       $result.=&hashref2str($elem).'&';
 3142:     } elsif(ref($elem)) {
 3143:       #print("Got a ref of ".(ref($elem))." skipping.");
 3144:     } else {
 3145:       $result.=&escape($elem).'&';
 3146:     }
 3147:   }
 3148:   $result=~s/\&$//;
 3149:   $result .= '__END_ARRAY_REF__';
 3150:   return $result;
 3151: }
 3152: 
 3153: sub hash2str {
 3154:   my (%hash) = @_;
 3155:   my $result=&hashref2str(\%hash);
 3156:   $result=~s/^__HASH_REF__//;
 3157:   $result=~s/__END_HASH_REF__$//;
 3158:   return $result;
 3159: }
 3160: 
 3161: sub hashref2str {
 3162:   my ($hashref)=@_;
 3163:   my $result='__HASH_REF__';
 3164:   foreach my $key (sort(keys(%$hashref))) {
 3165:     if (ref($key) eq 'ARRAY') {
 3166:       $result.=&arrayref2str($key).'=';
 3167:     } elsif (ref($key) eq 'HASH') {
 3168:       $result.=&hashref2str($key).'=';
 3169:     } elsif (ref($key)) {
 3170:       $result.='=';
 3171:       #print("Got a ref of ".(ref($key))." skipping.");
 3172:     } else {
 3173: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3174:     }
 3175: 
 3176:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3177:       $result.=&arrayref2str($hashref->{$key}).'&';
 3178:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3179:       $result.=&hashref2str($hashref->{$key}).'&';
 3180:     } elsif(ref($hashref->{$key})) {
 3181:        $result.='&';
 3182:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3183:     } else {
 3184:       $result.=&escape($hashref->{$key}).'&';
 3185:     }
 3186:   }
 3187:   $result=~s/\&$//;
 3188:   $result .= '__END_HASH_REF__';
 3189:   return $result;
 3190: }
 3191: 
 3192: sub str2hash {
 3193:     my ($string)=@_;
 3194:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3195:     return %$hash;
 3196: }
 3197: 
 3198: sub str2hashref {
 3199:   my ($string) = @_;
 3200: 
 3201:   my %hash;
 3202: 
 3203:   if($string !~ /^__HASH_REF__/) {
 3204:       if (! ($string eq '' || !defined($string))) {
 3205: 	  $hash{'error'}='Not hash reference';
 3206:       }
 3207:       return (\%hash, $string);
 3208:   }
 3209: 
 3210:   $string =~ s/^__HASH_REF__//;
 3211: 
 3212:   while($string !~ /^__END_HASH_REF__/) {
 3213:       #key
 3214:       my $key='';
 3215:       if($string =~ /^__HASH_REF__/) {
 3216:           ($key, $string)=&str2hashref($string);
 3217:           if(defined($key->{'error'})) {
 3218:               $hash{'error'}='Bad data';
 3219:               return (\%hash, $string);
 3220:           }
 3221:       } elsif($string =~ /^__ARRAY_REF__/) {
 3222:           ($key, $string)=&str2arrayref($string);
 3223:           if($key->[0] eq 'Array reference error') {
 3224:               $hash{'error'}='Bad data';
 3225:               return (\%hash, $string);
 3226:           }
 3227:       } else {
 3228:           $string =~ s/^(.*?)=//;
 3229: 	  $key=&unescape($1);
 3230:       }
 3231:       $string =~ s/^=//;
 3232: 
 3233:       #value
 3234:       my $value='';
 3235:       if($string =~ /^__HASH_REF__/) {
 3236:           ($value, $string)=&str2hashref($string);
 3237:           if(defined($value->{'error'})) {
 3238:               $hash{'error'}='Bad data';
 3239:               return (\%hash, $string);
 3240:           }
 3241:       } elsif($string =~ /^__ARRAY_REF__/) {
 3242:           ($value, $string)=&str2arrayref($string);
 3243:           if($value->[0] eq 'Array reference error') {
 3244:               $hash{'error'}='Bad data';
 3245:               return (\%hash, $string);
 3246:           }
 3247:       } else {
 3248: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3249:       }
 3250:       $string =~ s/^&//;
 3251: 
 3252:       $hash{$key}=$value;
 3253:   }
 3254: 
 3255:   $string =~ s/^__END_HASH_REF__//;
 3256: 
 3257:   return (\%hash, $string);
 3258: }
 3259: 
 3260: sub str2array {
 3261:     my ($string)=@_;
 3262:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3263:     return @$array;
 3264: }
 3265: 
 3266: sub str2arrayref {
 3267:   my ($string) = @_;
 3268:   my @array;
 3269: 
 3270:   if($string !~ /^__ARRAY_REF__/) {
 3271:       if (! ($string eq '' || !defined($string))) {
 3272: 	  $array[0]='Array reference error';
 3273:       }
 3274:       return (\@array, $string);
 3275:   }
 3276: 
 3277:   $string =~ s/^__ARRAY_REF__//;
 3278: 
 3279:   while($string !~ /^__END_ARRAY_REF__/) {
 3280:       my $value='';
 3281:       if($string =~ /^__HASH_REF__/) {
 3282:           ($value, $string)=&str2hashref($string);
 3283:           if(defined($value->{'error'})) {
 3284:               $array[0] ='Array reference error';
 3285:               return (\@array, $string);
 3286:           }
 3287:       } elsif($string =~ /^__ARRAY_REF__/) {
 3288:           ($value, $string)=&str2arrayref($string);
 3289:           if($value->[0] eq 'Array reference error') {
 3290:               $array[0] ='Array reference error';
 3291:               return (\@array, $string);
 3292:           }
 3293:       } else {
 3294: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3295:       }
 3296:       $string =~ s/^&//;
 3297: 
 3298:       push(@array, $value);
 3299:   }
 3300: 
 3301:   $string =~ s/^__END_ARRAY_REF__//;
 3302: 
 3303:   return (\@array, $string);
 3304: }
 3305: 
 3306: # -------------------------------------------------------------------Temp Store
 3307: 
 3308: sub tmpreset {
 3309:   my ($symb,$namespace,$domain,$stuname) = @_;
 3310:   if (!$symb) {
 3311:     $symb=&symbread();
 3312:     if (!$symb) { $symb= $env{'request.url'}; }
 3313:   }
 3314:   $symb=escape($symb);
 3315: 
 3316:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3317:   $namespace=~s/\//\_/g;
 3318:   $namespace=~s/\W//g;
 3319: 
 3320:   if (!$domain) { $domain=$env{'user.domain'}; }
 3321:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3322:   if ($domain eq 'public' && $stuname eq 'public') {
 3323:       $stuname=$ENV{'REMOTE_ADDR'};
 3324:   }
 3325:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3326:   my %hash;
 3327:   if (tie(%hash,'GDBM_File',
 3328: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3329: 	  &GDBM_WRCREAT(),0640)) {
 3330:     foreach my $key (keys %hash) {
 3331:       if ($key=~ /:$symb/) {
 3332: 	delete($hash{$key});
 3333:       }
 3334:     }
 3335:   }
 3336: }
 3337: 
 3338: sub tmpstore {
 3339:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3340: 
 3341:   if (!$symb) {
 3342:     $symb=&symbread();
 3343:     if (!$symb) { $symb= $env{'request.url'}; }
 3344:   }
 3345:   $symb=escape($symb);
 3346: 
 3347:   if (!$namespace) {
 3348:     # I don't think we would ever want to store this for a course.
 3349:     # it seems this will only be used if we don't have a course.
 3350:     #$namespace=$env{'request.course.id'};
 3351:     #if (!$namespace) {
 3352:       $namespace=$env{'request.state'};
 3353:     #}
 3354:   }
 3355:   $namespace=~s/\//\_/g;
 3356:   $namespace=~s/\W//g;
 3357:   if (!$domain) { $domain=$env{'user.domain'}; }
 3358:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3359:   if ($domain eq 'public' && $stuname eq 'public') {
 3360:       $stuname=$ENV{'REMOTE_ADDR'};
 3361:   }
 3362:   my $now=time;
 3363:   my %hash;
 3364:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3365:   if (tie(%hash,'GDBM_File',
 3366: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3367: 	  &GDBM_WRCREAT(),0640)) {
 3368:     $hash{"version:$symb"}++;
 3369:     my $version=$hash{"version:$symb"};
 3370:     my $allkeys=''; 
 3371:     foreach my $key (keys(%$storehash)) {
 3372:       $allkeys.=$key.':';
 3373:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3374:     }
 3375:     $hash{"$version:$symb:timestamp"}=$now;
 3376:     $allkeys.='timestamp';
 3377:     $hash{"$version:keys:$symb"}=$allkeys;
 3378:     if (untie(%hash)) {
 3379:       return 'ok';
 3380:     } else {
 3381:       return "error:$!";
 3382:     }
 3383:   } else {
 3384:     return "error:$!";
 3385:   }
 3386: }
 3387: 
 3388: # -----------------------------------------------------------------Temp Restore
 3389: 
 3390: sub tmprestore {
 3391:   my ($symb,$namespace,$domain,$stuname) = @_;
 3392: 
 3393:   if (!$symb) {
 3394:     $symb=&symbread();
 3395:     if (!$symb) { $symb= $env{'request.url'}; }
 3396:   }
 3397:   $symb=escape($symb);
 3398: 
 3399:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3400: 
 3401:   if (!$domain) { $domain=$env{'user.domain'}; }
 3402:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3403:   if ($domain eq 'public' && $stuname eq 'public') {
 3404:       $stuname=$ENV{'REMOTE_ADDR'};
 3405:   }
 3406:   my %returnhash;
 3407:   $namespace=~s/\//\_/g;
 3408:   $namespace=~s/\W//g;
 3409:   my %hash;
 3410:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3411:   if (tie(%hash,'GDBM_File',
 3412: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3413: 	  &GDBM_READER(),0640)) {
 3414:     my $version=$hash{"version:$symb"};
 3415:     $returnhash{'version'}=$version;
 3416:     my $scope;
 3417:     for ($scope=1;$scope<=$version;$scope++) {
 3418:       my $vkeys=$hash{"$scope:keys:$symb"};
 3419:       my @keys=split(/:/,$vkeys);
 3420:       my $key;
 3421:       $returnhash{"$scope:keys"}=$vkeys;
 3422:       foreach $key (@keys) {
 3423: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3424: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3425:       }
 3426:     }
 3427:     if (!(untie(%hash))) {
 3428:       return "error:$!";
 3429:     }
 3430:   } else {
 3431:     return "error:$!";
 3432:   }
 3433:   return %returnhash;
 3434: }
 3435: 
 3436: # ----------------------------------------------------------------------- Store
 3437: 
 3438: sub store {
 3439:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3440:     my $home='';
 3441: 
 3442:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3443: 
 3444:     $symb=&symbclean($symb);
 3445:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3446: 
 3447:     if (!$domain) { $domain=$env{'user.domain'}; }
 3448:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3449: 
 3450:     &devalidate($symb,$stuname,$domain);
 3451: 
 3452:     $symb=escape($symb);
 3453:     if (!$namespace) { 
 3454:        unless ($namespace=$env{'request.course.id'}) { 
 3455:           return ''; 
 3456:        } 
 3457:     }
 3458:     if (!$home) { $home=$env{'user.home'}; }
 3459: 
 3460:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3461:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3462: 
 3463:     my $namevalue='';
 3464:     foreach my $key (keys(%$storehash)) {
 3465:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3466:     }
 3467:     $namevalue=~s/\&$//;
 3468:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3469:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3470: }
 3471: 
 3472: # -------------------------------------------------------------- Critical Store
 3473: 
 3474: sub cstore {
 3475:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3476:     my $home='';
 3477: 
 3478:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3479: 
 3480:     $symb=&symbclean($symb);
 3481:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3482: 
 3483:     if (!$domain) { $domain=$env{'user.domain'}; }
 3484:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3485: 
 3486:     &devalidate($symb,$stuname,$domain);
 3487: 
 3488:     $symb=escape($symb);
 3489:     if (!$namespace) { 
 3490:        unless ($namespace=$env{'request.course.id'}) { 
 3491:           return ''; 
 3492:        } 
 3493:     }
 3494:     if (!$home) { $home=$env{'user.home'}; }
 3495: 
 3496:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3497:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3498: 
 3499:     my $namevalue='';
 3500:     foreach my $key (keys(%$storehash)) {
 3501:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3502:     }
 3503:     $namevalue=~s/\&$//;
 3504:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3505:     return critical
 3506:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3507: }
 3508: 
 3509: # --------------------------------------------------------------------- Restore
 3510: 
 3511: sub restore {
 3512:     my ($symb,$namespace,$domain,$stuname) = @_;
 3513:     my $home='';
 3514: 
 3515:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3516: 
 3517:     if (!$symb) {
 3518:       unless ($symb=escape(&symbread())) { return ''; }
 3519:     } else {
 3520:       $symb=&escape(&symbclean($symb));
 3521:     }
 3522:     if (!$namespace) { 
 3523:        unless ($namespace=$env{'request.course.id'}) { 
 3524:           return ''; 
 3525:        } 
 3526:     }
 3527:     if (!$domain) { $domain=$env{'user.domain'}; }
 3528:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3529:     if (!$home) { $home=$env{'user.home'}; }
 3530:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3531: 
 3532:     my %returnhash=();
 3533:     foreach my $line (split(/\&/,$answer)) {
 3534: 	my ($name,$value)=split(/\=/,$line);
 3535:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3536:     }
 3537:     my $version;
 3538:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3539:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3540:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3541:        }
 3542:     }
 3543:     return %returnhash;
 3544: }
 3545: 
 3546: # ---------------------------------------------------------- Course Description
 3547: 
 3548: sub coursedescription {
 3549:     my ($courseid,$args)=@_;
 3550:     $courseid=~s/^\///;
 3551:     $courseid=~s/\_/\//g;
 3552:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3553:     my $chome=&homeserver($cnum,$cdomain);
 3554:     my $normalid=$cdomain.'_'.$cnum;
 3555:     # need to always cache even if we get errors otherwise we keep 
 3556:     # trying and trying and trying to get the course description.
 3557:     my %envhash=();
 3558:     my %returnhash=();
 3559:     
 3560:     my $expiretime=600;
 3561:     if ($env{'request.course.id'} eq $normalid) {
 3562: 	$expiretime=120;
 3563:     }
 3564: 
 3565:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3566:     if (!$args->{'freshen_cache'}
 3567: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3568: 	foreach my $key (keys(%env)) {
 3569: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3570: 	    my ($setting) = $1;
 3571: 	    $returnhash{$setting} = $env{$key};
 3572: 	}
 3573: 	return %returnhash;
 3574:     }
 3575: 
 3576:     # get the data agin
 3577:     if (!$args->{'one_time'}) {
 3578: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3579:     }
 3580: 
 3581:     if ($chome ne 'no_host') {
 3582:        %returnhash=&dump('environment',$cdomain,$cnum);
 3583:        if (!exists($returnhash{'con_lost'})) {
 3584:            $returnhash{'home'}= $chome;
 3585: 	   $returnhash{'domain'} = $cdomain;
 3586: 	   $returnhash{'num'} = $cnum;
 3587:            if (!defined($returnhash{'type'})) {
 3588:                $returnhash{'type'} = 'Course';
 3589:            }
 3590:            while (my ($name,$value) = each %returnhash) {
 3591:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3592:            }
 3593:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3594:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3595: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3596:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3597:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3598:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3599:        }
 3600:     }
 3601:     if (!$args->{'one_time'}) {
 3602: 	&appenv(\%envhash);
 3603:     }
 3604:     return %returnhash;
 3605: }
 3606: 
 3607: # -------------------------------------------------See if a user is privileged
 3608: 
 3609: sub privileged {
 3610:     my ($username,$domain)=@_;
 3611:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3612: 			&homeserver($username,$domain));
 3613:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3614:     my $now=time;
 3615:     if ($rolesdump ne '') {
 3616:         foreach my $entry (split(/&/,$rolesdump)) {
 3617: 	    if ($entry!~/^rolesdef_/) {
 3618: 		my ($area,$role)=split(/=/,$entry);
 3619: 		$area=~s/\_\w\w$//;
 3620: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3621: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3622: 		    my $active=1;
 3623: 		    if ($tend) {
 3624: 			if ($tend<$now) { $active=0; }
 3625: 		    }
 3626: 		    if ($tstart) {
 3627: 			if ($tstart>$now) { $active=0; }
 3628: 		    }
 3629: 		    if ($active) { return 1; }
 3630: 		}
 3631: 	    }
 3632: 	}
 3633:     }
 3634:     return 0;
 3635: }
 3636: 
 3637: # -------------------------------------------------------- Get user privileges
 3638: 
 3639: sub rolesinit {
 3640:     my ($domain,$username,$authhost)=@_;
 3641:     my %userroles;
 3642:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3643:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3644:     my %allroles=();
 3645:     my %allgroups=();   
 3646:     my $now=time;
 3647:     %userroles = ('user.login.time' => $now);
 3648:     my $group_privs;
 3649: 
 3650:     if ($rolesdump ne '') {
 3651:         foreach my $entry (split(/&/,$rolesdump)) {
 3652: 	  if ($entry!~/^rolesdef_/) {
 3653:             my ($area,$role)=split(/=/,$entry);
 3654: 	    $area=~s/\_\w\w$//;
 3655:             my ($trole,$tend,$tstart,$group_privs);
 3656: 	    if ($role=~/^cr/) { 
 3657: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3658: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3659: 		    ($tend,$tstart)=split('_',$trest);
 3660: 		} else {
 3661: 		    $trole=$role;
 3662: 		}
 3663:             } elsif ($role =~ m|^gr/|) {
 3664:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3665:                 ($trole,$group_privs) = split(/\//,$trole);
 3666:                 $group_privs = &unescape($group_privs);
 3667: 	    } else {
 3668: 		($trole,$tend,$tstart)=split(/_/,$role);
 3669: 	    }
 3670: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3671: 					 $username);
 3672: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3673:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3674:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3675:             if (($area ne '') && ($trole ne '')) {
 3676: 		my $spec=$trole.'.'.$area;
 3677: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3678: 		if ($trole =~ /^cr\//) {
 3679:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3680:                 } elsif ($trole eq 'gr') {
 3681:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3682: 		} else {
 3683:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3684: 		}
 3685:             }
 3686:           }
 3687:         }
 3688:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3689:         $userroles{'user.adv'}    = $adv;
 3690: 	$userroles{'user.author'} = $author;
 3691:         $env{'user.adv'}=$adv;
 3692:     }
 3693:     return \%userroles;  
 3694: }
 3695: 
 3696: sub set_arearole {
 3697:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3698: # log the associated role with the area
 3699:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3700:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3701: }
 3702: 
 3703: sub custom_roleprivs {
 3704:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3705:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3706:     my $homsvr=homeserver($rauthor,$rdomain);
 3707:     if (&hostname($homsvr) ne '') {
 3708:         my ($rdummy,$roledef)=
 3709:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3710:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3711:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3712:             if (defined($syspriv)) {
 3713:                 $$allroles{'cm./'}.=':'.$syspriv;
 3714:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3715:             }
 3716:             if ($tdomain ne '') {
 3717:                 if (defined($dompriv)) {
 3718:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3719:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3720:                 }
 3721:                 if (($trest ne '') && (defined($coursepriv))) {
 3722:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3723:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3724:                 }
 3725:             }
 3726:         }
 3727:     }
 3728: }
 3729: 
 3730: sub group_roleprivs {
 3731:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3732:     my $access = 1;
 3733:     my $now = time;
 3734:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3735:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3736:     if ($access) {
 3737:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3738:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3739:     }
 3740: }
 3741: 
 3742: sub standard_roleprivs {
 3743:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3744:     if (defined($pr{$trole.':s'})) {
 3745:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3746:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3747:     }
 3748:     if ($tdomain ne '') {
 3749:         if (defined($pr{$trole.':d'})) {
 3750:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3751:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3752:         }
 3753:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3754:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3755:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3756:         }
 3757:     }
 3758: }
 3759: 
 3760: sub set_userprivs {
 3761:     my ($userroles,$allroles,$allgroups) = @_; 
 3762:     my $author=0;
 3763:     my $adv=0;
 3764:     my %grouproles = ();
 3765:     if (keys(%{$allgroups}) > 0) {
 3766:         foreach my $role (keys %{$allroles}) {
 3767:             my ($trole,$area,$sec,$extendedarea);
 3768:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3769:                 $trole = $1;
 3770:                 $area = $2;
 3771:                 $sec = $3;
 3772:                 $extendedarea = $area.$sec;
 3773:                 if (exists($$allgroups{$area})) {
 3774:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3775:                         my $spec = $trole.'.'.$extendedarea;
 3776:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3777:                                                 $$allgroups{$area}{$group};
 3778:                     }
 3779:                 }
 3780:             }
 3781:         }
 3782:     }
 3783:     foreach my $group (keys(%grouproles)) {
 3784:         $$allroles{$group} = $grouproles{$group};
 3785:     }
 3786:     foreach my $role (keys(%{$allroles})) {
 3787:         my %thesepriv;
 3788:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3789:         foreach my $item (split(/:/,$$allroles{$role})) {
 3790:             if ($item ne '') {
 3791:                 my ($privilege,$restrictions)=split(/&/,$item);
 3792:                 if ($restrictions eq '') {
 3793:                     $thesepriv{$privilege}='F';
 3794:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3795:                     $thesepriv{$privilege}.=$restrictions;
 3796:                 }
 3797:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3798:             }
 3799:         }
 3800:         my $thesestr='';
 3801:         foreach my $priv (keys(%thesepriv)) {
 3802: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3803: 	}
 3804:         $userroles->{'user.priv.'.$role} = $thesestr;
 3805:     }
 3806:     return ($author,$adv);
 3807: }
 3808: 
 3809: # --------------------------------------------------------------- get interface
 3810: 
 3811: sub get {
 3812:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3813:    my $items='';
 3814:    foreach my $item (@$storearr) {
 3815:        $items.=&escape($item).'&';
 3816:    }
 3817:    $items=~s/\&$//;
 3818:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3819:    if (!$uname) { $uname=$env{'user.name'}; }
 3820:    my $uhome=&homeserver($uname,$udomain);
 3821: 
 3822:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3823:    my @pairs=split(/\&/,$rep);
 3824:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3825:      return @pairs;
 3826:    }
 3827:    my %returnhash=();
 3828:    my $i=0;
 3829:    foreach my $item (@$storearr) {
 3830:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3831:       $i++;
 3832:    }
 3833:    return %returnhash;
 3834: }
 3835: 
 3836: # --------------------------------------------------------------- del interface
 3837: 
 3838: sub del {
 3839:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3840:    my $items='';
 3841:    foreach my $item (@$storearr) {
 3842:        $items.=&escape($item).'&';
 3843:    }
 3844:    $items=~s/\&$//;
 3845:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3846:    if (!$uname) { $uname=$env{'user.name'}; }
 3847:    my $uhome=&homeserver($uname,$udomain);
 3848: 
 3849:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3850: }
 3851: 
 3852: # -------------------------------------------------------------- dump interface
 3853: 
 3854: sub dump {
 3855:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3856:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3857:     if (!$uname) { $uname=$env{'user.name'}; }
 3858:     my $uhome=&homeserver($uname,$udomain);
 3859:     if ($regexp) {
 3860: 	$regexp=&escape($regexp);
 3861:     } else {
 3862: 	$regexp='.';
 3863:     }
 3864:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3865:     my @pairs=split(/\&/,$rep);
 3866:     my %returnhash=();
 3867:     foreach my $item (@pairs) {
 3868: 	my ($key,$value)=split(/=/,$item,2);
 3869: 	$key = &unescape($key);
 3870: 	next if ($key =~ /^error: 2 /);
 3871: 	$returnhash{$key}=&thaw_unescape($value);
 3872:     }
 3873:     return %returnhash;
 3874: }
 3875: 
 3876: # --------------------------------------------------------- dumpstore interface
 3877: 
 3878: sub dumpstore {
 3879:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3880:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3881:    if (!$uname) { $uname=$env{'user.name'}; }
 3882:    my $uhome=&homeserver($uname,$udomain);
 3883:    if ($regexp) {
 3884:        $regexp=&escape($regexp);
 3885:    } else {
 3886:        $regexp='.';
 3887:    }
 3888:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3889:    my @pairs=split(/\&/,$rep);
 3890:    my %returnhash=();
 3891:    foreach my $item (@pairs) {
 3892:        my ($key,$value)=split(/=/,$item,2);
 3893:        next if ($key =~ /^error: 2 /);
 3894:        $returnhash{$key}=&thaw_unescape($value);
 3895:    }
 3896:    return %returnhash;
 3897: }
 3898: 
 3899: # -------------------------------------------------------------- keys interface
 3900: 
 3901: sub getkeys {
 3902:    my ($namespace,$udomain,$uname)=@_;
 3903:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3904:    if (!$uname) { $uname=$env{'user.name'}; }
 3905:    my $uhome=&homeserver($uname,$udomain);
 3906:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3907:    my @keyarray=();
 3908:    foreach my $key (split(/\&/,$rep)) {
 3909:       next if ($key =~ /^error: 2 /);
 3910:       push(@keyarray,&unescape($key));
 3911:    }
 3912:    return @keyarray;
 3913: }
 3914: 
 3915: # --------------------------------------------------------------- currentdump
 3916: sub currentdump {
 3917:    my ($courseid,$sdom,$sname)=@_;
 3918:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3919:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3920:    $sname    = $env{'user.name'}         if (! defined($sname));
 3921:    my $uhome = &homeserver($sname,$sdom);
 3922:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3923:    return if ($rep =~ /^(error:|no_such_host)/);
 3924:    #
 3925:    my %returnhash=();
 3926:    #
 3927:    if ($rep eq "unknown_cmd") { 
 3928:        # an old lond will not know currentdump
 3929:        # Do a dump and make it look like a currentdump
 3930:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3931:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3932:        my %hash = @tmp;
 3933:        @tmp=();
 3934:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3935:    } else {
 3936:        my @pairs=split(/\&/,$rep);
 3937:        foreach my $pair (@pairs) {
 3938:            my ($key,$value)=split(/=/,$pair,2);
 3939:            my ($symb,$param) = split(/:/,$key);
 3940:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3941:                                                         &thaw_unescape($value);
 3942:        }
 3943:    }
 3944:    return %returnhash;
 3945: }
 3946: 
 3947: sub convert_dump_to_currentdump{
 3948:     my %hash = %{shift()};
 3949:     my %returnhash;
 3950:     # Code ripped from lond, essentially.  The only difference
 3951:     # here is the unescaping done by lonnet::dump().  Conceivably
 3952:     # we might run in to problems with parameter names =~ /^v\./
 3953:     while (my ($key,$value) = each(%hash)) {
 3954:         my ($v,$symb,$param) = split(/:/,$key);
 3955: 	$symb  = &unescape($symb);
 3956: 	$param = &unescape($param);
 3957:         next if ($v eq 'version' || $symb eq 'keys');
 3958:         next if (exists($returnhash{$symb}) &&
 3959:                  exists($returnhash{$symb}->{$param}) &&
 3960:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3961:         $returnhash{$symb}->{$param}=$value;
 3962:         $returnhash{$symb}->{'v.'.$param}=$v;
 3963:     }
 3964:     #
 3965:     # Remove all of the keys in the hashes which keep track of
 3966:     # the version of the parameter.
 3967:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3968:         # use a foreach because we are going to delete from the hash.
 3969:         foreach my $key (keys(%$param_hash)) {
 3970:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3971:         }
 3972:     }
 3973:     return \%returnhash;
 3974: }
 3975: 
 3976: # ------------------------------------------------------ critical inc interface
 3977: 
 3978: sub cinc {
 3979:     return &inc(@_,'critical');
 3980: }
 3981: 
 3982: # --------------------------------------------------------------- inc interface
 3983: 
 3984: sub inc {
 3985:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3986:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3987:     if (!$uname) { $uname=$env{'user.name'}; }
 3988:     my $uhome=&homeserver($uname,$udomain);
 3989:     my $items='';
 3990:     if (! ref($store)) {
 3991:         # got a single value, so use that instead
 3992:         $items = &escape($store).'=&';
 3993:     } elsif (ref($store) eq 'SCALAR') {
 3994:         $items = &escape($$store).'=&';        
 3995:     } elsif (ref($store) eq 'ARRAY') {
 3996:         $items = join('=&',map {&escape($_);} @{$store});
 3997:     } elsif (ref($store) eq 'HASH') {
 3998:         while (my($key,$value) = each(%{$store})) {
 3999:             $items.= &escape($key).'='.&escape($value).'&';
 4000:         }
 4001:     }
 4002:     $items=~s/\&$//;
 4003:     if ($critical) {
 4004: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4005:     } else {
 4006: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4007:     }
 4008: }
 4009: 
 4010: # --------------------------------------------------------------- put interface
 4011: 
 4012: sub put {
 4013:    my ($namespace,$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 $item (keys(%$storehash)) {
 4019:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4020:    }
 4021:    $items=~s/\&$//;
 4022:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4023: }
 4024: 
 4025: # ------------------------------------------------------------ newput interface
 4026: 
 4027: sub newput {
 4028:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4029:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4030:    if (!$uname) { $uname=$env{'user.name'}; }
 4031:    my $uhome=&homeserver($uname,$udomain);
 4032:    my $items='';
 4033:    foreach my $key (keys(%$storehash)) {
 4034:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4035:    }
 4036:    $items=~s/\&$//;
 4037:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4038: }
 4039: 
 4040: # ---------------------------------------------------------  putstore interface
 4041: 
 4042: sub putstore {
 4043:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4044:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4045:    if (!$uname) { $uname=$env{'user.name'}; }
 4046:    my $uhome=&homeserver($uname,$udomain);
 4047:    my $items='';
 4048:    foreach my $key (keys(%$storehash)) {
 4049:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4050:    }
 4051:    $items=~s/\&$//;
 4052:    my $esc_symb=&escape($symb);
 4053:    my $esc_v=&escape($version);
 4054:    my $reply =
 4055:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4056: 	      $uhome);
 4057:    if ($reply eq 'unknown_cmd') {
 4058:        # gfall back to way things use to be done
 4059:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4060: 			    $uname);
 4061:    }
 4062:    return $reply;
 4063: }
 4064: 
 4065: sub old_putstore {
 4066:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4067:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4068:     if (!$uname) { $uname=$env{'user.name'}; }
 4069:     my $uhome=&homeserver($uname,$udomain);
 4070:     my %newstorehash;
 4071:     foreach my $item (keys(%$storehash)) {
 4072: 	my $key = $version.':'.&escape($symb).':'.$item;
 4073: 	$newstorehash{$key} = $storehash->{$item};
 4074:     }
 4075:     my $items='';
 4076:     my %allitems = ();
 4077:     foreach my $item (keys(%newstorehash)) {
 4078: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4079: 	    my $key = $1.':keys:'.$2;
 4080: 	    $allitems{$key} .= $3.':';
 4081: 	}
 4082: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4083:     }
 4084:     foreach my $item (keys(%allitems)) {
 4085: 	$allitems{$item} =~ s/\:$//;
 4086: 	$items.= $item.'='.$allitems{$item}.'&';
 4087:     }
 4088:     $items=~s/\&$//;
 4089:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4090: }
 4091: 
 4092: # ------------------------------------------------------ critical put interface
 4093: 
 4094: sub cput {
 4095:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4096:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4097:    if (!$uname) { $uname=$env{'user.name'}; }
 4098:    my $uhome=&homeserver($uname,$udomain);
 4099:    my $items='';
 4100:    foreach my $item (keys(%$storehash)) {
 4101:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4102:    }
 4103:    $items=~s/\&$//;
 4104:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4105: }
 4106: 
 4107: # -------------------------------------------------------------- eget interface
 4108: 
 4109: sub eget {
 4110:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4111:    my $items='';
 4112:    foreach my $item (@$storearr) {
 4113:        $items.=&escape($item).'&';
 4114:    }
 4115:    $items=~s/\&$//;
 4116:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4117:    if (!$uname) { $uname=$env{'user.name'}; }
 4118:    my $uhome=&homeserver($uname,$udomain);
 4119:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4120:    my @pairs=split(/\&/,$rep);
 4121:    my %returnhash=();
 4122:    my $i=0;
 4123:    foreach my $item (@$storearr) {
 4124:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4125:       $i++;
 4126:    }
 4127:    return %returnhash;
 4128: }
 4129: 
 4130: # ------------------------------------------------------------ tmpput interface
 4131: sub tmpput {
 4132:     my ($storehash,$server,$context)=@_;
 4133:     my $items='';
 4134:     foreach my $item (keys(%$storehash)) {
 4135: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4136:     }
 4137:     $items=~s/\&$//;
 4138:     if (defined($context)) {
 4139:         $items .= ':'.&escape($context);
 4140:     }
 4141:     return &reply("tmpput:$items",$server);
 4142: }
 4143: 
 4144: # ------------------------------------------------------------ tmpget interface
 4145: sub tmpget {
 4146:     my ($token,$server)=@_;
 4147:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4148:     my $rep=&reply("tmpget:$token",$server);
 4149:     my %returnhash;
 4150:     foreach my $item (split(/\&/,$rep)) {
 4151: 	my ($key,$value)=split(/=/,$item);
 4152:         next if ($key =~ /^error: 2 /);
 4153: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4154:     }
 4155:     return %returnhash;
 4156: }
 4157: 
 4158: # ------------------------------------------------------------ tmpget interface
 4159: sub tmpdel {
 4160:     my ($token,$server)=@_;
 4161:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4162:     return &reply("tmpdel:$token",$server);
 4163: }
 4164: 
 4165: # -------------------------------------------------- portfolio access checking
 4166: 
 4167: sub portfolio_access {
 4168:     my ($requrl) = @_;
 4169:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4170:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4171:     if ($result) {
 4172:         my %setters;
 4173:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4174:             my ($startblock,$endblock) =
 4175:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4176:             if ($startblock && $endblock) {
 4177:                 return 'B';
 4178:             }
 4179:         } else {
 4180:             my ($startblock,$endblock) =
 4181:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4182:             if ($startblock && $endblock) {
 4183:                 return 'B';
 4184:             }
 4185:         }
 4186:     }
 4187:     if ($result eq 'ok') {
 4188:        return 'F';
 4189:     } elsif ($result =~ /^[^:]+:guest_/) {
 4190:        return 'A';
 4191:     }
 4192:     return '';
 4193: }
 4194: 
 4195: sub get_portfolio_access {
 4196:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4197: 
 4198:     if (!ref($access_hash)) {
 4199: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4200: 	my %access_controls = &get_access_controls($current_perms,$group,
 4201: 						   $file_name);
 4202: 	$access_hash = $access_controls{$file_name};
 4203:     }
 4204: 
 4205:     my ($public,$guest,@domains,@users,@courses,@groups);
 4206:     my $now = time;
 4207:     if (ref($access_hash) eq 'HASH') {
 4208:         foreach my $key (keys(%{$access_hash})) {
 4209:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4210:             if ($start > $now) {
 4211:                 next;
 4212:             }
 4213:             if ($end && $end<$now) {
 4214:                 next;
 4215:             }
 4216:             if ($scope eq 'public') {
 4217:                 $public = $key;
 4218:                 last;
 4219:             } elsif ($scope eq 'guest') {
 4220:                 $guest = $key;
 4221:             } elsif ($scope eq 'domains') {
 4222:                 push(@domains,$key);
 4223:             } elsif ($scope eq 'users') {
 4224:                 push(@users,$key);
 4225:             } elsif ($scope eq 'course') {
 4226:                 push(@courses,$key);
 4227:             } elsif ($scope eq 'group') {
 4228:                 push(@groups,$key);
 4229:             }
 4230:         }
 4231:         if ($public) {
 4232:             return 'ok';
 4233:         }
 4234:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4235:             if ($guest) {
 4236:                 return $guest;
 4237:             }
 4238:         } else {
 4239:             if (@domains > 0) {
 4240:                 foreach my $domkey (@domains) {
 4241:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4242:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4243:                             return 'ok';
 4244:                         }
 4245:                     }
 4246:                 }
 4247:             }
 4248:             if (@users > 0) {
 4249:                 foreach my $userkey (@users) {
 4250:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4251:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4252:                             if (ref($item) eq 'HASH') {
 4253:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4254:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4255:                                     return 'ok';
 4256:                                 }
 4257:                             }
 4258:                         }
 4259:                     } 
 4260:                 }
 4261:             }
 4262:             my %roleshash;
 4263:             my @courses_and_groups = @courses;
 4264:             push(@courses_and_groups,@groups); 
 4265:             if (@courses_and_groups > 0) {
 4266:                 my (%allgroups,%allroles); 
 4267:                 my ($start,$end,$role,$sec,$group);
 4268:                 foreach my $envkey (%env) {
 4269:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4270:                         my $cid = $2.'_'.$3; 
 4271:                         if ($1 eq 'gr') {
 4272:                             $group = $4;
 4273:                             $allgroups{$cid}{$group} = $env{$envkey};
 4274:                         } else {
 4275:                             if ($4 eq '') {
 4276:                                 $sec = 'none';
 4277:                             } else {
 4278:                                 $sec = $4;
 4279:                             }
 4280:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4281:                         }
 4282:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4283:                         my $cid = $2.'_'.$3;
 4284:                         if ($4 eq '') {
 4285:                             $sec = 'none';
 4286:                         } else {
 4287:                             $sec = $4;
 4288:                         }
 4289:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4290:                     }
 4291:                 }
 4292:                 if (keys(%allroles) == 0) {
 4293:                     return;
 4294:                 }
 4295:                 foreach my $key (@courses_and_groups) {
 4296:                     my %content = %{$$access_hash{$key}};
 4297:                     my $cnum = $content{'number'};
 4298:                     my $cdom = $content{'domain'};
 4299:                     my $cid = $cdom.'_'.$cnum;
 4300:                     if (!exists($allroles{$cid})) {
 4301:                         next;
 4302:                     }    
 4303:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4304:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4305:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4306:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4307:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4308:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4309:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4310:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4311:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4312:                                         if (grep/^all$/,@sections) {
 4313:                                             return 'ok';
 4314:                                         } else {
 4315:                                             if (grep/^$sec$/,@sections) {
 4316:                                                 return 'ok';
 4317:                                             }
 4318:                                         }
 4319:                                     }
 4320:                                 }
 4321:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4322:                                     if (grep/^none$/,@groups) {
 4323:                                         return 'ok';
 4324:                                     }
 4325:                                 } else {
 4326:                                     if (grep/^all$/,@groups) {
 4327:                                         return 'ok';
 4328:                                     } 
 4329:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4330:                                         if (grep/^$group$/,@groups) {
 4331:                                             return 'ok';
 4332:                                         }
 4333:                                     }
 4334:                                 } 
 4335:                             }
 4336:                         }
 4337:                     }
 4338:                 }
 4339:             }
 4340:             if ($guest) {
 4341:                 return $guest;
 4342:             }
 4343:         }
 4344:     }
 4345:     return;
 4346: }
 4347: 
 4348: sub course_group_datechecker {
 4349:     my ($dates,$now,$status) = @_;
 4350:     my ($start,$end) = split(/\./,$dates);
 4351:     if (!$start && !$end) {
 4352:         return 'ok';
 4353:     }
 4354:     if (grep/^active$/,@{$status}) {
 4355:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4356:             return 'ok';
 4357:         }
 4358:     }
 4359:     if (grep/^previous$/,@{$status}) {
 4360:         if ($end > $now ) {
 4361:             return 'ok';
 4362:         }
 4363:     }
 4364:     if (grep/^future$/,@{$status}) {
 4365:         if ($start > $now) {
 4366:             return 'ok';
 4367:         }
 4368:     }
 4369:     return; 
 4370: }
 4371: 
 4372: sub parse_portfolio_url {
 4373:     my ($url) = @_;
 4374: 
 4375:     my ($type,$udom,$unum,$group,$file_name);
 4376:     
 4377:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4378: 	$type = 1;
 4379:         $udom = $1;
 4380:         $unum = $2;
 4381:         $file_name = $3;
 4382:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4383: 	$type = 2;
 4384:         $udom = $1;
 4385:         $unum = $2;
 4386:         $group = $3;
 4387:         $file_name = $3.'/'.$4;
 4388:     }
 4389:     if (wantarray) {
 4390: 	return ($type,$udom,$unum,$file_name,$group);
 4391:     }
 4392:     return $type;
 4393: }
 4394: 
 4395: sub is_portfolio_url {
 4396:     my ($url) = @_;
 4397:     return scalar(&parse_portfolio_url($url));
 4398: }
 4399: 
 4400: sub is_portfolio_file {
 4401:     my ($file) = @_;
 4402:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4403:         return 1;
 4404:     }
 4405:     return;
 4406: }
 4407: 
 4408: sub usertools_access {
 4409:     my ($uname,$udom,$tool,$action) = @_;
 4410:     my $access;
 4411:     my %tools = (
 4412:                   aboutme   => 1,
 4413:                   blog      => 1,
 4414:                   portfolio => 1,
 4415:                 );
 4416:     return if (!defined($tools{$tool}));
 4417: 
 4418:     if ((!defined($udom)) || (!defined($uname))) {
 4419:         $udom = $env{'user.domain'};
 4420:         $uname = $env{'user.name'};
 4421:     }
 4422: 
 4423:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4424:         if ($action ne 'reload') {
 4425:             return $env{'environment.availabletools.'.$tool};
 4426:         } 
 4427:     }
 4428: 
 4429:     my ($toolstatus,$inststatus);
 4430: 
 4431:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4432:         $toolstatus = $env{'environment.tools.'.$tool};
 4433:         $inststatus = $env{'environment.inststatus'};
 4434:     } else {
 4435:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
 4436:         $toolstatus = $userenv{'tools.'.$tool};
 4437:         $inststatus = $userenv{'inststatus'};
 4438:     }
 4439: 
 4440:     if ($toolstatus ne '') {
 4441:         if ($toolstatus) {
 4442:             $access = 1;
 4443:         } else {
 4444:             $access = 0;
 4445:         }
 4446:         return $access;
 4447:     }
 4448: 
 4449:     my $is_adv = &is_advanced_user($udom,$uname);
 4450:     my %domdef = &get_domain_defaults($udom);
 4451:     if (ref($domdef{$tool}) eq 'HASH') {
 4452:         if ($is_adv) {
 4453:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4454:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4455:                     $access = 1;
 4456:                 } else {
 4457:                     $access = 0;
 4458:                 }
 4459:                 return $access;
 4460:             }
 4461:         }
 4462:         if ($inststatus ne '') {
 4463:             my ($hasaccess,$hasnoaccess);
 4464:             foreach my $affiliation (split(/:/,$inststatus)) {
 4465:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4466:                     if ($domdef{$tool}{$affiliation}) {
 4467:                         $hasaccess = 1;
 4468:                     } else {
 4469:                         $hasnoaccess = 1;
 4470:                     }
 4471:                 }
 4472:             }
 4473:             if ($hasaccess || $hasnoaccess) {
 4474:                 if ($hasaccess) {
 4475:                     $access = 1;
 4476:                 } elsif ($hasnoaccess) {
 4477:                     $access = 0; 
 4478:                 }
 4479:                 return $access;
 4480:             }
 4481:         } else {
 4482:             if ($domdef{$tool}{'default'} ne '') {
 4483:                 if ($domdef{$tool}{'default'}) {
 4484:                     $access = 1;
 4485:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4486:                     $access = 0;
 4487:                 }
 4488:                 return $access;
 4489:             }
 4490:         }
 4491:     } else {
 4492:         $access = 1;
 4493:         return $access;
 4494:     }
 4495: }
 4496: 
 4497: sub is_advanced_user {
 4498:     my ($udom,$uname) = @_;
 4499:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4500:     my %allroles;
 4501:     my $is_adv;
 4502:     foreach my $role (keys(%roleshash)) {
 4503:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4504:         my $area = '/'.$tdomain.'/'.$trest;
 4505:         if ($sec ne '') {
 4506:             $area .= '/'.$sec;
 4507:         }
 4508:         if (($area ne '') && ($trole ne '')) {
 4509:             my $spec=$trole.'.'.$area;
 4510:             if ($trole =~ /^cr\//) {
 4511:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4512:             } elsif ($trole ne 'gr') {
 4513:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4514:             }
 4515:         }
 4516:     }
 4517:     foreach my $role (keys(%allroles)) {
 4518:         last if ($is_adv);
 4519:         foreach my $item (split(/:/,$allroles{$role})) {
 4520:             if ($item ne '') {
 4521:                 my ($privilege,$restrictions)=split(/&/,$item);
 4522:                 if ($privilege eq 'adv') {
 4523:                     $is_adv = 1;
 4524:                     last;
 4525:                 }
 4526:             }
 4527:         }
 4528:     }
 4529:     return $is_adv;
 4530: }
 4531: 
 4532: # ---------------------------------------------- Custom access rule evaluation
 4533: 
 4534: sub customaccess {
 4535:     my ($priv,$uri)=@_;
 4536:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4537:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4538:     $udom = &LONCAPA::clean_domain($udom);
 4539:     $ucrs = &LONCAPA::clean_username($ucrs);
 4540:     my $access=0;
 4541:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4542: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4543: 	if ($type eq 'user') {
 4544: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4545: 		my ($tdom,$tuname)=split(m{/},$scope);
 4546: 		if ($tdom) {
 4547: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4548: 		}
 4549: 		if ($tuname) {
 4550: 		    if ($tuname ne $env{'user.name'}) { next; }
 4551: 		}
 4552: 		$access=($effect eq 'allow');
 4553: 		last;
 4554: 	    }
 4555: 	} else {
 4556: 	    if ($role) {
 4557: 		if ($role ne $urole) { next; }
 4558: 	    }
 4559: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4560: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4561: 		if ($tdom) {
 4562: 		    if ($tdom ne $udom) { next; }
 4563: 		}
 4564: 		if ($tcrs) {
 4565: 		    if ($tcrs ne $ucrs) { next; }
 4566: 		}
 4567: 		if ($tsec) {
 4568: 		    if ($tsec ne $usec) { next; }
 4569: 		}
 4570: 		$access=($effect eq 'allow');
 4571: 		last;
 4572: 	    }
 4573: 	    if ($realm eq '' && $role eq '') {
 4574: 		$access=($effect eq 'allow');
 4575: 	    }
 4576: 	}
 4577:     }
 4578:     return $access;
 4579: }
 4580: 
 4581: # ------------------------------------------------- Check for a user privilege
 4582: 
 4583: sub allowed {
 4584:     my ($priv,$uri,$symb,$role)=@_;
 4585:     my $ver_orguri=$uri;
 4586:     $uri=&deversion($uri);
 4587:     my $orguri=$uri;
 4588:     $uri=&declutter($uri);
 4589: 
 4590:     if ($priv eq 'evb') {
 4591: # Evade communication block restrictions for specified role in a course
 4592:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4593:             return $1;
 4594:         } else {
 4595:             return;
 4596:         }
 4597:     }
 4598: 
 4599:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4600: # Free bre access to adm and meta resources
 4601:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4602: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4603: 	&& ($priv eq 'bre')) {
 4604: 	return 'F';
 4605:     }
 4606: 
 4607: # Free bre access to user's own portfolio contents
 4608:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4609:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4610: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4611:         my %setters;
 4612:         my ($startblock,$endblock) = 
 4613:             &Apache::loncommon::blockcheck(\%setters,'port');
 4614:         if ($startblock && $endblock) {
 4615:             return 'B';
 4616:         } else {
 4617:             return 'F';
 4618:         }
 4619:     }
 4620: 
 4621: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4622:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4623:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4624:         if (exists($env{'request.course.id'})) {
 4625:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4626:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4627:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4628:                 my $courseprivid=$env{'request.course.id'};
 4629:                 $courseprivid=~s/\_/\//;
 4630:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4631:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4632:                     return $1; 
 4633:                 } else {
 4634:                     if ($env{'request.course.sec'}) {
 4635:                         $courseprivid.='/'.$env{'request.course.sec'};
 4636:                     }
 4637:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4638:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4639:                         return $2;
 4640:                     }
 4641:                 }
 4642:             }
 4643:         }
 4644:     }
 4645: 
 4646: # Free bre to public access
 4647: 
 4648:     if ($priv eq 'bre') {
 4649:         my $copyright=&metadata($uri,'copyright');
 4650: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4651:            return 'F'; 
 4652:         }
 4653:         if ($copyright eq 'priv') {
 4654:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4655: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4656: 		return '';
 4657:             }
 4658:         }
 4659:         if ($copyright eq 'domain') {
 4660:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4661: 	    unless (($env{'user.domain'} eq $1) ||
 4662:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4663: 		return '';
 4664:             }
 4665:         }
 4666:         if ($env{'request.role'}=~ /li\.\//) {
 4667:             # Library role, so allow browsing of resources in this domain.
 4668:             return 'F';
 4669:         }
 4670:         if ($copyright eq 'custom') {
 4671: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4672:         }
 4673:     }
 4674:     # Domain coordinator is trying to create a course
 4675:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4676:         # uri is the requested domain in this case.
 4677:         # comparison to 'request.role.domain' shows if the user has selected
 4678:         # a role of dc for the domain in question.
 4679:         return 'F' if ($uri eq $env{'request.role.domain'});
 4680:     }
 4681: 
 4682:     my $thisallowed='';
 4683:     my $statecond=0;
 4684:     my $courseprivid='';
 4685: 
 4686: # Course
 4687: 
 4688:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4689:        $thisallowed.=$1;
 4690:     }
 4691: 
 4692: # Domain
 4693: 
 4694:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4695:        =~/\Q$priv\E\&([^\:]*)/) {
 4696:        $thisallowed.=$1;
 4697:     }
 4698: 
 4699: # Course: uri itself is a course
 4700:     my $courseuri=$uri;
 4701:     $courseuri=~s/\_(\d)/\/$1/;
 4702:     $courseuri=~s/^([^\/])/\/$1/;
 4703: 
 4704:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4705:        =~/\Q$priv\E\&([^\:]*)/) {
 4706:        $thisallowed.=$1;
 4707:     }
 4708: 
 4709: # URI is an uploaded document for this course, default permissions don't matter
 4710: # not allowing 'edit' access (editupload) to uploaded course docs
 4711:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4712: 	$thisallowed='';
 4713:         my ($match)=&is_on_map($uri);
 4714:         if ($match) {
 4715:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4716:                   =~/\Q$priv\E\&([^\:]*)/) {
 4717:                 $thisallowed.=$1;
 4718:             }
 4719:         } else {
 4720:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4721:             if ($refuri) {
 4722:                 if ($refuri =~ m|^/adm/|) {
 4723:                     $thisallowed='F';
 4724:                 } else {
 4725:                     $refuri=&declutter($refuri);
 4726:                     my ($match) = &is_on_map($refuri);
 4727:                     if ($match) {
 4728:                         $thisallowed='F';
 4729:                     }
 4730:                 }
 4731:             }
 4732:         }
 4733:     }
 4734: 
 4735:     if ($priv eq 'bre'
 4736: 	&& $thisallowed ne 'F' 
 4737: 	&& $thisallowed ne '2'
 4738: 	&& &is_portfolio_url($uri)) {
 4739: 	$thisallowed = &portfolio_access($uri);
 4740:     }
 4741:     
 4742: # Full access at system, domain or course-wide level? Exit.
 4743:     if ($thisallowed=~/F/) {
 4744: 	return 'F';
 4745:     }
 4746: 
 4747: # If this is generating or modifying users, exit with special codes
 4748: 
 4749:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4750: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4751: 	    my ($audom,$auname)=split('/',$uri);
 4752: # no author name given, so this just checks on the general right to make a co-author in this domain
 4753: 	    unless ($auname) { return $thisallowed; }
 4754: # an author name is given, so we are about to actually make a co-author for a certain account
 4755: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4756: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4757: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4758: 	}
 4759: 	return $thisallowed;
 4760:     }
 4761: #
 4762: # Gathered so far: system, domain and course wide privileges
 4763: #
 4764: # Course: See if uri or referer is an individual resource that is part of 
 4765: # the course
 4766: 
 4767:     if ($env{'request.course.id'}) {
 4768: 
 4769:        $courseprivid=$env{'request.course.id'};
 4770:        if ($env{'request.course.sec'}) {
 4771:           $courseprivid.='/'.$env{'request.course.sec'};
 4772:        }
 4773:        $courseprivid=~s/\_/\//;
 4774:        my $checkreferer=1;
 4775:        my ($match,$cond)=&is_on_map($uri);
 4776:        if ($match) {
 4777:            $statecond=$cond;
 4778:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4779:                =~/\Q$priv\E\&([^\:]*)/) {
 4780:                $thisallowed.=$1;
 4781:                $checkreferer=0;
 4782:            }
 4783:        }
 4784:        
 4785:        if ($checkreferer) {
 4786: 	  my $refuri=$env{'httpref.'.$orguri};
 4787:             unless ($refuri) {
 4788:                 foreach my $key (keys(%env)) {
 4789: 		    if ($key=~/^httpref\..*\*/) {
 4790: 			my $pattern=$key;
 4791:                         $pattern=~s/^httpref\.\/res\///;
 4792:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4793:                         $pattern=~s/\//\\\//g;
 4794:                         if ($orguri=~/$pattern/) {
 4795: 			    $refuri=$env{$key};
 4796:                         }
 4797:                     }
 4798:                 }
 4799:             }
 4800: 
 4801:          if ($refuri) { 
 4802: 	  $refuri=&declutter($refuri);
 4803:           my ($match,$cond)=&is_on_map($refuri);
 4804:             if ($match) {
 4805:               my $refstatecond=$cond;
 4806:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4807:                   =~/\Q$priv\E\&([^\:]*)/) {
 4808:                   $thisallowed.=$1;
 4809:                   $uri=$refuri;
 4810:                   $statecond=$refstatecond;
 4811:               }
 4812:           }
 4813:         }
 4814:        }
 4815:    }
 4816: 
 4817: #
 4818: # Gathered now: all privileges that could apply, and condition number
 4819: # 
 4820: #
 4821: # Full or no access?
 4822: #
 4823: 
 4824:     if ($thisallowed=~/F/) {
 4825: 	return 'F';
 4826:     }
 4827: 
 4828:     unless ($thisallowed) {
 4829:         return '';
 4830:     }
 4831: 
 4832: # Restrictions exist, deal with them
 4833: #
 4834: #   C:according to course preferences
 4835: #   R:according to resource settings
 4836: #   L:unless locked
 4837: #   X:according to user session state
 4838: #
 4839: 
 4840: # Possibly locked functionality, check all courses
 4841: # Locks might take effect only after 10 minutes cache expiration for other
 4842: # courses, and 2 minutes for current course
 4843: 
 4844:     my $envkey;
 4845:     if ($thisallowed=~/L/) {
 4846:         foreach $envkey (keys %env) {
 4847:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4848:                my $courseid=$2;
 4849:                my $roleid=$1.'.'.$2;
 4850:                $courseid=~s/^\///;
 4851:                my $expiretime=600;
 4852:                if ($env{'request.role'} eq $roleid) {
 4853: 		  $expiretime=120;
 4854:                }
 4855: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4856:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4857:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4858: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4859:                }
 4860:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4861:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4862: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4863:                        &log($env{'user.domain'},$env{'user.name'},
 4864:                             $env{'user.home'},
 4865:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4866:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4867:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4868: 		       return '';
 4869:                    }
 4870:                }
 4871:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4872:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4873: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4874:                        &log($env{'user.domain'},$env{'user.name'},
 4875:                             $env{'user.home'},
 4876:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4877:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4878:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4879: 		       return '';
 4880:                    }
 4881:                }
 4882: 	   }
 4883:        }
 4884:     }
 4885:    
 4886: #
 4887: # Rest of the restrictions depend on selected course
 4888: #
 4889: 
 4890:     unless ($env{'request.course.id'}) {
 4891: 	if ($thisallowed eq 'A') {
 4892: 	    return 'A';
 4893:         } elsif ($thisallowed eq 'B') {
 4894:             return 'B';
 4895: 	} else {
 4896: 	    return '1';
 4897: 	}
 4898:     }
 4899: 
 4900: #
 4901: # Now user is definitely in a course
 4902: #
 4903: 
 4904: 
 4905: # Course preferences
 4906: 
 4907:    if ($thisallowed=~/C/) {
 4908:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4909:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4910:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4911: 	   =~/\Q$rolecode\E/) {
 4912: 	   if ($priv ne 'pch') { 
 4913: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4914: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4915: 			$env{'request.course.id'});
 4916: 	   }
 4917:            return '';
 4918:        }
 4919: 
 4920:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4921: 	   =~/\Q$unamedom\E/) {
 4922: 	   if ($priv ne 'pch') { 
 4923: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4924: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4925: 			$env{'request.course.id'});
 4926: 	   }
 4927:            return '';
 4928:        }
 4929:    }
 4930: 
 4931: # Resource preferences
 4932: 
 4933:    if ($thisallowed=~/R/) {
 4934:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4935:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4936: 	   if ($priv ne 'pch') { 
 4937: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4938: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4939: 	   }
 4940: 	   return '';
 4941:        }
 4942:    }
 4943: 
 4944: # Restricted by state or randomout?
 4945: 
 4946:    if ($thisallowed=~/X/) {
 4947:       if ($env{'acc.randomout'}) {
 4948: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4949:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4950:             return ''; 
 4951:          }
 4952:       }
 4953:       if (&condval($statecond)) {
 4954: 	 return '2';
 4955:       } else {
 4956:          return '';
 4957:       }
 4958:    }
 4959: 
 4960:     if ($thisallowed eq 'A') {
 4961: 	return 'A';
 4962:     } elsif ($thisallowed eq 'B') {
 4963:         return 'B';
 4964:     }
 4965:    return 'F';
 4966: }
 4967: 
 4968: sub split_uri_for_cond {
 4969:     my $uri=&deversion(&declutter(shift));
 4970:     my @uriparts=split(/\//,$uri);
 4971:     my $filename=pop(@uriparts);
 4972:     my $pathname=join('/',@uriparts);
 4973:     return ($pathname,$filename);
 4974: }
 4975: # --------------------------------------------------- Is a resource on the map?
 4976: 
 4977: sub is_on_map {
 4978:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4979:     #Trying to find the conditional for the file
 4980:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4981: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4982:     if ($match) {
 4983: 	return (1,$1);
 4984:     } else {
 4985: 	return (0,0);
 4986:     }
 4987: }
 4988: 
 4989: # --------------------------------------------------------- Get symb from alias
 4990: 
 4991: sub get_symb_from_alias {
 4992:     my $symb=shift;
 4993:     my ($map,$resid,$url)=&decode_symb($symb);
 4994: # Already is a symb
 4995:     if ($url) { return $symb; }
 4996: # Must be an alias
 4997:     my $aliassymb='';
 4998:     my %bighash;
 4999:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5000:                             &GDBM_READER(),0640)) {
 5001:         my $rid=$bighash{'mapalias_'.$symb};
 5002: 	if ($rid) {
 5003: 	    my ($mapid,$resid)=split(/\./,$rid);
 5004: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5005: 				    $resid,$bighash{'src_'.$rid});
 5006: 	}
 5007:         untie %bighash;
 5008:     }
 5009:     return $aliassymb;
 5010: }
 5011: 
 5012: # ----------------------------------------------------------------- Define Role
 5013: 
 5014: sub definerole {
 5015:   if (allowed('mcr','/')) {
 5016:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5017:     foreach my $role (split(':',$sysrole)) {
 5018: 	my ($crole,$cqual)=split(/\&/,$role);
 5019:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5020:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5021: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5022:                return "refused:s:$crole&$cqual"; 
 5023:             }
 5024:         }
 5025:     }
 5026:     foreach my $role (split(':',$domrole)) {
 5027: 	my ($crole,$cqual)=split(/\&/,$role);
 5028:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5029:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5030: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5031:                return "refused:d:$crole&$cqual"; 
 5032:             }
 5033:         }
 5034:     }
 5035:     foreach my $role (split(':',$courole)) {
 5036: 	my ($crole,$cqual)=split(/\&/,$role);
 5037:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5038:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5039: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5040:                return "refused:c:$crole&$cqual"; 
 5041:             }
 5042:         }
 5043:     }
 5044:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5045:                 "$env{'user.domain'}:$env{'user.name'}:".
 5046: 	        "rolesdef_$rolename=".
 5047:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5048:     return reply($command,$env{'user.home'});
 5049:   } else {
 5050:     return 'refused';
 5051:   }
 5052: }
 5053: 
 5054: # ---------------- Make a metadata query against the network of library servers
 5055: 
 5056: sub metadata_query {
 5057:     my ($query,$custom,$customshow,$server_array)=@_;
 5058:     my %rhash;
 5059:     my %libserv = &all_library();
 5060:     my @server_list = (defined($server_array) ? @$server_array
 5061:                                               : keys(%libserv) );
 5062:     for my $server (@server_list) {
 5063: 	unless ($custom or $customshow) {
 5064: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5065: 	    $rhash{$server}=$reply;
 5066: 	}
 5067: 	else {
 5068: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5069: 			     &escape($custom).':'.&escape($customshow),
 5070: 			     $server);
 5071: 	    $rhash{$server}=$reply;
 5072: 	}
 5073:     }
 5074:     return \%rhash;
 5075: }
 5076: 
 5077: # ----------------------------------------- Send log queries and wait for reply
 5078: 
 5079: sub log_query {
 5080:     my ($uname,$udom,$query,%filters)=@_;
 5081:     my $uhome=&homeserver($uname,$udom);
 5082:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5083:     my $uhost=&hostname($uhome);
 5084:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5085:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5086:                        $uhome);
 5087:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5088:     return get_query_reply($queryid);
 5089: }
 5090: 
 5091: # -------------------------- Update MySQL table for portfolio file
 5092: 
 5093: sub update_portfolio_table {
 5094:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5095:     if ($group ne '') {
 5096:         $file_name =~s /^\Q$group\E//;
 5097:     }
 5098:     my $homeserver = &homeserver($uname,$udom);
 5099:     my $queryid=
 5100:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5101:                ':'.&escape($file_name).':'.$action,$homeserver);
 5102:     my $reply = &get_query_reply($queryid);
 5103:     return $reply;
 5104: }
 5105: 
 5106: # -------------------------- Update MySQL allusers table
 5107: 
 5108: sub update_allusers_table {
 5109:     my ($uname,$udom,$names) = @_;
 5110:     my $homeserver = &homeserver($uname,$udom);
 5111:     my $queryid=
 5112:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5113:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5114:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5115:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5116:                'generation='.&escape($names->{'generation'}).'%%'.
 5117:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5118:                'id='.&escape($names->{'id'}),$homeserver);
 5119:     my $reply = &get_query_reply($queryid);
 5120:     return $reply;
 5121: }
 5122: 
 5123: # ------- Request retrieval of institutional classlists for course(s)
 5124: 
 5125: sub fetch_enrollment_query {
 5126:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5127:     my $homeserver;
 5128:     my $maxtries = 1;
 5129:     if ($context eq 'automated') {
 5130:         $homeserver = $perlvar{'lonHostID'};
 5131:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5132:     } else {
 5133:         $homeserver = &homeserver($cnum,$dom);
 5134:     }
 5135:     my $host=&hostname($homeserver);
 5136:     my $cmd = '';
 5137:     foreach my $affiliate (keys %{$affiliatesref}) {
 5138:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5139:     }
 5140:     $cmd =~ s/%%$//;
 5141:     $cmd = &escape($cmd);
 5142:     my $query = 'fetchenrollment';
 5143:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5144:     unless ($queryid=~/^\Q$host\E\_/) { 
 5145:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5146:         return 'error: '.$queryid;
 5147:     }
 5148:     my $reply = &get_query_reply($queryid);
 5149:     my $tries = 1;
 5150:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5151:         $reply = &get_query_reply($queryid);
 5152:         $tries ++;
 5153:     }
 5154:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5155:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5156:     } else {
 5157:         my @responses = split(/:/,$reply);
 5158:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5159:             foreach my $line (@responses) {
 5160:                 my ($key,$value) = split(/=/,$line,2);
 5161:                 $$replyref{$key} = $value;
 5162:             }
 5163:         } else {
 5164:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5165:             foreach my $line (@responses) {
 5166:                 my ($key,$value) = split(/=/,$line);
 5167:                 $$replyref{$key} = $value;
 5168:                 if ($value > 0) {
 5169:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5170:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5171:                         my $destname = $pathname.'/'.$filename;
 5172:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5173:                         if ($xml_classlist =~ /^error/) {
 5174:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5175:                         } else {
 5176:                             if ( open(FILE,">$destname") ) {
 5177:                                 print FILE &unescape($xml_classlist);
 5178:                                 close(FILE);
 5179:                             } else {
 5180:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5181:                             }
 5182:                         }
 5183:                     }
 5184:                 }
 5185:             }
 5186:         }
 5187:         return 'ok';
 5188:     }
 5189:     return 'error';
 5190: }
 5191: 
 5192: sub get_query_reply {
 5193:     my $queryid=shift;
 5194:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5195:     my $reply='';
 5196:     for (1..100) {
 5197: 	sleep 2;
 5198:         if (-e $replyfile.'.end') {
 5199: 	    if (open(my $fh,$replyfile)) {
 5200: 		$reply = join('',<$fh>);
 5201: 		close($fh);
 5202: 	   } else { return 'error: reply_file_error'; }
 5203:            return &unescape($reply);
 5204: 	}
 5205:     }
 5206:     return 'timeout:'.$queryid;
 5207: }
 5208: 
 5209: sub courselog_query {
 5210: #
 5211: # possible filters:
 5212: # url: url or symb
 5213: # username
 5214: # domain
 5215: # action: view, submit, grade
 5216: # start: timestamp
 5217: # end: timestamp
 5218: #
 5219:     my (%filters)=@_;
 5220:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5221:     if ($filters{'url'}) {
 5222: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5223:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5224:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5225:     }
 5226:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5227:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5228:     return &log_query($cname,$cdom,'courselog',%filters);
 5229: }
 5230: 
 5231: sub userlog_query {
 5232: #
 5233: # possible filters:
 5234: # action: log check role
 5235: # start: timestamp
 5236: # end: timestamp
 5237: #
 5238:     my ($uname,$udom,%filters)=@_;
 5239:     return &log_query($uname,$udom,'userlog',%filters);
 5240: }
 5241: 
 5242: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5243: 
 5244: sub auto_run {
 5245:     my ($cnum,$cdom) = @_;
 5246:     my $response = 0;
 5247:     my $settings;
 5248:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5249:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5250:         $settings = $domconfig{'autoenroll'};
 5251:         if ($settings->{'run'} eq '1') {
 5252:             $response = 1;
 5253:         }
 5254:     } else {
 5255:         my $homeserver;
 5256:         if (&is_course($cdom,$cnum)) {
 5257:             $homeserver = &homeserver($cnum,$cdom);
 5258:         } else {
 5259:             $homeserver = &domain($cdom,'primary');
 5260:         }
 5261:         if ($homeserver ne 'no_host') {
 5262:             $response = &reply('autorun:'.$cdom,$homeserver);
 5263:         }
 5264:     }
 5265:     return $response;
 5266: }
 5267: 
 5268: sub auto_get_sections {
 5269:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5270:     my $homeserver = &homeserver($cnum,$cdom);
 5271:     my @secs = ();
 5272:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5273:     unless ($response eq 'refused') {
 5274:         @secs = split(/:/,$response);
 5275:     }
 5276:     return @secs;
 5277: }
 5278: 
 5279: sub auto_new_course {
 5280:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5281:     my $homeserver = &homeserver($cnum,$cdom);
 5282:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5283:     return $response;
 5284: }
 5285: 
 5286: sub auto_validate_courseID {
 5287:     my ($cnum,$cdom,$inst_course_id) = @_;
 5288:     my $homeserver = &homeserver($cnum,$cdom);
 5289:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5290:     return $response;
 5291: }
 5292: 
 5293: sub auto_create_password {
 5294:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5295:     my ($homeserver,$response);
 5296:     my $create_passwd = 0;
 5297:     my $authchk = '';
 5298:     if ($udom =~ /^$match_domain$/) {
 5299:         $homeserver = &domain($udom,'primary');
 5300:     }
 5301:     if ($homeserver eq '') {
 5302:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5303:             $homeserver = &homeserver($cnum,$cdom);
 5304:         }
 5305:     }
 5306:     if ($homeserver eq '') {
 5307:         $authchk = 'nodomain';
 5308:     } else {
 5309:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5310:         if ($response eq 'refused') {
 5311:             $authchk = 'refused';
 5312:         } else {
 5313:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5314:         }
 5315:     }
 5316:     return ($authparam,$create_passwd,$authchk);
 5317: }
 5318: 
 5319: sub auto_photo_permission {
 5320:     my ($cnum,$cdom,$students) = @_;
 5321:     my $homeserver = &homeserver($cnum,$cdom);
 5322:     my ($outcome,$perm_reqd,$conditions) = 
 5323: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5324:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5325: 	return (undef,undef);
 5326:     }
 5327:     return ($outcome,$perm_reqd,$conditions);
 5328: }
 5329: 
 5330: sub auto_checkphotos {
 5331:     my ($uname,$udom,$pid) = @_;
 5332:     my $homeserver = &homeserver($uname,$udom);
 5333:     my ($result,$resulttype);
 5334:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5335: 				   &escape($uname).':'.&escape($pid),
 5336: 				   $homeserver));
 5337:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5338: 	return (undef,undef);
 5339:     }
 5340:     if ($outcome) {
 5341:         ($result,$resulttype) = split(/:/,$outcome);
 5342:     } 
 5343:     return ($result,$resulttype);
 5344: }
 5345: 
 5346: sub auto_photochoice {
 5347:     my ($cnum,$cdom) = @_;
 5348:     my $homeserver = &homeserver($cnum,$cdom);
 5349:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5350: 						       &escape($cdom),
 5351: 						       $homeserver)));
 5352:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5353: 	return (undef,undef);
 5354:     }
 5355:     return ($update,$comment);
 5356: }
 5357: 
 5358: sub auto_photoupdate {
 5359:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5360:     my $homeserver = &homeserver($cnum,$dom);
 5361:     my $host=&hostname($homeserver);
 5362:     my $cmd = '';
 5363:     my $maxtries = 1;
 5364:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5365:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5366:     }
 5367:     $cmd =~ s/%%$//;
 5368:     $cmd = &escape($cmd);
 5369:     my $query = 'institutionalphotos';
 5370:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5371:     unless ($queryid=~/^\Q$host\E\_/) {
 5372:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5373:         return 'error: '.$queryid;
 5374:     }
 5375:     my $reply = &get_query_reply($queryid);
 5376:     my $tries = 1;
 5377:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5378:         $reply = &get_query_reply($queryid);
 5379:         $tries ++;
 5380:     }
 5381:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5382:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5383:     } else {
 5384:         my @responses = split(/:/,$reply);
 5385:         my $outcome = shift(@responses); 
 5386:         foreach my $item (@responses) {
 5387:             my ($key,$value) = split(/=/,$item);
 5388:             $$photo{$key} = $value;
 5389:         }
 5390:         return $outcome;
 5391:     }
 5392:     return 'error';
 5393: }
 5394: 
 5395: sub auto_instcode_format {
 5396:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5397: 	$cat_order) = @_;
 5398:     my $courses = '';
 5399:     my @homeservers;
 5400:     if ($caller eq 'global') {
 5401: 	my %servers = &get_servers($codedom,'library');
 5402: 	foreach my $tryserver (keys(%servers)) {
 5403: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5404: 		push(@homeservers,$tryserver);
 5405: 	    }
 5406:         }
 5407:     } else {
 5408:         push(@homeservers,&homeserver($caller,$codedom));
 5409:     }
 5410:     foreach my $code (keys(%{$instcodes})) {
 5411:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5412:     }
 5413:     chop($courses);
 5414:     my $ok_response = 0;
 5415:     my $response;
 5416:     while (@homeservers > 0 && $ok_response == 0) {
 5417:         my $server = shift(@homeservers); 
 5418:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5419:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5420:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5421: 		split(/:/,$response);
 5422:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5423:             push(@{$codetitles},&str2array($codetitles_str));
 5424:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5425:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5426:             $ok_response = 1;
 5427:         }
 5428:     }
 5429:     if ($ok_response) {
 5430:         return 'ok';
 5431:     } else {
 5432:         return $response;
 5433:     }
 5434: }
 5435: 
 5436: sub auto_instcode_defaults {
 5437:     my ($domain,$returnhash,$code_order) = @_;
 5438:     my @homeservers;
 5439: 
 5440:     my %servers = &get_servers($domain,'library');
 5441:     foreach my $tryserver (keys(%servers)) {
 5442: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5443: 	    push(@homeservers,$tryserver);
 5444: 	}
 5445:     }
 5446: 
 5447:     my $response;
 5448:     foreach my $server (@homeservers) {
 5449:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5450:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5451: 	
 5452: 	foreach my $pair (split(/\&/,$response)) {
 5453: 	    my ($name,$value)=split(/\=/,$pair);
 5454: 	    if ($name eq 'code_order') {
 5455: 		@{$code_order} = split(/\&/,&unescape($value));
 5456: 	    } else {
 5457: 		$returnhash->{&unescape($name)}=&unescape($value);
 5458: 	    }
 5459: 	}
 5460: 	return 'ok';
 5461:     }
 5462: 
 5463:     return $response;
 5464: } 
 5465: 
 5466: sub auto_validate_class_sec {
 5467:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5468:     my $homeserver = &homeserver($cnum,$cdom);
 5469:     my $ownerlist;
 5470:     if (ref($owners) eq 'ARRAY') {
 5471:         $ownerlist = join(',',@{$owners});
 5472:     } else {
 5473:         $ownerlist = $owners;
 5474:     }
 5475:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5476:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5477:     return $response;
 5478: }
 5479: 
 5480: # ------------------------------------------------------- Course Group routines
 5481: 
 5482: sub get_coursegroups {
 5483:     my ($cdom,$cnum,$group,$namespace) = @_;
 5484:     return(&dump($namespace,$cdom,$cnum,$group));
 5485: }
 5486: 
 5487: sub modify_coursegroup {
 5488:     my ($cdom,$cnum,$groupsettings) = @_;
 5489:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5490: }
 5491: 
 5492: sub toggle_coursegroup_status {
 5493:     my ($cdom,$cnum,$group,$action) = @_;
 5494:     my ($from_namespace,$to_namespace);
 5495:     if ($action eq 'delete') {
 5496:         $from_namespace = 'coursegroups';
 5497:         $to_namespace = 'deleted_groups';
 5498:     } else {
 5499:         $from_namespace = 'deleted_groups';
 5500:         $to_namespace = 'coursegroups';
 5501:     }
 5502:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5503:     if (my $tmp = &error(%curr_group)) {
 5504:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5505:         return ('read error',$tmp);
 5506:     } else {
 5507:         my %savedsettings = %curr_group; 
 5508:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5509:         my $deloutcome;
 5510:         if ($result eq 'ok') {
 5511:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5512:         } else {
 5513:             return ('write error',$result);
 5514:         }
 5515:         if ($deloutcome eq 'ok') {
 5516:             return 'ok';
 5517:         } else {
 5518:             return ('delete error',$deloutcome);
 5519:         }
 5520:     }
 5521: }
 5522: 
 5523: sub modify_group_roles {
 5524:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5525:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5526:     my $role = 'gr/'.&escape($userprivs);
 5527:     my ($uname,$udom) = split(/:/,$user);
 5528:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5529:     if ($result eq 'ok') {
 5530:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5531:     }
 5532:     return $result;
 5533: }
 5534: 
 5535: sub modify_coursegroup_membership {
 5536:     my ($cdom,$cnum,$membership) = @_;
 5537:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5538:     return $result;
 5539: }
 5540: 
 5541: sub get_active_groups {
 5542:     my ($udom,$uname,$cdom,$cnum) = @_;
 5543:     my $now = time;
 5544:     my %groups = ();
 5545:     foreach my $key (keys(%env)) {
 5546:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5547:             my ($start,$end) = split(/\./,$env{$key});
 5548:             if (($end!=0) && ($end<$now)) { next; }
 5549:             if (($start!=0) && ($start>$now)) { next; }
 5550:             if ($1 eq $cdom && $2 eq $cnum) {
 5551:                 $groups{$3} = $env{$key} ;
 5552:             }
 5553:         }
 5554:     }
 5555:     return %groups;
 5556: }
 5557: 
 5558: sub get_group_membership {
 5559:     my ($cdom,$cnum,$group) = @_;
 5560:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5561: }
 5562: 
 5563: sub get_users_groups {
 5564:     my ($udom,$uname,$courseid) = @_;
 5565:     my @usersgroups;
 5566:     my $cachetime=1800;
 5567: 
 5568:     my $hashid="$udom:$uname:$courseid";
 5569:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5570:     if (defined($cached)) {
 5571:         @usersgroups = split(/:/,$grouplist);
 5572:     } else {  
 5573:         $grouplist = '';
 5574:         my $courseurl = &courseid_to_courseurl($courseid);
 5575:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5576:         my $access_end = $env{'course.'.$courseid.
 5577:                               '.default_enrollment_end_date'};
 5578:         my $now = time;
 5579:         foreach my $key (keys(%roleshash)) {
 5580:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5581:                 my $group = $1;
 5582:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5583:                     my $start = $2;
 5584:                     my $end = $1;
 5585:                     if ($start == -1) { next; } # deleted from group
 5586:                     if (($start!=0) && ($start>$now)) { next; }
 5587:                     if (($end!=0) && ($end<$now)) {
 5588:                         if ($access_end && $access_end < $now) {
 5589:                             if ($access_end - $end < 86400) {
 5590:                                 push(@usersgroups,$group);
 5591:                             }
 5592:                         }
 5593:                         next;
 5594:                     }
 5595:                     push(@usersgroups,$group);
 5596:                 }
 5597:             }
 5598:         }
 5599:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5600:         $grouplist = join(':',@usersgroups);
 5601:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5602:     }
 5603:     return @usersgroups;
 5604: }
 5605: 
 5606: sub devalidate_getgroups_cache {
 5607:     my ($udom,$uname,$cdom,$cnum)=@_;
 5608:     my $courseid = $cdom.'_'.$cnum;
 5609: 
 5610:     my $hashid="$udom:$uname:$courseid";
 5611:     &devalidate_cache_new('getgroups',$hashid);
 5612: }
 5613: 
 5614: # ------------------------------------------------------------------ Plain Text
 5615: 
 5616: sub plaintext {
 5617:     my ($short,$type,$cid) = @_;
 5618:     if ($short =~ /^cr/) {
 5619: 	return (split('/',$short))[-1];
 5620:     }
 5621:     if (!defined($cid)) {
 5622:         $cid = $env{'request.course.id'};
 5623:     }
 5624:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5625:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5626:                                           '.plaintext'});
 5627:     }
 5628:     my %rolenames = (
 5629:                       Course => 'std',
 5630:                       Group => 'alt1',
 5631:                     );
 5632:     if (defined($type) && 
 5633:          defined($rolenames{$type}) && 
 5634:          defined($prp{$short}{$rolenames{$type}})) {
 5635:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5636:     } else {
 5637:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5638:     }
 5639: }
 5640: 
 5641: # ----------------------------------------------------------------- Assign Role
 5642: 
 5643: sub assignrole {
 5644:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5645:         $context)=@_;
 5646:     my $mrole;
 5647:     if ($role =~ /^cr\//) {
 5648:         my $cwosec=$url;
 5649:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5650: 	unless (&allowed('ccr',$cwosec)) {
 5651:            &logthis('Refused custom assignrole: '.
 5652:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5653: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5654:            return 'refused'; 
 5655:         }
 5656:         $mrole='cr';
 5657:     } elsif ($role =~ /^gr\//) {
 5658:         my $cwogrp=$url;
 5659:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5660:         unless (&allowed('mdg',$cwogrp)) {
 5661:             &logthis('Refused group assignrole: '.
 5662:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5663:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5664:             return 'refused';
 5665:         }
 5666:         $mrole='gr';
 5667:     } else {
 5668:         my $cwosec=$url;
 5669:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5670:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5671:             my $refused;
 5672:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5673:                 if (!(&allowed('c'.$role,$url))) {
 5674:                     $refused = 1;
 5675:                 }
 5676:             } else {
 5677:                 $refused = 1;
 5678:             }
 5679:             if ($refused) {
 5680:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5681:                     $refused = '';
 5682:                 } else {
 5683:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5684:                              ' '.$role.' '.$end.' '.$start.' by '.
 5685: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5686:                     return 'refused';
 5687:                 }
 5688:             }
 5689:         }
 5690:         $mrole=$role;
 5691:     }
 5692:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5693:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5694:     if ($end) { $command.='_'.$end; }
 5695:     if ($start) {
 5696: 	if ($end) { 
 5697:            $command.='_'.$start; 
 5698:         } else {
 5699:            $command.='_0_'.$start;
 5700:         }
 5701:     }
 5702:     my $origstart = $start;
 5703:     my $origend = $end;
 5704:     my $delflag;
 5705: # actually delete
 5706:     if ($deleteflag) {
 5707: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5708: # modify command to delete the role
 5709:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5710:                 "$udom:$uname:$url".'_'."$mrole";
 5711: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5712: # set start and finish to negative values for userrolelog
 5713:            $start=-1;
 5714:            $end=-1;
 5715:            $delflag = 1;
 5716:         }
 5717:     }
 5718: # send command
 5719:     my $answer=&reply($command,&homeserver($uname,$udom));
 5720: # log new user role if status is ok
 5721:     if ($answer eq 'ok') {
 5722: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5723: # for course roles, perform group memberships changes triggered by role change.
 5724:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5725:         unless ($role =~ /^gr/) {
 5726:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5727:                                              $origstart,$selfenroll,$context);
 5728:         }
 5729:     }
 5730:     return $answer;
 5731: }
 5732: 
 5733: # -------------------------------------------------- Modify user authentication
 5734: # Overrides without validation
 5735: 
 5736: sub modifyuserauth {
 5737:     my ($udom,$uname,$umode,$upass)=@_;
 5738:     my $uhome=&homeserver($uname,$udom);
 5739:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5740:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5741:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5742:              ' in domain '.$env{'request.role.domain'});  
 5743:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5744: 		     &escape($upass),$uhome);
 5745:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5746:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5747:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5748:     &log($udom,,$uname,$uhome,
 5749:         'Authentication changed by '.$env{'user.domain'}.', '.
 5750:                                      $env{'user.name'}.', '.$umode.
 5751:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5752:     unless ($reply eq 'ok') {
 5753:         &logthis('Authentication mode error: '.$reply);
 5754: 	return 'error: '.$reply;
 5755:     }   
 5756:     return 'ok';
 5757: }
 5758: 
 5759: # --------------------------------------------------------------- Modify a user
 5760: 
 5761: sub modifyuser {
 5762:     my ($udom,    $uname, $uid,
 5763:         $umode,   $upass, $first,
 5764:         $middle,  $last,  $gene,
 5765:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5766:     $udom= &LONCAPA::clean_domain($udom);
 5767:     $uname=&LONCAPA::clean_username($uname);
 5768:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5769:              $umode.', '.$first.', '.$middle.', '.
 5770: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5771:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5772:                                      ' desiredhome not specified'). 
 5773:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5774:              ' in domain '.$env{'request.role.domain'});
 5775:     my $uhome=&homeserver($uname,$udom,'true');
 5776: # ----------------------------------------------------------------- Create User
 5777:     if (($uhome eq 'no_host') && 
 5778: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5779:         my $unhome='';
 5780:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5781:             $unhome = $desiredhome;
 5782: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5783: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5784:         } else { # load balancing routine for determining $unhome
 5785:             my $loadm=10000000;
 5786: 	    my %servers = &get_servers($udom,'library');
 5787: 	    foreach my $tryserver (keys(%servers)) {
 5788: 		my $answer=reply('load',$tryserver);
 5789: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5790: 		    $loadm=$answer;
 5791: 		    $unhome=$tryserver;
 5792: 		}
 5793: 	    }
 5794:         }
 5795:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5796: 	    return 'error: unable to find a home server for '.$uname.
 5797:                    ' in domain '.$udom;
 5798:         }
 5799:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5800:                          &escape($upass),$unhome);
 5801: 	unless ($reply eq 'ok') {
 5802:             return 'error: '.$reply;
 5803:         }   
 5804:         $uhome=&homeserver($uname,$udom,'true');
 5805:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5806: 	    return 'error: unable verify users home machine.';
 5807:         }
 5808:     }   # End of creation of new user
 5809: # ---------------------------------------------------------------------- Add ID
 5810:     if ($uid) {
 5811:        $uid=~tr/A-Z/a-z/;
 5812:        my %uidhash=&idrget($udom,$uname);
 5813:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5814:          && (!$forceid)) {
 5815: 	  unless ($uid eq $uidhash{$uname}) {
 5816: 	      return 'error: user id "'.$uid.'" does not match '.
 5817:                   'current user id "'.$uidhash{$uname}.'".';
 5818:           }
 5819:        } else {
 5820: 	  &idput($udom,($uname => $uid));
 5821:        }
 5822:     }
 5823: # -------------------------------------------------------------- Add names, etc
 5824:     my @tmp=&get('environment',
 5825: 		   ['firstname','middlename','lastname','generation','id',
 5826:                     'permanentemail','inststatus'],
 5827: 		   $udom,$uname);
 5828:     my %names;
 5829:     if ($tmp[0] =~ m/^error:.*/) { 
 5830:         %names=(); 
 5831:     } else {
 5832:         %names = @tmp;
 5833:     }
 5834: #
 5835: # Make sure to not trash student environment if instructor does not bother
 5836: # to supply name and email information
 5837: #
 5838:     if ($first)  { $names{'firstname'}  = $first; }
 5839:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5840:     if ($last)   { $names{'lastname'}   = $last; }
 5841:     if (defined($gene))   { $names{'generation'} = $gene; }
 5842:     if ($email) {
 5843:        $email=~s/[^\w\@\.\-\,]//gs;
 5844:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5845:     }
 5846:     if ($uid) { $names{'id'}  = $uid; }
 5847:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
 5848:     my $reply = &put('environment', \%names, $udom,$uname);
 5849:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5850:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5851:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5852:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5853:                  $umode.', '.$first.', '.$middle.', '.
 5854: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5855:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5856:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5857:     } else {
 5858:         $logmsg .= ' during self creation';
 5859:     }
 5860:     &logthis($logmsg);
 5861:     return 'ok';
 5862: }
 5863: 
 5864: # -------------------------------------------------------------- Modify student
 5865: 
 5866: sub modifystudent {
 5867:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5868:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5869:         $selfenroll,$context)=@_;
 5870:     if (!$cid) {
 5871: 	unless ($cid=$env{'request.course.id'}) {
 5872: 	    return 'not_in_class';
 5873: 	}
 5874:     }
 5875: # --------------------------------------------------------------- Make the user
 5876:     my $reply=&modifyuser
 5877: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5878:          $desiredhome,$email);
 5879:     unless ($reply eq 'ok') { return $reply; }
 5880:     # This will cause &modify_student_enrollment to get the uid from the
 5881:     # students environment
 5882:     $uid = undef if (!$forceid);
 5883:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5884: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5885:     return $reply;
 5886: }
 5887: 
 5888: sub modify_student_enrollment {
 5889:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5890:     my ($cdom,$cnum,$chome);
 5891:     if (!$cid) {
 5892: 	unless ($cid=$env{'request.course.id'}) {
 5893: 	    return 'not_in_class';
 5894: 	}
 5895: 	$cdom=$env{'course.'.$cid.'.domain'};
 5896: 	$cnum=$env{'course.'.$cid.'.num'};
 5897:     } else {
 5898: 	($cdom,$cnum)=split(/_/,$cid);
 5899:     }
 5900:     $chome=$env{'course.'.$cid.'.home'};
 5901:     if (!$chome) {
 5902: 	$chome=&homeserver($cnum,$cdom);
 5903:     }
 5904:     if (!$chome) { return 'unknown_course'; }
 5905:     # Make sure the user exists
 5906:     my $uhome=&homeserver($uname,$udom);
 5907:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5908: 	return 'error: no such user';
 5909:     }
 5910:     # Get student data if we were not given enough information
 5911:     if (!defined($first)  || $first  eq '' || 
 5912:         !defined($last)   || $last   eq '' || 
 5913:         !defined($uid)    || $uid    eq '' || 
 5914:         !defined($middle) || $middle eq '' || 
 5915:         !defined($gene)   || $gene   eq '') {
 5916:         # They did not supply us with enough data to enroll the student, so
 5917:         # we need to pick up more information.
 5918:         my %tmp = &get('environment',
 5919:                        ['firstname','middlename','lastname', 'generation','id']
 5920:                        ,$udom,$uname);
 5921: 
 5922:         #foreach my $key (keys(%tmp)) {
 5923:         #    &logthis("key $key = ".$tmp{$key});
 5924:         #}
 5925:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5926:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5927:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5928:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5929:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5930:     }
 5931:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5932:     my $reply=cput('classlist',
 5933: 		   {"$uname:$udom" => 
 5934: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5935: 		   $cdom,$cnum);
 5936:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5937: 	return 'error: '.$reply;
 5938:     } else {
 5939: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5940:     }
 5941:     # Add student role to user
 5942:     my $uurl='/'.$cid;
 5943:     $uurl=~s/\_/\//g;
 5944:     if ($usec) {
 5945: 	$uurl.='/'.$usec;
 5946:     }
 5947:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 5948: }
 5949: 
 5950: sub format_name {
 5951:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5952:     my $name;
 5953:     if ($first ne 'lastname') {
 5954: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5955:     } else {
 5956: 	if ($lastname=~/\S/) {
 5957: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5958: 	    $name=~s/\s+,/,/;
 5959: 	} else {
 5960: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5961: 	}
 5962:     }
 5963:     $name=~s/^\s+//;
 5964:     $name=~s/\s+$//;
 5965:     $name=~s/\s+/ /g;
 5966:     return $name;
 5967: }
 5968: 
 5969: # ------------------------------------------------- Write to course preferences
 5970: 
 5971: sub writecoursepref {
 5972:     my ($courseid,%prefs)=@_;
 5973:     $courseid=~s/^\///;
 5974:     $courseid=~s/\_/\//g;
 5975:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5976:     my $chome=homeserver($cnum,$cdomain);
 5977:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5978: 	return 'error: no such course';
 5979:     }
 5980:     my $cstring='';
 5981:     foreach my $pref (keys(%prefs)) {
 5982: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5983:     }
 5984:     $cstring=~s/\&$//;
 5985:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5986: }
 5987: 
 5988: # ---------------------------------------------------------- Make/modify course
 5989: 
 5990: sub createcourse {
 5991:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5992:         $course_owner,$crstype)=@_;
 5993:     $url=&declutter($url);
 5994:     my $cid='';
 5995:     unless (&allowed('ccc',$udom)) {
 5996:         return 'refused';
 5997:     }
 5998: # ------------------------------------------------------------------- Create ID
 5999:    my $uname=int(1+rand(9)).
 6000:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6001:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6002:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6003: # ----------------------------------------------- Make sure that does not exist
 6004:    my $uhome=&homeserver($uname,$udom,'true');
 6005:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6006:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6007:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6008:        $uhome=&homeserver($uname,$udom,'true');       
 6009:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6010:            return 'error: unable to generate unique course-ID';
 6011:        } 
 6012:    }
 6013: # ------------------------------------------------ Check supplied server name
 6014:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6015:     if (! &is_library($course_server)) {
 6016:         return 'error:bad server name '.$course_server;
 6017:     }
 6018: # ------------------------------------------------------------- Make the course
 6019:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6020:                       $course_server);
 6021:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6022:     $uhome=&homeserver($uname,$udom,'true');
 6023:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6024: 	return 'error: no such course';
 6025:     }
 6026: # ----------------------------------------------------------------- Course made
 6027: # log existence
 6028:     my $newcourse = {
 6029:                     $udom.'_'.$uname => {
 6030:                                      description => $description,
 6031:                                      inst_code   => $inst_code,
 6032:                                      owner       => $course_owner,
 6033:                                      type        => $crstype,
 6034:                                                 },
 6035:                     };
 6036:     &courseidput($udom,$newcourse,$uhome,'notime');
 6037: # set toplevel url
 6038:     my $topurl=$url;
 6039:     unless ($nonstandard) {
 6040: # ------------------------------------------ For standard courses, make top url
 6041:         my $mapurl=&clutter($url);
 6042:         if ($mapurl eq '/res/') { $mapurl=''; }
 6043:         $env{'form.initmap'}=(<<ENDINITMAP);
 6044: <map>
 6045: <resource id="1" type="start"></resource>
 6046: <resource id="2" src="$mapurl"></resource>
 6047: <resource id="3" type="finish"></resource>
 6048: <link index="1" from="1" to="2"></link>
 6049: <link index="2" from="2" to="3"></link>
 6050: </map>
 6051: ENDINITMAP
 6052:         $topurl=&declutter(
 6053:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6054:                           );
 6055:     }
 6056: # ----------------------------------------------------------- Write preferences
 6057:     &writecoursepref($udom.'_'.$uname,
 6058:                      ('description' => $description,
 6059:                       'url'         => $topurl));
 6060:     return '/'.$udom.'/'.$uname;
 6061: }
 6062: 
 6063: sub is_course {
 6064:     my ($cdom,$cnum) = @_;
 6065:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6066: 				undef,'.');
 6067:     if (exists($courses{$cdom.'_'.$cnum})) {
 6068:         return 1;
 6069:     }
 6070:     return 0;
 6071: }
 6072: 
 6073: # ---------------------------------------------------------- Assign Custom Role
 6074: 
 6075: sub assigncustomrole {
 6076:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6077:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6078:                        $end,$start,$deleteflag,$selfenroll,$context);
 6079: }
 6080: 
 6081: # ----------------------------------------------------------------- Revoke Role
 6082: 
 6083: sub revokerole {
 6084:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6085:     my $now=time;
 6086:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6087: }
 6088: 
 6089: # ---------------------------------------------------------- Revoke Custom Role
 6090: 
 6091: sub revokecustomrole {
 6092:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6093:     my $now=time;
 6094:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6095:            $deleteflag,$selfenroll,$context);
 6096: }
 6097: 
 6098: # ------------------------------------------------------------ Disk usage
 6099: sub diskusage {
 6100:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6101:     $directorypath =~ s/\/$//;
 6102:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6103:                        .&escape($getpropath).':'.&escape($uname).':'
 6104:                        .&escape($udom),homeserver($uname,$udom));
 6105:     if ($listing eq 'unknown_cmd') {
 6106:         if ($getpropath) {
 6107:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6108:         }
 6109:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6110:     }
 6111:     return $listing;
 6112: }
 6113: 
 6114: sub is_locked {
 6115:     my ($file_name, $domain, $user) = @_;
 6116:     my @check;
 6117:     my $is_locked;
 6118:     push @check, $file_name;
 6119:     my %locked = &get('file_permissions',\@check,
 6120: 		      $env{'user.domain'},$env{'user.name'});
 6121:     my ($tmp)=keys(%locked);
 6122:     if ($tmp=~/^error:/) { undef(%locked); }
 6123:     
 6124:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6125:         $is_locked = 'false';
 6126:         foreach my $entry (@{$locked{$file_name}}) {
 6127:            if (ref($entry) eq 'ARRAY') { 
 6128:                $is_locked = 'true';
 6129:                last;
 6130:            }
 6131:        }
 6132:     } else {
 6133:         $is_locked = 'false';
 6134:     }
 6135: }
 6136: 
 6137: sub declutter_portfile {
 6138:     my ($file) = @_;
 6139:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6140:     return $file;
 6141: }
 6142: 
 6143: # ------------------------------------------------------------- Mark as Read Only
 6144: 
 6145: sub mark_as_readonly {
 6146:     my ($domain,$user,$files,$what) = @_;
 6147:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6148:     my ($tmp)=keys(%current_permissions);
 6149:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6150:     foreach my $file (@{$files}) {
 6151: 	$file = &declutter_portfile($file);
 6152:         push(@{$current_permissions{$file}},$what);
 6153:     }
 6154:     &put('file_permissions',\%current_permissions,$domain,$user);
 6155:     return;
 6156: }
 6157: 
 6158: # ------------------------------------------------------------Save Selected Files
 6159: 
 6160: sub save_selected_files {
 6161:     my ($user, $path, @files) = @_;
 6162:     my $filename = $user."savedfiles";
 6163:     my @other_files = &files_not_in_path($user, $path);
 6164:     open (OUT, '>'.$tmpdir.$filename);
 6165:     foreach my $file (@files) {
 6166:         print (OUT $env{'form.currentpath'}.$file."\n");
 6167:     }
 6168:     foreach my $file (@other_files) {
 6169:         print (OUT $file."\n");
 6170:     }
 6171:     close (OUT);
 6172:     return 'ok';
 6173: }
 6174: 
 6175: sub clear_selected_files {
 6176:     my ($user) = @_;
 6177:     my $filename = $user."savedfiles";
 6178:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6179:     print (OUT undef);
 6180:     close (OUT);
 6181:     return ("ok");    
 6182: }
 6183: 
 6184: sub files_in_path {
 6185:     my ($user, $path) = @_;
 6186:     my $filename = $user."savedfiles";
 6187:     my %return_files;
 6188:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6189:     while (my $line_in = <IN>) {
 6190:         chomp ($line_in);
 6191:         my @paths_and_file = split (m!/!, $line_in);
 6192:         my $file_part = pop (@paths_and_file);
 6193:         my $path_part = join ('/', @paths_and_file);
 6194:         $path_part.='/';
 6195:         my $path_and_file = $path_part.$file_part;
 6196:         if ($path_part eq $path) {
 6197:             $return_files{$file_part}= 'selected';
 6198:         }
 6199:     }
 6200:     close (IN);
 6201:     return (\%return_files);
 6202: }
 6203: 
 6204: # called in portfolio select mode, to show files selected NOT in current directory
 6205: sub files_not_in_path {
 6206:     my ($user, $path) = @_;
 6207:     my $filename = $user."savedfiles";
 6208:     my @return_files;
 6209:     my $path_part;
 6210:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6211:     while (my $line = <IN>) {
 6212:         #ok, I know it's clunky, but I want it to work
 6213:         my @paths_and_file = split(m|/|, $line);
 6214:         my $file_part = pop(@paths_and_file);
 6215:         chomp($file_part);
 6216:         my $path_part = join('/', @paths_and_file);
 6217:         $path_part .= '/';
 6218:         my $path_and_file = $path_part.$file_part;
 6219:         if ($path_part ne $path) {
 6220:             push(@return_files, ($path_and_file));
 6221:         }
 6222:     }
 6223:     close(OUT);
 6224:     return (@return_files);
 6225: }
 6226: 
 6227: #----------------------------------------------Get portfolio file permissions
 6228: 
 6229: sub get_portfile_permissions {
 6230:     my ($domain,$user) = @_;
 6231:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6232:     my ($tmp)=keys(%current_permissions);
 6233:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6234:     return \%current_permissions;
 6235: }
 6236: 
 6237: #---------------------------------------------Get portfolio file access controls
 6238: 
 6239: sub get_access_controls {
 6240:     my ($current_permissions,$group,$file) = @_;
 6241:     my %access;
 6242:     my $real_file = $file;
 6243:     $file =~ s/\.meta$//;
 6244:     if (defined($file)) {
 6245:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6246:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6247:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6248:             }
 6249:         }
 6250:     } else {
 6251:         foreach my $key (keys(%{$current_permissions})) {
 6252:             if ($key =~ /\0accesscontrol$/) {
 6253:                 if (defined($group)) {
 6254:                     if ($key !~ m-^\Q$group\E/-) {
 6255:                         next;
 6256:                     }
 6257:                 }
 6258:                 my ($fullpath) = split(/\0/,$key);
 6259:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6260:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6261:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6262:                     }
 6263:                 }
 6264:             }
 6265:         }
 6266:     }
 6267:     return %access;
 6268: }
 6269: 
 6270: sub modify_access_controls {
 6271:     my ($file_name,$changes,$domain,$user)=@_;
 6272:     my ($outcome,$deloutcome);
 6273:     my %store_permissions;
 6274:     my %new_values;
 6275:     my %new_control;
 6276:     my %translation;
 6277:     my @deletions = ();
 6278:     my $now = time;
 6279:     if (exists($$changes{'activate'})) {
 6280:         if (ref($$changes{'activate'}) eq 'HASH') {
 6281:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6282:             my $numnew = scalar(@newitems);
 6283:             for (my $i=0; $i<$numnew; $i++) {
 6284:                 my $newkey = $newitems[$i];
 6285:                 my $newid = &Apache::loncommon::get_cgi_id();
 6286:                 if ($newkey =~ /^\d+:/) { 
 6287:                     $newkey =~ s/^(\d+)/$newid/;
 6288:                     $translation{$1} = $newid;
 6289:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6290:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6291:                     $translation{$1} = $newid;
 6292:                 }
 6293:                 $new_values{$file_name."\0".$newkey} = 
 6294:                                           $$changes{'activate'}{$newitems[$i]};
 6295:                 $new_control{$newkey} = $now;
 6296:             }
 6297:         }
 6298:     }
 6299:     my %todelete;
 6300:     my %changed_items;
 6301:     foreach my $action ('delete','update') {
 6302:         if (exists($$changes{$action})) {
 6303:             if (ref($$changes{$action}) eq 'HASH') {
 6304:                 foreach my $key (keys(%{$$changes{$action}})) {
 6305:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6306:                     if ($action eq 'delete') { 
 6307:                         $todelete{$itemnum} = 1;
 6308:                     } else {
 6309:                         $changed_items{$itemnum} = $key;
 6310:                     }
 6311:                 }
 6312:             }
 6313:         }
 6314:     }
 6315:     # get lock on access controls for file.
 6316:     my $lockhash = {
 6317:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6318:                                                        ':'.$env{'user.domain'},
 6319:                    }; 
 6320:     my $tries = 0;
 6321:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6322:    
 6323:     while (($gotlock ne 'ok') && $tries <3) {
 6324:         $tries ++;
 6325:         sleep 1;
 6326:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6327:     }
 6328:     if ($gotlock eq 'ok') {
 6329:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6330:         my ($tmp)=keys(%curr_permissions);
 6331:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6332:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6333:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6334:             if (ref($curr_controls) eq 'HASH') {
 6335:                 foreach my $control_item (keys(%{$curr_controls})) {
 6336:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6337:                     if (defined($todelete{$itemnum})) {
 6338:                         push(@deletions,$file_name."\0".$control_item);
 6339:                     } else {
 6340:                         if (defined($changed_items{$itemnum})) {
 6341:                             $new_control{$changed_items{$itemnum}} = $now;
 6342:                             push(@deletions,$file_name."\0".$control_item);
 6343:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6344:                         } else {
 6345:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6346:                         }
 6347:                     }
 6348:                 }
 6349:             }
 6350:         }
 6351:         my ($group);
 6352:         if (&is_course($domain,$user)) {
 6353:             ($group,my $file) = split(/\//,$file_name,2);
 6354:         }
 6355:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6356:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6357:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6358:         #  remove lock
 6359:         my @del_lock = ($file_name."\0".'locked_access_records');
 6360:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6361:         my $sqlresult =
 6362:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6363:                                     $group);
 6364:     } else {
 6365:         $outcome = "error: could not obtain lockfile\n";  
 6366:     }
 6367:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6368: }
 6369: 
 6370: sub make_public_indefinitely {
 6371:     my ($requrl) = @_;
 6372:     my $now = time;
 6373:     my $action = 'activate';
 6374:     my $aclnum = 0;
 6375:     if (&is_portfolio_url($requrl)) {
 6376:         my (undef,$udom,$unum,$file_name,$group) =
 6377:             &parse_portfolio_url($requrl);
 6378:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6379:         my %access_controls = &get_access_controls($current_perms,
 6380:                                                    $group,$file_name);
 6381:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6382:             my ($num,$scope,$end,$start) = 
 6383:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6384:             if ($scope eq 'public') {
 6385:                 if ($start <= $now && $end == 0) {
 6386:                     $action = 'none';
 6387:                 } else {
 6388:                     $action = 'update';
 6389:                     $aclnum = $num;
 6390:                 }
 6391:                 last;
 6392:             }
 6393:         }
 6394:         if ($action eq 'none') {
 6395:              return 'ok';
 6396:         } else {
 6397:             my %changes;
 6398:             my $newend = 0;
 6399:             my $newstart = $now;
 6400:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6401:             $changes{$action}{$newkey} = {
 6402:                 type => 'public',
 6403:                 time => {
 6404:                     start => $newstart,
 6405:                     end   => $newend,
 6406:                 },
 6407:             };
 6408:             my ($outcome,$deloutcome,$new_values,$translation) =
 6409:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6410:             return $outcome;
 6411:         }
 6412:     } else {
 6413:         return 'invalid';
 6414:     }
 6415: }
 6416: 
 6417: #------------------------------------------------------Get Marked as Read Only
 6418: 
 6419: sub get_marked_as_readonly {
 6420:     my ($domain,$user,$what,$group) = @_;
 6421:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6422:     my @readonly_files;
 6423:     my $cmp1=$what;
 6424:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6425:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6426:         if (defined($group)) {
 6427:             if ($file_name !~ m-^\Q$group\E/-) {
 6428:                 next;
 6429:             }
 6430:         }
 6431:         if (ref($value) eq "ARRAY"){
 6432:             foreach my $stored_what (@{$value}) {
 6433:                 my $cmp2=$stored_what;
 6434:                 if (ref($stored_what) eq 'ARRAY') {
 6435:                     $cmp2=join('',@{$stored_what});
 6436:                 }
 6437:                 if ($cmp1 eq $cmp2) {
 6438:                     push(@readonly_files, $file_name);
 6439:                     last;
 6440:                 } elsif (!defined($what)) {
 6441:                     push(@readonly_files, $file_name);
 6442:                     last;
 6443:                 }
 6444:             }
 6445:         }
 6446:     }
 6447:     return @readonly_files;
 6448: }
 6449: #-----------------------------------------------------------Get Marked as Read Only Hash
 6450: 
 6451: sub get_marked_as_readonly_hash {
 6452:     my ($current_permissions,$group,$what) = @_;
 6453:     my %readonly_files;
 6454:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6455:         if (defined($group)) {
 6456:             if ($file_name !~ m-^\Q$group\E/-) {
 6457:                 next;
 6458:             }
 6459:         }
 6460:         if (ref($value) eq "ARRAY"){
 6461:             foreach my $stored_what (@{$value}) {
 6462:                 if (ref($stored_what) eq 'ARRAY') {
 6463:                     foreach my $lock_descriptor(@{$stored_what}) {
 6464:                         if ($lock_descriptor eq 'graded') {
 6465:                             $readonly_files{$file_name} = 'graded';
 6466:                         } elsif ($lock_descriptor eq 'handback') {
 6467:                             $readonly_files{$file_name} = 'handback';
 6468:                         } else {
 6469:                             if (!exists($readonly_files{$file_name})) {
 6470:                                 $readonly_files{$file_name} = 'locked';
 6471:                             }
 6472:                         }
 6473:                     }
 6474:                 } 
 6475:             }
 6476:         } 
 6477:     }
 6478:     return %readonly_files;
 6479: }
 6480: # ------------------------------------------------------------ Unmark as Read Only
 6481: 
 6482: sub unmark_as_readonly {
 6483:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6484:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6485:     my ($domain,$user,$what,$file_name,$group) = @_;
 6486:     $file_name = &declutter_portfile($file_name);
 6487:     my $symb_crs = $what;
 6488:     if (ref($what)) { $symb_crs=join('',@$what); }
 6489:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6490:     my ($tmp)=keys(%current_permissions);
 6491:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6492:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6493:     foreach my $file (@readonly_files) {
 6494: 	my $clean_file = &declutter_portfile($file);
 6495: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6496: 	my $current_locks = $current_permissions{$file};
 6497:         my @new_locks;
 6498:         my @del_keys;
 6499:         if (ref($current_locks) eq "ARRAY"){
 6500:             foreach my $locker (@{$current_locks}) {
 6501:                 my $compare=$locker;
 6502:                 if (ref($locker) eq 'ARRAY') {
 6503:                     $compare=join('',@{$locker});
 6504:                     if ($compare ne $symb_crs) {
 6505:                         push(@new_locks, $locker);
 6506:                     }
 6507:                 }
 6508:             }
 6509:             if (scalar(@new_locks) > 0) {
 6510:                 $current_permissions{$file} = \@new_locks;
 6511:             } else {
 6512:                 push(@del_keys, $file);
 6513:                 &del('file_permissions',\@del_keys, $domain, $user);
 6514:                 delete($current_permissions{$file});
 6515:             }
 6516:         }
 6517:     }
 6518:     &put('file_permissions',\%current_permissions,$domain,$user);
 6519:     return;
 6520: }
 6521: 
 6522: # ------------------------------------------------------------ Directory lister
 6523: 
 6524: sub dirlist {
 6525:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6526:     $uri=~s/^\///;
 6527:     $uri=~s/\/$//;
 6528:     my ($udom, $uname);
 6529:     if ($getuserdir) {
 6530:         $udom = $userdomain;
 6531:         $uname = $username;
 6532:     } else {
 6533:         (undef,$udom,$uname)=split(/\//,$uri);
 6534:         if(defined($userdomain)) {
 6535:             $udom = $userdomain;
 6536:         }
 6537:         if(defined($username)) {
 6538:             $uname = $username;
 6539:         }
 6540:     }
 6541:     my ($dirRoot,$listing,@listing_results);
 6542: 
 6543:     $dirRoot = $perlvar{'lonDocRoot'};
 6544:     if (defined($getpropath)) {
 6545:         $dirRoot = &propath($udom,$uname);
 6546:         $dirRoot =~ s/\/$//;
 6547:     } elsif (defined($getuserdir)) {
 6548:         my $subdir=$uname.'__';
 6549:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6550:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6551:                    ."/$udom/$subdir/$uname";
 6552:     } elsif (defined($alternateRoot)) {
 6553:         $dirRoot = $alternateRoot;
 6554:     }
 6555: 
 6556:     if($udom) {
 6557:         if($uname) {
 6558:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6559:                               .$getuserdir.':'.&escape($dirRoot)
 6560:                               .':'.&escape($uname).':'.&escape($udom),
 6561:                               &homeserver($uname,$udom));
 6562:             if ($listing eq 'unknown_cmd') {
 6563:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6564:                                   &homeserver($uname,$udom));
 6565:             } else {
 6566:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6567:             }
 6568:             if ($listing eq 'unknown_cmd') {
 6569:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6570: 				  &homeserver($uname,$udom));
 6571:                 @listing_results = split(/:/,$listing);
 6572:             } else {
 6573:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6574:             }
 6575:             return @listing_results;
 6576:         } elsif(!$alternateRoot) {
 6577:             my %allusers;
 6578: 	    my %servers = &get_servers($udom,'library');
 6579:  	    foreach my $tryserver (keys(%servers)) {
 6580:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6581:                                   &escape($udom),$tryserver);
 6582:                 if ($listing eq 'unknown_cmd') {
 6583: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6584: 				      $udom, $tryserver);
 6585:                 } else {
 6586:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6587:                 }
 6588: 		if ($listing eq 'unknown_cmd') {
 6589: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6590: 				      $udom, $tryserver);
 6591: 		    @listing_results = split(/:/,$listing);
 6592: 		} else {
 6593: 		    @listing_results =
 6594: 			map { &unescape($_); } split(/:/,$listing);
 6595: 		}
 6596: 		if ($listing_results[0] ne 'no_such_dir' && 
 6597: 		    $listing_results[0] ne 'empty'       &&
 6598: 		    $listing_results[0] ne 'con_lost') {
 6599: 		    foreach my $line (@listing_results) {
 6600: 			my ($entry) = split(/&/,$line,2);
 6601: 			$allusers{$entry} = 1;
 6602: 		    }
 6603: 		}
 6604:             }
 6605:             my $alluserstr='';
 6606:             foreach my $user (sort(keys(%allusers))) {
 6607:                 $alluserstr.=$user.'&user:';
 6608:             }
 6609:             $alluserstr=~s/:$//;
 6610:             return split(/:/,$alluserstr);
 6611:         } else {
 6612:             return ('missing user name');
 6613:         }
 6614:     } elsif(!defined($getpropath)) {
 6615:         my @all_domains = sort(&all_domains());
 6616:         foreach my $domain (@all_domains) {
 6617:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6618:         }
 6619:         return @all_domains;
 6620:     } else {
 6621:         return ('missing domain');
 6622:     }
 6623: }
 6624: 
 6625: # --------------------------------------------- GetFileTimestamp
 6626: # This function utilizes dirlist and returns the date stamp for
 6627: # when it was last modified.  It will also return an error of -1
 6628: # if an error occurs
 6629: 
 6630: sub GetFileTimestamp {
 6631:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6632:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6633:     $studentName   = &LONCAPA::clean_username($studentName);
 6634:     my ($fileStat) = 
 6635:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6636:                                  undef,$getuserdir);
 6637:     my @stats = split('&', $fileStat);
 6638:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6639:         # @stats contains first the filename, then the stat output
 6640:         return $stats[10]; # so this is 10 instead of 9.
 6641:     } else {
 6642:         return -1;
 6643:     }
 6644: }
 6645: 
 6646: sub stat_file {
 6647:     my ($uri) = @_;
 6648:     $uri = &clutter_with_no_wrapper($uri);
 6649: 
 6650:     my ($udom,$uname,$file);
 6651:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6652: 	($udom,$uname,$file) =
 6653: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6654: 	$file = 'userfiles/'.$file;
 6655:     }
 6656:     if ($uri =~ m-^/res/-) {
 6657: 	($udom,$uname) = 
 6658: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6659: 	$file = $uri;
 6660:     }
 6661: 
 6662:     if (!$udom || !$uname || !$file) {
 6663: 	# unable to handle the uri
 6664: 	return ();
 6665:     }
 6666:     my $getpropath;
 6667:     if ($file =~ /^userfiles\//) {
 6668:         $getpropath = 1;
 6669:     }
 6670:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6671:     my @stats = split('&', $result);
 6672:     
 6673:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6674: 	shift(@stats); #filename is first
 6675: 	return @stats;
 6676:     }
 6677:     return ();
 6678: }
 6679: 
 6680: # -------------------------------------------------------- Value of a Condition
 6681: 
 6682: # gets the value of a specific preevaluated condition
 6683: #    stored in the string  $env{user.state.<cid>}
 6684: # or looks up a condition reference in the bighash and if if hasn't
 6685: # already been evaluated recurses into docondval to get the value of
 6686: # the condition, then memoizing it to 
 6687: #   $env{user.state.<cid>.<condition>}
 6688: sub directcondval {
 6689:     my $number=shift;
 6690:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6691: 	&Apache::lonuserstate::evalstate();
 6692:     }
 6693:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6694: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6695:     } elsif ($number =~ /^_/) {
 6696: 	my $sub_condition;
 6697: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6698: 		&GDBM_READER(),0640)) {
 6699: 	    $sub_condition=$bighash{'conditions'.$number};
 6700: 	    untie(%bighash);
 6701: 	}
 6702: 	my $value = &docondval($sub_condition);
 6703: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6704: 	return $value;
 6705:     }
 6706:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6707:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6708:     } else {
 6709:        return 2;
 6710:     }
 6711: }
 6712: 
 6713: # get the collection of conditions for this resource
 6714: sub condval {
 6715:     my $condidx=shift;
 6716:     my $allpathcond='';
 6717:     foreach my $cond (split(/\|/,$condidx)) {
 6718: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6719: 	    $allpathcond.=
 6720: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6721: 	}
 6722:     }
 6723:     $allpathcond=~s/\|$//;
 6724:     return &docondval($allpathcond);
 6725: }
 6726: 
 6727: #evaluates an expression of conditions
 6728: sub docondval {
 6729:     my ($allpathcond) = @_;
 6730:     my $result=0;
 6731:     if ($env{'request.course.id'}
 6732: 	&& defined($allpathcond)) {
 6733: 	my $operand='|';
 6734: 	my @stack;
 6735: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6736: 	    if ($chunk eq '(') {
 6737: 		push @stack,($operand,$result);
 6738: 	    } elsif ($chunk eq ')') {
 6739: 		my $before=pop @stack;
 6740: 		if (pop @stack eq '&') {
 6741: 		    $result=$result>$before?$before:$result;
 6742: 		} else {
 6743: 		    $result=$result>$before?$result:$before;
 6744: 		}
 6745: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6746: 		$operand=$chunk;
 6747: 	    } else {
 6748: 		my $new=directcondval($chunk);
 6749: 		if ($operand eq '&') {
 6750: 		    $result=$result>$new?$new:$result;
 6751: 		} else {
 6752: 		    $result=$result>$new?$result:$new;
 6753: 		}
 6754: 	    }
 6755: 	}
 6756:     }
 6757:     return $result;
 6758: }
 6759: 
 6760: # ---------------------------------------------------- Devalidate courseresdata
 6761: 
 6762: sub devalidatecourseresdata {
 6763:     my ($coursenum,$coursedomain)=@_;
 6764:     my $hashid=$coursenum.':'.$coursedomain;
 6765:     &devalidate_cache_new('courseres',$hashid);
 6766: }
 6767: 
 6768: 
 6769: # --------------------------------------------------- Course Resourcedata Query
 6770: #
 6771: #  Parameters:
 6772: #      $coursenum    - Number of the course.
 6773: #      $coursedomain - Domain at which the course was created.
 6774: #  Returns:
 6775: #     A hash of the course parameters along (I think) with timestamps
 6776: #     and version info.
 6777: 
 6778: sub get_courseresdata {
 6779:     my ($coursenum,$coursedomain)=@_;
 6780:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6781:     my $hashid=$coursenum.':'.$coursedomain;
 6782:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6783:     my %dumpreply;
 6784:     unless (defined($cached)) {
 6785: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6786: 	$result=\%dumpreply;
 6787: 	my ($tmp) = keys(%dumpreply);
 6788: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6789: 	    &do_cache_new('courseres',$hashid,$result,600);
 6790: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6791: 	    return $tmp;
 6792: 	} elsif ($tmp =~ /^(error)/) {
 6793: 	    $result=undef;
 6794: 	    &do_cache_new('courseres',$hashid,$result,600);
 6795: 	}
 6796:     }
 6797:     return $result;
 6798: }
 6799: 
 6800: sub devalidateuserresdata {
 6801:     my ($uname,$udom)=@_;
 6802:     my $hashid="$udom:$uname";
 6803:     &devalidate_cache_new('userres',$hashid);
 6804: }
 6805: 
 6806: sub get_userresdata {
 6807:     my ($uname,$udom)=@_;
 6808:     #most student don\'t have any data set, check if there is some data
 6809:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6810: 
 6811:     my $hashid="$udom:$uname";
 6812:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6813:     if (!defined($cached)) {
 6814: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6815: 	$result=\%resourcedata;
 6816: 	&do_cache_new('userres',$hashid,$result,600);
 6817:     }
 6818:     my ($tmp)=keys(%$result);
 6819:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6820: 	return $result;
 6821:     }
 6822:     #error 2 occurs when the .db doesn't exist
 6823:     if ($tmp!~/error: 2 /) {
 6824: 	&logthis("<font color=\"blue\">WARNING:".
 6825: 		 " Trying to get resource data for ".
 6826: 		 $uname." at ".$udom.": ".
 6827: 		 $tmp."</font>");
 6828:     } elsif ($tmp=~/error: 2 /) {
 6829: 	#&EXT_cache_set($udom,$uname);
 6830: 	&do_cache_new('userres',$hashid,undef,600);
 6831: 	undef($tmp); # not really an error so don't send it back
 6832:     }
 6833:     return $tmp;
 6834: }
 6835: #----------------------------------------------- resdata - return resource data
 6836: #  Purpose:
 6837: #    Return resource data for either users or for a course.
 6838: #  Parameters:
 6839: #     $name      - Course/user name.
 6840: #     $domain    - Name of the domain the user/course is registered on.
 6841: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6842: #     @which     - Array of names of resources desired.
 6843: #  Returns:
 6844: #     The value of the first reasource in @which that is found in the
 6845: #     resource hash.
 6846: #  Exceptional Conditions:
 6847: #     If the $type passed in is not valid (not the string 'course' or 
 6848: #     'user', an undefined  reference is returned.
 6849: #     If none of the resources are found, an undef is returned
 6850: sub resdata {
 6851:     my ($name,$domain,$type,@which)=@_;
 6852:     my $result;
 6853:     if ($type eq 'course') {
 6854: 	$result=&get_courseresdata($name,$domain);
 6855:     } elsif ($type eq 'user') {
 6856: 	$result=&get_userresdata($name,$domain);
 6857:     }
 6858:     if (!ref($result)) { return $result; }    
 6859:     foreach my $item (@which) {
 6860: 	if (defined($result->{$item->[0]})) {
 6861: 	    return [$result->{$item->[0]},$item->[1]];
 6862: 	}
 6863:     }
 6864:     return undef;
 6865: }
 6866: 
 6867: #
 6868: # EXT resource caching routines
 6869: #
 6870: 
 6871: sub clear_EXT_cache_status {
 6872:     &delenv('cache.EXT.');
 6873: }
 6874: 
 6875: sub EXT_cache_status {
 6876:     my ($target_domain,$target_user) = @_;
 6877:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6878:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6879:         # We know already the user has no data
 6880:         return 1;
 6881:     } else {
 6882:         return 0;
 6883:     }
 6884: }
 6885: 
 6886: sub EXT_cache_set {
 6887:     my ($target_domain,$target_user) = @_;
 6888:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6889:     #&appenv({$cachename => time});
 6890: }
 6891: 
 6892: # --------------------------------------------------------- Value of a Variable
 6893: sub EXT {
 6894: 
 6895:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6896:     unless ($varname) { return ''; }
 6897:     #get real user name/domain, courseid and symb
 6898:     my $courseid;
 6899:     my $publicuser;
 6900:     if ($symbparm) {
 6901: 	$symbparm=&get_symb_from_alias($symbparm);
 6902:     }
 6903:     if (!($uname && $udom)) {
 6904:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6905:       if (!$symbparm) {	$symbparm=$cursymb; }
 6906:     } else {
 6907: 	$courseid=$env{'request.course.id'};
 6908:     }
 6909:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6910:     my $rest;
 6911:     if (defined($therest[0])) {
 6912:        $rest=join('.',@therest);
 6913:     } else {
 6914:        $rest='';
 6915:     }
 6916: 
 6917:     my $qualifierrest=$qualifier;
 6918:     if ($rest) { $qualifierrest.='.'.$rest; }
 6919:     my $spacequalifierrest=$space;
 6920:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6921:     if ($realm eq 'user') {
 6922: # --------------------------------------------------------------- user.resource
 6923: 	if ($space eq 'resource') {
 6924: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6925: 		  || defined($Apache::lonhomework::parsing_a_task))
 6926: 		 &&
 6927: 		 ($symbparm eq &symbread()) ) {	
 6928: 		# if we are in the middle of processing the resource the
 6929: 		# get the value we are planning on committing
 6930:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6931:                     return $Apache::lonhomework::results{$qualifierrest};
 6932:                 } else {
 6933:                     return $Apache::lonhomework::history{$qualifierrest};
 6934:                 }
 6935: 	    } else {
 6936: 		my %restored;
 6937: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6938: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6939: 		} else {
 6940: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6941: 		}
 6942: 		return $restored{$qualifierrest};
 6943: 	    }
 6944: # ----------------------------------------------------------------- user.access
 6945:         } elsif ($space eq 'access') {
 6946: 	    # FIXME - not supporting calls for a specific user
 6947:             return &allowed($qualifier,$rest);
 6948: # ------------------------------------------ user.preferences, user.environment
 6949:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6950: 	    if (($uname eq $env{'user.name'}) &&
 6951: 		($udom eq $env{'user.domain'})) {
 6952: 		return $env{join('.',('environment',$qualifierrest))};
 6953: 	    } else {
 6954: 		my %returnhash;
 6955: 		if (!$publicuser) {
 6956: 		    %returnhash=&userenvironment($udom,$uname,
 6957: 						 $qualifierrest);
 6958: 		}
 6959: 		return $returnhash{$qualifierrest};
 6960: 	    }
 6961: # ----------------------------------------------------------------- user.course
 6962:         } elsif ($space eq 'course') {
 6963: 	    # FIXME - not supporting calls for a specific user
 6964:             return $env{join('.',('request.course',$qualifier))};
 6965: # ------------------------------------------------------------------- user.role
 6966:         } elsif ($space eq 'role') {
 6967: 	    # FIXME - not supporting calls for a specific user
 6968:             my ($role,$where)=split(/\./,$env{'request.role'});
 6969:             if ($qualifier eq 'value') {
 6970: 		return $role;
 6971:             } elsif ($qualifier eq 'extent') {
 6972:                 return $where;
 6973:             }
 6974: # ----------------------------------------------------------------- user.domain
 6975:         } elsif ($space eq 'domain') {
 6976:             return $udom;
 6977: # ------------------------------------------------------------------- user.name
 6978:         } elsif ($space eq 'name') {
 6979:             return $uname;
 6980: # ---------------------------------------------------- Any other user namespace
 6981:         } else {
 6982: 	    my %reply;
 6983: 	    if (!$publicuser) {
 6984: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6985: 	    }
 6986: 	    return $reply{$qualifierrest};
 6987:         }
 6988:     } elsif ($realm eq 'query') {
 6989: # ---------------------------------------------- pull stuff out of query string
 6990:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6991: 						[$spacequalifierrest]);
 6992: 	return $env{'form.'.$spacequalifierrest}; 
 6993:    } elsif ($realm eq 'request') {
 6994: # ------------------------------------------------------------- request.browser
 6995:         if ($space eq 'browser') {
 6996: 	    if ($qualifier eq 'textremote') {
 6997: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6998: 		    return 1;
 6999: 		} else {
 7000: 		    return 0;
 7001: 		}
 7002: 	    } else {
 7003: 		return $env{'browser.'.$qualifier};
 7004: 	    }
 7005: # ------------------------------------------------------------ request.filename
 7006:         } else {
 7007:             return $env{'request.'.$spacequalifierrest};
 7008:         }
 7009:     } elsif ($realm eq 'course') {
 7010: # ---------------------------------------------------------- course.description
 7011:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7012:     } elsif ($realm eq 'resource') {
 7013: 
 7014: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7015: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7016: 	}
 7017: 
 7018: 	if ($space eq 'title') {
 7019: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7020: 	    return &gettitle($symbparm);
 7021: 	}
 7022: 	
 7023: 	if ($space eq 'map') {
 7024: 	    my ($map) = &decode_symb($symbparm);
 7025: 	    return &symbread($map);
 7026: 	}
 7027: 	if ($space eq 'filename') {
 7028: 	    if ($symbparm) {
 7029: 		return &clutter((&decode_symb($symbparm))[2]);
 7030: 	    }
 7031: 	    return &hreflocation('',$env{'request.filename'});
 7032: 	}
 7033: 
 7034: 	my ($section, $group, @groups);
 7035: 	my ($courselevelm,$courselevel);
 7036: 	if ($symbparm && defined($courseid) && 
 7037: 	    $courseid eq $env{'request.course.id'}) {
 7038: 
 7039: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7040: 
 7041: # ----------------------------------------------------- Cascading lookup scheme
 7042: 	    my $symbp=$symbparm;
 7043: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7044: 
 7045: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7046: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7047: 
 7048: 	    if (($env{'user.name'} eq $uname) &&
 7049: 		($env{'user.domain'} eq $udom)) {
 7050: 		$section=$env{'request.course.sec'};
 7051:                 @groups = split(/:/,$env{'request.course.groups'});  
 7052:                 @groups=&sort_course_groups($courseid,@groups); 
 7053: 	    } else {
 7054: 		if (! defined($usection)) {
 7055: 		    $section=&getsection($udom,$uname,$courseid);
 7056: 		} else {
 7057: 		    $section = $usection;
 7058: 		}
 7059:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7060: 	    }
 7061: 
 7062: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7063: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7064: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7065: 
 7066: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7067: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7068: 	    $courselevelm=$courseid.'.'.$mapparm;
 7069: 
 7070: # ----------------------------------------------------------- first, check user
 7071: 
 7072: 	    my $userreply=&resdata($uname,$udom,'user',
 7073: 				       ([$courselevelr,'resource'],
 7074: 					[$courselevelm,'map'     ],
 7075: 					[$courselevel, 'course'  ]));
 7076: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7077: 
 7078: # ------------------------------------------------ second, check some of course
 7079:             my $coursereply;
 7080:             if (@groups > 0) {
 7081:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7082:                                        $mapparm,$spacequalifierrest);
 7083:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7084:             }
 7085: 
 7086: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7087: 				  $env{'course.'.$courseid.'.domain'},
 7088: 				  'course',
 7089: 				  ([$seclevelr,   'resource'],
 7090: 				   [$seclevelm,   'map'     ],
 7091: 				   [$seclevel,    'course'  ],
 7092: 				   [$courselevelr,'resource']));
 7093: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7094: 
 7095: # ------------------------------------------------------ third, check map parms
 7096: 	    my %parmhash=();
 7097: 	    my $thisparm='';
 7098: 	    if (tie(%parmhash,'GDBM_File',
 7099: 		    $env{'request.course.fn'}.'_parms.db',
 7100: 		    &GDBM_READER(),0640)) {
 7101: 		$thisparm=$parmhash{$symbparm};
 7102: 		untie(%parmhash);
 7103: 	    }
 7104: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7105: 	}
 7106: # ------------------------------------------ fourth, look in resource metadata
 7107: 
 7108: 	$spacequalifierrest=~s/\./\_/;
 7109: 	my $filename;
 7110: 	if (!$symbparm) { $symbparm=&symbread(); }
 7111: 	if ($symbparm) {
 7112: 	    $filename=(&decode_symb($symbparm))[2];
 7113: 	} else {
 7114: 	    $filename=$env{'request.filename'};
 7115: 	}
 7116: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7117: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7118: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7119: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7120: 
 7121: # ---------------------------------------------- fourth, look in rest of course
 7122: 	if ($symbparm && defined($courseid) && 
 7123: 	    $courseid eq $env{'request.course.id'}) {
 7124: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7125: 				     $env{'course.'.$courseid.'.domain'},
 7126: 				     'course',
 7127: 				     ([$courselevelm,'map'   ],
 7128: 				      [$courselevel, 'course']));
 7129: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7130: 	}
 7131: # ------------------------------------------------------------------ Cascade up
 7132: 	unless ($space eq '0') {
 7133: 	    my @parts=split(/_/,$space);
 7134: 	    my $id=pop(@parts);
 7135: 	    my $part=join('_',@parts);
 7136: 	    if ($part eq '') { $part='0'; }
 7137: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7138: 				 $symbparm,$udom,$uname,$section,1);
 7139: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7140: 	}
 7141: 	if ($recurse) { return undef; }
 7142: 	my $pack_def=&packages_tab_default($filename,$varname);
 7143: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7144: # ---------------------------------------------------- Any other user namespace
 7145:     } elsif ($realm eq 'environment') {
 7146: # ----------------------------------------------------------------- environment
 7147: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7148: 	    return $env{'environment.'.$spacequalifierrest};
 7149: 	} else {
 7150: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7151: 		return '';
 7152: 	    }
 7153: 	    my %returnhash=&userenvironment($udom,$uname,
 7154: 					    $spacequalifierrest);
 7155: 	    return $returnhash{$spacequalifierrest};
 7156: 	}
 7157:     } elsif ($realm eq 'system') {
 7158: # ----------------------------------------------------------------- system.time
 7159: 	if ($space eq 'time') {
 7160: 	    return time;
 7161:         }
 7162:     } elsif ($realm eq 'server') {
 7163: # ----------------------------------------------------------------- system.time
 7164: 	if ($space eq 'name') {
 7165: 	    return $ENV{'SERVER_NAME'};
 7166:         }
 7167:     }
 7168:     return '';
 7169: }
 7170: 
 7171: sub get_reply {
 7172:     my ($reply_value) = @_;
 7173:     if (ref($reply_value) eq 'ARRAY') {
 7174:         if (wantarray) {
 7175: 	    return @$reply_value;
 7176:         }
 7177:         return $reply_value->[0];
 7178:     } else {
 7179:         return $reply_value;
 7180:     }
 7181: }
 7182: 
 7183: sub check_group_parms {
 7184:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7185:     my @groupitems = ();
 7186:     my $resultitem;
 7187:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7188:     foreach my $group (@{$groups}) {
 7189:         foreach my $level (@levels) {
 7190:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7191:              push(@groupitems,[$item,$level->[1]]);
 7192:         }
 7193:     }
 7194:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7195:                             $env{'course.'.$courseid.'.domain'},
 7196:                                      'course',@groupitems);
 7197:     return $coursereply;
 7198: }
 7199: 
 7200: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7201:     my ($courseid,@groups) = @_;
 7202:     @groups = sort(@groups);
 7203:     return @groups;
 7204: }
 7205: 
 7206: sub packages_tab_default {
 7207:     my ($uri,$varname)=@_;
 7208:     my (undef,$part,$name)=split(/\./,$varname);
 7209: 
 7210:     my (@extension,@specifics,$do_default);
 7211:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7212: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7213: 	if ($pack_type eq 'default') {
 7214: 	    $do_default=1;
 7215: 	} elsif ($pack_type eq 'extension') {
 7216: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7217: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7218: 	    # only look at packages defaults for packages that this id is
 7219: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7220: 	}
 7221:     }
 7222:     # first look for a package that matches the requested part id
 7223:     foreach my $package (@specifics) {
 7224: 	my (undef,$pack_type,$pack_part)=@{$package};
 7225: 	next if ($pack_part ne $part);
 7226: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7227: 	    return $packagetab{"$pack_type&$name&default"};
 7228: 	}
 7229:     }
 7230:     # look for any possible matching non extension_ package
 7231:     foreach my $package (@specifics) {
 7232: 	my (undef,$pack_type,$pack_part)=@{$package};
 7233: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7234: 	    return $packagetab{"$pack_type&$name&default"};
 7235: 	}
 7236: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7237: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7238: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7239: 	}
 7240:     }
 7241:     # look for any posible extension_ match
 7242:     foreach my $package (@extension) {
 7243: 	my ($package,$pack_type)=@{$package};
 7244: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7245: 	    return $packagetab{"$pack_type&$name&default"};
 7246: 	}
 7247: 	if (defined($packagetab{$package."&$name&default"})) {
 7248: 	    return $packagetab{$package."&$name&default"};
 7249: 	}
 7250:     }
 7251:     # look for a global default setting
 7252:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7253: 	return $packagetab{"default&$name&default"};
 7254:     }
 7255:     return undef;
 7256: }
 7257: 
 7258: sub add_prefix_and_part {
 7259:     my ($prefix,$part)=@_;
 7260:     my $keyroot;
 7261:     if (defined($prefix) && $prefix !~ /^__/) {
 7262: 	# prefix that has a part already
 7263: 	$keyroot=$prefix;
 7264:     } elsif (defined($prefix)) {
 7265: 	# prefix that is missing a part
 7266: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7267:     } else {
 7268: 	# no prefix at all
 7269: 	if (defined($part)) { $keyroot='_'.$part; }
 7270:     }
 7271:     return $keyroot;
 7272: }
 7273: 
 7274: # ---------------------------------------------------------------- Get metadata
 7275: 
 7276: my %metaentry;
 7277: sub metadata {
 7278:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7279:     $uri=&declutter($uri);
 7280:     # if it is a non metadata possible uri return quickly
 7281:     if (($uri eq '') || 
 7282: 	(($uri =~ m|^/*adm/|) && 
 7283: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7284:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7285: 	return undef;
 7286:     }
 7287:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7288: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7289: 	return undef;
 7290:     }
 7291:     my $filename=$uri;
 7292:     $uri=~s/\.meta$//;
 7293: #
 7294: # Is the metadata already cached?
 7295: # Look at timestamp of caching
 7296: # Everything is cached by the main uri, libraries are never directly cached
 7297: #
 7298:     if (!defined($liburi)) {
 7299: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7300: 	if (defined($cached)) { return $result->{':'.$what}; }
 7301:     }
 7302:     {
 7303: #
 7304: # Is this a recursive call for a library?
 7305: #
 7306: #	if (! exists($metacache{$uri})) {
 7307: #	    $metacache{$uri}={};
 7308: #	}
 7309: 	my $cachetime = 60*60;
 7310:         if ($liburi) {
 7311: 	    $liburi=&declutter($liburi);
 7312:             $filename=$liburi;
 7313:         } else {
 7314: 	    &devalidate_cache_new('meta',$uri);
 7315: 	    undef(%metaentry);
 7316: 	}
 7317:         my %metathesekeys=();
 7318:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7319: 	my $metastring;
 7320: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7321: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7322: 	    $metastring = 
 7323: 		&Apache::lonnet::ssi_body($which,
 7324: 					  ('grade_target' => 'meta'));
 7325: 	    $cachetime = 1; # only want this cached in the child not long term
 7326: 	} elsif ($uri !~ m -^(editupload)/-) {
 7327: 	    my $file=&filelocation('',&clutter($filename));
 7328: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7329: 	    $metastring=&getfile($file);
 7330: 	}
 7331:         my $parser=HTML::LCParser->new(\$metastring);
 7332:         my $token;
 7333:         undef %metathesekeys;
 7334:         while ($token=$parser->get_token) {
 7335: 	    if ($token->[0] eq 'S') {
 7336: 		if (defined($token->[2]->{'package'})) {
 7337: #
 7338: # This is a package - get package info
 7339: #
 7340: 		    my $package=$token->[2]->{'package'};
 7341: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7342: 		    if (defined($token->[2]->{'id'})) { 
 7343: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7344: 		    }
 7345: 		    if ($metaentry{':packages'}) {
 7346: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7347: 		    } else {
 7348: 			$metaentry{':packages'}=$package.$keyroot;
 7349: 		    }
 7350: 		    foreach my $pack_entry (keys(%packagetab)) {
 7351: 			my $part=$keyroot;
 7352: 			$part=~s/^\_//;
 7353: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7354: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7355: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7356: 			    # ignore package.tab specified default values
 7357:                             # here &package_tab_default() will fetch those
 7358: 			    if ($subp eq 'default') { next; }
 7359: 			    my $value=$packagetab{$pack_entry};
 7360: 			    my $unikey;
 7361: 			    if ($pack =~ /_0$/) {
 7362: 				$unikey='parameter_0_'.$name;
 7363: 				$part=0;
 7364: 			    } else {
 7365: 				$unikey='parameter'.$keyroot.'_'.$name;
 7366: 			    }
 7367: 			    if ($subp eq 'display') {
 7368: 				$value.=' [Part: '.$part.']';
 7369: 			    }
 7370: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7371: 			    $metathesekeys{$unikey}=1;
 7372: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7373: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7374: 			    }
 7375: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7376: 				$metaentry{':'.$unikey}=
 7377: 				    $metaentry{':'.$unikey.'.default'};
 7378: 			    }
 7379: 			}
 7380: 		    }
 7381: 		} else {
 7382: #
 7383: # This is not a package - some other kind of start tag
 7384: #
 7385: 		    my $entry=$token->[1];
 7386: 		    my $unikey;
 7387: 		    if ($entry eq 'import') {
 7388: 			$unikey='';
 7389: 		    } else {
 7390: 			$unikey=$entry;
 7391: 		    }
 7392: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7393: 
 7394: 		    if (defined($token->[2]->{'id'})) { 
 7395: 			$unikey.='_'.$token->[2]->{'id'}; 
 7396: 		    }
 7397: 
 7398: 		    if ($entry eq 'import') {
 7399: #
 7400: # Importing a library here
 7401: #
 7402: 			if ($depthcount<20) {
 7403: 			    my $location=$parser->get_text('/import');
 7404: 			    my $dir=$filename;
 7405: 			    $dir=~s|[^/]*$||;
 7406: 			    $location=&filelocation($dir,$location);
 7407: 			    my $metadata = 
 7408: 				&metadata($uri,'keys', $location,$unikey,
 7409: 					  $depthcount+1);
 7410: 			    foreach my $meta (split(',',$metadata)) {
 7411: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7412: 				$metathesekeys{$meta}=1;
 7413: 			    }
 7414: 			}
 7415: 		    } else { 
 7416: 			
 7417: 			if (defined($token->[2]->{'name'})) { 
 7418: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7419: 			}
 7420: 			$metathesekeys{$unikey}=1;
 7421: 			foreach my $param (@{$token->[3]}) {
 7422: 			    $metaentry{':'.$unikey.'.'.$param} =
 7423: 				$token->[2]->{$param};
 7424: 			}
 7425: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7426: 			my $default=$metaentry{':'.$unikey.'.default'};
 7427: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7428: 		 # only ws inside the tag, and not in default, so use default
 7429: 		 # as value
 7430: 			    $metaentry{':'.$unikey}=$default;
 7431: 			} elsif ( $internaltext =~ /\S/ ) {
 7432: 		  # something interesting inside the tag
 7433: 			    $metaentry{':'.$unikey}=$internaltext;
 7434: 			} else {
 7435: 		  # no interesting values, don't set a default
 7436: 			}
 7437: # end of not-a-package not-a-library import
 7438: 		    }
 7439: # end of not-a-package start tag
 7440: 		}
 7441: # the next is the end of "start tag"
 7442: 	    }
 7443: 	}
 7444: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7445: 	$extension = lc($extension);
 7446: 	if ($extension eq 'htm') { $extension='html'; }
 7447: 
 7448: 	foreach my $key (keys(%packagetab)) {
 7449: 	    #no specific packages #how's our extension
 7450: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7451: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7452: 					 \%metathesekeys);
 7453: 	}
 7454: 
 7455: 	if (!exists($metaentry{':packages'})
 7456: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7457: 	    foreach my $key (keys(%packagetab)) {
 7458: 		#no specific packages well let's get default then
 7459: 		if ($key!~/^default&/) { next; }
 7460: 		&metadata_create_package_def($uri,$key,'default',
 7461: 					     \%metathesekeys);
 7462: 	    }
 7463: 	}
 7464: # are there custom rights to evaluate
 7465: 	if ($metaentry{':copyright'} eq 'custom') {
 7466: 
 7467:     #
 7468:     # Importing a rights file here
 7469:     #
 7470: 	    unless ($depthcount) {
 7471: 		my $location=$metaentry{':customdistributionfile'};
 7472: 		my $dir=$filename;
 7473: 		$dir=~s|[^/]*$||;
 7474: 		$location=&filelocation($dir,$location);
 7475: 		my $rights_metadata =
 7476: 		    &metadata($uri,'keys',$location,'_rights',
 7477: 			      $depthcount+1);
 7478: 		foreach my $rights (split(',',$rights_metadata)) {
 7479: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7480: 		    $metathesekeys{$rights}=1;
 7481: 		}
 7482: 	    }
 7483: 	}
 7484: 	# uniqifiy package listing
 7485: 	my %seen;
 7486: 	my @uniq_packages =
 7487: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7488: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7489: 
 7490: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7491: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7492: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7493: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7494: # this is the end of "was not already recently cached
 7495:     }
 7496:     return $metaentry{':'.$what};
 7497: }
 7498: 
 7499: sub metadata_create_package_def {
 7500:     my ($uri,$key,$package,$metathesekeys)=@_;
 7501:     my ($pack,$name,$subp)=split(/\&/,$key);
 7502:     if ($subp eq 'default') { next; }
 7503:     
 7504:     if (defined($metaentry{':packages'})) {
 7505: 	$metaentry{':packages'}.=','.$package;
 7506:     } else {
 7507: 	$metaentry{':packages'}=$package;
 7508:     }
 7509:     my $value=$packagetab{$key};
 7510:     my $unikey;
 7511:     $unikey='parameter_0_'.$name;
 7512:     $metaentry{':'.$unikey.'.part'}=0;
 7513:     $$metathesekeys{$unikey}=1;
 7514:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7515: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7516:     }
 7517:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7518: 	$metaentry{':'.$unikey}=
 7519: 	    $metaentry{':'.$unikey.'.default'};
 7520:     }
 7521: }
 7522: 
 7523: sub metadata_generate_part0 {
 7524:     my ($metadata,$metacache,$uri) = @_;
 7525:     my %allnames;
 7526:     foreach my $metakey (keys(%$metadata)) {
 7527: 	if ($metakey=~/^parameter\_(.*)/) {
 7528: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7529: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7530: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7531: 	    $allnames{$name}=$part;
 7532: 	  }
 7533: 	}
 7534:     }
 7535:     foreach my $name (keys(%allnames)) {
 7536:       $$metadata{"parameter_0_$name"}=1;
 7537:       my $key=":parameter_0_$name";
 7538:       $$metacache{"$key.part"}='0';
 7539:       $$metacache{"$key.name"}=$name;
 7540:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7541: 					   $allnames{$name}.'_'.$name.
 7542: 					   '.type'};
 7543:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7544: 			     '.display'};
 7545:       my $expr='[Part: '.$allnames{$name}.']';
 7546:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7547:       $$metacache{"$key.display"}=$olddis;
 7548:     }
 7549: }
 7550: 
 7551: # ------------------------------------------------------ Devalidate title cache
 7552: 
 7553: sub devalidate_title_cache {
 7554:     my ($url)=@_;
 7555:     if (!$env{'request.course.id'}) { return; }
 7556:     my $symb=&symbread($url);
 7557:     if (!$symb) { return; }
 7558:     my $key=$env{'request.course.id'}."\0".$symb;
 7559:     &devalidate_cache_new('title',$key);
 7560: }
 7561: 
 7562: # ------------------------------------------------- Get the title of a resource
 7563: 
 7564: sub gettitle {
 7565:     my $urlsymb=shift;
 7566:     my $symb=&symbread($urlsymb);
 7567:     if ($symb) {
 7568: 	my $key=$env{'request.course.id'}."\0".$symb;
 7569: 	my ($result,$cached)=&is_cached_new('title',$key);
 7570: 	if (defined($cached)) { 
 7571: 	    return $result;
 7572: 	}
 7573: 	my ($map,$resid,$url)=&decode_symb($symb);
 7574: 	my $title='';
 7575: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7576: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7577: 	} else {
 7578: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7579: 		    &GDBM_READER(),0640)) {
 7580: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7581: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7582: 		untie(%bighash);
 7583: 	    }
 7584: 	}
 7585: 	$title=~s/\&colon\;/\:/gs;
 7586: 	if ($title) {
 7587: 	    return &do_cache_new('title',$key,$title,600);
 7588: 	}
 7589: 	$urlsymb=$url;
 7590:     }
 7591:     my $title=&metadata($urlsymb,'title');
 7592:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7593:     return $title;
 7594: }
 7595: 
 7596: sub get_slot {
 7597:     my ($which,$cnum,$cdom)=@_;
 7598:     if (!$cnum || !$cdom) {
 7599: 	(undef,my $courseid)=&whichuser();
 7600: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7601: 	$cnum=$env{'course.'.$courseid.'.num'};
 7602:     }
 7603:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7604:     my %slotinfo;
 7605:     if (exists($remembered{$key})) {
 7606: 	$slotinfo{$which} = $remembered{$key};
 7607:     } else {
 7608: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7609: 	&Apache::lonhomework::showhash(%slotinfo);
 7610: 	my ($tmp)=keys(%slotinfo);
 7611: 	if ($tmp=~/^error:/) { return (); }
 7612: 	$remembered{$key} = $slotinfo{$which};
 7613:     }
 7614:     if (ref($slotinfo{$which}) eq 'HASH') {
 7615: 	return %{$slotinfo{$which}};
 7616:     }
 7617:     return $slotinfo{$which};
 7618: }
 7619: # ------------------------------------------------- Update symbolic store links
 7620: 
 7621: sub symblist {
 7622:     my ($mapname,%newhash)=@_;
 7623:     $mapname=&deversion(&declutter($mapname));
 7624:     my %hash;
 7625:     if (($env{'request.course.fn'}) && (%newhash)) {
 7626:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7627:                       &GDBM_WRCREAT(),0640)) {
 7628: 	    foreach my $url (keys %newhash) {
 7629: 		next if ($url eq 'last_known'
 7630: 			 && $env{'form.no_update_last_known'});
 7631: 		$hash{declutter($url)}=&encode_symb($mapname,
 7632: 						    $newhash{$url}->[1],
 7633: 						    $newhash{$url}->[0]);
 7634:             }
 7635:             if (untie(%hash)) {
 7636: 		return 'ok';
 7637:             }
 7638:         }
 7639:     }
 7640:     return 'error';
 7641: }
 7642: 
 7643: # --------------------------------------------------------------- Verify a symb
 7644: 
 7645: sub symbverify {
 7646:     my ($symb,$thisurl)=@_;
 7647:     my $thisfn=$thisurl;
 7648:     $thisfn=&declutter($thisfn);
 7649: # direct jump to resource in page or to a sequence - will construct own symbs
 7650:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7651: # check URL part
 7652:     my ($map,$resid,$url)=&decode_symb($symb);
 7653: 
 7654:     unless ($url eq $thisfn) { return 0; }
 7655: 
 7656:     $symb=&symbclean($symb);
 7657:     $thisurl=&deversion($thisurl);
 7658:     $thisfn=&deversion($thisfn);
 7659: 
 7660:     my %bighash;
 7661:     my $okay=0;
 7662: 
 7663:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7664:                             &GDBM_READER(),0640)) {
 7665:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7666:         unless ($ids) { 
 7667:            $ids=$bighash{'ids_/'.$thisurl};
 7668:         }
 7669:         if ($ids) {
 7670: # ------------------------------------------------------------------- Has ID(s)
 7671: 	    foreach my $id (split(/\,/,$ids)) {
 7672: 	       my ($mapid,$resid)=split(/\./,$id);
 7673:                if (
 7674:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7675:    eq $symb) { 
 7676: 		   if (($env{'request.role.adv'}) ||
 7677: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7678: 		       $okay=1; 
 7679: 		   }
 7680: 	       }
 7681: 	   }
 7682:         }
 7683: 	untie(%bighash);
 7684:     }
 7685:     return $okay;
 7686: }
 7687: 
 7688: # --------------------------------------------------------------- Clean-up symb
 7689: 
 7690: sub symbclean {
 7691:     my $symb=shift;
 7692:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7693: # remove version from map
 7694:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7695: 
 7696: # remove version from URL
 7697:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7698: 
 7699: # remove wrapper
 7700: 
 7701:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7702:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7703:     return $symb;
 7704: }
 7705: 
 7706: # ---------------------------------------------- Split symb to find map and url
 7707: 
 7708: sub encode_symb {
 7709:     my ($map,$resid,$url)=@_;
 7710:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7711: }
 7712: 
 7713: sub decode_symb {
 7714:     my $symb=shift;
 7715:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7716:     my ($map,$resid,$url)=split(/___/,$symb);
 7717:     return (&fixversion($map),$resid,&fixversion($url));
 7718: }
 7719: 
 7720: sub fixversion {
 7721:     my $fn=shift;
 7722:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7723:     my %bighash;
 7724:     my $uri=&clutter($fn);
 7725:     my $key=$env{'request.course.id'}.'_'.$uri;
 7726: # is this cached?
 7727:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7728:     if (defined($cached)) { return $result; }
 7729: # unfortunately not cached, or expired
 7730:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7731: 	    &GDBM_READER(),0640)) {
 7732:  	if ($bighash{'version_'.$uri}) {
 7733:  	    my $version=$bighash{'version_'.$uri};
 7734:  	    unless (($version eq 'mostrecent') || 
 7735: 		    ($version==&getversion($uri))) {
 7736:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7737:  	    }
 7738:  	}
 7739:  	untie %bighash;
 7740:     }
 7741:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7742: }
 7743: 
 7744: sub deversion {
 7745:     my $url=shift;
 7746:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7747:     return $url;
 7748: }
 7749: 
 7750: # ------------------------------------------------------ Return symb list entry
 7751: 
 7752: sub symbread {
 7753:     my ($thisfn,$donotrecurse)=@_;
 7754:     my $cache_str='request.symbread.cached.'.$thisfn;
 7755:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7756: # no filename provided? try from environment
 7757:     unless ($thisfn) {
 7758:         if ($env{'request.symb'}) {
 7759: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7760: 	}
 7761: 	$thisfn=$env{'request.filename'};
 7762:     }
 7763:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7764: # is that filename actually a symb? Verify, clean, and return
 7765:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7766: 	if (&symbverify($thisfn,$1)) {
 7767: 	    return $env{$cache_str}=&symbclean($thisfn);
 7768: 	}
 7769:     }
 7770:     $thisfn=declutter($thisfn);
 7771:     my %hash;
 7772:     my %bighash;
 7773:     my $syval='';
 7774:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7775:         my $targetfn = $thisfn;
 7776:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7777:             $targetfn = 'adm/wrapper/'.$thisfn;
 7778:         }
 7779: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7780: 	    $targetfn=$1;
 7781: 	}
 7782:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7783:                       &GDBM_READER(),0640)) {
 7784: 	    $syval=$hash{$targetfn};
 7785:             untie(%hash);
 7786:         }
 7787: # ---------------------------------------------------------- There was an entry
 7788:         if ($syval) {
 7789: 	    #unless ($syval=~/\_\d+$/) {
 7790: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7791: 		    #&appenv({'request.ambiguous' => $thisfn});
 7792: 		    #return $env{$cache_str}='';
 7793: 		#}    
 7794: 		#$syval.=$1;
 7795: 	    #}
 7796:         } else {
 7797: # ------------------------------------------------------- Was not in symb table
 7798:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7799:                             &GDBM_READER(),0640)) {
 7800: # ---------------------------------------------- Get ID(s) for current resource
 7801:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7802:               unless ($ids) { 
 7803:                  $ids=$bighash{'ids_/'.$thisfn};
 7804:               }
 7805:               unless ($ids) {
 7806: # alias?
 7807: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7808:               }
 7809:               if ($ids) {
 7810: # ------------------------------------------------------------------- Has ID(s)
 7811:                  my @possibilities=split(/\,/,$ids);
 7812:                  if ($#possibilities==0) {
 7813: # ----------------------------------------------- There is only one possibility
 7814: 		     my ($mapid,$resid)=split(/\./,$ids);
 7815: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7816: 						    $resid,$thisfn);
 7817:                  } elsif (!$donotrecurse) {
 7818: # ------------------------------------------ There is more than one possibility
 7819:                      my $realpossible=0;
 7820:                      foreach my $id (@possibilities) {
 7821: 			 my $file=$bighash{'src_'.$id};
 7822:                          if (&allowed('bre',$file)) {
 7823:          		    my ($mapid,$resid)=split(/\./,$id);
 7824:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7825: 				$realpossible++;
 7826:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7827: 						    $resid,$thisfn);
 7828:                             }
 7829: 			 }
 7830:                      }
 7831: 		     if ($realpossible!=1) { $syval=''; }
 7832:                  } else {
 7833:                      $syval='';
 7834:                  }
 7835: 	      }
 7836:               untie(%bighash)
 7837:            }
 7838:         }
 7839:         if ($syval) {
 7840: 	    return $env{$cache_str}=$syval;
 7841:         }
 7842:     }
 7843:     &appenv({'request.ambiguous' => $thisfn});
 7844:     return $env{$cache_str}='';
 7845: }
 7846: 
 7847: # ---------------------------------------------------------- Return random seed
 7848: 
 7849: sub numval {
 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:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7859:     return int($txt);
 7860: }
 7861: 
 7862: sub numval2 {
 7863:     my $txt=shift;
 7864:     $txt=~tr/A-J/0-9/;
 7865:     $txt=~tr/a-j/0-9/;
 7866:     $txt=~tr/K-T/0-9/;
 7867:     $txt=~tr/k-t/0-9/;
 7868:     $txt=~tr/U-Z/0-5/;
 7869:     $txt=~tr/u-z/0-5/;
 7870:     $txt=~s/\D//g;
 7871:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7872:     my $total;
 7873:     foreach my $val (@txts) { $total+=$val; }
 7874:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7875:     return int($total);
 7876: }
 7877: 
 7878: sub numval3 {
 7879:     use integer;
 7880:     my $txt=shift;
 7881:     $txt=~tr/A-J/0-9/;
 7882:     $txt=~tr/a-j/0-9/;
 7883:     $txt=~tr/K-T/0-9/;
 7884:     $txt=~tr/k-t/0-9/;
 7885:     $txt=~tr/U-Z/0-5/;
 7886:     $txt=~tr/u-z/0-5/;
 7887:     $txt=~s/\D//g;
 7888:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7889:     my $total;
 7890:     foreach my $val (@txts) { $total+=$val; }
 7891:     if ($_64bit) { $total=(($total<<32)>>32); }
 7892:     return $total;
 7893: }
 7894: 
 7895: sub digest {
 7896:     my ($data)=@_;
 7897:     my $digest=&Digest::MD5::md5($data);
 7898:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7899:     my ($e,$f);
 7900:     {
 7901:         use integer;
 7902:         $e=($a+$b);
 7903:         $f=($c+$d);
 7904:         if ($_64bit) {
 7905:             $e=(($e<<32)>>32);
 7906:             $f=(($f<<32)>>32);
 7907:         }
 7908:     }
 7909:     if (wantarray) {
 7910: 	return ($e,$f);
 7911:     } else {
 7912: 	my $g;
 7913: 	{
 7914: 	    use integer;
 7915: 	    $g=($e+$f);
 7916: 	    if ($_64bit) {
 7917: 		$g=(($g<<32)>>32);
 7918: 	    }
 7919: 	}
 7920: 	return $g;
 7921:     }
 7922: }
 7923: 
 7924: sub latest_rnd_algorithm_id {
 7925:     return '64bit5';
 7926: }
 7927: 
 7928: sub get_rand_alg {
 7929:     my ($courseid)=@_;
 7930:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7931:     if ($courseid) {
 7932: 	return $env{"course.$courseid.rndseed"};
 7933:     }
 7934:     return &latest_rnd_algorithm_id();
 7935: }
 7936: 
 7937: sub validCODE {
 7938:     my ($CODE)=@_;
 7939:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7940:     return 0;
 7941: }
 7942: 
 7943: sub getCODE {
 7944:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7945:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7946: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7947: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7948: 	return $Apache::lonhomework::history{'resource.CODE'};
 7949:     }
 7950:     return undef;
 7951: }
 7952: 
 7953: sub rndseed {
 7954:     my ($symb,$courseid,$domain,$username)=@_;
 7955:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7956:     if (!defined($symb)) {
 7957: 	unless ($symb=$wsymb) { return time; }
 7958:     }
 7959:     if (!$courseid) { $courseid=$wcourseid; }
 7960:     if (!$domain) { $domain=$wdomain; }
 7961:     if (!$username) { $username=$wusername }
 7962:     my $which=&get_rand_alg();
 7963: 
 7964:     if (defined(&getCODE())) {
 7965: 	if ($which eq '64bit5') {
 7966: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7967: 	} elsif ($which eq '64bit4') {
 7968: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7969: 	} else {
 7970: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7971: 	}
 7972:     } elsif ($which eq '64bit5') {
 7973: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7974:     } elsif ($which eq '64bit4') {
 7975: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7976:     } elsif ($which eq '64bit3') {
 7977: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7978:     } elsif ($which eq '64bit2') {
 7979: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7980:     } elsif ($which eq '64bit') {
 7981: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7982:     }
 7983:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7984: }
 7985: 
 7986: sub rndseed_32bit {
 7987:     my ($symb,$courseid,$domain,$username)=@_;
 7988:     {
 7989: 	use integer;
 7990: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7991: 	my $symbseed=numval($symb) << 22;
 7992: 	my $namechck=unpack("%32C*",$username) << 17;
 7993: 	my $nameseed=numval($username) << 12;
 7994: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7995: 	my $courseseed=unpack("%32C*",$courseid);
 7996: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7997: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7998: 	#&logthis("rndseed :$num:$symb");
 7999: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8000: 	return $num;
 8001:     }
 8002: }
 8003: 
 8004: sub rndseed_64bit {
 8005:     my ($symb,$courseid,$domain,$username)=@_;
 8006:     {
 8007: 	use integer;
 8008: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8009: 	my $symbseed=numval($symb) << 10;
 8010: 	my $namechck=unpack("%32S*",$username);
 8011: 	
 8012: 	my $nameseed=numval($username) << 21;
 8013: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8014: 	my $courseseed=unpack("%32S*",$courseid);
 8015: 	
 8016: 	my $num1=$symbchck+$symbseed+$namechck;
 8017: 	my $num2=$nameseed+$domainseed+$courseseed;
 8018: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8019: 	#&logthis("rndseed :$num:$symb");
 8020: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8021: 	return "$num1,$num2";
 8022:     }
 8023: }
 8024: 
 8025: sub rndseed_64bit2 {
 8026:     my ($symb,$courseid,$domain,$username)=@_;
 8027:     {
 8028: 	use integer;
 8029: 	# strings need to be an even # of cahracters long, it it is odd the
 8030:         # last characters gets thrown away
 8031: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8032: 	my $symbseed=numval($symb) << 10;
 8033: 	my $namechck=unpack("%32S*",$username.' ');
 8034: 	
 8035: 	my $nameseed=numval($username) << 21;
 8036: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8037: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8038: 	
 8039: 	my $num1=$symbchck+$symbseed+$namechck;
 8040: 	my $num2=$nameseed+$domainseed+$courseseed;
 8041: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8042: 	#&logthis("rndseed :$num:$symb");
 8043: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8044: 	return "$num1,$num2";
 8045:     }
 8046: }
 8047: 
 8048: sub rndseed_64bit3 {
 8049:     my ($symb,$courseid,$domain,$username)=@_;
 8050:     {
 8051: 	use integer;
 8052: 	# strings need to be an even # of cahracters long, it it is odd the
 8053:         # last characters gets thrown away
 8054: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8055: 	my $symbseed=numval2($symb) << 10;
 8056: 	my $namechck=unpack("%32S*",$username.' ');
 8057: 	
 8058: 	my $nameseed=numval2($username) << 21;
 8059: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8060: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8061: 	
 8062: 	my $num1=$symbchck+$symbseed+$namechck;
 8063: 	my $num2=$nameseed+$domainseed+$courseseed;
 8064: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8065: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8066: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8067: 	
 8068: 	return "$num1:$num2";
 8069:     }
 8070: }
 8071: 
 8072: sub rndseed_64bit4 {
 8073:     my ($symb,$courseid,$domain,$username)=@_;
 8074:     {
 8075: 	use integer;
 8076: 	# strings need to be an even # of cahracters long, it it is odd the
 8077:         # last characters gets thrown away
 8078: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8079: 	my $symbseed=numval3($symb) << 10;
 8080: 	my $namechck=unpack("%32S*",$username.' ');
 8081: 	
 8082: 	my $nameseed=numval3($username) << 21;
 8083: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8084: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8085: 	
 8086: 	my $num1=$symbchck+$symbseed+$namechck;
 8087: 	my $num2=$nameseed+$domainseed+$courseseed;
 8088: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8089: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8090: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8091: 	
 8092: 	return "$num1:$num2";
 8093:     }
 8094: }
 8095: 
 8096: sub rndseed_64bit5 {
 8097:     my ($symb,$courseid,$domain,$username)=@_;
 8098:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8099:     return "$num1:$num2";
 8100: }
 8101: 
 8102: sub rndseed_CODE_64bit {
 8103:     my ($symb,$courseid,$domain,$username)=@_;
 8104:     {
 8105: 	use integer;
 8106: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8107: 	my $symbseed=numval2($symb);
 8108: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8109: 	my $CODEseed=numval(&getCODE());
 8110: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8111: 	my $num1=$symbseed+$CODEchck;
 8112: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8113: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8114: 	#&logthis("rndseed :$num1:$num2:$symb");
 8115: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8116: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8117: 	return "$num1:$num2";
 8118:     }
 8119: }
 8120: 
 8121: sub rndseed_CODE_64bit4 {
 8122:     my ($symb,$courseid,$domain,$username)=@_;
 8123:     {
 8124: 	use integer;
 8125: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8126: 	my $symbseed=numval3($symb);
 8127: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8128: 	my $CODEseed=numval3(&getCODE());
 8129: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8130: 	my $num1=$symbseed+$CODEchck;
 8131: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8132: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8133: 	#&logthis("rndseed :$num1:$num2:$symb");
 8134: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8135: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8136: 	return "$num1:$num2";
 8137:     }
 8138: }
 8139: 
 8140: sub rndseed_CODE_64bit5 {
 8141:     my ($symb,$courseid,$domain,$username)=@_;
 8142:     my $code = &getCODE();
 8143:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8144:     return "$num1:$num2";
 8145: }
 8146: 
 8147: sub setup_random_from_rndseed {
 8148:     my ($rndseed)=@_;
 8149:     if ($rndseed =~/([,:])/) {
 8150: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8151: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8152:     } else {
 8153: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8154:     }
 8155: }
 8156: 
 8157: sub latest_receipt_algorithm_id {
 8158:     return 'receipt3';
 8159: }
 8160: 
 8161: sub recunique {
 8162:     my $fucourseid=shift;
 8163:     my $unique;
 8164:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8165: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8166: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8167:     } else {
 8168: 	$unique=$perlvar{'lonReceipt'};
 8169:     }
 8170:     return unpack("%32C*",$unique);
 8171: }
 8172: 
 8173: sub recprefix {
 8174:     my $fucourseid=shift;
 8175:     my $prefix;
 8176:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8177: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8178: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8179:     } else {
 8180: 	$prefix=$perlvar{'lonHostID'};
 8181:     }
 8182:     return unpack("%32C*",$prefix);
 8183: }
 8184: 
 8185: sub ireceipt {
 8186:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8187: 
 8188:     my $return =&recprefix($fucourseid).'-';
 8189: 
 8190:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8191: 	$env{'request.state'} eq 'construct') {
 8192: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8193: 	return $return;
 8194:     }
 8195: 
 8196:     my $cuname=unpack("%32C*",$funame);
 8197:     my $cudom=unpack("%32C*",$fudom);
 8198:     my $cucourseid=unpack("%32C*",$fucourseid);
 8199:     my $cusymb=unpack("%32C*",$fusymb);
 8200:     my $cunique=&recunique($fucourseid);
 8201:     my $cpart=unpack("%32S*",$part);
 8202:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8203: 
 8204: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8205: 			       
 8206: 	$return.= ($cunique%$cuname+
 8207: 		   $cunique%$cudom+
 8208: 		   $cusymb%$cuname+
 8209: 		   $cusymb%$cudom+
 8210: 		   $cucourseid%$cuname+
 8211: 		   $cucourseid%$cudom+
 8212: 		   $cpart%$cuname+
 8213: 		   $cpart%$cudom);
 8214:     } else {
 8215: 	$return.= ($cunique%$cuname+
 8216: 		   $cunique%$cudom+
 8217: 		   $cusymb%$cuname+
 8218: 		   $cusymb%$cudom+
 8219: 		   $cucourseid%$cuname+
 8220: 		   $cucourseid%$cudom);
 8221:     }
 8222:     return $return;
 8223: }
 8224: 
 8225: sub receipt {
 8226:     my ($part)=@_;
 8227:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8228:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8229: }
 8230: 
 8231: sub whichuser {
 8232:     my ($passedsymb)=@_;
 8233:     my ($symb,$courseid,$domain,$name,$publicuser);
 8234:     if (defined($env{'form.grade_symb'})) {
 8235: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8236: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8237: 	if (!$allowed &&
 8238: 	    exists($env{'request.course.sec'}) &&
 8239: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8240: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8241: 			      '/'.$env{'request.course.sec'});
 8242: 	}
 8243: 	if ($allowed) {
 8244: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8245: 	    $courseid=$tmp_courseid;
 8246: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8247: 	    ($name)=&get_env_multiple('form.grade_username');
 8248: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8249: 	}
 8250:     }
 8251:     if (!$passedsymb) {
 8252: 	$symb=&symbread();
 8253:     } else {
 8254: 	$symb=$passedsymb;
 8255:     }
 8256:     $courseid=$env{'request.course.id'};
 8257:     $domain=$env{'user.domain'};
 8258:     $name=$env{'user.name'};
 8259:     if ($name eq 'public' && $domain eq 'public') {
 8260: 	if (!defined($env{'form.username'})) {
 8261: 	    $env{'form.username'}.=time.rand(10000000);
 8262: 	}
 8263: 	$name.=$env{'form.username'};
 8264:     }
 8265:     return ($symb,$courseid,$domain,$name,$publicuser);
 8266: 
 8267: }
 8268: 
 8269: # ------------------------------------------------------------ Serves up a file
 8270: # returns either the contents of the file or 
 8271: # -1 if the file doesn't exist
 8272: #
 8273: # if the target is a file that was uploaded via DOCS, 
 8274: # a check will be made to see if a current copy exists on the local server,
 8275: # if it does this will be served, otherwise a copy will be retrieved from
 8276: # the home server for the course and stored in /home/httpd/html/userfiles on
 8277: # the local server.   
 8278: 
 8279: sub getfile {
 8280:     my ($file) = @_;
 8281:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8282:     &repcopy($file);
 8283:     return &readfile($file);
 8284: }
 8285: 
 8286: sub repcopy_userfile {
 8287:     my ($file)=@_;
 8288:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8289:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8290:     my ($cdom,$cnum,$filename) = 
 8291: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8292:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8293:     if (-e "$file") {
 8294: # we already have a local copy, check it out
 8295: 	my @fileinfo = stat($file);
 8296: 	my $rtncode;
 8297: 	my $info;
 8298: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8299: 	if ($lwpresp ne 'ok') {
 8300: # there is no such file anymore, even though we had a local copy
 8301: 	    if ($rtncode eq '404') {
 8302: 		unlink($file);
 8303: 	    }
 8304: 	    return -1;
 8305: 	}
 8306: 	if ($info < $fileinfo[9]) {
 8307: # nice, the file we have is up-to-date, just say okay
 8308: 	    return 'ok';
 8309: 	} else {
 8310: # the file is outdated, get rid of it
 8311: 	    unlink($file);
 8312: 	}
 8313:     }
 8314: # one way or the other, at this point, we don't have the file
 8315: # construct the correct path for the file
 8316:     my @parts = ($cdom,$cnum); 
 8317:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8318: 	push @parts, split(/\//,$1);
 8319:     }
 8320:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8321:     foreach my $part (@parts) {
 8322: 	$path .= '/'.$part;
 8323: 	if (!-e $path) {
 8324: 	    mkdir($path,0770);
 8325: 	}
 8326:     }
 8327: # now the path exists for sure
 8328: # get a user agent
 8329:     my $ua=new LWP::UserAgent;
 8330:     my $transferfile=$file.'.in.transfer';
 8331: # FIXME: this should flock
 8332:     if (-e $transferfile) { return 'ok'; }
 8333:     my $request;
 8334:     $uri=~s/^\///;
 8335:     my $homeserver = &homeserver($cnum,$cdom);
 8336:     my $protocol = $protocol{$homeserver};
 8337:     $protocol = 'http' if ($protocol ne 'https');
 8338:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8339:     my $response=$ua->request($request,$transferfile);
 8340: # did it work?
 8341:     if ($response->is_error()) {
 8342: 	unlink($transferfile);
 8343: 	&logthis("Userfile repcopy failed for $uri");
 8344: 	return -1;
 8345:     }
 8346: # worked, rename the transfer file
 8347:     rename($transferfile,$file);
 8348:     return 'ok';
 8349: }
 8350: 
 8351: sub tokenwrapper {
 8352:     my $uri=shift;
 8353:     $uri=~s|^https?\://([^/]+)||;
 8354:     $uri=~s|^/||;
 8355:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8356:     my $token=$1;
 8357:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8358:     if ($udom && $uname && $file) {
 8359: 	$file=~s|(\?\.*)*$||;
 8360:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8361:         my $homeserver = &homeserver($uname,$udom);
 8362:         my $protocol = $protocol{$homeserver};
 8363:         $protocol = 'http' if ($protocol ne 'https');
 8364:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8365:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8366:                                '&tokenissued='.$perlvar{'lonHostID'};
 8367:     } else {
 8368:         return '/adm/notfound.html';
 8369:     }
 8370: }
 8371: 
 8372: # call with reqtype HEAD: get last modification time
 8373: # call with reqtype GET: get the file contents
 8374: # Do not call this with reqtype GET for large files! It loads everything into memory
 8375: #
 8376: sub getuploaded {
 8377:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8378:     $uri=~s/^\///;
 8379:     my $homeserver = &homeserver($cnum,$cdom);
 8380:     my $protocol = $protocol{$homeserver};
 8381:     $protocol = 'http' if ($protocol ne 'https');
 8382:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8383:     my $ua=new LWP::UserAgent;
 8384:     my $request=new HTTP::Request($reqtype,$uri);
 8385:     my $response=$ua->request($request);
 8386:     $$rtncode = $response->code;
 8387:     if (! $response->is_success()) {
 8388: 	return 'failed';
 8389:     }      
 8390:     if ($reqtype eq 'HEAD') {
 8391: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8392:     } elsif ($reqtype eq 'GET') {
 8393: 	$$info = $response->content;
 8394:     }
 8395:     return 'ok';
 8396: }
 8397: 
 8398: sub readfile {
 8399:     my $file = shift;
 8400:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8401:     my $fh;
 8402:     open($fh,"<$file");
 8403:     my $a='';
 8404:     while (my $line = <$fh>) { $a .= $line; }
 8405:     return $a;
 8406: }
 8407: 
 8408: sub filelocation {
 8409:     my ($dir,$file) = @_;
 8410:     my $location;
 8411:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8412: 
 8413:     if ($file =~ m-^/adm/-) {
 8414: 	$file=~s-^/adm/wrapper/-/-;
 8415: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8416:     }
 8417: 
 8418:     if ($file=~m:^/~:) { # is a contruction space reference
 8419:         $location = $file;
 8420:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8421:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8422: 	# is a correct contruction space reference
 8423:         $location = $file;
 8424:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8425:         $location = $file;
 8426:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8427:         my ($udom,$uname,$filename)=
 8428:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8429:         my $home=&homeserver($uname,$udom);
 8430:         my $is_me=0;
 8431:         my @ids=&current_machine_ids();
 8432:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8433:         if ($is_me) {
 8434:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8435:         } else {
 8436:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8437:   	      $udom.'/'.$uname.'/'.$filename;
 8438:         }
 8439:     } elsif ($file =~ m-^/adm/-) {
 8440: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8441:     } else {
 8442:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8443:         $file=~s:^/res/:/:;
 8444:         if ( !( $file =~ m:^/:) ) {
 8445:             $location = $dir. '/'.$file;
 8446:         } else {
 8447:             $location = '/home/httpd/html/res'.$file;
 8448:         }
 8449:     }
 8450:     $location=~s://+:/:g; # remove duplicate /
 8451:     while ($location=~m{/\.\./}) {
 8452: 	if ($location =~ m{/[^/]+/\.\./}) {
 8453: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8454: 	} else {
 8455: 	    $location=~ s{/\.\./}{/}g;
 8456: 	}
 8457:     } #remove dir/..
 8458:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8459:     return $location;
 8460: }
 8461: 
 8462: sub hreflocation {
 8463:     my ($dir,$file)=@_;
 8464:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8465: 	$file=filelocation($dir,$file);
 8466:     } elsif ($file=~m-^/adm/-) {
 8467: 	$file=~s-^/adm/wrapper/-/-;
 8468: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8469:     }
 8470:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8471: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8472:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8473: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8474:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8475: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8476: 	    -/uploaded/$1/$2/-x;
 8477:     }
 8478:     if ($file=~ m{^/userfiles/}) {
 8479: 	$file =~ s{^/userfiles/}{/uploaded/};
 8480:     }
 8481:     return $file;
 8482: }
 8483: 
 8484: sub current_machine_domains {
 8485:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8486: }
 8487: 
 8488: sub machine_domains {
 8489:     my ($hostname) = @_;
 8490:     my @domains;
 8491:     my %hostname = &all_hostnames();
 8492:     while( my($id, $name) = each(%hostname)) {
 8493: #	&logthis("-$id-$name-$hostname-");
 8494: 	if ($hostname eq $name) {
 8495: 	    push(@domains,&host_domain($id));
 8496: 	}
 8497:     }
 8498:     return @domains;
 8499: }
 8500: 
 8501: sub current_machine_ids {
 8502:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8503: }
 8504: 
 8505: sub machine_ids {
 8506:     my ($hostname) = @_;
 8507:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8508:     my @ids;
 8509:     my %name_to_host = &all_names();
 8510:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8511: 	return @{ $name_to_host{$hostname} };
 8512:     }
 8513:     return;
 8514: }
 8515: 
 8516: sub additional_machine_domains {
 8517:     my @domains;
 8518:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8519:     while( my $line = <$fh>) {
 8520:         $line =~ s/\s//g;
 8521:         push(@domains,$line);
 8522:     }
 8523:     return @domains;
 8524: }
 8525: 
 8526: sub default_login_domain {
 8527:     my $domain = $perlvar{'lonDefDomain'};
 8528:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8529:     foreach my $posdom (&current_machine_domains(),
 8530:                         &additional_machine_domains()) {
 8531:         if (lc($posdom) eq lc($testdomain)) {
 8532:             $domain=$posdom;
 8533:             last;
 8534:         }
 8535:     }
 8536:     return $domain;
 8537: }
 8538: 
 8539: # ------------------------------------------------------------- Declutters URLs
 8540: 
 8541: sub declutter {
 8542:     my $thisfn=shift;
 8543:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8544:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8545:     $thisfn=~s/^\///;
 8546:     $thisfn=~s|^adm/wrapper/||;
 8547:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8548:     $thisfn=~s/^res\///;
 8549:     $thisfn=~s/\?.+$//;
 8550:     return $thisfn;
 8551: }
 8552: 
 8553: # ------------------------------------------------------------- Clutter up URLs
 8554: 
 8555: sub clutter {
 8556:     my $thisfn='/'.&declutter(shift);
 8557:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8558: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8559:        $thisfn='/res'.$thisfn; 
 8560:     }
 8561:     if ($thisfn !~m|/adm|) {
 8562: 	if ($thisfn =~ m|/ext/|) {
 8563: 	    $thisfn='/adm/wrapper'.$thisfn;
 8564: 	} else {
 8565: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8566: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8567: 	    if ($embstyle eq 'ssi'
 8568: 		|| ($embstyle eq 'hdn')
 8569: 		|| ($embstyle eq 'rat')
 8570: 		|| ($embstyle eq 'prv')
 8571: 		|| ($embstyle eq 'ign')) {
 8572: 		#do nothing with these
 8573: 	    } elsif (($embstyle eq 'img') 
 8574: 		|| ($embstyle eq 'emb')
 8575: 		|| ($embstyle eq 'wrp')) {
 8576: 		$thisfn='/adm/wrapper'.$thisfn;
 8577: 	    } elsif ($embstyle eq 'unk'
 8578: 		     && $thisfn!~/\.(sequence|page)$/) {
 8579: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8580: 	    } else {
 8581: #		&logthis("Got a blank emb style");
 8582: 	    }
 8583: 	}
 8584:     }
 8585:     return $thisfn;
 8586: }
 8587: 
 8588: sub clutter_with_no_wrapper {
 8589:     my $uri = &clutter(shift);
 8590:     if ($uri =~ m-^/adm/-) {
 8591: 	$uri =~ s-^/adm/wrapper/-/-;
 8592: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8593:     }
 8594:     return $uri;
 8595: }
 8596: 
 8597: sub freeze_escape {
 8598:     my ($value)=@_;
 8599:     if (ref($value)) {
 8600: 	$value=&nfreeze($value);
 8601: 	return '__FROZEN__'.&escape($value);
 8602:     }
 8603:     return &escape($value);
 8604: }
 8605: 
 8606: 
 8607: sub thaw_unescape {
 8608:     my ($value)=@_;
 8609:     if ($value =~ /^__FROZEN__/) {
 8610: 	substr($value,0,10,undef);
 8611: 	$value=&unescape($value);
 8612: 	return &thaw($value);
 8613:     }
 8614:     return &unescape($value);
 8615: }
 8616: 
 8617: sub correct_line_ends {
 8618:     my ($result)=@_;
 8619:     $$result =~s/\r\n/\n/mg;
 8620:     $$result =~s/\r/\n/mg;
 8621: }
 8622: # ================================================================ Main Program
 8623: 
 8624: sub goodbye {
 8625:    &logthis("Starting Shut down");
 8626: #not converted to using infrastruture and probably shouldn't be
 8627:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8628: #converted
 8629: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8630:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8631: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8632: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8633: #1.1 only
 8634: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8635: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8636: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8637: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8638:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8639:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8640:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8641:    &flushcourselogs();
 8642:    &logthis("Shutting down");
 8643: }
 8644: 
 8645: sub get_dns {
 8646:     my ($url,$func,$ignore_cache) = @_;
 8647:     if (!$ignore_cache) {
 8648: 	my ($content,$cached)=
 8649: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8650: 	if ($cached) {
 8651: 	    &$func($content);
 8652: 	    return;
 8653: 	}
 8654:     }
 8655: 
 8656:     my %alldns;
 8657:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8658:     foreach my $dns (<$config>) {
 8659: 	next if ($dns !~ /^\^(\S*)/x);
 8660:         my $line = $1;
 8661:         my ($host,$protocol) = split(/:/,$line);
 8662:         if ($protocol ne 'https') {
 8663:             $protocol = 'http';
 8664:         }
 8665: 	$alldns{$host} = $protocol;
 8666:     }
 8667:     while (%alldns) {
 8668: 	my ($dns) = keys(%alldns);
 8669: 	my $ua=new LWP::UserAgent;
 8670: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8671: 	my $response=$ua->request($request);
 8672:         delete($alldns{$dns});
 8673: 	next if ($response->is_error());
 8674: 	my @content = split("\n",$response->content);
 8675: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8676: 	&$func(\@content);
 8677: 	return;
 8678:     }
 8679:     close($config);
 8680:     my $which = (split('/',$url))[3];
 8681:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8682:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8683:     my @content = <$config>;
 8684:     &$func(\@content);
 8685:     return;
 8686: }
 8687: # ------------------------------------------------------------ Read domain file
 8688: {
 8689:     my $loaded;
 8690:     my %domain;
 8691: 
 8692:     sub parse_domain_tab {
 8693: 	my ($lines) = @_;
 8694: 	foreach my $line (@$lines) {
 8695: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8696: 
 8697: 	    chomp($line);
 8698: 	    my ($name,@elements) = split(/:/,$line,9);
 8699: 	    my %this_domain;
 8700: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8701: 			       'lang_def', 'city', 'longi', 'lati',
 8702: 			       'primary') {
 8703: 		$this_domain{$field} = shift(@elements);
 8704: 	    }
 8705: 	    $domain{$name} = \%this_domain;
 8706: 	}
 8707:     }
 8708: 
 8709:     sub reset_domain_info {
 8710: 	undef($loaded);
 8711: 	undef(%domain);
 8712:     }
 8713: 
 8714:     sub load_domain_tab {
 8715: 	my ($ignore_cache) = @_;
 8716: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8717: 	my $fh;
 8718: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8719: 	    my @lines = <$fh>;
 8720: 	    &parse_domain_tab(\@lines);
 8721: 	}
 8722: 	close($fh);
 8723: 	$loaded = 1;
 8724:     }
 8725: 
 8726:     sub domain {
 8727: 	&load_domain_tab() if (!$loaded);
 8728: 
 8729: 	my ($name,$what) = @_;
 8730: 	return if ( !exists($domain{$name}) );
 8731: 
 8732: 	if (!$what) {
 8733: 	    return $domain{$name}{'description'};
 8734: 	}
 8735: 	return $domain{$name}{$what};
 8736:     }
 8737: 
 8738:     sub domain_info {
 8739:         &load_domain_tab() if (!$loaded);
 8740:         return %domain;
 8741:     }
 8742: 
 8743: }
 8744: 
 8745: 
 8746: # ------------------------------------------------------------- Read hosts file
 8747: {
 8748:     my %hostname;
 8749:     my %hostdom;
 8750:     my %libserv;
 8751:     my $loaded;
 8752:     my %name_to_host;
 8753: 
 8754:     sub parse_hosts_tab {
 8755: 	my ($file) = @_;
 8756: 	foreach my $configline (@$file) {
 8757: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8758: 	    next if ($configline =~ /^\^/);
 8759: 	    chomp($configline);
 8760: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8761: 	    $name=~s/\s//g;
 8762: 	    if ($id && $domain && $role && $name) {
 8763: 		$hostname{$id}=$name;
 8764: 		push(@{$name_to_host{$name}}, $id);
 8765: 		$hostdom{$id}=$domain;
 8766: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8767:                 if (defined($protocol)) {
 8768:                     if ($protocol eq 'https') {
 8769:                         $protocol{$id} = $protocol;
 8770:                     } else {
 8771:                         $protocol{$id} = 'http'; 
 8772:                     }
 8773:                 } else {
 8774:                     $protocol{$id} = 'http';
 8775:                 }
 8776: 	    }
 8777: 	}
 8778:     }
 8779:     
 8780:     sub reset_hosts_info {
 8781: 	&purge_remembered();
 8782: 	&reset_domain_info();
 8783: 	&reset_hosts_ip_info();
 8784: 	undef(%name_to_host);
 8785: 	undef(%hostname);
 8786: 	undef(%hostdom);
 8787: 	undef(%libserv);
 8788: 	undef($loaded);
 8789:     }
 8790: 
 8791:     sub load_hosts_tab {
 8792: 	my ($ignore_cache) = @_;
 8793: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8794: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8795: 	my @config = <$config>;
 8796: 	&parse_hosts_tab(\@config);
 8797: 	close($config);
 8798: 	$loaded=1;
 8799:     }
 8800: 
 8801:     sub hostname {
 8802: 	&load_hosts_tab() if (!$loaded);
 8803: 
 8804: 	my ($lonid) = @_;
 8805: 	return $hostname{$lonid};
 8806:     }
 8807: 
 8808:     sub all_hostnames {
 8809: 	&load_hosts_tab() if (!$loaded);
 8810: 
 8811: 	return %hostname;
 8812:     }
 8813: 
 8814:     sub all_names {
 8815: 	&load_hosts_tab() if (!$loaded);
 8816: 
 8817: 	return %name_to_host;
 8818:     }
 8819: 
 8820:     sub all_host_domain {
 8821:         &load_hosts_tab() if (!$loaded);
 8822:         return %hostdom;
 8823:     }
 8824: 
 8825:     sub is_library {
 8826: 	&load_hosts_tab() if (!$loaded);
 8827: 
 8828: 	return exists($libserv{$_[0]});
 8829:     }
 8830: 
 8831:     sub all_library {
 8832: 	&load_hosts_tab() if (!$loaded);
 8833: 
 8834: 	return %libserv;
 8835:     }
 8836: 
 8837:     sub get_servers {
 8838: 	&load_hosts_tab() if (!$loaded);
 8839: 
 8840: 	my ($domain,$type) = @_;
 8841: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8842: 	                                          : %hostname;
 8843: 	my %result;
 8844: 	if (ref($domain) eq 'ARRAY') {
 8845: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8846: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8847: 		    $result{$host} = $hostname;
 8848: 		}
 8849: 	    }
 8850: 	} else {
 8851: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8852: 		if ($hostdom{$host} eq $domain) {
 8853: 		    $result{$host} = $hostname;
 8854: 		}
 8855: 	    }
 8856: 	}
 8857: 	return %result;
 8858:     }
 8859: 
 8860:     sub host_domain {
 8861: 	&load_hosts_tab() if (!$loaded);
 8862: 
 8863: 	my ($lonid) = @_;
 8864: 	return $hostdom{$lonid};
 8865:     }
 8866: 
 8867:     sub all_domains {
 8868: 	&load_hosts_tab() if (!$loaded);
 8869: 
 8870: 	my %seen;
 8871: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8872: 	return @uniq;
 8873:     }
 8874: }
 8875: 
 8876: { 
 8877:     my %iphost;
 8878:     my %name_to_ip;
 8879:     my %lonid_to_ip;
 8880: 
 8881:     sub get_hosts_from_ip {
 8882: 	my ($ip) = @_;
 8883: 	my %iphosts = &get_iphost();
 8884: 	if (ref($iphosts{$ip})) {
 8885: 	    return @{$iphosts{$ip}};
 8886: 	}
 8887: 	return;
 8888:     }
 8889:     
 8890:     sub reset_hosts_ip_info {
 8891: 	undef(%iphost);
 8892: 	undef(%name_to_ip);
 8893: 	undef(%lonid_to_ip);
 8894:     }
 8895: 
 8896:     sub get_host_ip {
 8897: 	my ($lonid) = @_;
 8898: 	if (exists($lonid_to_ip{$lonid})) {
 8899: 	    return $lonid_to_ip{$lonid};
 8900: 	}
 8901: 	my $name=&hostname($lonid);
 8902:    	my $ip = gethostbyname($name);
 8903: 	return if (!$ip || length($ip) ne 4);
 8904: 	$ip=inet_ntoa($ip);
 8905: 	$name_to_ip{$name}   = $ip;
 8906: 	$lonid_to_ip{$lonid} = $ip;
 8907: 	return $ip;
 8908:     }
 8909:     
 8910:     sub get_iphost {
 8911: 	my ($ignore_cache) = @_;
 8912: 
 8913: 	if (!$ignore_cache) {
 8914: 	    if (%iphost) {
 8915: 		return %iphost;
 8916: 	    }
 8917: 	    my ($ip_info,$cached)=
 8918: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8919: 	    if ($cached) {
 8920: 		%iphost      = %{$ip_info->[0]};
 8921: 		%name_to_ip  = %{$ip_info->[1]};
 8922: 		%lonid_to_ip = %{$ip_info->[2]};
 8923: 		return %iphost;
 8924: 	    }
 8925: 	}
 8926: 
 8927: 	# get yesterday's info for fallback
 8928: 	my %old_name_to_ip;
 8929: 	my ($ip_info,$cached)=
 8930: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8931: 	if ($cached) {
 8932: 	    %old_name_to_ip = %{$ip_info->[1]};
 8933: 	}
 8934: 
 8935: 	my %name_to_host = &all_names();
 8936: 	foreach my $name (keys(%name_to_host)) {
 8937: 	    my $ip;
 8938: 	    if (!exists($name_to_ip{$name})) {
 8939: 		$ip = gethostbyname($name);
 8940: 		if (!$ip || length($ip) ne 4) {
 8941: 		    if (defined($old_name_to_ip{$name})) {
 8942: 			$ip = $old_name_to_ip{$name};
 8943: 			&logthis("Can't find $name defaulting to old $ip");
 8944: 		    } else {
 8945: 			&logthis("Name $name no IP found");
 8946: 			next;
 8947: 		    }
 8948: 		} else {
 8949: 		    $ip=inet_ntoa($ip);
 8950: 		}
 8951: 		$name_to_ip{$name} = $ip;
 8952: 	    } else {
 8953: 		$ip = $name_to_ip{$name};
 8954: 	    }
 8955: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8956: 		$lonid_to_ip{$id} = $ip;
 8957: 	    }
 8958: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8959: 	}
 8960: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8961: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8962: 				      48*60*60);
 8963: 
 8964: 	return %iphost;
 8965:     }
 8966: }
 8967: 
 8968: BEGIN {
 8969: 
 8970: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8971:     unless ($readit) {
 8972: {
 8973:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8974:     %perlvar = (%perlvar,%{$configvars});
 8975: }
 8976: 
 8977: 
 8978: # ------------------------------------------------------ Read spare server file
 8979: {
 8980:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8981: 
 8982:     while (my $configline=<$config>) {
 8983:        chomp($configline);
 8984:        if ($configline) {
 8985: 	   my ($host,$type) = split(':',$configline,2);
 8986: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8987: 	   push(@{ $spareid{$type} }, $host);
 8988:        }
 8989:     }
 8990:     close($config);
 8991: }
 8992: # ------------------------------------------------------------ Read permissions
 8993: {
 8994:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8995: 
 8996:     while (my $configline=<$config>) {
 8997: 	chomp($configline);
 8998: 	if ($configline) {
 8999: 	    my ($role,$perm)=split(/ /,$configline);
 9000: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9001: 	}
 9002:     }
 9003:     close($config);
 9004: }
 9005: 
 9006: # -------------------------------------------- Read plain texts for permissions
 9007: {
 9008:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9009: 
 9010:     while (my $configline=<$config>) {
 9011: 	chomp($configline);
 9012: 	if ($configline) {
 9013: 	    my ($short,@plain)=split(/:/,$configline);
 9014:             %{$prp{$short}} = ();
 9015: 	    if (@plain > 0) {
 9016:                 $prp{$short}{'std'} = $plain[0];
 9017:                 for (my $i=1; $i<@plain; $i++) {
 9018:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9019:                 }
 9020:             }
 9021: 	}
 9022:     }
 9023:     close($config);
 9024: }
 9025: 
 9026: # ---------------------------------------------------------- Read package table
 9027: {
 9028:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9029: 
 9030:     while (my $configline=<$config>) {
 9031: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9032: 	chomp($configline);
 9033: 	my ($short,$plain)=split(/:/,$configline);
 9034: 	my ($pack,$name)=split(/\&/,$short);
 9035: 	if ($plain ne '') {
 9036: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9037: 	    $packagetab{$short}=$plain; 
 9038: 	}
 9039:     }
 9040:     close($config);
 9041: }
 9042: 
 9043: # ------------- set up temporary directory
 9044: {
 9045:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9046: 
 9047: }
 9048: 
 9049: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9050: 				'compress_threshold'=> 20_000,
 9051:  			        });
 9052: 
 9053: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9054: $dumpcount=0;
 9055: $locknum=0;
 9056: 
 9057: &logtouch();
 9058: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9059: $readit=1;
 9060:     {
 9061: 	use integer;
 9062: 	my $test=(2**32)+1;
 9063: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9064: 	&logthis(" Detected 64bit platform ($_64bit)");
 9065:     }
 9066: }
 9067: }
 9068: 
 9069: 1;
 9070: __END__
 9071: 
 9072: =pod
 9073: 
 9074: =head1 NAME
 9075: 
 9076: Apache::lonnet - Subroutines to ask questions about things in the network.
 9077: 
 9078: =head1 SYNOPSIS
 9079: 
 9080: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9081: 
 9082:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9083: 
 9084: Common parameters:
 9085: 
 9086: =over 4
 9087: 
 9088: =item *
 9089: 
 9090: $uname : an internal username (if $cname expecting a course Id specifically)
 9091: 
 9092: =item *
 9093: 
 9094: $udom : a domain (if $cdom expecting a course's domain specifically)
 9095: 
 9096: =item *
 9097: 
 9098: $symb : a resource instance identifier
 9099: 
 9100: =item *
 9101: 
 9102: $namespace : the name of a .db file that contains the data needed or
 9103: being set.
 9104: 
 9105: =back
 9106: 
 9107: =head1 OVERVIEW
 9108: 
 9109: lonnet provides subroutines which interact with the
 9110: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9111: about classes, users, and resources.
 9112: 
 9113: For many of these objects you can also use this to store data about
 9114: them or modify them in various ways.
 9115: 
 9116: =head2 Symbs
 9117: 
 9118: To identify a specific instance of a resource, LON-CAPA uses symbols
 9119: or "symbs"X<symb>. These identifiers are built from the URL of the
 9120: map, the resource number of the resource in the map, and the URL of
 9121: the resource itself. The latter is somewhat redundant, but might help
 9122: if maps change.
 9123: 
 9124: An example is
 9125: 
 9126:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9127: 
 9128: The respective map entry is
 9129: 
 9130:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9131:   title="Problem 2">
 9132:  </resource>
 9133: 
 9134: Symbs are used by the random number generator, as well as to store and
 9135: restore data specific to a certain instance of for example a problem.
 9136: 
 9137: =head2 Storing And Retrieving Data
 9138: 
 9139: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9140: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9141: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9142: is is the non-critical message twin of cstore. These functions are for
 9143: handlers to store a perl hash to a user's permanent data space in an
 9144: easy manner, and to retrieve it again on another call. It is expected
 9145: that a handler would use this once at the beginning to retrieve data,
 9146: and then again once at the end to send only the new data back.
 9147: 
 9148: The data is stored in the user's data directory on the user's
 9149: homeserver under the ID of the course.
 9150: 
 9151: The hash that is returned by restore will have all of the previous
 9152: value for all of the elements of the hash.
 9153: 
 9154: Example:
 9155: 
 9156:  #creating a hash
 9157:  my %hash;
 9158:  $hash{'foo'}='bar';
 9159: 
 9160:  #storing it
 9161:  &Apache::lonnet::cstore(\%hash);
 9162: 
 9163:  #changing a value
 9164:  $hash{'foo'}='notbar';
 9165: 
 9166:  #adding a new value
 9167:  $hash{'bar'}='foo';
 9168:  &Apache::lonnet::cstore(\%hash);
 9169: 
 9170:  #retrieving the hash
 9171:  my %history=&Apache::lonnet::restore();
 9172: 
 9173:  #print the hash
 9174:  foreach my $key (sort(keys(%history))) {
 9175:    print("\%history{$key} = $history{$key}");
 9176:  }
 9177: 
 9178: Will print out:
 9179: 
 9180:  %history{1:foo} = bar
 9181:  %history{1:keys} = foo:timestamp
 9182:  %history{1:timestamp} = 990455579
 9183:  %history{2:bar} = foo
 9184:  %history{2:foo} = notbar
 9185:  %history{2:keys} = foo:bar:timestamp
 9186:  %history{2:timestamp} = 990455580
 9187:  %history{bar} = foo
 9188:  %history{foo} = notbar
 9189:  %history{timestamp} = 990455580
 9190:  %history{version} = 2
 9191: 
 9192: Note that the special hash entries C<keys>, C<version> and
 9193: C<timestamp> were added to the hash. C<version> will be equal to the
 9194: total number of versions of the data that have been stored. The
 9195: C<timestamp> attribute will be the UNIX time the hash was
 9196: stored. C<keys> is available in every historical section to list which
 9197: keys were added or changed at a specific historical revision of a
 9198: hash.
 9199: 
 9200: B<Warning>: do not store the hash that restore returns directly. This
 9201: will cause a mess since it will restore the historical keys as if the
 9202: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9203: 
 9204: Calling convention:
 9205: 
 9206:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9207:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9208: 
 9209: For more detailed information, see lonnet specific documentation.
 9210: 
 9211: =head1 RETURN MESSAGES
 9212: 
 9213: =over 4
 9214: 
 9215: =item * B<con_lost>: unable to contact remote host
 9216: 
 9217: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9218: when the connection is brought back up
 9219: 
 9220: =item * B<con_failed>: unable to contact remote host and unable to save message
 9221: for later delivery
 9222: 
 9223: =item * B<error:>: an error a occurred, a description of the error follows the :
 9224: 
 9225: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9226: that was requested
 9227: 
 9228: =back
 9229: 
 9230: =head1 PUBLIC SUBROUTINES
 9231: 
 9232: =head2 Session Environment Functions
 9233: 
 9234: =over 4
 9235: 
 9236: =item * 
 9237: X<appenv()>
 9238: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9239: the user envirnoment file, and will be restored for each access this
 9240: user makes during this session, also modifies the %env for the current
 9241: process. Optional rolesarrayref - if defined contains a reference to an array
 9242: of roles which are exempt from the restriction on modifying user.role entries 
 9243: in the user's environment.db and in %env.    
 9244: 
 9245: =item *
 9246: X<delenv()>
 9247: B<delenv($regexp)>: removes all items from the session
 9248: environment file that matches the regular expression in $regexp. The
 9249: values are also delted from the current processes %env.
 9250: 
 9251: =item * get_env_multiple($name) 
 9252: 
 9253: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9254: values may be defined and end up as an array ref.
 9255: 
 9256: returns an array of values
 9257: 
 9258: =back
 9259: 
 9260: =head2 User Information
 9261: 
 9262: =over 4
 9263: 
 9264: =item *
 9265: X<queryauthenticate()>
 9266: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9267: authentication scheme
 9268: 
 9269: =item *
 9270: X<authenticate()>
 9271: B<authenticate($uname,$upass,$udom)>: try to
 9272: authenticate user from domain's lib servers (first use the current
 9273: one). C<$upass> should be the users password.
 9274: 
 9275: =item *
 9276: X<homeserver()>
 9277: B<homeserver($uname,$udom)>: find the server which has
 9278: the user's directory and files (there must be only one), this caches
 9279: the answer, and also caches if there is a borken connection.
 9280: 
 9281: =item *
 9282: X<idget()>
 9283: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9284: (IDs are a unique resource in a domain, there must be only 1 ID per
 9285: username, and only 1 username per ID in a specific domain) (returns
 9286: hash: id=>name,id=>name)
 9287: 
 9288: =item *
 9289: X<idrget()>
 9290: B<idrget($udom,@unames)>: find the IDs behind a list of
 9291: usernames (returns hash: name=>id,name=>id)
 9292: 
 9293: =item *
 9294: X<idput()>
 9295: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9296: 
 9297: =item *
 9298: X<rolesinit()>
 9299: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9300: 
 9301: =item *
 9302: X<getsection()>
 9303: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9304: course $cname, return section name/number or '' for "not in course"
 9305: and '-1' for "no section"
 9306: 
 9307: =item *
 9308: X<userenvironment()>
 9309: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9310: passed in @what from the requested user's environment, returns a hash
 9311: 
 9312: =item * 
 9313: X<userlog_query()>
 9314: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9315: activity.log file. %filters defines filters applied when parsing the
 9316: log file. These can be start or end timestamps, or the type of action
 9317: - log to look for Login or Logout events, check for Checkin or
 9318: Checkout, role for role selection. The response is in the form
 9319: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9320: escaped strings of the action recorded in the activity.log file.
 9321: 
 9322: =back
 9323: 
 9324: =head2 User Roles
 9325: 
 9326: =over 4
 9327: 
 9328: =item *
 9329: 
 9330: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9331:  F: full access
 9332:  U,I,K: authentication modes (cxx only)
 9333:  '': forbidden
 9334:  1: user needs to choose course
 9335:  2: browse allowed
 9336:  A: passphrase authentication needed
 9337: 
 9338: =item *
 9339: 
 9340: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9341: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9342: and course level
 9343: 
 9344: =item *
 9345: 
 9346: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 9347: explanation of a user role term
 9348: 
 9349: =item *
 9350: 
 9351: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9352: All arguments are optional. Returns a hash of a roles, either for
 9353: co-author/assistant author roles for a user's Construction Space
 9354: (default), or if $context is 'userroles', roles for the user himself,
 9355: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9356: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9357: For each key, value is set to colon-separated start and end times for
 9358: the role.  If no username and domain are specified, will default to
 9359: current user/domain. Types, roles, and roledoms are references to arrays
 9360: of role statuses (active, future or previous), roles 
 9361: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9362: to restrict the list of roles reported. If no array ref is 
 9363: provided for types, will default to return only active roles.
 9364: 
 9365: =back
 9366: 
 9367: =head2 User Modification
 9368: 
 9369: =over 4
 9370: 
 9371: =item *
 9372: 
 9373: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9374: user for the level given by URL.  Optional start and end dates (leave empty
 9375: string or zero for "no date")
 9376: 
 9377: =item *
 9378: 
 9379: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9380: change a users, password, possible return values are: ok,
 9381: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9382: refused
 9383: 
 9384: =item *
 9385: 
 9386: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9387: 
 9388: =item *
 9389: 
 9390: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9391:            $forceid,$desiredhome,$email,$inststatus) : 
 9392: modify user
 9393: 
 9394: =item *
 9395: 
 9396: modifystudent
 9397: 
 9398: modify a student's enrollment and identification information.
 9399: The course id is resolved based on the current users environment.  
 9400: This means the envoking user must be a course coordinator or otherwise
 9401: associated with a course.
 9402: 
 9403: This call is essentially a wrapper for lonnet::modifyuser and
 9404: lonnet::modify_student_enrollment
 9405: 
 9406: Inputs: 
 9407: 
 9408: =over 4
 9409: 
 9410: =item B<$udom> Student's loncapa domain
 9411: 
 9412: =item B<$uname> Student's loncapa login name
 9413: 
 9414: =item B<$uid> Student/Employee ID
 9415: 
 9416: =item B<$umode> Student's authentication mode
 9417: 
 9418: =item B<$upass> Student's password
 9419: 
 9420: =item B<$first> Student's first name
 9421: 
 9422: =item B<$middle> Student's middle name
 9423: 
 9424: =item B<$last> Student's last name
 9425: 
 9426: =item B<$gene> Student's generation
 9427: 
 9428: =item B<$usec> Student's section in course
 9429: 
 9430: =item B<$end> Unix time of the roles expiration
 9431: 
 9432: =item B<$start> Unix time of the roles start date
 9433: 
 9434: =item B<$forceid> If defined, allow $uid to be changed
 9435: 
 9436: =item B<$desiredhome> server to use as home server for student
 9437: 
 9438: =item B<$email> Student's permanent e-mail address
 9439: 
 9440: =item B<$type> Type of enrollment (auto or manual)
 9441: 
 9442: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9443: 
 9444: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9445: 
 9446: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9447: 
 9448: =item B<$context> role change context (shown in User Management Logs display in a course)
 9449: 
 9450: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9451: 
 9452: =back
 9453: 
 9454: =item *
 9455: 
 9456: modify_student_enrollment
 9457: 
 9458: Change a students enrollment status in a class.  The environment variable
 9459: 'role.request.course' must be defined for this function to proceed.
 9460: 
 9461: Inputs:
 9462: 
 9463: =over 4
 9464: 
 9465: =item $udom, students domain
 9466: 
 9467: =item $uname, students name
 9468: 
 9469: =item $uid, students user id
 9470: 
 9471: =item $first, students first name
 9472: 
 9473: =item $middle
 9474: 
 9475: =item $last
 9476: 
 9477: =item $gene
 9478: 
 9479: =item $usec
 9480: 
 9481: =item $end
 9482: 
 9483: =item $start
 9484: 
 9485: =item $type
 9486: 
 9487: =item $locktype
 9488: 
 9489: =item $cid
 9490: 
 9491: =item $selfenroll
 9492: 
 9493: =item $context
 9494: 
 9495: =back
 9496: 
 9497: 
 9498: =item *
 9499: 
 9500: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9501: custom role; give a custom role to a user for the level given by URL.  Specify
 9502: name and domain of role author, and role name
 9503: 
 9504: =item *
 9505: 
 9506: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9507: 
 9508: =item *
 9509: 
 9510: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9511: 
 9512: =back
 9513: 
 9514: =head2 Course Infomation
 9515: 
 9516: =over 4
 9517: 
 9518: =item *
 9519: 
 9520: coursedescription($courseid) : returns a hash of information about the
 9521: specified course id, including all environment settings for the
 9522: course, the description of the course will be in the hash under the
 9523: key 'description'
 9524: 
 9525: =item *
 9526: 
 9527: resdata($name,$domain,$type,@which) : request for current parameter
 9528: setting for a specific $type, where $type is either 'course' or 'user',
 9529: @what should be a list of parameters to ask about. This routine caches
 9530: answers for 5 minutes.
 9531: 
 9532: =item *
 9533: 
 9534: get_courseresdata($courseid, $domain) : dump the entire course resource
 9535: data base, returning a hash that is keyed by the resource name and has
 9536: values that are the resource value.  I believe that the timestamps and
 9537: versions are also returned.
 9538: 
 9539: 
 9540: =back
 9541: 
 9542: =head2 Course Modification
 9543: 
 9544: =over 4
 9545: 
 9546: =item *
 9547: 
 9548: writecoursepref($courseid,%prefs) : write preferences (environment
 9549: database) for a course
 9550: 
 9551: =item *
 9552: 
 9553: createcourse($udom,$description,$url) : make/modify course
 9554: 
 9555: =back
 9556: 
 9557: =head2 Resource Subroutines
 9558: 
 9559: =over 4
 9560: 
 9561: =item *
 9562: 
 9563: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9564: 
 9565: =item *
 9566: 
 9567: repcopy($filename) : subscribes to the requested file, and attempts to
 9568: replicate from the owning library server, Might return
 9569: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9570: 'bad_request', also attempts to grab the metadata for the
 9571: resource. Expects the local filesystem pathname
 9572: (/home/httpd/html/res/....)
 9573: 
 9574: =back
 9575: 
 9576: =head2 Resource Information
 9577: 
 9578: =over 4
 9579: 
 9580: =item *
 9581: 
 9582: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9583: a vairety of different possible values, $varname should be a request
 9584: string, and the other parameters can be used to specify who and what
 9585: one is asking about.
 9586: 
 9587: Possible values for $varname are environment.lastname (or other item
 9588: from the envirnment hash), user.name (or someother aspect about the
 9589: user), resource.0.maxtries (or some other part and parameter of a
 9590: resource)
 9591: 
 9592: =item *
 9593: 
 9594: directcondval($number) : get current value of a condition; reads from a state
 9595: string
 9596: 
 9597: =item *
 9598: 
 9599: condval($condidx) : value of condition index based on state
 9600: 
 9601: =item *
 9602: 
 9603: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9604: resource's metadata, $what should be either a specific key, or either
 9605: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9606: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9607: 
 9608: this function automatically caches all requests
 9609: 
 9610: =item *
 9611: 
 9612: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9613: network of library servers; returns file handle of where SQL and regex results
 9614: will be stored for query
 9615: 
 9616: =item *
 9617: 
 9618: symbread($filename) : return symbolic list entry (filename argument optional);
 9619: returns the data handle
 9620: 
 9621: =item *
 9622: 
 9623: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9624: a possible symb for the URL in $thisfn, and if is an encryypted
 9625: resource that the user accessed using /enc/ returns a 1 on success, 0
 9626: on failure, user must be in a course, as it assumes the existance of
 9627: the course initial hash, and uses $env('request.course.id'}
 9628: 
 9629: 
 9630: =item *
 9631: 
 9632: symbclean($symb) : removes versions numbers from a symb, returns the
 9633: cleaned symb
 9634: 
 9635: =item *
 9636: 
 9637: is_on_map($uri) : checks if the $uri is somewhere on the current
 9638: course map, user must be in a course for it to work.
 9639: 
 9640: =item *
 9641: 
 9642: numval($salt) : return random seed value (addend for rndseed)
 9643: 
 9644: =item *
 9645: 
 9646: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9647: a random seed, all arguments are optional, if they aren't sent it uses the
 9648: environment to derive them. Note: if symb isn't sent and it can't get one
 9649: from &symbread it will use the current time as its return value
 9650: 
 9651: =item *
 9652: 
 9653: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9654: unfakeable, receipt
 9655: 
 9656: =item *
 9657: 
 9658: receipt() : API to ireceipt working off of env values; given out to users
 9659: 
 9660: =item *
 9661: 
 9662: countacc($url) : count the number of accesses to a given URL
 9663: 
 9664: =item *
 9665: 
 9666: 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
 9667: 
 9668: =item *
 9669: 
 9670: 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)
 9671: 
 9672: =item *
 9673: 
 9674: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9675: 
 9676: =item *
 9677: 
 9678: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9679: forcing spreadsheet to reevaluate the resource scores next time.
 9680: 
 9681: =back
 9682: 
 9683: =head2 Storing/Retreiving Data
 9684: 
 9685: =over 4
 9686: 
 9687: =item *
 9688: 
 9689: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9690: for this url; hashref needs to be given and should be a \%hashname; the
 9691: remaining args aren't required and if they aren't passed or are '' they will
 9692: be derived from the env
 9693: 
 9694: =item *
 9695: 
 9696: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9697: uses critical subroutine
 9698: 
 9699: =item *
 9700: 
 9701: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9702: all args are optional
 9703: 
 9704: =item *
 9705: 
 9706: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9707: dumps the complete (or key matching regexp) namespace into a hash
 9708: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9709: normally &store()ed into
 9710: 
 9711: $range should be either an integer '100' (give me the first 100
 9712:                                            matching records)
 9713:               or be  two integers sperated by a - with no spaces
 9714:                  '30-50' (give me the 30th through the 50th matching
 9715:                           records)
 9716: 
 9717: 
 9718: =item *
 9719: 
 9720: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9721: replaces a &store() version of data with a replacement set of data
 9722: for a particular resource in a namespace passed in the $storehash hash 
 9723: reference
 9724: 
 9725: =item *
 9726: 
 9727: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9728: works very similar to store/cstore, but all data is stored in a
 9729: temporary location and can be reset using tmpreset, $storehash should
 9730: be a hash reference, returns nothing on success
 9731: 
 9732: =item *
 9733: 
 9734: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9735: similar to restore, but all data is stored in a temporary location and
 9736: can be reset using tmpreset. Returns a hash of values on success,
 9737: error string otherwise.
 9738: 
 9739: =item *
 9740: 
 9741: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9742: deltes all keys for $symb form the temporary storage hash.
 9743: 
 9744: =item *
 9745: 
 9746: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9747: reference filled in from namesp ($udom and $uname are optional)
 9748: 
 9749: =item *
 9750: 
 9751: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9752: namesp ($udom and $uname are optional)
 9753: 
 9754: =item *
 9755: 
 9756: dump($namespace,$udom,$uname,$regexp,$range) : 
 9757: dumps the complete (or key matching regexp) namespace into a hash
 9758: ($udom, $uname, $regexp, $range are optional)
 9759: 
 9760: $range should be either an integer '100' (give me the first 100
 9761:                                            matching records)
 9762:               or be  two integers sperated by a - with no spaces
 9763:                  '30-50' (give me the 30th through the 50th matching
 9764:                           records)
 9765: =item *
 9766: 
 9767: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9768: $store can be a scalar, an array reference, or if the amount to be 
 9769: incremented is > 1, a hash reference.
 9770: 
 9771: ($udom and $uname are optional)
 9772: 
 9773: =item *
 9774: 
 9775: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9776: ($udom and $uname are optional)
 9777: 
 9778: =item *
 9779: 
 9780: cput($namespace,$storehash,$udom,$uname) : critical put
 9781: ($udom and $uname are optional)
 9782: 
 9783: =item *
 9784: 
 9785: newput($namespace,$storehash,$udom,$uname) :
 9786: 
 9787: Attempts to store the items in the $storehash, but only if they don't
 9788: currently exist, if this succeeds you can be certain that you have 
 9789: successfully created a new key value pair in the $namespace db.
 9790: 
 9791: 
 9792: Args:
 9793:  $namespace: name of database to store values to
 9794:  $storehash: hashref to store to the db
 9795:  $udom: (optional) domain of user containing the db
 9796:  $uname: (optional) name of user caontaining the db
 9797: 
 9798: Returns:
 9799:  'ok' -> succeeded in storing all keys of $storehash
 9800:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9801:                         least <key> already existed in the db (other
 9802:                         requested keys may also already exist)
 9803:  'error: <msg>' -> unable to tie the DB or other error occurred
 9804:  'con_lost' -> unable to contact request server
 9805:  'refused' -> action was not allowed by remote machine
 9806: 
 9807: 
 9808: =item *
 9809: 
 9810: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9811: reference filled in from namesp (encrypts the return communication)
 9812: ($udom and $uname are optional)
 9813: 
 9814: =item *
 9815: 
 9816: log($udom,$name,$home,$message) : write to permanent log for user; use
 9817: critical subroutine
 9818: 
 9819: =item *
 9820: 
 9821: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9822: array reference filled in from namespace found in domain level on either
 9823: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9824: 
 9825: =item *
 9826: 
 9827: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9828: domain level either on specified domain server ($uhome) or primary domain 
 9829: server ($udom and $uhome are optional)
 9830: 
 9831: =item * 
 9832: 
 9833: get_domain_defaults($target_domain) : returns hash with defaults for
 9834: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9835: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9836: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9837: Values are retrieved from cache (if current), or from domain's configuration.db
 9838: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9839: or lonTabs/domain.tab. 
 9840: 
 9841: %domdefaults = &get_auth_defaults($target_domain);
 9842: 
 9843: =back
 9844: 
 9845: =head2 Network Status Functions
 9846: 
 9847: =over 4
 9848: 
 9849: =item *
 9850: 
 9851: dirlist($uri) : return directory list based on URI
 9852: 
 9853: =item *
 9854: 
 9855: spareserver() : find server with least workload from spare.tab
 9856: 
 9857: =back
 9858: 
 9859: =head2 Apache Request
 9860: 
 9861: =over 4
 9862: 
 9863: =item *
 9864: 
 9865: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9866: localhost, posts hash
 9867: 
 9868: =back
 9869: 
 9870: =head2 Data to String to Data
 9871: 
 9872: =over 4
 9873: 
 9874: =item *
 9875: 
 9876: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9877: and '&' separators, supports elements that are arrayrefs and hashrefs
 9878: 
 9879: =item *
 9880: 
 9881: hashref2str($hashref) : convert a hashref into a string complete with
 9882: escaping and '=' and '&' separators, supports elements that are
 9883: arrayrefs and hashrefs
 9884: 
 9885: =item *
 9886: 
 9887: arrayref2str($arrayref) : convert an arrayref into a string complete
 9888: with escaping and '&' separators, supports elements that are arrayrefs
 9889: and hashrefs
 9890: 
 9891: =item *
 9892: 
 9893: str2hash($string) : convert string to hash using unescaping and
 9894: splitting on '=' and '&', supports elements that are arrayrefs and
 9895: hashrefs
 9896: 
 9897: =item *
 9898: 
 9899: str2array($string) : convert string to hash using unescaping and
 9900: splitting on '&', supports elements that are arrayrefs and hashrefs
 9901: 
 9902: =back
 9903: 
 9904: =head2 Logging Routines
 9905: 
 9906: =over 4
 9907: 
 9908: These routines allow one to make log messages in the lonnet.log and
 9909: lonnet.perm logfiles.
 9910: 
 9911: =item *
 9912: 
 9913: logtouch() : make sure the logfile, lonnet.log, exists
 9914: 
 9915: =item *
 9916: 
 9917: logthis() : append message to the normal lonnet.log file, it gets
 9918: preiodically rolled over and deleted.
 9919: 
 9920: =item *
 9921: 
 9922: logperm() : append a permanent message to lonnet.perm.log, this log
 9923: file never gets deleted by any automated portion of the system, only
 9924: messages of critical importance should go in here.
 9925: 
 9926: =back
 9927: 
 9928: =head2 General File Helper Routines
 9929: 
 9930: =over 4
 9931: 
 9932: =item *
 9933: 
 9934: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9935: (a) files in /uploaded
 9936:   (i) If a local copy of the file exists - 
 9937:       compares modification date of local copy with last-modified date for 
 9938:       definitive version stored on home server for course. If local copy is 
 9939:       stale, requests a new version from the home server and stores it. 
 9940:       If the original has been removed from the home server, then local copy 
 9941:       is unlinked.
 9942:   (ii) If local copy does not exist -
 9943:       requests the file from the home server and stores it. 
 9944:   
 9945:   If $caller is 'uploadrep':  
 9946:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9947:     for request for files originally uploaded via DOCS. 
 9948:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9949:   
 9950:   Otherwise:
 9951:      This indicates a call from the content generation phase of the request.
 9952:      -  returns the entire contents of the file or -1.
 9953:      
 9954: (b) files in /res
 9955:    - returns the entire contents of a file or -1; 
 9956:    it properly subscribes to and replicates the file if neccessary.
 9957: 
 9958: 
 9959: =item *
 9960: 
 9961: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9962:                   reference
 9963: 
 9964: returns either a stat() list of data about the file or an empty list
 9965: if the file doesn't exist or couldn't find out about it (connection
 9966: problems or user unknown)
 9967: 
 9968: =item *
 9969: 
 9970: filelocation($dir,$file) : returns file system location of a file
 9971: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9972: directory that relative $file lookups are to looked in ($dir of /a/dir
 9973: and a file of ../bob will become /a/bob)
 9974: 
 9975: =item *
 9976: 
 9977: hreflocation($dir,$file) : returns file system location or a URL; same as
 9978: filelocation except for hrefs
 9979: 
 9980: =item *
 9981: 
 9982: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9983: 
 9984: =back
 9985: 
 9986: =head2 Usererfile file routines (/uploaded*)
 9987: 
 9988: =over 4
 9989: 
 9990: =item *
 9991: 
 9992: userfileupload(): main rotine for putting a file in a user or course's
 9993:                   filespace, arguments are,
 9994: 
 9995:  formname - required - this is the name of the element in $env where the
 9996:            filename, and the contents of the file to create/modifed exist
 9997:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9998:            contents of the file is located in $env{'form.'.$formname}
 9999:  coursedoc - if true, store the file in the course of the active role
10000:              of the current user
10001:  subdir - required - subdirectory to put the file in under ../userfiles/
10002:          if undefined, it will be placed in "unknown"
10003: 
10004:  (This routine calls clean_filename() to remove any dangerous
10005:  characters from the filename, and then calls finuserfileupload() to
10006:  complete the transaction)
10007: 
10008:  returns either the url of the uploaded file (/uploaded/....) if successful
10009:  and /adm/notfound.html if unsuccessful
10010: 
10011: =item *
10012: 
10013: clean_filename(): routine for cleaing a filename up for storage in
10014:                  userfile space, argument is:
10015: 
10016:  filename - proposed filename
10017: 
10018: returns: the new clean filename
10019: 
10020: =item *
10021: 
10022: finishuserfileupload(): routine that creaes and sends the file to
10023: userspace, probably shouldn't be called directly
10024: 
10025:   docuname: username or courseid of destination for the file
10026:   docudom: domain of user/course of destination for the file
10027:   formname: same as for userfileupload()
10028:   fname: filename (inculding subdirectories) for the file
10029: 
10030:  returns either the url of the uploaded file (/uploaded/....) if successful
10031:  and /adm/notfound.html if unsuccessful
10032: 
10033: =item *
10034: 
10035: renameuserfile(): renames an existing userfile to a new name
10036: 
10037:   Args:
10038:    docuname: username or courseid of destination for the file
10039:    docudom: domain of user/course of destination for the file
10040:    old: current file name (including any subdirs under userfiles)
10041:    new: desired file name (including any subdirs under userfiles)
10042: 
10043: =item *
10044: 
10045: mkdiruserfile(): creates a directory is a userfiles dir
10046: 
10047:   Args:
10048:    docuname: username or courseid of destination for the file
10049:    docudom: domain of user/course of destination for the file
10050:    dir: dir to create (including any subdirs under userfiles)
10051: 
10052: =item *
10053: 
10054: removeuserfile(): removes a file that exists in userfiles
10055: 
10056:   Args:
10057:    docuname: username or courseid of destination for the file
10058:    docudom: domain of user/course of destination for the file
10059:    fname: filname to delete (including any subdirs under userfiles)
10060: 
10061: =item *
10062: 
10063: removeuploadedurl(): convience function for removeuserfile()
10064: 
10065:   Args:
10066:    url:  a full /uploaded/... url to delete
10067: 
10068: =item * 
10069: 
10070: get_portfile_permissions():
10071:   Args:
10072:     domain: domain of user or course contain the portfolio files
10073:     user: name of user or num of course contain the portfolio files
10074:   Returns:
10075:     hashref of a dump of the proper file_permissions.db
10076:    
10077: 
10078: =item * 
10079: 
10080: get_access_controls():
10081: 
10082: Args:
10083:   current_permissions: the hash ref returned from get_portfile_permissions()
10084:   group: (optional) the group you want the files associated with
10085:   file: (optional) the file you want access info on
10086: 
10087: Returns:
10088:     a hash (keys are file names) of hashes containing
10089:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10090:         values are XML containing access control settings (see below) 
10091: 
10092: Internal notes:
10093: 
10094:  access controls are stored in file_permissions.db as key=value pairs.
10095:     key -> path to file/file_name\0uniqueID:scope_end_start
10096:         where scope -> public,guest,course,group,domains or users.
10097:               end -> UNIX time for end of access (0 -> no end date)
10098:               start -> UNIX time for start of access
10099: 
10100:     value -> XML description of access control
10101:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10102:             <start></start>
10103:             <end></end>
10104: 
10105:             <password></password>  for scope type = guest
10106: 
10107:             <domain></domain>     for scope type = course or group
10108:             <number></number>
10109:             <roles id="">
10110:              <role></role>
10111:              <access></access>
10112:              <section></section>
10113:              <group></group>
10114:             </roles>
10115: 
10116:             <dom></dom>         for scope type = domains
10117: 
10118:             <users>             for scope type = users
10119:              <user>
10120:               <uname></uname>
10121:               <udom></udom>
10122:              </user>
10123:             </users>
10124:            </scope> 
10125:               
10126:  Access data is also aggregated for each file in an additional key=value pair:
10127:  key -> path to file/file_name\0accesscontrol 
10128:  value -> reference to hash
10129:           hash contains key = value pairs
10130:           where key = uniqueID:scope_end_start
10131:                 value = UNIX time record was last updated
10132: 
10133:           Used to improve speed of look-ups of access controls for each file.  
10134:  
10135:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10136: 
10137: modify_access_controls():
10138: 
10139: Modifies access controls for a portfolio file
10140: Args
10141: 1. file name
10142: 2. reference to hash of required changes,
10143: 3. domain
10144: 4. username
10145:   where domain,username are the domain of the portfolio owner 
10146:   (either a user or a course) 
10147: 
10148: Returns:
10149: 1. result of additions or updates ('ok' or 'error', with error message). 
10150: 2. result of deletions ('ok' or 'error', with error message).
10151: 3. reference to hash of any new or updated access controls.
10152: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10153:    key = integer (inbound ID)
10154:    value = uniqueID  
10155: 
10156: =back
10157: 
10158: =head2 HTTP Helper Routines
10159: 
10160: =over 4
10161: 
10162: =item *
10163: 
10164: escape() : unpack non-word characters into CGI-compatible hex codes
10165: 
10166: =item *
10167: 
10168: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10169: 
10170: =back
10171: 
10172: =head1 PRIVATE SUBROUTINES
10173: 
10174: =head2 Underlying communication routines (Shouldn't call)
10175: 
10176: =over 4
10177: 
10178: =item *
10179: 
10180: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10181: 
10182: =item *
10183: 
10184: reply() : uses subreply to send a message to remote machine, logs all failures
10185: 
10186: =item *
10187: 
10188: critical() : passes a critical message to another server; if cannot
10189: get through then place message in connection buffer directory and
10190: returns con_delayed, if incapable of saving message, returns
10191: con_failed
10192: 
10193: =item *
10194: 
10195: reconlonc() : tries to reconnect lonc client processes.
10196: 
10197: =back
10198: 
10199: =head2 Resource Access Logging
10200: 
10201: =over 4
10202: 
10203: =item *
10204: 
10205: flushcourselogs() : flush (save) buffer logs and access logs
10206: 
10207: =item *
10208: 
10209: courselog($what) : save message for course in hash
10210: 
10211: =item *
10212: 
10213: courseacclog($what) : save message for course using &courselog().  Perform
10214: special processing for specific resource types (problems, exams, quizzes, etc).
10215: 
10216: =item *
10217: 
10218: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10219: as a PerlChildExitHandler
10220: 
10221: =back
10222: 
10223: =head2 Other
10224: 
10225: =over 4
10226: 
10227: =item *
10228: 
10229: symblist($mapname,%newhash) : update symbolic storage links
10230: 
10231: =back
10232: 
10233: =cut
10234: 

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