File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1058: download - view: text, annotated - select for diffs
Sun Mar 21 21:05:51 2010 UTC (14 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 5805.
  - Allow existing non-empty entries for user information (lastname, middlename, firstname, generation, id and permanentemail) to be overwritten with empty entries, if field is included in $candelete array ref (new arg for lonnet::modifyuser().
  - Overwriting with empty entries allowed when:
    (a) Updating user information for a single user from "Modify User"        (domain, author or course context) - subject to domain config        for user modification.
    (b) Autoupdate.pl updates from institutional directory data,
        subject to domain config for Autoupdate.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1058 2010/03/21 21:05:51 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 vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol);
   80: 
   81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   84:     %courseownerbuf, %coursetypebuf,$locknum);
   85: 
   86: use IO::Socket;
   87: use GDBM_File;
   88: use HTML::LCParser;
   89: use Fcntl qw(:flock);
   90: use Storable qw(thaw nfreeze);
   91: use Time::HiRes qw( gettimeofday tv_interval );
   92: use Cache::Memcached;
   93: use Digest::MD5;
   94: use Math::Random;
   95: use File::MMagic;
   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: require Exporter;
  103: 
  104: our @ISA = qw (Exporter);
  105: our @EXPORT = qw(%env);
  106: 
  107: 
  108: # --------------------------------------------------------------------- Logging
  109: {
  110:     my $logid;
  111:     sub instructor_log {
  112: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  113:         if (($cnum eq '') || ($cdom eq '')) {
  114:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  115:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  116:         }
  117: 	$logid++;
  118:         my $now = time();
  119: 	my $id=$now.'00000'.$$.'00000'.$logid;
  120: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  121: 				    { $id => {
  122: 					'exe_uname' => $env{'user.name'},
  123: 					'exe_udom'  => $env{'user.domain'},
  124: 					'exe_time'  => $now,
  125: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  126: 					'delflag'   => $delflag,
  127: 					'logentry'  => $storehash,
  128: 					'uname'     => $uname,
  129: 					'udom'      => $udom,
  130: 				    }
  131: 				  },$cdom,$cnum);
  132:     }
  133: }
  134: 
  135: sub logtouch {
  136:     my $execdir=$perlvar{'lonDaemons'};
  137:     unless (-e "$execdir/logs/lonnet.log") {	
  138: 	open(my $fh,">>$execdir/logs/lonnet.log");
  139: 	close $fh;
  140:     }
  141:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  142:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  143: }
  144: 
  145: sub logthis {
  146:     my $message=shift;
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     my $now=time;
  149:     my $local=localtime($now);
  150:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  151: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  152: 	print $fh $logstring;
  153: 	close($fh);
  154:     }
  155:     return 1;
  156: }
  157: 
  158: sub logperm {
  159:     my $message=shift;
  160:     my $execdir=$perlvar{'lonDaemons'};
  161:     my $now=time;
  162:     my $local=localtime($now);
  163:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  164: 	print $fh "$now:$message:$local\n";
  165: 	close($fh);
  166:     }
  167:     return 1;
  168: }
  169: 
  170: sub create_connection {
  171:     my ($hostname,$lonid) = @_;
  172:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  173: 				     Type    => SOCK_STREAM,
  174: 				     Timeout => 10);
  175:     return 0 if (!$client);
  176:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  177:     my $result = <$client>;
  178:     chomp($result);
  179:     return 1 if ($result eq 'done');
  180:     return 0;
  181: }
  182: 
  183: sub get_server_timezone {
  184:     my ($cnum,$cdom) = @_;
  185:     my $home=&homeserver($cnum,$cdom);
  186:     if ($home ne 'no_host') {
  187:         my $cachetime = 24*3600;
  188:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  189:         if (defined($cached)) {
  190:             return $timezone;
  191:         } else {
  192:             my $timezone = &reply('servertimezone',$home);
  193:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  194:         }
  195:     }
  196: }
  197: 
  198: sub get_server_loncaparev {
  199:     my ($dom,$lonhost) = @_;
  200:     if (defined($lonhost)) {
  201:         if (!defined(&hostname($lonhost))) {
  202:             undef($lonhost);
  203:         }
  204:     }
  205:     if (!defined($lonhost)) {
  206:         if (defined(&domain($dom,'primary'))) {
  207:             $lonhost=&domain($dom,'primary');
  208:             if ($lonhost eq 'no_host') {
  209:                 undef($lonhost);
  210:             }
  211:         }
  212:     }
  213:     if (defined($lonhost)) {
  214:         my $cachetime = 24*3600;
  215:         my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  216:         if (defined($cached)) {
  217:             return $loncaparev;
  218:         } else {
  219:             my $loncaparev = &reply('serverloncaparev',$lonhost);
  220:             return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  221:         }
  222:     }
  223: }
  224: 
  225: # -------------------------------------------------- Non-critical communication
  226: sub subreply {
  227:     my ($cmd,$server)=@_;
  228:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  229:     #
  230:     #  With loncnew process trimming, there's a timing hole between lonc server
  231:     #  process exit and the master server picking up the listen on the AF_UNIX
  232:     #  socket.  In that time interval, a lock file will exist:
  233: 
  234:     my $lockfile=$peerfile.".lock";
  235:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  236: 	sleep(1);
  237:     }
  238:     # At this point, either a loncnew parent is listening or an old lonc
  239:     # or loncnew child is listening so we can connect or everything's dead.
  240:     #
  241:     #   We'll give the connection a few tries before abandoning it.  If
  242:     #   connection is not possible, we'll con_lost back to the client.
  243:     #   
  244:     my $client;
  245:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  246: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  247: 				      Type    => SOCK_STREAM,
  248: 				      Timeout => 10);
  249: 	if ($client) {
  250: 	    last;		# Connected!
  251: 	} else {
  252: 	    &create_connection(&hostname($server),$server);
  253: 	}
  254:         sleep(1);		# Try again later if failed connection.
  255:     }
  256:     my $answer;
  257:     if ($client) {
  258: 	print $client "sethost:$server:$cmd\n";
  259: 	$answer=<$client>;
  260: 	if (!$answer) { $answer="con_lost"; }
  261: 	chomp($answer);
  262:     } else {
  263: 	$answer = 'con_lost';	# Failed connection.
  264:     }
  265:     return $answer;
  266: }
  267: 
  268: sub reply {
  269:     my ($cmd,$server)=@_;
  270:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  271:     my $answer=subreply($cmd,$server);
  272:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  273:        &logthis("<font color=\"blue\">WARNING:".
  274:                 " $cmd to $server returned $answer</font>");
  275:     }
  276:     return $answer;
  277: }
  278: 
  279: # ----------------------------------------------------------- Send USR1 to lonc
  280: 
  281: sub reconlonc {
  282:     my ($lonid) = @_;
  283:     my $hostname = &hostname($lonid);
  284:     if ($lonid) {
  285: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  286: 	if ($hostname && -e $peerfile) {
  287: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  288: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  289: 					     Type    => SOCK_STREAM,
  290: 					     Timeout => 10);
  291: 	    if ($client) {
  292: 		print $client ("reset_retries\n");
  293: 		my $answer=<$client>;
  294: 		#reset just this one.
  295: 	    }
  296: 	}
  297: 	return;
  298:     }
  299: 
  300:     &logthis("Trying to reconnect lonc");
  301:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  302:     if (open(my $fh,"<$loncfile")) {
  303: 	my $loncpid=<$fh>;
  304:         chomp($loncpid);
  305:         if (kill 0 => $loncpid) {
  306: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  307:             kill USR1 => $loncpid;
  308:             sleep 1;
  309:          } else {
  310: 	    &logthis(
  311:                "<font color=\"blue\">WARNING:".
  312:                " lonc at pid $loncpid not responding, giving up</font>");
  313:         }
  314:     } else {
  315: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  316:     }
  317: }
  318: 
  319: # ------------------------------------------------------ Critical communication
  320: 
  321: sub critical {
  322:     my ($cmd,$server)=@_;
  323:     unless (&hostname($server)) {
  324:         &logthis("<font color=\"blue\">WARNING:".
  325:                " Critical message to unknown server ($server)</font>");
  326:         return 'no_such_host';
  327:     }
  328:     my $answer=reply($cmd,$server);
  329:     if ($answer eq 'con_lost') {
  330: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  331: 	my $answer=reply($cmd,$server);
  332:         if ($answer eq 'con_lost') {
  333:             my $now=time;
  334:             my $middlename=$cmd;
  335:             $middlename=substr($middlename,0,16);
  336:             $middlename=~s/\W//g;
  337:             my $dfilename=
  338:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  339:             $dumpcount++;
  340:             {
  341: 		my $dfh;
  342: 		if (open($dfh,">$dfilename")) {
  343: 		    print $dfh "$cmd\n"; 
  344: 		    close($dfh);
  345: 		}
  346:             }
  347:             sleep 2;
  348:             my $wcmd='';
  349:             {
  350: 		my $dfh;
  351: 		if (open($dfh,"<$dfilename")) {
  352: 		    $wcmd=<$dfh>; 
  353: 		    close($dfh);
  354: 		}
  355:             }
  356:             chomp($wcmd);
  357:             if ($wcmd eq $cmd) {
  358: 		&logthis("<font color=\"blue\">WARNING: ".
  359:                          "Connection buffer $dfilename: $cmd</font>");
  360:                 &logperm("D:$server:$cmd");
  361: 	        return 'con_delayed';
  362:             } else {
  363:                 &logthis("<font color=\"red\">CRITICAL:"
  364:                         ." Critical connection failed: $server $cmd</font>");
  365:                 &logperm("F:$server:$cmd");
  366:                 return 'con_failed';
  367:             }
  368:         }
  369:     }
  370:     return $answer;
  371: }
  372: 
  373: # ------------------------------------------- check if return value is an error
  374: 
  375: sub error {
  376:     my ($result) = @_;
  377:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  378: 	if ($2 == 2) { return undef; }
  379: 	return $1;
  380:     }
  381:     return undef;
  382: }
  383: 
  384: sub convert_and_load_session_env {
  385:     my ($lonidsdir,$handle)=@_;
  386:     my @profile;
  387:     {
  388: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  389: 	if (!$opened) {
  390: 	    return 0;
  391: 	}
  392: 	flock($idf,LOCK_SH);
  393: 	@profile=<$idf>;
  394: 	close($idf);
  395:     }
  396:     my %temp_env;
  397:     foreach my $line (@profile) {
  398: 	if ($line !~ m/=/) {
  399: 	    return 0;
  400: 	}
  401: 	chomp($line);
  402: 	my ($envname,$envvalue)=split(/=/,$line,2);
  403: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  404:     }
  405:     unlink("$lonidsdir/$handle.id");
  406:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  407: 	    0640)) {
  408: 	%disk_env = %temp_env;
  409: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  410: 	untie(%disk_env);
  411:     }
  412:     return 1;
  413: }
  414: 
  415: # ------------------------------------------- Transfer profile into environment
  416: my $env_loaded;
  417: sub transfer_profile_to_env {
  418:     my ($lonidsdir,$handle,$force_transfer) = @_;
  419:     if (!$force_transfer && $env_loaded) { return; } 
  420: 
  421:     if (!defined($lonidsdir)) {
  422: 	$lonidsdir = $perlvar{'lonIDsDir'};
  423:     }
  424:     if (!defined($handle)) {
  425:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  426:     }
  427: 
  428:     my $convert;
  429:     {
  430:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  431: 	if (!$opened) {
  432: 	    return;
  433: 	}
  434: 	flock($idf,LOCK_SH);
  435: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  436: 		&GDBM_READER(),0640)) {
  437: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  438: 	    untie(%disk_env);
  439: 	} else {
  440: 	    $convert = 1;
  441: 	}
  442:     }
  443:     if ($convert) {
  444: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  445: 	    &logthis("Failed to load session, or convert session.");
  446: 	}
  447:     }
  448: 
  449:     my %remove;
  450:     while ( my $envname = each(%env) ) {
  451:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  452:             if ($time < time-300) {
  453:                 $remove{$key}++;
  454:             }
  455:         }
  456:     }
  457: 
  458:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  459:     $env_loaded=1;
  460:     foreach my $expired_key (keys(%remove)) {
  461:         &delenv($expired_key);
  462:     }
  463: }
  464: 
  465: # ---------------------------------------------------- Check for valid session 
  466: sub check_for_valid_session {
  467:     my ($r) = @_;
  468:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  469:     my $lonid=$cookies{'lonID'};
  470:     return undef if (!$lonid);
  471: 
  472:     my $handle=&LONCAPA::clean_handle($lonid->value);
  473:     my $lonidsdir=$r->dir_config('lonIDsDir');
  474:     return undef if (!-e "$lonidsdir/$handle.id");
  475: 
  476:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  477:     return undef if (!$opened);
  478: 
  479:     flock($idf,LOCK_SH);
  480:     my %disk_env;
  481:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  482: 	    &GDBM_READER(),0640)) {
  483: 	return undef;	
  484:     }
  485: 
  486:     if (!defined($disk_env{'user.name'})
  487: 	|| !defined($disk_env{'user.domain'})) {
  488: 	return undef;
  489:     }
  490:     return $handle;
  491: }
  492: 
  493: sub timed_flock {
  494:     my ($file,$lock_type) = @_;
  495:     my $failed=0;
  496:     eval {
  497: 	local $SIG{__DIE__}='DEFAULT';
  498: 	local $SIG{ALRM}=sub {
  499: 	    $failed=1;
  500: 	    die("failed lock");
  501: 	};
  502: 	alarm(13);
  503: 	flock($file,$lock_type);
  504: 	alarm(0);
  505:     };
  506:     if ($failed) {
  507: 	return undef;
  508:     } else {
  509: 	return 1;
  510:     }
  511: }
  512: 
  513: # ---------------------------------------------------------- Append Environment
  514: 
  515: sub appenv {
  516:     my ($newenv,$roles) = @_;
  517:     if (ref($newenv) eq 'HASH') {
  518:         foreach my $key (keys(%{$newenv})) {
  519:             my $refused = 0;
  520: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  521:                 $refused = 1;
  522:                 if (ref($roles) eq 'ARRAY') {
  523:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  524:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  525:                         $refused = 0;
  526:                     }
  527:                 }
  528:             }
  529:             if ($refused) {
  530:                 &logthis("<font color=\"blue\">WARNING: ".
  531:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  532:                          .'</font>');
  533: 	        delete($newenv->{$key});
  534:             } else {
  535:                 $env{$key}=$newenv->{$key};
  536:             }
  537:         }
  538:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  539:         if ($opened
  540: 	    && &timed_flock($env_file,LOCK_EX)
  541: 	    &&
  542: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  543: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  544: 	    while (my ($key,$value) = each(%{$newenv})) {
  545: 	        $disk_env{$key} = $value;
  546: 	    }
  547: 	    untie(%disk_env);
  548:         }
  549:     }
  550:     return 'ok';
  551: }
  552: # ----------------------------------------------------- Delete from Environment
  553: 
  554: sub delenv {
  555:     my ($delthis,$regexp) = @_;
  556:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  557:         &logthis("<font color=\"blue\">WARNING: ".
  558:                 "Attempt to delete from environment ".$delthis);
  559:         return 'error';
  560:     }
  561:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  562:     if ($opened
  563: 	&& &timed_flock($env_file,LOCK_EX)
  564: 	&&
  565: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  566: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  567: 	foreach my $key (keys(%disk_env)) {
  568: 	    if ($regexp) {
  569:                 if ($key=~/^$delthis/) {
  570:                     delete($env{$key});
  571:                     delete($disk_env{$key});
  572:                 } 
  573:             } else {
  574:                 if ($key=~/^\Q$delthis\E/) {
  575: 		    delete($env{$key});
  576: 		    delete($disk_env{$key});
  577: 	        }
  578:             }
  579: 	}
  580: 	untie(%disk_env);
  581:     }
  582:     return 'ok';
  583: }
  584: 
  585: sub get_env_multiple {
  586:     my ($name) = @_;
  587:     my @values;
  588:     if (defined($env{$name})) {
  589:         # exists is it an array
  590:         if (ref($env{$name})) {
  591:             @values=@{ $env{$name} };
  592:         } else {
  593:             $values[0]=$env{$name};
  594:         }
  595:     }
  596:     return(@values);
  597: }
  598: 
  599: # ------------------------------------------------------------------- Locking
  600: 
  601: sub set_lock {
  602:     my ($text)=@_;
  603:     $locknum++;
  604:     my $id=$$.'-'.$locknum;
  605:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  606:              'session.lock.'.$id => $text});
  607:     return $id;
  608: }
  609: 
  610: sub get_locks {
  611:     my $num=0;
  612:     my %texts=();
  613:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  614:        if ($lock=~/\w/) {
  615:           $num++;
  616:           $texts{$lock}=$env{'session.lock.'.$lock};
  617:        }
  618:    }
  619:    return ($num,%texts);
  620: }
  621: 
  622: sub remove_lock {
  623:     my ($id)=@_;
  624:     my $newlocks='';
  625:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  626:        if (($lock=~/\w/) && ($lock ne $id)) {
  627:           $newlocks.=','.$lock;
  628:        }
  629:     }
  630:     &appenv({'session.locks' => $newlocks});
  631:     &delenv('session.lock.'.$id);
  632: }
  633: 
  634: sub remove_all_locks {
  635:     my $activelocks=$env{'session.locks'};
  636:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  637:        if ($lock=~/\w/) {
  638:           &remove_lock($lock);
  639:        }
  640:     }
  641: }
  642: 
  643: 
  644: # ------------------------------------------ Find out current server userload
  645: sub userload {
  646:     my $numusers=0;
  647:     {
  648: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  649: 	my $filename;
  650: 	my $curtime=time;
  651: 	while ($filename=readdir(LONIDS)) {
  652: 	    next if ($filename eq '.' || $filename eq '..');
  653: 	    next if ($filename =~ /publicuser_\d+\.id/);
  654: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  655: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  656: 	}
  657: 	closedir(LONIDS);
  658:     }
  659:     my $userloadpercent=0;
  660:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  661:     if ($maxuserload) {
  662: 	$userloadpercent=100*$numusers/$maxuserload;
  663:     }
  664:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  665:     return $userloadpercent;
  666: }
  667: 
  668: # ------------------------------------------ Fight off request when overloaded
  669: 
  670: sub overloaderror {
  671:     my ($r,$checkserver)=@_;
  672:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  673:     my $loadavg;
  674:     if ($checkserver eq $perlvar{'lonHostID'}) {
  675:        open(my $loadfile,'/proc/loadavg');
  676:        $loadavg=<$loadfile>;
  677:        $loadavg =~ s/\s.*//g;
  678:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  679:        close($loadfile);
  680:     } else {
  681:        $loadavg=&reply('load',$checkserver);
  682:     }
  683:     my $overload=$loadavg-100;
  684:     if ($overload>0) {
  685: 	$r->err_headers_out->{'Retry-After'}=$overload;
  686:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  687:         return 413;
  688:     }    
  689:     return '';
  690: }
  691: 
  692: # ------------------------------ Find server with least workload from spare.tab
  693: 
  694: sub spareserver {
  695:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  696:     my $spare_server;
  697:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  698:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  699:                                                      :  $userloadpercent;
  700:     
  701:     foreach my $try_server (@{ $spareid{'primary'} }) {
  702: 	($spare_server, $lowest_load) =
  703: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  704:     }
  705: 
  706:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  707: 
  708:     if (!$found_server) {
  709: 	foreach my $try_server (@{ $spareid{'default'} }) {
  710: 	    ($spare_server, $lowest_load) =
  711: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  712: 	}
  713:     }
  714: 
  715:     if (!$want_server_name) {
  716:         my $protocol = 'http';
  717:         if ($protocol{$spare_server} eq 'https') {
  718:             $protocol = $protocol{$spare_server};
  719:         }
  720:         if (defined($spare_server)) {
  721:             my $hostname = &hostname($spare_server);
  722:             if (defined($hostname)) {  
  723: 	        $spare_server = $protocol.'://'.$hostname;
  724:             }
  725:         }
  726:     }
  727:     return $spare_server;
  728: }
  729: 
  730: sub compare_server_load {
  731:     my ($try_server, $spare_server, $lowest_load) = @_;
  732: 
  733:     my $loadans     = &reply('load',    $try_server);
  734:     my $userloadans = &reply('userload',$try_server);
  735: 
  736:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  737: 	next; #didn't get a number from the server
  738:     }
  739: 
  740:     my $load;
  741:     if ($loadans =~ /\d/) {
  742: 	if ($userloadans =~ /\d/) {
  743: 	    #both are numbers, pick the bigger one
  744: 	    $load = ($loadans > $userloadans) ? $loadans 
  745: 		                              : $userloadans;
  746: 	} else {
  747: 	    $load = $loadans;
  748: 	}
  749:     } else {
  750: 	$load = $userloadans;
  751:     }
  752: 
  753:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  754: 	$spare_server = $try_server;
  755: 	$lowest_load  = $load;
  756:     }
  757:     return ($spare_server,$lowest_load);
  758: }
  759: 
  760: # --------------------------- ask offload servers if user already has a session
  761: sub find_existing_session {
  762:     my ($udom,$uname) = @_;
  763:     foreach my $try_server (@{ $spareid{'primary'} },
  764: 			    @{ $spareid{'default'} }) {
  765: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  766:     }
  767:     return;
  768: }
  769: 
  770: # -------------------------------- ask if server already has a session for user
  771: sub has_user_session {
  772:     my ($lonid,$udom,$uname) = @_;
  773:     my $result = &reply(join(':','userhassession',
  774: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  775:     return 1 if ($result eq 'ok');
  776: 
  777:     return 0;
  778: }
  779: 
  780: # --------------------------------------------- Try to change a user's password
  781: 
  782: sub changepass {
  783:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  784:     $currentpass = &escape($currentpass);
  785:     $newpass     = &escape($newpass);
  786:     my $lonhost = $perlvar{'lonHostID'};
  787:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  788: 		       $server);
  789:     if (! $answer) {
  790: 	&logthis("No reply on password change request to $server ".
  791: 		 "by $uname in domain $udom.");
  792:     } elsif ($answer =~ "^ok") {
  793:         &logthis("$uname in $udom successfully changed their password ".
  794: 		 "on $server.");
  795:     } elsif ($answer =~ "^pwchange_failure") {
  796: 	&logthis("$uname in $udom was unable to change their password ".
  797: 		 "on $server.  The action was blocked by either lcpasswd ".
  798: 		 "or pwchange");
  799:     } elsif ($answer =~ "^non_authorized") {
  800:         &logthis("$uname in $udom did not get their password correct when ".
  801: 		 "attempting to change it on $server.");
  802:     } elsif ($answer =~ "^auth_mode_error") {
  803:         &logthis("$uname in $udom attempted to change their password despite ".
  804: 		 "not being locally or internally authenticated on $server.");
  805:     } elsif ($answer =~ "^unknown_user") {
  806:         &logthis("$uname in $udom attempted to change their password ".
  807: 		 "on $server but were unable to because $server is not ".
  808: 		 "their home server.");
  809:     } elsif ($answer =~ "^refused") {
  810: 	&logthis("$server refused to change $uname in $udom password because ".
  811: 		 "it was sent an unencrypted request to change the password.");
  812:     } elsif ($answer =~ "invalid_client") {
  813:         &logthis("$server refused to change $uname in $udom password because ".
  814:                  "it was a reset by e-mail originating from an invalid server.");
  815:     }
  816:     return $answer;
  817: }
  818: 
  819: # ----------------------- Try to determine user's current authentication scheme
  820: 
  821: sub queryauthenticate {
  822:     my ($uname,$udom)=@_;
  823:     my $uhome=&homeserver($uname,$udom);
  824:     if (!$uhome) {
  825: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  826: 	return 'no_host';
  827:     }
  828:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  829:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  830: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  831:     }
  832:     return $answer;
  833: }
  834: 
  835: # --------- Try to authenticate user from domain's lib servers (first this one)
  836: 
  837: sub authenticate {
  838:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  839:     $upass=&escape($upass);
  840:     $uname= &LONCAPA::clean_username($uname);
  841:     my $uhome=&homeserver($uname,$udom,1);
  842:     my $newhome;
  843:     if ((!$uhome) || ($uhome eq 'no_host')) {
  844: # Maybe the machine was offline and only re-appeared again recently?
  845:         &reconlonc();
  846: # One more
  847: 	$uhome=&homeserver($uname,$udom,1);
  848:         if (($uhome eq 'no_host') && $checkdefauth) {
  849:             if (defined(&domain($udom,'primary'))) {
  850:                 $newhome=&domain($udom,'primary');
  851:             }
  852:             if ($newhome ne '') {
  853:                 $uhome = $newhome;
  854:             }
  855:         }
  856: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  857: 	    &logthis("User $uname at $udom is unknown in authenticate");
  858: 	    return 'no_host';
  859:         }
  860:     }
  861:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  862:     if ($answer eq 'authorized') {
  863:         if ($newhome) {
  864:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  865:             return 'no_account_on_host'; 
  866:         } else {
  867:             &logthis("User $uname at $udom authorized by $uhome");
  868:             return $uhome;
  869:         }
  870:     }
  871:     if ($answer eq 'non_authorized') {
  872: 	&logthis("User $uname at $udom rejected by $uhome");
  873: 	return 'no_host'; 
  874:     }
  875:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  876:     return 'no_host';
  877: }
  878: 
  879: # ---------------------- Find the homebase for a user from domain's lib servers
  880: 
  881: my %homecache;
  882: sub homeserver {
  883:     my ($uname,$udom,$ignoreBadCache)=@_;
  884:     my $index="$uname:$udom";
  885: 
  886:     if (exists($homecache{$index})) { return $homecache{$index}; }
  887: 
  888:     my %servers = &get_servers($udom,'library');
  889:     foreach my $tryserver (keys(%servers)) {
  890:         next if ($ignoreBadCache ne 'true' && 
  891: 		 exists($badServerCache{$tryserver}));
  892: 
  893: 	my $answer=reply("home:$udom:$uname",$tryserver);
  894: 	if ($answer eq 'found') {
  895: 	    delete($badServerCache{$tryserver}); 
  896: 	    return $homecache{$index}=$tryserver;
  897: 	} elsif ($answer eq 'no_host') {
  898: 	    $badServerCache{$tryserver}=1;
  899: 	}
  900:     }    
  901:     return 'no_host';
  902: }
  903: 
  904: # ------------------------------------- Find the usernames behind a list of IDs
  905: 
  906: sub idget {
  907:     my ($udom,@ids)=@_;
  908:     my %returnhash=();
  909:     
  910:     my %servers = &get_servers($udom,'library');
  911:     foreach my $tryserver (keys(%servers)) {
  912: 	my $idlist=join('&',@ids);
  913: 	$idlist=~tr/A-Z/a-z/; 
  914: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  915: 	my @answer=();
  916: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  917: 	    @answer=split(/\&/,$reply);
  918: 	}                    ;
  919: 	my $i;
  920: 	for ($i=0;$i<=$#ids;$i++) {
  921: 	    if ($answer[$i]) {
  922: 		$returnhash{$ids[$i]}=$answer[$i];
  923: 	    } 
  924: 	}
  925:     } 
  926:     return %returnhash;
  927: }
  928: 
  929: # ------------------------------------- Find the IDs behind a list of usernames
  930: 
  931: sub idrget {
  932:     my ($udom,@unames)=@_;
  933:     my %returnhash=();
  934:     foreach my $uname (@unames) {
  935:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  936:     }
  937:     return %returnhash;
  938: }
  939: 
  940: # ------------------------------- Store away a list of names and associated IDs
  941: 
  942: sub idput {
  943:     my ($udom,%ids)=@_;
  944:     my %servers=();
  945:     foreach my $uname (keys(%ids)) {
  946: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  947:         my $uhom=&homeserver($uname,$udom);
  948:         if ($uhom ne 'no_host') {
  949:             my $id=&escape($ids{$uname});
  950:             $id=~tr/A-Z/a-z/;
  951:             my $esc_unam=&escape($uname);
  952: 	    if ($servers{$uhom}) {
  953: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  954:             } else {
  955:                 $servers{$uhom}=$id.'='.$esc_unam;
  956:             }
  957:         }
  958:     }
  959:     foreach my $server (keys(%servers)) {
  960:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  961:     }
  962: }
  963: 
  964: # ------------------------------dump from db file owned by domainconfig user
  965: sub dump_dom {
  966:     my ($namespace,$udom,$regexp,$range)=@_;
  967:     if (!$udom) {
  968:         $udom=$env{'user.domain'};
  969:     }
  970:     my %returnhash;
  971:     if ($udom) {
  972:         my $uname = &get_domainconfiguser($udom);
  973:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
  974:     }
  975:     return %returnhash;
  976: }
  977: 
  978: # ------------------------------------------ get items from domain db files   
  979: 
  980: sub get_dom {
  981:     my ($namespace,$storearr,$udom,$uhome)=@_;
  982:     my $items='';
  983:     foreach my $item (@$storearr) {
  984:         $items.=&escape($item).'&';
  985:     }
  986:     $items=~s/\&$//;
  987:     if (!$udom) {
  988:         $udom=$env{'user.domain'};
  989:         if (defined(&domain($udom,'primary'))) {
  990:             $uhome=&domain($udom,'primary');
  991:         } else {
  992:             undef($uhome);
  993:         }
  994:     } else {
  995:         if (!$uhome) {
  996:             if (defined(&domain($udom,'primary'))) {
  997:                 $uhome=&domain($udom,'primary');
  998:             }
  999:         }
 1000:     }
 1001:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1002:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1003:         my %returnhash;
 1004:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1005:             return %returnhash;
 1006:         }
 1007:         my @pairs=split(/\&/,$rep);
 1008:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1009:             return @pairs;
 1010:         }
 1011:         my $i=0;
 1012:         foreach my $item (@$storearr) {
 1013:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1014:             $i++;
 1015:         }
 1016:         return %returnhash;
 1017:     } else {
 1018:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1019:     }
 1020: }
 1021: 
 1022: # -------------------------------------------- put items in domain db files 
 1023: 
 1024: sub put_dom {
 1025:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1026:     if (!$udom) {
 1027:         $udom=$env{'user.domain'};
 1028:         if (defined(&domain($udom,'primary'))) {
 1029:             $uhome=&domain($udom,'primary');
 1030:         } else {
 1031:             undef($uhome);
 1032:         }
 1033:     } else {
 1034:         if (!$uhome) {
 1035:             if (defined(&domain($udom,'primary'))) {
 1036:                 $uhome=&domain($udom,'primary');
 1037:             }
 1038:         }
 1039:     } 
 1040:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1041:         my $items='';
 1042:         foreach my $item (keys(%$storehash)) {
 1043:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1044:         }
 1045:         $items=~s/\&$//;
 1046:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1047:     } else {
 1048:         &logthis("put_dom failed - no homeserver and/or domain");
 1049:     }
 1050: }
 1051: 
 1052: # --------------------- newput for items in db file owned by domainconfig user
 1053: sub newput_dom {
 1054:     my ($namespace,$storehash,$udom) = @_;
 1055:     my $result;
 1056:     if (!$udom) {
 1057:         $udom=$env{'user.domain'};
 1058:     }
 1059:     if ($udom) {
 1060:         my $uname = &get_domainconfiguser($udom);
 1061:         $result = &newput($namespace,$storehash,$udom,$uname);
 1062:     }
 1063:     return $result;
 1064: }
 1065: 
 1066: # --------------------- delete for items in db file owned by domainconfig user
 1067: sub del_dom {
 1068:     my ($namespace,$storearr,$udom)=@_;
 1069:     if (ref($storearr) eq 'ARRAY') {
 1070:         if (!$udom) {
 1071:             $udom=$env{'user.domain'};
 1072:         }
 1073:         if ($udom) {
 1074:             my $uname = &get_domainconfiguser($udom); 
 1075:             return &del($namespace,$storearr,$udom,$uname);
 1076:         }
 1077:     }
 1078: }
 1079: 
 1080: # ----------------------------------construct domainconfig user for a domain 
 1081: sub get_domainconfiguser {
 1082:     my ($udom) = @_;
 1083:     return $udom.'-domainconfig';
 1084: }
 1085: 
 1086: sub retrieve_inst_usertypes {
 1087:     my ($udom) = @_;
 1088:     my (%returnhash,@order);
 1089:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1090:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1091:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1092:         %returnhash = %{$domdefs{'inststatustypes'}};
 1093:         @order = @{$domdefs{'inststatusorder'}};
 1094:     } else {
 1095:         if (defined(&domain($udom,'primary'))) {
 1096:             my $uhome=&domain($udom,'primary');
 1097:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1098:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1099:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1100:                 return (\%returnhash,\@order);
 1101:             }
 1102:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1103:             my @pairs=split(/\&/,$hashitems);
 1104:             foreach my $item (@pairs) {
 1105:                 my ($key,$value)=split(/=/,$item,2);
 1106:                 $key = &unescape($key);
 1107:                 next if ($key =~ /^error: 2 /);
 1108:                 $returnhash{$key}=&thaw_unescape($value);
 1109:             }
 1110:             my @esc_order = split(/\&/,$orderitems);
 1111:             foreach my $item (@esc_order) {
 1112:                 push(@order,&unescape($item));
 1113:             }
 1114:         } else {
 1115:             &logthis("get_dom failed - no primary domain server for $udom");
 1116:         }
 1117:     }
 1118:     return (\%returnhash,\@order);
 1119: }
 1120: 
 1121: sub is_domainimage {
 1122:     my ($url) = @_;
 1123:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1124:         if (&domain($1) ne '') {
 1125:             return '1';
 1126:         }
 1127:     }
 1128:     return;
 1129: }
 1130: 
 1131: sub inst_directory_query {
 1132:     my ($srch) = @_;
 1133:     my $udom = $srch->{'srchdomain'};
 1134:     my %results;
 1135:     my $homeserver = &domain($udom,'primary');
 1136:     my $outcome;
 1137:     if ($homeserver ne '') {
 1138: 	my $queryid=&reply("querysend:instdirsearch:".
 1139: 			   &escape($srch->{'srchby'}).':'.
 1140: 			   &escape($srch->{'srchterm'}).':'.
 1141: 			   &escape($srch->{'srchtype'}),$homeserver);
 1142: 	my $host=&hostname($homeserver);
 1143: 	if ($queryid !~/^\Q$host\E\_/) {
 1144: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1145: 	    return;
 1146: 	}
 1147: 	my $response = &get_query_reply($queryid);
 1148: 	my $maxtries = 5;
 1149: 	my $tries = 1;
 1150: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1151: 	    $response = &get_query_reply($queryid);
 1152: 	    $tries ++;
 1153: 	}
 1154: 
 1155:         if (!&error($response) && $response ne 'refused') {
 1156:             if ($response eq 'unavailable') {
 1157:                 $outcome = $response;
 1158:             } else {
 1159:                 $outcome = 'ok';
 1160:                 my @matches = split(/\n/,$response);
 1161:                 foreach my $match (@matches) {
 1162:                     my ($key,$value) = split(/=/,$match);
 1163:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1164:                 }
 1165:             }
 1166:         }
 1167:     }
 1168:     return ($outcome,%results);
 1169: }
 1170: 
 1171: sub usersearch {
 1172:     my ($srch) = @_;
 1173:     my $dom = $srch->{'srchdomain'};
 1174:     my %results;
 1175:     my %libserv = &all_library();
 1176:     my $query = 'usersearch';
 1177:     foreach my $tryserver (keys(%libserv)) {
 1178:         if (&host_domain($tryserver) eq $dom) {
 1179:             my $host=&hostname($tryserver);
 1180:             my $queryid=
 1181:                 &reply("querysend:".&escape($query).':'.
 1182:                        &escape($srch->{'srchby'}).':'.
 1183:                        &escape($srch->{'srchtype'}).':'.
 1184:                        &escape($srch->{'srchterm'}),$tryserver);
 1185:             if ($queryid !~/^\Q$host\E\_/) {
 1186:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1187:                 next;
 1188:             }
 1189:             my $reply = &get_query_reply($queryid);
 1190:             my $maxtries = 1;
 1191:             my $tries = 1;
 1192:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1193:                 $reply = &get_query_reply($queryid);
 1194:                 $tries ++;
 1195:             }
 1196:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1197:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1198:             } else {
 1199:                 my @matches;
 1200:                 if ($reply =~ /\n/) {
 1201:                     @matches = split(/\n/,$reply);
 1202:                 } else {
 1203:                     @matches = split(/\&/,$reply);
 1204:                 }
 1205:                 foreach my $match (@matches) {
 1206:                     my ($uname,$udom,%userhash);
 1207:                     foreach my $entry (split(/:/,$match)) {
 1208:                         my ($key,$value) =
 1209:                             map {&unescape($_);} split(/=/,$entry);
 1210:                         $userhash{$key} = $value;
 1211:                         if ($key eq 'username') {
 1212:                             $uname = $value;
 1213:                         } elsif ($key eq 'domain') {
 1214:                             $udom = $value;
 1215:                         }
 1216:                     }
 1217:                     $results{$uname.':'.$udom} = \%userhash;
 1218:                 }
 1219:             }
 1220:         }
 1221:     }
 1222:     return %results;
 1223: }
 1224: 
 1225: sub get_instuser {
 1226:     my ($udom,$uname,$id) = @_;
 1227:     my $homeserver = &domain($udom,'primary');
 1228:     my ($outcome,%results);
 1229:     if ($homeserver ne '') {
 1230:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1231:                            &escape($id).':'.&escape($udom),$homeserver);
 1232:         my $host=&hostname($homeserver);
 1233:         if ($queryid !~/^\Q$host\E\_/) {
 1234:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1235:             return;
 1236:         }
 1237:         my $response = &get_query_reply($queryid);
 1238:         my $maxtries = 5;
 1239:         my $tries = 1;
 1240:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1241:             $response = &get_query_reply($queryid);
 1242:             $tries ++;
 1243:         }
 1244:         if (!&error($response) && $response ne 'refused') {
 1245:             if ($response eq 'unavailable') {
 1246:                 $outcome = $response;
 1247:             } else {
 1248:                 $outcome = 'ok';
 1249:                 my @matches = split(/\n/,$response);
 1250:                 foreach my $match (@matches) {
 1251:                     my ($key,$value) = split(/=/,$match);
 1252:                     $results{&unescape($key)} = &thaw_unescape($value);
 1253:                 }
 1254:             }
 1255:         }
 1256:     }
 1257:     my %userinfo;
 1258:     if (ref($results{$uname}) eq 'HASH') {
 1259:         %userinfo = %{$results{$uname}};
 1260:     } 
 1261:     return ($outcome,%userinfo);
 1262: }
 1263: 
 1264: sub inst_rulecheck {
 1265:     my ($udom,$uname,$id,$item,$rules) = @_;
 1266:     my %returnhash;
 1267:     if ($udom ne '') {
 1268:         if (ref($rules) eq 'ARRAY') {
 1269:             @{$rules} = map {&escape($_);} (@{$rules});
 1270:             my $rulestr = join(':',@{$rules});
 1271:             my $homeserver=&domain($udom,'primary');
 1272:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1273:                 my $response;
 1274:                 if ($item eq 'username') {                
 1275:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1276:                                               ':'.&escape($uname).':'.$rulestr,
 1277:                                               $homeserver));
 1278:                 } elsif ($item eq 'id') {
 1279:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1280:                                               ':'.&escape($id).':'.$rulestr,
 1281:                                               $homeserver));
 1282:                 } elsif ($item eq 'selfcreate') {
 1283:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1284:                                                &escape($udom).':'.&escape($uname).
 1285:                                               ':'.$rulestr,$homeserver));
 1286:                 }
 1287:                 if ($response ne 'refused') {
 1288:                     my @pairs=split(/\&/,$response);
 1289:                     foreach my $item (@pairs) {
 1290:                         my ($key,$value)=split(/=/,$item,2);
 1291:                         $key = &unescape($key);
 1292:                         next if ($key =~ /^error: 2 /);
 1293:                         $returnhash{$key}=&thaw_unescape($value);
 1294:                     }
 1295:                 }
 1296:             }
 1297:         }
 1298:     }
 1299:     return %returnhash;
 1300: }
 1301: 
 1302: sub inst_userrules {
 1303:     my ($udom,$check) = @_;
 1304:     my (%ruleshash,@ruleorder);
 1305:     if ($udom ne '') {
 1306:         my $homeserver=&domain($udom,'primary');
 1307:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1308:             my $response;
 1309:             if ($check eq 'id') {
 1310:                 $response=&reply('instidrules:'.&escape($udom),
 1311:                                  $homeserver);
 1312:             } elsif ($check eq 'email') {
 1313:                 $response=&reply('instemailrules:'.&escape($udom),
 1314:                                  $homeserver);
 1315:             } else {
 1316:                 $response=&reply('instuserrules:'.&escape($udom),
 1317:                                  $homeserver);
 1318:             }
 1319:             if (($response ne 'refused') && ($response ne 'error') && 
 1320:                 ($response ne 'unknown_cmd') && 
 1321:                 ($response ne 'no_such_host')) {
 1322:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1323:                 my @pairs=split(/\&/,$hashitems);
 1324:                 foreach my $item (@pairs) {
 1325:                     my ($key,$value)=split(/=/,$item,2);
 1326:                     $key = &unescape($key);
 1327:                     next if ($key =~ /^error: 2 /);
 1328:                     $ruleshash{$key}=&thaw_unescape($value);
 1329:                 }
 1330:                 my @esc_order = split(/\&/,$orderitems);
 1331:                 foreach my $item (@esc_order) {
 1332:                     push(@ruleorder,&unescape($item));
 1333:                 }
 1334:             }
 1335:         }
 1336:     }
 1337:     return (\%ruleshash,\@ruleorder);
 1338: }
 1339: 
 1340: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1341: 
 1342: sub get_domain_defaults {
 1343:     my ($domain) = @_;
 1344:     my $cachetime = 60*60*24;
 1345:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1346:     if (defined($cached)) {
 1347:         if (ref($result) eq 'HASH') {
 1348:             return %{$result};
 1349:         }
 1350:     }
 1351:     my %domdefaults;
 1352:     my %domconfig =
 1353:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1354:                                   'requestcourses','inststatus',
 1355:                                   'coursedefaults'],$domain);
 1356:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1357:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1358:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1359:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1360:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1361:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1362:     } else {
 1363:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1364:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1365:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1366:     }
 1367:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1368:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1369:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1370:         } else {
 1371:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1372:         } 
 1373:         my @usertools = ('aboutme','blog','portfolio');
 1374:         foreach my $item (@usertools) {
 1375:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1376:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1377:             }
 1378:         }
 1379:     }
 1380:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1381:         foreach my $item ('official','unofficial','community') {
 1382:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1383:         }
 1384:     }
 1385:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1386:         foreach my $item ('inststatustypes','inststatusorder') {
 1387:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1388:         }
 1389:     }
 1390:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1391:         foreach my $item ('canuse_pdfforms') {
 1392:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1393:         }
 1394:     }
 1395:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1396:                                   $cachetime);
 1397:     return %domdefaults;
 1398: }
 1399: 
 1400: # --------------------------------------------------- Assign a key to a student
 1401: 
 1402: sub assign_access_key {
 1403: #
 1404: # a valid key looks like uname:udom#comments
 1405: # comments are being appended
 1406: #
 1407:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1408:     $kdom=
 1409:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1410:     $knum=
 1411:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1412:     $cdom=
 1413:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1414:     $cnum=
 1415:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1416:     $udom=$env{'user.name'} unless (defined($udom));
 1417:     $uname=$env{'user.domain'} unless (defined($uname));
 1418:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1419:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1420:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1421:                                                   # assigned to this person
 1422:                                                   # - this should not happen,
 1423:                                                   # unless something went wrong
 1424:                                                   # the first time around
 1425: # ready to assign
 1426:         $logentry=$1.'; '.$logentry;
 1427:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1428:                                                  $kdom,$knum) eq 'ok') {
 1429: # key now belongs to user
 1430: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1431:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1432:                 &appenv({'environment.'.$envkey => $ckey});
 1433:                 return 'ok';
 1434:             } else {
 1435:                 return 
 1436:   'error: Count not permanently assign key, will need to be re-entered later.';
 1437: 	    }
 1438:         } else {
 1439:             return 'error: Could not assign key, try again later.';
 1440:         }
 1441:     } elsif (!$existing{$ckey}) {
 1442: # the key does not exist
 1443: 	return 'error: The key does not exist';
 1444:     } else {
 1445: # the key is somebody else's
 1446: 	return 'error: The key is already in use';
 1447:     }
 1448: }
 1449: 
 1450: # ------------------------------------------ put an additional comment on a key
 1451: 
 1452: sub comment_access_key {
 1453: #
 1454: # a valid key looks like uname:udom#comments
 1455: # comments are being appended
 1456: #
 1457:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1458:     $cdom=
 1459:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1460:     $cnum=
 1461:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1462:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1463:     if ($existing{$ckey}) {
 1464:         $existing{$ckey}.='; '.$logentry;
 1465: # ready to assign
 1466:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1467:                                                  $cdom,$cnum) eq 'ok') {
 1468: 	    return 'ok';
 1469:         } else {
 1470: 	    return 'error: Count not store comment.';
 1471:         }
 1472:     } else {
 1473: # the key does not exist
 1474: 	return 'error: The key does not exist';
 1475:     }
 1476: }
 1477: 
 1478: # ------------------------------------------------------ Generate a set of keys
 1479: 
 1480: sub generate_access_keys {
 1481:     my ($number,$cdom,$cnum,$logentry)=@_;
 1482:     $cdom=
 1483:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1484:     $cnum=
 1485:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1486:     unless (&allowed('mky',$cdom)) { return 0; }
 1487:     unless (($cdom) && ($cnum)) { return 0; }
 1488:     if ($number>10000) { return 0; }
 1489:     sleep(2); # make sure don't get same seed twice
 1490:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1491:     my $total=0;
 1492:     for (my $i=1;$i<=$number;$i++) {
 1493:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1494:                   sprintf("%lx",int(100000*rand)).'-'.
 1495:                   sprintf("%lx",int(100000*rand));
 1496:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1497:        $newkey=~s/0/h/g; # and also 0 and O
 1498:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1499:        if ($existing{$newkey}) {
 1500:            $i--;
 1501:        } else {
 1502: 	  if (&put('accesskeys',
 1503:               { $newkey => '# generated '.localtime().
 1504:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1505:                            '; '.$logentry },
 1506: 		   $cdom,$cnum) eq 'ok') {
 1507:               $total++;
 1508: 	  }
 1509:        }
 1510:     }
 1511:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1512:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1513:     return $total;
 1514: }
 1515: 
 1516: # ------------------------------------------------------- Validate an accesskey
 1517: 
 1518: sub validate_access_key {
 1519:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1520:     $cdom=
 1521:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1522:     $cnum=
 1523:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1524:     $udom=$env{'user.domain'} unless (defined($udom));
 1525:     $uname=$env{'user.name'} unless (defined($uname));
 1526:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1527:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1528: }
 1529: 
 1530: # ------------------------------------- Find the section of student in a course
 1531: sub devalidate_getsection_cache {
 1532:     my ($udom,$unam,$courseid)=@_;
 1533:     my $hashid="$udom:$unam:$courseid";
 1534:     &devalidate_cache_new('getsection',$hashid);
 1535: }
 1536: 
 1537: sub courseid_to_courseurl {
 1538:     my ($courseid) = @_;
 1539:     #already url style courseid
 1540:     return $courseid if ($courseid =~ m{^/});
 1541: 
 1542:     if (exists($env{'course.'.$courseid.'.num'})) {
 1543: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1544: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1545: 	return "/$cdom/$cnum";
 1546:     }
 1547: 
 1548:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1549:     if (exists($courseinfo{'num'})) {
 1550: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1551:     }
 1552: 
 1553:     return undef;
 1554: }
 1555: 
 1556: sub getsection {
 1557:     my ($udom,$unam,$courseid)=@_;
 1558:     my $cachetime=1800;
 1559: 
 1560:     my $hashid="$udom:$unam:$courseid";
 1561:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1562:     if (defined($cached)) { return $result; }
 1563: 
 1564:     my %Pending; 
 1565:     my %Expired;
 1566:     #
 1567:     # Each role can either have not started yet (pending), be active, 
 1568:     #    or have expired.
 1569:     #
 1570:     # If there is an active role, we are done.
 1571:     #
 1572:     # If there is more than one role which has not started yet, 
 1573:     #     choose the one which will start sooner
 1574:     # If there is one role which has not started yet, return it.
 1575:     #
 1576:     # If there is more than one expired role, choose the one which ended last.
 1577:     # If there is a role which has expired, return it.
 1578:     #
 1579:     $courseid = &courseid_to_courseurl($courseid);
 1580:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1581:     foreach my $key (keys(%roleshash)) {
 1582:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1583:         my $section=$1;
 1584:         if ($key eq $courseid.'_st') { $section=''; }
 1585:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1586:         my $now=time;
 1587:         if (defined($end) && $end && ($now > $end)) {
 1588:             $Expired{$end}=$section;
 1589:             next;
 1590:         }
 1591:         if (defined($start) && $start && ($now < $start)) {
 1592:             $Pending{$start}=$section;
 1593:             next;
 1594:         }
 1595:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1596:     }
 1597:     #
 1598:     # Presumedly there will be few matching roles from the above
 1599:     # loop and the sorting time will be negligible.
 1600:     if (scalar(keys(%Pending))) {
 1601:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1602:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1603:     } 
 1604:     if (scalar(keys(%Expired))) {
 1605:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1606:         my $time = pop(@sorted);
 1607:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1608:     }
 1609:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1610: }
 1611: 
 1612: sub save_cache {
 1613:     &purge_remembered();
 1614:     #&Apache::loncommon::validate_page();
 1615:     undef(%env);
 1616:     undef($env_loaded);
 1617: }
 1618: 
 1619: my $to_remember=-1;
 1620: my %remembered;
 1621: my %accessed;
 1622: my $kicks=0;
 1623: my $hits=0;
 1624: sub make_key {
 1625:     my ($name,$id) = @_;
 1626:     if (length($id) > 65 
 1627: 	&& length(&escape($id)) > 200) {
 1628: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1629:     }
 1630:     return &escape($name.':'.$id);
 1631: }
 1632: 
 1633: sub devalidate_cache_new {
 1634:     my ($name,$id,$debug) = @_;
 1635:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1636:     $id=&make_key($name,$id);
 1637:     $memcache->delete($id);
 1638:     delete($remembered{$id});
 1639:     delete($accessed{$id});
 1640: }
 1641: 
 1642: sub is_cached_new {
 1643:     my ($name,$id,$debug) = @_;
 1644:     $id=&make_key($name,$id);
 1645:     if (exists($remembered{$id})) {
 1646: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1647: 	$accessed{$id}=[&gettimeofday()];
 1648: 	$hits++;
 1649: 	return ($remembered{$id},1);
 1650:     }
 1651:     my $value = $memcache->get($id);
 1652:     if (!(defined($value))) {
 1653: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1654: 	return (undef,undef);
 1655:     }
 1656:     if ($value eq '__undef__') {
 1657: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1658: 	$value=undef;
 1659:     }
 1660:     &make_room($id,$value,$debug);
 1661:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1662:     return ($value,1);
 1663: }
 1664: 
 1665: sub do_cache_new {
 1666:     my ($name,$id,$value,$time,$debug) = @_;
 1667:     $id=&make_key($name,$id);
 1668:     my $setvalue=$value;
 1669:     if (!defined($setvalue)) {
 1670: 	$setvalue='__undef__';
 1671:     }
 1672:     if (!defined($time) ) {
 1673: 	$time=600;
 1674:     }
 1675:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1676:     my $result = $memcache->set($id,$setvalue,$time);
 1677:     if (! $result) {
 1678: 	&logthis("caching of id -> $id  failed");
 1679: 	$memcache->disconnect_all();
 1680:     }
 1681:     # need to make a copy of $value
 1682:     &make_room($id,$value,$debug);
 1683:     return $value;
 1684: }
 1685: 
 1686: sub make_room {
 1687:     my ($id,$value,$debug)=@_;
 1688: 
 1689:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1690:                                     : $value;
 1691:     if ($to_remember<0) { return; }
 1692:     $accessed{$id}=[&gettimeofday()];
 1693:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1694:     my $to_kick;
 1695:     my $max_time=0;
 1696:     foreach my $other (keys(%accessed)) {
 1697: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1698: 	    $to_kick=$other;
 1699: 	    $max_time=&tv_interval($accessed{$other});
 1700: 	}
 1701:     }
 1702:     delete($remembered{$to_kick});
 1703:     delete($accessed{$to_kick});
 1704:     $kicks++;
 1705:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1706:     return;
 1707: }
 1708: 
 1709: sub purge_remembered {
 1710:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1711:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1712:     undef(%remembered);
 1713:     undef(%accessed);
 1714: }
 1715: # ------------------------------------- Read an entry from a user's environment
 1716: 
 1717: sub userenvironment {
 1718:     my ($udom,$unam,@what)=@_;
 1719:     my $items;
 1720:     foreach my $item (@what) {
 1721:         $items.=&escape($item).'&';
 1722:     }
 1723:     $items=~s/\&$//;
 1724:     my %returnhash=();
 1725:     my $uhome = &homeserver($unam,$udom);
 1726:     unless ($uhome eq 'no_host') {
 1727:         my @answer=split(/\&/, 
 1728:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 1729:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 1730:             return %returnhash;
 1731:         }
 1732:         my $i;
 1733:         for ($i=0;$i<=$#what;$i++) {
 1734: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 1735:         }
 1736:     }
 1737:     return %returnhash;
 1738: }
 1739: 
 1740: # ---------------------------------------------------------- Get a studentphoto
 1741: sub studentphoto {
 1742:     my ($udom,$unam,$ext) = @_;
 1743:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1744:     if (defined($env{'request.course.id'})) {
 1745:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1746:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1747:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1748:             } else {
 1749:                 my ($result,$perm_reqd)=
 1750: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1751:                 if ($result eq 'ok') {
 1752:                     if (!($perm_reqd eq 'yes')) {
 1753:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1754:                     }
 1755:                 }
 1756:             }
 1757:         }
 1758:     } else {
 1759:         my ($result,$perm_reqd) = 
 1760: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1761:         if ($result eq 'ok') {
 1762:             if (!($perm_reqd eq 'yes')) {
 1763:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1764:             }
 1765:         }
 1766:     }
 1767:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1768: }
 1769: 
 1770: sub retrievestudentphoto {
 1771:     my ($udom,$unam,$ext,$type) = @_;
 1772:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1773:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1774:     if ($ret eq 'ok') {
 1775:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1776:         if ($type eq 'thumbnail') {
 1777:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1778:         }
 1779:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1780:         return $tokenurl;
 1781:     } else {
 1782:         if ($type eq 'thumbnail') {
 1783:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1784:         } else { 
 1785:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1786:         }
 1787:     }
 1788: }
 1789: 
 1790: # -------------------------------------------------------------------- New chat
 1791: 
 1792: sub chatsend {
 1793:     my ($newentry,$anon,$group)=@_;
 1794:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1795:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1796:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1797:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1798: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1799: 		   &escape($newentry)).':'.$group,$chome);
 1800: }
 1801: 
 1802: # ------------------------------------------ Find current version of a resource
 1803: 
 1804: sub getversion {
 1805:     my $fname=&clutter(shift);
 1806:     unless ($fname=~/^\/res\//) { return -1; }
 1807:     return &currentversion(&filelocation('',$fname));
 1808: }
 1809: 
 1810: sub currentversion {
 1811:     my $fname=shift;
 1812:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1813:     if (defined($cached)) { return $result; }
 1814:     my $author=$fname;
 1815:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1816:     my ($udom,$uname)=split(/\//,$author);
 1817:     my $home=homeserver($uname,$udom);
 1818:     if ($home eq 'no_host') { 
 1819:         return -1; 
 1820:     }
 1821:     my $answer=reply("currentversion:$fname",$home);
 1822:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1823: 	return -1;
 1824:     }
 1825:     return &do_cache_new('resversion',$fname,$answer,600);
 1826: }
 1827: 
 1828: # ----------------------------- Subscribe to a resource, return URL if possible
 1829: 
 1830: sub subscribe {
 1831:     my $fname=shift;
 1832:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1833:     $fname=~s/[\n\r]//g;
 1834:     my $author=$fname;
 1835:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1836:     my ($udom,$uname)=split(/\//,$author);
 1837:     my $home=homeserver($uname,$udom);
 1838:     if ($home eq 'no_host') {
 1839:         return 'not_found';
 1840:     }
 1841:     my $answer=reply("sub:$fname",$home);
 1842:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1843: 	$answer.=' by '.$home;
 1844:     }
 1845:     return $answer;
 1846: }
 1847:     
 1848: # -------------------------------------------------------------- Replicate file
 1849: 
 1850: sub repcopy {
 1851:     my $filename=shift;
 1852:     $filename=~s/\/+/\//g;
 1853:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1854:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1855:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1856: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1857: 	return &repcopy_userfile($filename);
 1858:     }
 1859:     $filename=~s/[\n\r]//g;
 1860:     my $transname="$filename.in.transfer";
 1861: # FIXME: this should flock
 1862:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1863:     my $remoteurl=subscribe($filename);
 1864:     if ($remoteurl =~ /^con_lost by/) {
 1865: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1866:            return 'unavailable';
 1867:     } elsif ($remoteurl eq 'not_found') {
 1868: 	   #&logthis("Subscribe returned not_found: $filename");
 1869: 	   return 'not_found';
 1870:     } elsif ($remoteurl =~ /^rejected by/) {
 1871: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1872:            return 'forbidden';
 1873:     } elsif ($remoteurl eq 'directory') {
 1874:            return 'ok';
 1875:     } else {
 1876:         my $author=$filename;
 1877:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1878:         my ($udom,$uname)=split(/\//,$author);
 1879:         my $home=homeserver($uname,$udom);
 1880:         unless ($home eq $perlvar{'lonHostID'}) {
 1881:            my @parts=split(/\//,$filename);
 1882:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1883:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1884:                &logthis("Malconfiguration for replication: $filename");
 1885: 	       return 'bad_request';
 1886:            }
 1887:            my $count;
 1888:            for ($count=5;$count<$#parts;$count++) {
 1889:                $path.="/$parts[$count]";
 1890:                if ((-e $path)!=1) {
 1891: 		   mkdir($path,0777);
 1892:                }
 1893:            }
 1894:            my $ua=new LWP::UserAgent;
 1895:            my $request=new HTTP::Request('GET',"$remoteurl");
 1896:            my $response=$ua->request($request,$transname);
 1897:            if ($response->is_error()) {
 1898: 	       unlink($transname);
 1899:                my $message=$response->status_line;
 1900:                &logthis("<font color=\"blue\">WARNING:"
 1901:                        ." LWP get: $message: $filename</font>");
 1902:                return 'unavailable';
 1903:            } else {
 1904: 	       if ($remoteurl!~/\.meta$/) {
 1905:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1906:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1907:                   if ($mresponse->is_error()) {
 1908: 		      unlink($filename.'.meta');
 1909:                       &logthis(
 1910:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1911:                   }
 1912: 	       }
 1913:                rename($transname,$filename);
 1914:                return 'ok';
 1915:            }
 1916:        }
 1917:     }
 1918: }
 1919: 
 1920: # ------------------------------------------------ Get server side include body
 1921: sub ssi_body {
 1922:     my ($filelink,%form)=@_;
 1923:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1924:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1925:     }
 1926:     my $output='';
 1927:     my $response;
 1928:     if ($filelink=~/^https?\:/) {
 1929:        ($output,$response)=&externalssi($filelink);
 1930:     } else {
 1931:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 1932:        $filelink .= 'inhibitmenu=yes';
 1933:        ($output,$response)=&ssi($filelink,%form);
 1934:     }
 1935:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1936:     $output=~s/^.*?\<body[^\>]*\>//si;
 1937:     $output=~s/\<\/body\s*\>.*?$//si;
 1938:     if (wantarray) {
 1939:         return ($output, $response);
 1940:     } else {
 1941:         return $output;
 1942:     }
 1943: }
 1944: 
 1945: # --------------------------------------------------------- Server Side Include
 1946: 
 1947: sub absolute_url {
 1948:     my ($host_name) = @_;
 1949:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1950:     if ($host_name eq '') {
 1951: 	$host_name = $ENV{'SERVER_NAME'};
 1952:     }
 1953:     return $protocol.$host_name;
 1954: }
 1955: 
 1956: #
 1957: #   Server side include.
 1958: # Parameters:
 1959: #  fn     Possibly encrypted resource name/id.
 1960: #  form   Hash that describes how the rendering should be done
 1961: #         and other things.
 1962: # Returns:
 1963: #   Scalar context: The content of the response.
 1964: #   Array context:  2 element list of the content and the full response object.
 1965: #     
 1966: sub ssi {
 1967: 
 1968:     my ($fn,%form)=@_;
 1969:     my $ua=new LWP::UserAgent;
 1970:     my $request;
 1971: 
 1972:     $form{'no_update_last_known'}=1;
 1973:     &Apache::lonenc::check_encrypt(\$fn);
 1974:     if (%form) {
 1975:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1976:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 1977:     } else {
 1978:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1979:     }
 1980: 
 1981:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1982:     my $response=$ua->request($request);
 1983: 
 1984:     if (wantarray) {
 1985: 	return ($response->content, $response);
 1986:     } else {
 1987: 	return $response->content;
 1988:     }
 1989: }
 1990: 
 1991: sub externalssi {
 1992:     my ($url)=@_;
 1993:     my $ua=new LWP::UserAgent;
 1994:     my $request=new HTTP::Request('GET',$url);
 1995:     my $response=$ua->request($request);
 1996:     if (wantarray) {
 1997:         return ($response->content, $response);
 1998:     } else {
 1999:         return $response->content;
 2000:     }
 2001: }
 2002: 
 2003: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2004: 
 2005: sub allowuploaded {
 2006:     my ($srcurl,$url)=@_;
 2007:     $url=&clutter(&declutter($url));
 2008:     my $dir=$url;
 2009:     $dir=~s/\/[^\/]+$//;
 2010:     my %httpref=();
 2011:     my $httpurl=&hreflocation('',$url);
 2012:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2013:     &Apache::lonnet::appenv(\%httpref);
 2014: }
 2015: 
 2016: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2017: # input: action, courseID, current domain, intended
 2018: #        path to file, source of file, instruction to parse file for objects,
 2019: #        ref to hash for embedded objects,
 2020: #        ref to hash for codebase of java objects.
 2021: #
 2022: # output: url to file (if action was uploaddoc), 
 2023: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2024: #
 2025: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2026: # course.
 2027: #
 2028: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2029: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2030: #          course's home server.
 2031: #
 2032: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2033: #          be copied from $source (current location) to 
 2034: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2035: #         and will then be copied to
 2036: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2037: #         course's home server.
 2038: #
 2039: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2040: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2041: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2042: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2043: #         in course's home server.
 2044: #
 2045: 
 2046: sub process_coursefile {
 2047:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 2048:     my $fetchresult;
 2049:     my $home=&homeserver($docuname,$docudom);
 2050:     if ($action eq 'propagate') {
 2051:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2052: 			     $home);
 2053:     } else {
 2054:         my $fpath = '';
 2055:         my $fname = $file;
 2056:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2057:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2058:         my $filepath = &build_filepath($fpath);
 2059:         if ($action eq 'copy') {
 2060:             if ($source eq '') {
 2061:                 $fetchresult = 'no source file';
 2062:                 return $fetchresult;
 2063:             } else {
 2064:                 my $destination = $filepath.'/'.$fname;
 2065:                 rename($source,$destination);
 2066:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2067:                                  $home);
 2068:             }
 2069:         } elsif ($action eq 'uploaddoc') {
 2070:             open(my $fh,'>'.$filepath.'/'.$fname);
 2071:             print $fh $env{'form.'.$source};
 2072:             close($fh);
 2073:             if ($parser eq 'parse') {
 2074:                 my $mm = new File::MMagic;
 2075:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
 2076:                 if ($mime_type eq 'text/html') {
 2077:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2078:                     unless ($parse_result eq 'ok') {
 2079:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2080:                     }
 2081:                 }
 2082:             }
 2083:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2084:                                  $home);
 2085:             if ($fetchresult eq 'ok') {
 2086:                 return '/uploaded/'.$fpath.'/'.$fname;
 2087:             } else {
 2088:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2089:                         ' to host '.$home.': '.$fetchresult);
 2090:                 return '/adm/notfound.html';
 2091:             }
 2092:         }
 2093:     }
 2094:     unless ( $fetchresult eq 'ok') {
 2095:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2096:              ' to host '.$home.': '.$fetchresult);
 2097:     }
 2098:     return $fetchresult;
 2099: }
 2100: 
 2101: sub build_filepath {
 2102:     my ($fpath) = @_;
 2103:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2104:     unless ($fpath eq '') {
 2105:         my @parts=split('/',$fpath);
 2106:         foreach my $part (@parts) {
 2107:             $filepath.= '/'.$part;
 2108:             if ((-e $filepath)!=1) {
 2109:                 mkdir($filepath,0777);
 2110:             }
 2111:         }
 2112:     }
 2113:     return $filepath;
 2114: }
 2115: 
 2116: sub store_edited_file {
 2117:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2118:     my $file = $primary_url;
 2119:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2120:     my $fpath = '';
 2121:     my $fname = $file;
 2122:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2123:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2124:     my $filepath = &build_filepath($fpath);
 2125:     open(my $fh,'>'.$filepath.'/'.$fname);
 2126:     print $fh $content;
 2127:     close($fh);
 2128:     my $home=&homeserver($docuname,$docudom);
 2129:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2130: 			  $home);
 2131:     if ($$fetchresult eq 'ok') {
 2132:         return '/uploaded/'.$fpath.'/'.$fname;
 2133:     } else {
 2134:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2135: 		 ' to host '.$home.': '.$$fetchresult);
 2136:         return '/adm/notfound.html';
 2137:     }
 2138: }
 2139: 
 2140: sub clean_filename {
 2141:     my ($fname,$args)=@_;
 2142: # Replace Windows backslashes by forward slashes
 2143:     $fname=~s/\\/\//g;
 2144:     if (!$args->{'keep_path'}) {
 2145:         # Get rid of everything but the actual filename
 2146: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2147:     }
 2148: # Replace spaces by underscores
 2149:     $fname=~s/\s+/\_/g;
 2150: # Replace all other weird characters by nothing
 2151:     $fname=~s{[^/\w\.\-]}{}g;
 2152: # Replace all .\d. sequences with _\d. so they no longer look like version
 2153: # numbers
 2154:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2155:     return $fname;
 2156: }
 2157: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2158: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2159: # image with the same aspect ratio as the original, but with dimensions which do 
 2160: # not exceed $resizewidth and $resizeheight.
 2161:  
 2162: sub resizeImage {
 2163:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2164:     my $ima = Image::Magick->new;
 2165:     my $resized;
 2166:     if (-e $img_path) {
 2167:         $ima->Read($img_path);
 2168:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2169:             my $width = $ima->Get('width');
 2170:             my $height = $ima->Get('height');
 2171:             if ($width > $resizewidth) {
 2172: 	        my $factor = $width/$resizewidth;
 2173:                 my $newheight = $height/$factor;
 2174:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2175:                 $resized = 1;
 2176:             }
 2177:         }
 2178:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2179:             my $width = $ima->Get('width');
 2180:             my $height = $ima->Get('height');
 2181:             if ($height > $resizeheight) {
 2182:                 my $factor = $height/$resizeheight;
 2183:                 my $newwidth = $width/$factor;
 2184:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2185:                 $resized = 1;
 2186:             }
 2187:         }
 2188:         if ($resized) {
 2189:             $ima->Write($img_path);
 2190:         }
 2191:     }
 2192:     return;
 2193: }
 2194: 
 2195: # --------------- Take an uploaded file and put it into the userfiles directory
 2196: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2197: #                    the desired filenam is in $env{"form.$formname.filename"}
 2198: #        $coursedoc - if true up to the current course
 2199: #                     if false
 2200: #        $subdir - directory in userfile to store the file into
 2201: #        $parser - instruction to parse file for objects ($parser = parse)    
 2202: #        $allfiles - reference to hash for embedded objects
 2203: #        $codebase - reference to hash for codebase of java objects
 2204: #        $desuname - username for permanent storage of uploaded file
 2205: #        $dsetudom - domain for permanaent storage of uploaded file
 2206: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2207: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2208: #        $resizewidth - width (pixels) to which to resize uploaded image
 2209: #        $resizeheight - height (pixels) to which to resize uploaded image
 2210: # 
 2211: # output: url of file in userspace, or error: <message> 
 2212: #             or /adm/notfound.html if failure to upload occurse
 2213: 
 2214: sub userfileupload {
 2215:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2216:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
 2217:     if (!defined($subdir)) { $subdir='unknown'; }
 2218:     my $fname=$env{'form.'.$formname.'.filename'};
 2219:     $fname=&clean_filename($fname);
 2220: # See if there is anything left
 2221:     unless ($fname) { return 'error: no uploaded file'; }
 2222:     chop($env{'form.'.$formname});
 2223:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2224:         my $now = time;
 2225:         my $filepath = 'tmp/helprequests/'.$now;
 2226:         my @parts=split(/\//,$filepath);
 2227:         my $fullpath = $perlvar{'lonDaemons'};
 2228:         for (my $i=0;$i<@parts;$i++) {
 2229:             $fullpath .= '/'.$parts[$i];
 2230:             if ((-e $fullpath)!=1) {
 2231:                 mkdir($fullpath,0777);
 2232:             }
 2233:         }
 2234:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2235:         print $fh $env{'form.'.$formname};
 2236:         close($fh);
 2237:         return $fullpath.'/'.$fname;
 2238:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2239:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2240:                        '_'.$env{'user.domain'}.'/pending';
 2241:         my @parts=split(/\//,$filepath);
 2242:         my $fullpath = $perlvar{'lonDaemons'};
 2243:         for (my $i=0;$i<@parts;$i++) {
 2244:             $fullpath .= '/'.$parts[$i];
 2245:             if ((-e $fullpath)!=1) {
 2246:                 mkdir($fullpath,0777);
 2247:             }
 2248:         }
 2249:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2250:         print $fh $env{'form.'.$formname};
 2251:         close($fh);
 2252:         return $fullpath.'/'.$fname;
 2253:     }
 2254:     if ($subdir eq 'scantron') {
 2255:         $fname = 'scantron_orig_'.$fname;
 2256:     } else {   
 2257: # Create the directory if not present
 2258:         $fname="$subdir/$fname";
 2259:     }
 2260:     if ($coursedoc) {
 2261: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2262: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2263:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2264:             return &finishuserfileupload($docuname,$docudom,
 2265: 					 $formname,$fname,$parser,$allfiles,
 2266: 					 $codebase,$thumbwidth,$thumbheight,
 2267:                                          $resizewidth,$resizeheight);
 2268:         } else {
 2269:             $fname=$env{'form.folder'}.'/'.$fname;
 2270:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2271: 				       $fname,$formname,$parser,
 2272: 				       $allfiles,$codebase);
 2273:         }
 2274:     } elsif (defined($destuname)) {
 2275:         my $docuname=$destuname;
 2276:         my $docudom=$destudom;
 2277: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2278: 				     $parser,$allfiles,$codebase,
 2279:                                      $thumbwidth,$thumbheight,
 2280:                                      $resizewidth,$resizeheight);
 2281:         
 2282:     } else {
 2283:         my $docuname=$env{'user.name'};
 2284:         my $docudom=$env{'user.domain'};
 2285:         if (exists($env{'form.group'})) {
 2286:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2287:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2288:         }
 2289: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2290: 				     $parser,$allfiles,$codebase,
 2291:                                      $thumbwidth,$thumbheight,
 2292:                                      $resizewidth,$resizeheight);
 2293:     }
 2294: }
 2295: 
 2296: sub finishuserfileupload {
 2297:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2298:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
 2299:     my $path=$docudom.'/'.$docuname.'/';
 2300:     my $filepath=$perlvar{'lonDocRoot'};
 2301:   
 2302:     my ($fnamepath,$file,$fetchthumb);
 2303:     $file=$fname;
 2304:     if ($fname=~m|/|) {
 2305:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2306: 	$path.=$fnamepath.'/';
 2307:     }
 2308:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2309:     my $count;
 2310:     for ($count=4;$count<=$#parts;$count++) {
 2311:         $filepath.="/$parts[$count]";
 2312:         if ((-e $filepath)!=1) {
 2313: 	    mkdir($filepath,0777);
 2314:         }
 2315:     }
 2316: 
 2317: # Save the file
 2318:     {
 2319: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2320: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2321: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2322: 	    return '/adm/notfound.html';
 2323: 	}
 2324: 	if (!print FH ($env{'form.'.$formname})) {
 2325: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2326: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2327: 	    return '/adm/notfound.html';
 2328: 	}
 2329: 	close(FH);
 2330:         if ($resizewidth && $resizeheight) {
 2331:             my $mm = new File::MMagic;
 2332:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2333:             if ($mime_type =~ m{^image/}) {
 2334: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2335:             }  
 2336: 	}
 2337:     }
 2338:     if ($parser eq 'parse') {
 2339:         my $mm = new File::MMagic;
 2340:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2341:         if ($mime_type eq 'text/html') {
 2342:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2343:                                                        $allfiles,$codebase);
 2344:             unless ($parse_result eq 'ok') {
 2345:                 &logthis('Failed to parse '.$filepath.$file.
 2346: 	   	         ' for embedded media: '.$parse_result); 
 2347:             }
 2348:         }
 2349:     }
 2350:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2351:         my $input = $filepath.'/'.$file;
 2352:         my $output = $filepath.'/'.'tn-'.$file;
 2353:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2354:         system("convert -sample $thumbsize $input $output");
 2355:         if (-e $filepath.'/'.'tn-'.$file) {
 2356:             $fetchthumb  = 1; 
 2357:         }
 2358:     }
 2359:  
 2360: # Notify homeserver to grep it
 2361: #
 2362:     my $docuhome=&homeserver($docuname,$docudom);	
 2363:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2364:     if ($fetchresult eq 'ok') {
 2365:         if ($fetchthumb) {
 2366:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2367:             if ($thumbresult ne 'ok') {
 2368:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2369:                          $docuhome.': '.$thumbresult);
 2370:             }
 2371:         }
 2372: #
 2373: # Return the URL to it
 2374:         return '/uploaded/'.$path.$file;
 2375:     } else {
 2376:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2377: 		 ': '.$fetchresult);
 2378:         return '/adm/notfound.html';
 2379:     }
 2380: }
 2381: 
 2382: sub extract_embedded_items {
 2383:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2384:     my @state = ();
 2385:     my %javafiles = (
 2386:                       codebase => '',
 2387:                       code => '',
 2388:                       archive => ''
 2389:                     );
 2390:     my %mediafiles = (
 2391:                       src => '',
 2392:                       movie => '',
 2393:                      );
 2394:     my $p;
 2395:     if ($content) {
 2396:         $p = HTML::LCParser->new($content);
 2397:     } else {
 2398:         $p = HTML::LCParser->new($fullpath);
 2399:     }
 2400:     while (my $t=$p->get_token()) {
 2401: 	if ($t->[0] eq 'S') {
 2402: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2403: 	    push(@state, $tagname);
 2404:             if (lc($tagname) eq 'allow') {
 2405:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2406:             }
 2407: 	    if (lc($tagname) eq 'img') {
 2408: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2409: 	    }
 2410: 	    if (lc($tagname) eq 'a') {
 2411: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2412: 	    }
 2413:             if (lc($tagname) eq 'script') {
 2414:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2415:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2416:                 } else {
 2417:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2418:                 }
 2419:             }
 2420:             if (lc($tagname) eq 'link') {
 2421:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2422:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2423:                 }
 2424:             }
 2425: 	    if (lc($tagname) eq 'object' ||
 2426: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2427: 		foreach my $item (keys(%javafiles)) {
 2428: 		    $javafiles{$item} = '';
 2429: 		}
 2430: 	    }
 2431: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2432: 		my $name = lc($attr->{'name'});
 2433: 		foreach my $item (keys(%javafiles)) {
 2434: 		    if ($name eq $item) {
 2435: 			$javafiles{$item} = $attr->{'value'};
 2436: 			last;
 2437: 		    }
 2438: 		}
 2439: 		foreach my $item (keys(%mediafiles)) {
 2440: 		    if ($name eq $item) {
 2441: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2442: 			last;
 2443: 		    }
 2444: 		}
 2445: 	    }
 2446: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2447: 		foreach my $item (keys(%javafiles)) {
 2448: 		    if ($attr->{$item}) {
 2449: 			$javafiles{$item} = $attr->{$item};
 2450: 			last;
 2451: 		    }
 2452: 		}
 2453: 		foreach my $item (keys(%mediafiles)) {
 2454: 		    if ($attr->{$item}) {
 2455: 			&add_filetype($allfiles,$attr->{$item},$item);
 2456: 			last;
 2457: 		    }
 2458: 		}
 2459: 	    }
 2460: 	} elsif ($t->[0] eq 'E') {
 2461: 	    my ($tagname) = ($t->[1]);
 2462: 	    if ($javafiles{'codebase'} ne '') {
 2463: 		$javafiles{'codebase'} .= '/';
 2464: 	    }  
 2465: 	    if (lc($tagname) eq 'applet' ||
 2466: 		lc($tagname) eq 'object' ||
 2467: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2468: 		) {
 2469: 		foreach my $item (keys(%javafiles)) {
 2470: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2471: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2472: 			&add_filetype($allfiles,$file,$item);
 2473: 		    }
 2474: 		}
 2475: 	    } 
 2476: 	    pop @state;
 2477: 	}
 2478:     }
 2479:     return 'ok';
 2480: }
 2481: 
 2482: sub add_filetype {
 2483:     my ($allfiles,$file,$type)=@_;
 2484:     if (exists($allfiles->{$file})) {
 2485: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2486: 	    push(@{$allfiles->{$file}}, &escape($type));
 2487: 	}
 2488:     } else {
 2489: 	@{$allfiles->{$file}} = (&escape($type));
 2490:     }
 2491: }
 2492: 
 2493: sub removeuploadedurl {
 2494:     my ($url)=@_;	
 2495:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2496:     return &removeuserfile($uname,$udom,$fname);
 2497: }
 2498: 
 2499: sub removeuserfile {
 2500:     my ($docuname,$docudom,$fname)=@_;
 2501:     my $home=&homeserver($docuname,$docudom);    
 2502:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2503:     if ($result eq 'ok') {	
 2504:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2505:             my $metafile = $fname.'.meta';
 2506:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2507: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2508:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2509:             my $sqlresult = 
 2510:                 &update_portfolio_table($docuname,$docudom,$file,
 2511:                                         'portfolio_metadata',$group,
 2512:                                         'delete');
 2513:         }
 2514:     }
 2515:     return $result;
 2516: }
 2517: 
 2518: sub mkdiruserfile {
 2519:     my ($docuname,$docudom,$dir)=@_;
 2520:     my $home=&homeserver($docuname,$docudom);
 2521:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2522: }
 2523: 
 2524: sub renameuserfile {
 2525:     my ($docuname,$docudom,$old,$new)=@_;
 2526:     my $home=&homeserver($docuname,$docudom);
 2527:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2528:                         &escape("$old").':'.&escape("$new"),$home);
 2529:     if ($result eq 'ok') {
 2530:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2531:             my $oldmeta = $old.'.meta';
 2532:             my $newmeta = $new.'.meta';
 2533:             my $metaresult = 
 2534:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2535: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2536:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2537:             my $sqlresult = 
 2538:                 &update_portfolio_table($docuname,$docudom,$file,
 2539:                                         'portfolio_metadata',$group,
 2540:                                         'delete');
 2541:         }
 2542:     }
 2543:     return $result;
 2544: }
 2545: 
 2546: # ------------------------------------------------------------------------- Log
 2547: 
 2548: sub log {
 2549:     my ($dom,$nam,$hom,$what)=@_;
 2550:     return critical("log:$dom:$nam:$what",$hom);
 2551: }
 2552: 
 2553: # ------------------------------------------------------------------ Course Log
 2554: #
 2555: # This routine flushes several buffers of non-mission-critical nature
 2556: #
 2557: 
 2558: sub flushcourselogs {
 2559:     &logthis('Flushing log buffers');
 2560: #
 2561: # course logs
 2562: # This is a log of all transactions in a course, which can be used
 2563: # for data mining purposes
 2564: #
 2565: # It also collects the courseid database, which lists last transaction
 2566: # times and course titles for all courseids
 2567: #
 2568:     my %courseidbuffer=();
 2569:     foreach my $crsid (keys(%courselogs)) {
 2570:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2571: 		          &escape($courselogs{$crsid}),
 2572: 		          $coursehombuf{$crsid}) eq 'ok') {
 2573: 	    delete $courselogs{$crsid};
 2574:         } else {
 2575:             &logthis('Failed to flush log buffer for '.$crsid);
 2576:             if (length($courselogs{$crsid})>40000) {
 2577:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2578:                         " exceeded maximum size, deleting.</font>");
 2579:                delete $courselogs{$crsid};
 2580:             }
 2581:         }
 2582:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2583:             'description' => $coursedescrbuf{$crsid},
 2584:             'inst_code'    => $courseinstcodebuf{$crsid},
 2585:             'type'        => $coursetypebuf{$crsid},
 2586:             'owner'       => $courseownerbuf{$crsid},
 2587:         };
 2588:     }
 2589: #
 2590: # Write course id database (reverse lookup) to homeserver of courses 
 2591: # Is used in pickcourse
 2592: #
 2593:     foreach my $crs_home (keys(%courseidbuffer)) {
 2594:         my $response = &courseidput(&host_domain($crs_home),
 2595:                                     $courseidbuffer{$crs_home},
 2596:                                     $crs_home,'timeonly');
 2597:     }
 2598: #
 2599: # File accesses
 2600: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2601: #
 2602:     foreach my $entry (keys(%accesshash)) {
 2603:         if ($entry =~ /___count$/) {
 2604:             my ($dom,$name);
 2605:             ($dom,$name,undef)=
 2606: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2607:             if (! defined($dom) || $dom eq '' || 
 2608:                 ! defined($name) || $name eq '') {
 2609:                 my $cid = $env{'request.course.id'};
 2610:                 $dom  = $env{'request.'.$cid.'.domain'};
 2611:                 $name = $env{'request.'.$cid.'.num'};
 2612:             }
 2613:             my $value = $accesshash{$entry};
 2614:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2615:             my %temphash=($url => $value);
 2616:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2617:             if ($result eq 'ok') {
 2618:                 delete $accesshash{$entry};
 2619:             } elsif ($result eq 'unknown_cmd') {
 2620:                 # Target server has old code running on it.
 2621:                 my %temphash=($entry => $value);
 2622:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2623:                     delete $accesshash{$entry};
 2624:                 }
 2625:             }
 2626:         } else {
 2627:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2628:             my %temphash=($entry => $accesshash{$entry});
 2629:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2630:                 delete $accesshash{$entry};
 2631:             }
 2632:         }
 2633:     }
 2634: #
 2635: # Roles
 2636: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2637: #
 2638:     foreach my $entry (keys(%userrolehash)) {
 2639:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2640: 	    split(/\:/,$entry);
 2641:         if (&Apache::lonnet::put('nohist_userroles',
 2642:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2643:                 $rudom,$runame) eq 'ok') {
 2644: 	    delete $userrolehash{$entry};
 2645:         }
 2646:     }
 2647: #
 2648: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2649: #
 2650:     my %domrolebuffer = ();
 2651:     foreach my $entry (keys(%domainrolehash)) {
 2652:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2653:         if ($domrolebuffer{$rudom}) {
 2654:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2655:                       '='.&escape($domainrolehash{$entry});
 2656:         } else {
 2657:             $domrolebuffer{$rudom}.=&escape($entry).
 2658:                       '='.&escape($domainrolehash{$entry});
 2659:         }
 2660:         delete $domainrolehash{$entry};
 2661:     }
 2662:     foreach my $dom (keys(%domrolebuffer)) {
 2663: 	my %servers = &get_servers($dom,'library');
 2664: 	foreach my $tryserver (keys(%servers)) {
 2665: 	    unless (&reply('domroleput:'.$dom.':'.
 2666: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2667: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2668: 	    }
 2669:         }
 2670:     }
 2671:     $dumpcount++;
 2672: }
 2673: 
 2674: sub courselog {
 2675:     my $what=shift;
 2676:     $what=time.':'.$what;
 2677:     unless ($env{'request.course.id'}) { return ''; }
 2678:     $coursedombuf{$env{'request.course.id'}}=
 2679:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2680:     $coursenumbuf{$env{'request.course.id'}}=
 2681:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2682:     $coursehombuf{$env{'request.course.id'}}=
 2683:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2684:     $coursedescrbuf{$env{'request.course.id'}}=
 2685:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2686:     $courseinstcodebuf{$env{'request.course.id'}}=
 2687:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2688:     $courseownerbuf{$env{'request.course.id'}}=
 2689:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2690:     $coursetypebuf{$env{'request.course.id'}}=
 2691:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2692:     if (defined $courselogs{$env{'request.course.id'}}) {
 2693: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2694:     } else {
 2695: 	$courselogs{$env{'request.course.id'}}.=$what;
 2696:     }
 2697:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2698: 	&flushcourselogs();
 2699:     }
 2700: }
 2701: 
 2702: sub courseacclog {
 2703:     my $fnsymb=shift;
 2704:     unless ($env{'request.course.id'}) { return ''; }
 2705:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2706:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2707:         $what.=':POST';
 2708:         # FIXME: Probably ought to escape things....
 2709: 	foreach my $key (keys(%env)) {
 2710:             if ($key=~/^form\.(.*)/) {
 2711:                 my $formitem = $1;
 2712:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2713:                     $what.=':'.$formitem.'='.$env{$key};
 2714:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2715:                     $what.=':'.$formitem.'='.$env{$key};
 2716:                 }
 2717:             }
 2718:         }
 2719:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2720:         # FIXME: We should not be depending on a form parameter that someone
 2721:         # editing lonsearchcat.pm might change in the future.
 2722:         if ($env{'form.phase'} eq 'course_search') {
 2723:             $what.= ':POST';
 2724:             # FIXME: Probably ought to escape things....
 2725:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2726:                                  'crsdiscuss') {
 2727:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2728:             }
 2729:         }
 2730:     }
 2731:     &courselog($what);
 2732: }
 2733: 
 2734: sub countacc {
 2735:     my $url=&declutter(shift);
 2736:     return if (! defined($url) || $url eq '');
 2737:     unless ($env{'request.course.id'}) { return ''; }
 2738:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2739:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2740:     $accesshash{$key}++;
 2741: }
 2742: 
 2743: sub linklog {
 2744:     my ($from,$to)=@_;
 2745:     $from=&declutter($from);
 2746:     $to=&declutter($to);
 2747:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2748:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2749: }
 2750:   
 2751: sub userrolelog {
 2752:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2753:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2754:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2755:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2756:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 2757:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2758:        $userrolehash
 2759:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2760:                     =$tend.':'.$tstart;
 2761:     }
 2762:     if (($env{'request.role'} =~ /dc\./) &&
 2763: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2764: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2765: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 2766:          ($trole=~/^co/))) {
 2767:        $userrolehash
 2768:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2769:                     =$tend.':'.$tstart;
 2770:     }
 2771:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2772:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2773:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2774:         ($trole=~/^sc/)) {
 2775:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2776:        $domainrolehash
 2777:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2778:                     = $tend.':'.$tstart;
 2779:     }
 2780: }
 2781: 
 2782: sub courserolelog {
 2783:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2784:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2785:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2786:         ($trole eq 'ta') || ($trole eq 'st') ||
 2787:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 2788:         ($trole eq 'co')) {
 2789:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2790:             my $cdom = $1;
 2791:             my $cnum = $2;
 2792:             my $sec = $3;
 2793:             my $namespace = 'rolelog';
 2794:             my %storehash = (
 2795:                                role    => $trole,
 2796:                                start   => $tstart,
 2797:                                end     => $tend,
 2798:                                selfenroll => $selfenroll,
 2799:                                context    => $context,
 2800:                             );
 2801:             if ($trole eq 'gr') {
 2802:                 $namespace = 'groupslog';
 2803:                 $storehash{'group'} = $sec;
 2804:             } else {
 2805:                 $storehash{'section'} = $sec;
 2806:             }
 2807:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2808:             if (($trole ne 'st') || ($sec ne '')) {
 2809:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2810:             }
 2811:         }
 2812:     }
 2813:     return;
 2814: }
 2815: 
 2816: sub get_course_adv_roles {
 2817:     my ($cid,$codes) = @_;
 2818:     $cid=$env{'request.course.id'} unless (defined($cid));
 2819:     my %coursehash=&coursedescription($cid);
 2820:     my $crstype = &Apache::loncommon::course_type($cid);
 2821:     my %nothide=();
 2822:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2823:         if ($user !~ /:/) {
 2824: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2825:         } else {
 2826:             $nothide{$user}=1;
 2827:         }
 2828:     }
 2829:     my %returnhash=();
 2830:     my %dumphash=
 2831:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2832:     my $now=time;
 2833:     my %privileged;
 2834:     foreach my $entry (keys(%dumphash)) {
 2835: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2836:         if (($tstart) && ($tstart<0)) { next; }
 2837:         if (($tend) && ($tend<$now)) { next; }
 2838:         if (($tstart) && ($now<$tstart)) { next; }
 2839:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2840: 	if ($username eq '' || $domain eq '') { next; }
 2841:         unless (ref($privileged{$domain}) eq 'HASH') {
 2842:             my %dompersonnel =
 2843:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2844:             $privileged{$domain} = {};
 2845:             foreach my $server (keys(%dompersonnel)) {
 2846:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2847:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2848:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2849:                         $privileged{$udom}{$uname} = 1;
 2850:                     }
 2851:                 }
 2852:             }
 2853:         }
 2854:         if ((exists($privileged{$domain}{$username})) && 
 2855:             (!$nothide{$username.':'.$domain})) { next; }
 2856: 	if ($role eq 'cr') { next; }
 2857:         if ($codes) {
 2858:             if ($section) { $role .= ':'.$section; }
 2859:             if ($returnhash{$role}) {
 2860:                 $returnhash{$role}.=','.$username.':'.$domain;
 2861:             } else {
 2862:                 $returnhash{$role}=$username.':'.$domain;
 2863:             }
 2864:         } else {
 2865:             my $key=&plaintext($role,$crstype);
 2866:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2867:             if ($returnhash{$key}) {
 2868: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2869:             } else {
 2870:                 $returnhash{$key}=$username.':'.$domain;
 2871:             }
 2872:         }
 2873:     }
 2874:     return %returnhash;
 2875: }
 2876: 
 2877: sub get_my_roles {
 2878:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2879:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2880:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2881:     my (%dumphash,%nothide);
 2882:     if ($context eq 'userroles') { 
 2883:         %dumphash = &dump('roles',$udom,$uname);
 2884:     } else {
 2885:         %dumphash=
 2886:             &dump('nohist_userroles',$udom,$uname);
 2887:         if ($hidepriv) {
 2888:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2889:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2890:                 if ($user !~ /:/) {
 2891:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2892:                 } else {
 2893:                     $nothide{$user} = 1;
 2894:                 }
 2895:             }
 2896:         }
 2897:     }
 2898:     my %returnhash=();
 2899:     my $now=time;
 2900:     my %privileged;
 2901:     foreach my $entry (keys(%dumphash)) {
 2902:         my ($role,$tend,$tstart);
 2903:         if ($context eq 'userroles') {
 2904: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2905:         } else {
 2906:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2907:         }
 2908:         if (($tstart) && ($tstart<0)) { next; }
 2909:         my $status = 'active';
 2910:         if (($tend) && ($tend<=$now)) {
 2911:             $status = 'previous';
 2912:         } 
 2913:         if (($tstart) && ($now<$tstart)) {
 2914:             $status = 'future';
 2915:         }
 2916:         if (ref($types) eq 'ARRAY') {
 2917:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2918:                 next;
 2919:             } 
 2920:         } else {
 2921:             if ($status ne 'active') {
 2922:                 next;
 2923:             }
 2924:         }
 2925:         my ($rolecode,$username,$domain,$section,$area);
 2926:         if ($context eq 'userroles') {
 2927:             ($area,$rolecode) = split(/_/,$entry);
 2928:             (undef,$domain,$username,$section) = split(/\//,$area);
 2929:         } else {
 2930:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2931:         }
 2932:         if (ref($roledoms) eq 'ARRAY') {
 2933:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2934:                 next;
 2935:             }
 2936:         }
 2937:         if (ref($roles) eq 'ARRAY') {
 2938:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2939:                 if ($role =~ /^cr\//) {
 2940:                     if (!grep(/^cr$/,@{$roles})) {
 2941:                         next;
 2942:                     }
 2943:                 } else {
 2944:                     next;
 2945:                 }
 2946:             }
 2947:         }
 2948:         if ($hidepriv) {
 2949:             if ($context eq 'userroles') {
 2950:                 if ((&privileged($username,$domain)) &&
 2951:                     (!$nothide{$username.':'.$domain})) {
 2952:                     next;
 2953:                 }
 2954:             } else {
 2955:                 unless (ref($privileged{$domain}) eq 'HASH') {
 2956:                     my %dompersonnel =
 2957:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2958:                     $privileged{$domain} = {};
 2959:                     if (keys(%dompersonnel)) {
 2960:                         foreach my $server (keys(%dompersonnel)) {
 2961:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 2962:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 2963:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 2964:                                     $privileged{$udom}{$uname} = $trole;
 2965:                                 }
 2966:                             }
 2967:                         }
 2968:                     }
 2969:                 }
 2970:                 if (exists($privileged{$domain}{$username})) {
 2971:                     if (!$nothide{$username.':'.$domain}) {
 2972:                         next;
 2973:                     }
 2974:                 }
 2975:             }
 2976:         }
 2977:         if ($withsec) {
 2978:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2979:                 $tstart.':'.$tend;
 2980:         } else {
 2981:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2982:         }
 2983:     }
 2984:     return %returnhash;
 2985: }
 2986: 
 2987: # ----------------------------------------------------- Frontpage Announcements
 2988: #
 2989: #
 2990: 
 2991: sub postannounce {
 2992:     my ($server,$text)=@_;
 2993:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2994:     unless ($text=~/\w/) { $text=''; }
 2995:     return &reply('setannounce:'.&escape($text),$server);
 2996: }
 2997: 
 2998: sub getannounce {
 2999: 
 3000:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3001: 	my $announcement='';
 3002: 	while (my $line = <$fh>) { $announcement .= $line; }
 3003: 	close($fh);
 3004: 	if ($announcement=~/\w/) { 
 3005: 	    return 
 3006:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3007:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3008: 	} else {
 3009: 	    return '';
 3010: 	}
 3011:     } else {
 3012: 	return '';
 3013:     }
 3014: }
 3015: 
 3016: # ---------------------------------------------------------- Course ID routines
 3017: # Deal with domain's nohist_courseid.db files
 3018: #
 3019: 
 3020: sub courseidput {
 3021:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3022:     return unless (ref($storehash) eq 'HASH');
 3023:     my $outcome;
 3024:     if ($caller eq 'timeonly') {
 3025:         my $cids = '';
 3026:         foreach my $item (keys(%$storehash)) {
 3027:             $cids.=&escape($item).'&';
 3028:         }
 3029:         $cids=~s/\&$//;
 3030:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3031:                           $coursehome);       
 3032:     } else {
 3033:         my $items = '';
 3034:         foreach my $item (keys(%$storehash)) {
 3035:             $items.= &escape($item).'='.
 3036:                      &freeze_escape($$storehash{$item}).'&';
 3037:         }
 3038:         $items=~s/\&$//;
 3039:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3040:                           $coursehome);
 3041:     }
 3042:     if ($outcome eq 'unknown_cmd') {
 3043:         my $what;
 3044:         foreach my $cid (keys(%$storehash)) {
 3045:             $what .= &escape($cid).'=';
 3046:             foreach my $item ('description','inst_code','owner','type') {
 3047:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3048:             }
 3049:             $what =~ s/\:$/&/;
 3050:         }
 3051:         $what =~ s/\&$//;  
 3052:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3053:     } else {
 3054:         return $outcome;
 3055:     }
 3056: }
 3057: 
 3058: sub courseiddump {
 3059:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3060:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3061:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3062:         $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
 3063:     my $as_hash = 1;
 3064:     my %returnhash;
 3065:     if (!$domfilter) { $domfilter=''; }
 3066:     my %libserv = &all_library();
 3067:     foreach my $tryserver (keys(%libserv)) {
 3068:         if ( (  $hostidflag == 1 
 3069: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3070: 	     || (!defined($hostidflag)) ) {
 3071: 
 3072: 	    if (($domfilter eq '') ||
 3073: 		(&host_domain($tryserver) eq $domfilter)) {
 3074:                 my $rep = 
 3075:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3076:                          $sincefilter.':'.&escape($descfilter).':'.
 3077:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3078:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3079:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3080:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3081:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3082:                          &escape($cc_clone).':'.$cloneonly.':'.
 3083:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3084:                          &escape($creationcontext),$tryserver);
 3085:                 my @pairs=split(/\&/,$rep);
 3086:                 foreach my $item (@pairs) {
 3087:                     my ($key,$value)=split(/\=/,$item,2);
 3088:                     $key = &unescape($key);
 3089:                     next if ($key =~ /^error: 2 /);
 3090:                     my $result = &thaw_unescape($value);
 3091:                     if (ref($result) eq 'HASH') {
 3092:                         $returnhash{$key}=$result;
 3093:                     } else {
 3094:                         my @responses = split(/:/,$value);
 3095:                         my @items = ('description','inst_code','owner','type');
 3096:                         for (my $i=0; $i<@responses; $i++) {
 3097:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3098:                         }
 3099:                     }
 3100:                 }
 3101:             }
 3102:         }
 3103:     }
 3104:     return %returnhash;
 3105: }
 3106: 
 3107: sub courselastaccess {
 3108:     my ($cdom,$cnum,$hostidref) = @_;
 3109:     my %returnhash;
 3110:     if ($cdom && $cnum) {
 3111:         my $chome = &homeserver($cnum,$cdom);
 3112:         if ($chome ne 'no_host') {
 3113:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3114:             &extract_lastaccess(\%returnhash,$rep);
 3115:         }
 3116:     } else {
 3117:         if (!$cdom) { $cdom=''; }
 3118:         my %libserv = &all_library();
 3119:         foreach my $tryserver (keys(%libserv)) {
 3120:             if (ref($hostidref) eq 'ARRAY') {
 3121:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3122:             } 
 3123:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3124:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3125:                 &extract_lastaccess(\%returnhash,$rep);
 3126:             }
 3127:         }
 3128:     }
 3129:     return %returnhash;
 3130: }
 3131: 
 3132: sub extract_lastaccess {
 3133:     my ($returnhash,$rep) = @_;
 3134:     if (ref($returnhash) eq 'HASH') {
 3135:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3136:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3137:                  $rep eq '') {
 3138:             my @pairs=split(/\&/,$rep);
 3139:             foreach my $item (@pairs) {
 3140:                 my ($key,$value)=split(/\=/,$item,2);
 3141:                 $key = &unescape($key);
 3142:                 next if ($key =~ /^error: 2 /);
 3143:                 $returnhash->{$key} = &thaw_unescape($value);
 3144:             }
 3145:         }
 3146:     }
 3147:     return;
 3148: }
 3149: 
 3150: # ---------------------------------------------------------- DC e-mail
 3151: 
 3152: sub dcmailput {
 3153:     my ($domain,$msgid,$message,$server)=@_;
 3154:     my $status = &Apache::lonnet::critical(
 3155:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3156:        &escape($message),$server);
 3157:     return $status;
 3158: }
 3159: 
 3160: sub dcmaildump {
 3161:     my ($dom,$startdate,$enddate,$senders) = @_;
 3162:     my %returnhash=();
 3163: 
 3164:     if (defined(&domain($dom,'primary'))) {
 3165:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3166:                                                          &escape($enddate).':';
 3167: 	my @esc_senders=map { &escape($_)} @$senders;
 3168: 	$cmd.=&escape(join('&',@esc_senders));
 3169: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3170:             my ($key,$value) = split(/\=/,$line,2);
 3171:             if (($key) && ($value)) {
 3172:                 $returnhash{&unescape($key)} = &unescape($value);
 3173:             }
 3174:         }
 3175:     }
 3176:     return %returnhash;
 3177: }
 3178: # ---------------------------------------------------------- Domain roles
 3179: 
 3180: sub get_domain_roles {
 3181:     my ($dom,$roles,$startdate,$enddate)=@_;
 3182:     if ((!defined($startdate)) || ($startdate eq '')) {
 3183:         $startdate = '.';
 3184:     }
 3185:     if ((!defined($enddate)) || ($enddate eq '')) {
 3186:         $enddate = '.';
 3187:     }
 3188:     my $rolelist;
 3189:     if (ref($roles) eq 'ARRAY') {
 3190:         $rolelist = join(':',@{$roles});
 3191:     }
 3192:     my %personnel = ();
 3193: 
 3194:     my %servers = &get_servers($dom,'library');
 3195:     foreach my $tryserver (keys(%servers)) {
 3196: 	%{$personnel{$tryserver}}=();
 3197: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3198: 					    &escape($startdate).':'.
 3199: 					    &escape($enddate).':'.
 3200: 					    &escape($rolelist), $tryserver))) {
 3201: 	    my ($key,$value) = split(/\=/,$line,2);
 3202: 	    if (($key) && ($value)) {
 3203: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3204: 	    }
 3205: 	}
 3206:     }
 3207:     return %personnel;
 3208: }
 3209: 
 3210: # ----------------------------------------------------------- Interval timing 
 3211: 
 3212: sub get_first_access {
 3213:     my ($type,$argsymb)=@_;
 3214:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3215:     if ($argsymb) { $symb=$argsymb; }
 3216:     my ($map,$id,$res)=&decode_symb($symb);
 3217:     if ($type eq 'course') {
 3218: 	$res='course';
 3219:     } elsif ($type eq 'map') {
 3220: 	$res=&symbread($map);
 3221:     } else {
 3222: 	$res=$symb;
 3223:     }
 3224:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3225:     return $times{"$courseid\0$res"};
 3226: }
 3227: 
 3228: sub set_first_access {
 3229:     my ($type)=@_;
 3230:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3231:     my ($map,$id,$res)=&decode_symb($symb);
 3232:     if ($type eq 'course') {
 3233: 	$res='course';
 3234:     } elsif ($type eq 'map') {
 3235: 	$res=&symbread($map);
 3236:     } else {
 3237: 	$res=$symb;
 3238:     }
 3239:     my $firstaccess=&get_first_access($type,$symb);
 3240:     if (!$firstaccess) {
 3241: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3242:     }
 3243:     return 'already_set';
 3244: }
 3245: 
 3246: # --------------------------------------------- Set Expire Date for Spreadsheet
 3247: 
 3248: sub expirespread {
 3249:     my ($uname,$udom,$stype,$usymb)=@_;
 3250:     my $cid=$env{'request.course.id'}; 
 3251:     if ($cid) {
 3252:        my $now=time;
 3253:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3254:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3255:                             $env{'course.'.$cid.'.num'}.
 3256: 	        	    ':nohist_expirationdates:'.
 3257:                             &escape($key).'='.$now,
 3258:                             $env{'course.'.$cid.'.home'})
 3259:     }
 3260:     return 'ok';
 3261: }
 3262: 
 3263: # ----------------------------------------------------- Devalidate Spreadsheets
 3264: 
 3265: sub devalidate {
 3266:     my ($symb,$uname,$udom)=@_;
 3267:     my $cid=$env{'request.course.id'}; 
 3268:     if ($cid) {
 3269:         # delete the stored spreadsheets for
 3270:         # - the student level sheet of this user in course's homespace
 3271:         # - the assessment level sheet for this resource 
 3272:         #   for this user in user's homespace
 3273: 	# - current conditional state info
 3274: 	my $key=$uname.':'.$udom.':';
 3275:         my $status=
 3276: 	    &del('nohist_calculatedsheets',
 3277: 		 [$key.'studentcalc:'],
 3278: 		 $env{'course.'.$cid.'.domain'},
 3279: 		 $env{'course.'.$cid.'.num'})
 3280: 		.' '.
 3281: 	    &del('nohist_calculatedsheets_'.$cid,
 3282: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3283:         unless ($status eq 'ok ok') {
 3284:            &logthis('Could not devalidate spreadsheet '.
 3285:                     $uname.' at '.$udom.' for '.
 3286: 		    $symb.': '.$status);
 3287:         }
 3288: 	&delenv('user.state.'.$cid);
 3289:     }
 3290: }
 3291: 
 3292: sub get_scalar {
 3293:     my ($string,$end) = @_;
 3294:     my $value;
 3295:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3296: 	$value = $1;
 3297:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3298: 	$value = $1;
 3299:     }
 3300:     return &unescape($value);
 3301: }
 3302: 
 3303: sub array2str {
 3304:   my (@array) = @_;
 3305:   my $result=&arrayref2str(\@array);
 3306:   $result=~s/^__ARRAY_REF__//;
 3307:   $result=~s/__END_ARRAY_REF__$//;
 3308:   return $result;
 3309: }
 3310: 
 3311: sub arrayref2str {
 3312:   my ($arrayref) = @_;
 3313:   my $result='__ARRAY_REF__';
 3314:   foreach my $elem (@$arrayref) {
 3315:     if(ref($elem) eq 'ARRAY') {
 3316:       $result.=&arrayref2str($elem).'&';
 3317:     } elsif(ref($elem) eq 'HASH') {
 3318:       $result.=&hashref2str($elem).'&';
 3319:     } elsif(ref($elem)) {
 3320:       #print("Got a ref of ".(ref($elem))." skipping.");
 3321:     } else {
 3322:       $result.=&escape($elem).'&';
 3323:     }
 3324:   }
 3325:   $result=~s/\&$//;
 3326:   $result .= '__END_ARRAY_REF__';
 3327:   return $result;
 3328: }
 3329: 
 3330: sub hash2str {
 3331:   my (%hash) = @_;
 3332:   my $result=&hashref2str(\%hash);
 3333:   $result=~s/^__HASH_REF__//;
 3334:   $result=~s/__END_HASH_REF__$//;
 3335:   return $result;
 3336: }
 3337: 
 3338: sub hashref2str {
 3339:   my ($hashref)=@_;
 3340:   my $result='__HASH_REF__';
 3341:   foreach my $key (sort(keys(%$hashref))) {
 3342:     if (ref($key) eq 'ARRAY') {
 3343:       $result.=&arrayref2str($key).'=';
 3344:     } elsif (ref($key) eq 'HASH') {
 3345:       $result.=&hashref2str($key).'=';
 3346:     } elsif (ref($key)) {
 3347:       $result.='=';
 3348:       #print("Got a ref of ".(ref($key))." skipping.");
 3349:     } else {
 3350: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3351:     }
 3352: 
 3353:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3354:       $result.=&arrayref2str($hashref->{$key}).'&';
 3355:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3356:       $result.=&hashref2str($hashref->{$key}).'&';
 3357:     } elsif(ref($hashref->{$key})) {
 3358:        $result.='&';
 3359:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3360:     } else {
 3361:       $result.=&escape($hashref->{$key}).'&';
 3362:     }
 3363:   }
 3364:   $result=~s/\&$//;
 3365:   $result .= '__END_HASH_REF__';
 3366:   return $result;
 3367: }
 3368: 
 3369: sub str2hash {
 3370:     my ($string)=@_;
 3371:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3372:     return %$hash;
 3373: }
 3374: 
 3375: sub str2hashref {
 3376:   my ($string) = @_;
 3377: 
 3378:   my %hash;
 3379: 
 3380:   if($string !~ /^__HASH_REF__/) {
 3381:       if (! ($string eq '' || !defined($string))) {
 3382: 	  $hash{'error'}='Not hash reference';
 3383:       }
 3384:       return (\%hash, $string);
 3385:   }
 3386: 
 3387:   $string =~ s/^__HASH_REF__//;
 3388: 
 3389:   while($string !~ /^__END_HASH_REF__/) {
 3390:       #key
 3391:       my $key='';
 3392:       if($string =~ /^__HASH_REF__/) {
 3393:           ($key, $string)=&str2hashref($string);
 3394:           if(defined($key->{'error'})) {
 3395:               $hash{'error'}='Bad data';
 3396:               return (\%hash, $string);
 3397:           }
 3398:       } elsif($string =~ /^__ARRAY_REF__/) {
 3399:           ($key, $string)=&str2arrayref($string);
 3400:           if($key->[0] eq 'Array reference error') {
 3401:               $hash{'error'}='Bad data';
 3402:               return (\%hash, $string);
 3403:           }
 3404:       } else {
 3405:           $string =~ s/^(.*?)=//;
 3406: 	  $key=&unescape($1);
 3407:       }
 3408:       $string =~ s/^=//;
 3409: 
 3410:       #value
 3411:       my $value='';
 3412:       if($string =~ /^__HASH_REF__/) {
 3413:           ($value, $string)=&str2hashref($string);
 3414:           if(defined($value->{'error'})) {
 3415:               $hash{'error'}='Bad data';
 3416:               return (\%hash, $string);
 3417:           }
 3418:       } elsif($string =~ /^__ARRAY_REF__/) {
 3419:           ($value, $string)=&str2arrayref($string);
 3420:           if($value->[0] eq 'Array reference error') {
 3421:               $hash{'error'}='Bad data';
 3422:               return (\%hash, $string);
 3423:           }
 3424:       } else {
 3425: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3426:       }
 3427:       $string =~ s/^&//;
 3428: 
 3429:       $hash{$key}=$value;
 3430:   }
 3431: 
 3432:   $string =~ s/^__END_HASH_REF__//;
 3433: 
 3434:   return (\%hash, $string);
 3435: }
 3436: 
 3437: sub str2array {
 3438:     my ($string)=@_;
 3439:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3440:     return @$array;
 3441: }
 3442: 
 3443: sub str2arrayref {
 3444:   my ($string) = @_;
 3445:   my @array;
 3446: 
 3447:   if($string !~ /^__ARRAY_REF__/) {
 3448:       if (! ($string eq '' || !defined($string))) {
 3449: 	  $array[0]='Array reference error';
 3450:       }
 3451:       return (\@array, $string);
 3452:   }
 3453: 
 3454:   $string =~ s/^__ARRAY_REF__//;
 3455: 
 3456:   while($string !~ /^__END_ARRAY_REF__/) {
 3457:       my $value='';
 3458:       if($string =~ /^__HASH_REF__/) {
 3459:           ($value, $string)=&str2hashref($string);
 3460:           if(defined($value->{'error'})) {
 3461:               $array[0] ='Array reference error';
 3462:               return (\@array, $string);
 3463:           }
 3464:       } elsif($string =~ /^__ARRAY_REF__/) {
 3465:           ($value, $string)=&str2arrayref($string);
 3466:           if($value->[0] eq 'Array reference error') {
 3467:               $array[0] ='Array reference error';
 3468:               return (\@array, $string);
 3469:           }
 3470:       } else {
 3471: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3472:       }
 3473:       $string =~ s/^&//;
 3474: 
 3475:       push(@array, $value);
 3476:   }
 3477: 
 3478:   $string =~ s/^__END_ARRAY_REF__//;
 3479: 
 3480:   return (\@array, $string);
 3481: }
 3482: 
 3483: # -------------------------------------------------------------------Temp Store
 3484: 
 3485: sub tmpreset {
 3486:   my ($symb,$namespace,$domain,$stuname) = @_;
 3487:   if (!$symb) {
 3488:     $symb=&symbread();
 3489:     if (!$symb) { $symb= $env{'request.url'}; }
 3490:   }
 3491:   $symb=escape($symb);
 3492: 
 3493:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3494:   $namespace=~s/\//\_/g;
 3495:   $namespace=~s/\W//g;
 3496: 
 3497:   if (!$domain) { $domain=$env{'user.domain'}; }
 3498:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3499:   if ($domain eq 'public' && $stuname eq 'public') {
 3500:       $stuname=$ENV{'REMOTE_ADDR'};
 3501:   }
 3502:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3503:   my %hash;
 3504:   if (tie(%hash,'GDBM_File',
 3505: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3506: 	  &GDBM_WRCREAT(),0640)) {
 3507:     foreach my $key (keys(%hash)) {
 3508:       if ($key=~ /:$symb/) {
 3509: 	delete($hash{$key});
 3510:       }
 3511:     }
 3512:   }
 3513: }
 3514: 
 3515: sub tmpstore {
 3516:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3517: 
 3518:   if (!$symb) {
 3519:     $symb=&symbread();
 3520:     if (!$symb) { $symb= $env{'request.url'}; }
 3521:   }
 3522:   $symb=escape($symb);
 3523: 
 3524:   if (!$namespace) {
 3525:     # I don't think we would ever want to store this for a course.
 3526:     # it seems this will only be used if we don't have a course.
 3527:     #$namespace=$env{'request.course.id'};
 3528:     #if (!$namespace) {
 3529:       $namespace=$env{'request.state'};
 3530:     #}
 3531:   }
 3532:   $namespace=~s/\//\_/g;
 3533:   $namespace=~s/\W//g;
 3534:   if (!$domain) { $domain=$env{'user.domain'}; }
 3535:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3536:   if ($domain eq 'public' && $stuname eq 'public') {
 3537:       $stuname=$ENV{'REMOTE_ADDR'};
 3538:   }
 3539:   my $now=time;
 3540:   my %hash;
 3541:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3542:   if (tie(%hash,'GDBM_File',
 3543: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3544: 	  &GDBM_WRCREAT(),0640)) {
 3545:     $hash{"version:$symb"}++;
 3546:     my $version=$hash{"version:$symb"};
 3547:     my $allkeys=''; 
 3548:     foreach my $key (keys(%$storehash)) {
 3549:       $allkeys.=$key.':';
 3550:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3551:     }
 3552:     $hash{"$version:$symb:timestamp"}=$now;
 3553:     $allkeys.='timestamp';
 3554:     $hash{"$version:keys:$symb"}=$allkeys;
 3555:     if (untie(%hash)) {
 3556:       return 'ok';
 3557:     } else {
 3558:       return "error:$!";
 3559:     }
 3560:   } else {
 3561:     return "error:$!";
 3562:   }
 3563: }
 3564: 
 3565: # -----------------------------------------------------------------Temp Restore
 3566: 
 3567: sub tmprestore {
 3568:   my ($symb,$namespace,$domain,$stuname) = @_;
 3569: 
 3570:   if (!$symb) {
 3571:     $symb=&symbread();
 3572:     if (!$symb) { $symb= $env{'request.url'}; }
 3573:   }
 3574:   $symb=escape($symb);
 3575: 
 3576:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3577: 
 3578:   if (!$domain) { $domain=$env{'user.domain'}; }
 3579:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3580:   if ($domain eq 'public' && $stuname eq 'public') {
 3581:       $stuname=$ENV{'REMOTE_ADDR'};
 3582:   }
 3583:   my %returnhash;
 3584:   $namespace=~s/\//\_/g;
 3585:   $namespace=~s/\W//g;
 3586:   my %hash;
 3587:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3588:   if (tie(%hash,'GDBM_File',
 3589: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3590: 	  &GDBM_READER(),0640)) {
 3591:     my $version=$hash{"version:$symb"};
 3592:     $returnhash{'version'}=$version;
 3593:     my $scope;
 3594:     for ($scope=1;$scope<=$version;$scope++) {
 3595:       my $vkeys=$hash{"$scope:keys:$symb"};
 3596:       my @keys=split(/:/,$vkeys);
 3597:       my $key;
 3598:       $returnhash{"$scope:keys"}=$vkeys;
 3599:       foreach $key (@keys) {
 3600: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3601: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3602:       }
 3603:     }
 3604:     if (!(untie(%hash))) {
 3605:       return "error:$!";
 3606:     }
 3607:   } else {
 3608:     return "error:$!";
 3609:   }
 3610:   return %returnhash;
 3611: }
 3612: 
 3613: # ----------------------------------------------------------------------- Store
 3614: 
 3615: sub store {
 3616:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3617:     my $home='';
 3618: 
 3619:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3620: 
 3621:     $symb=&symbclean($symb);
 3622:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3623: 
 3624:     if (!$domain) { $domain=$env{'user.domain'}; }
 3625:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3626: 
 3627:     &devalidate($symb,$stuname,$domain);
 3628: 
 3629:     $symb=escape($symb);
 3630:     if (!$namespace) { 
 3631:        unless ($namespace=$env{'request.course.id'}) { 
 3632:           return ''; 
 3633:        } 
 3634:     }
 3635:     if (!$home) { $home=$env{'user.home'}; }
 3636: 
 3637:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3638:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3639: 
 3640:     my $namevalue='';
 3641:     foreach my $key (keys(%$storehash)) {
 3642:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3643:     }
 3644:     $namevalue=~s/\&$//;
 3645:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3646:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3647: }
 3648: 
 3649: # -------------------------------------------------------------- Critical Store
 3650: 
 3651: sub cstore {
 3652:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3653:     my $home='';
 3654: 
 3655:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3656: 
 3657:     $symb=&symbclean($symb);
 3658:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3659: 
 3660:     if (!$domain) { $domain=$env{'user.domain'}; }
 3661:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3662: 
 3663:     &devalidate($symb,$stuname,$domain);
 3664: 
 3665:     $symb=escape($symb);
 3666:     if (!$namespace) { 
 3667:        unless ($namespace=$env{'request.course.id'}) { 
 3668:           return ''; 
 3669:        } 
 3670:     }
 3671:     if (!$home) { $home=$env{'user.home'}; }
 3672: 
 3673:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3674:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3675: 
 3676:     my $namevalue='';
 3677:     foreach my $key (keys(%$storehash)) {
 3678:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3679:     }
 3680:     $namevalue=~s/\&$//;
 3681:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3682:     return critical
 3683:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3684: }
 3685: 
 3686: # --------------------------------------------------------------------- Restore
 3687: 
 3688: sub restore {
 3689:     my ($symb,$namespace,$domain,$stuname) = @_;
 3690:     my $home='';
 3691: 
 3692:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3693: 
 3694:     if (!$symb) {
 3695:       unless ($symb=escape(&symbread())) { return ''; }
 3696:     } else {
 3697:       $symb=&escape(&symbclean($symb));
 3698:     }
 3699:     if (!$namespace) { 
 3700:        unless ($namespace=$env{'request.course.id'}) { 
 3701:           return ''; 
 3702:        } 
 3703:     }
 3704:     if (!$domain) { $domain=$env{'user.domain'}; }
 3705:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3706:     if (!$home) { $home=$env{'user.home'}; }
 3707:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3708: 
 3709:     my %returnhash=();
 3710:     foreach my $line (split(/\&/,$answer)) {
 3711: 	my ($name,$value)=split(/\=/,$line);
 3712:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3713:     }
 3714:     my $version;
 3715:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3716:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3717:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3718:        }
 3719:     }
 3720:     return %returnhash;
 3721: }
 3722: 
 3723: # ---------------------------------------------------------- Course Description
 3724: 
 3725: sub coursedescription {
 3726:     my ($courseid,$args)=@_;
 3727:     $courseid=~s/^\///;
 3728:     $courseid=~s/\_/\//g;
 3729:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3730:     my $chome=&homeserver($cnum,$cdomain);
 3731:     my $normalid=$cdomain.'_'.$cnum;
 3732:     # need to always cache even if we get errors otherwise we keep 
 3733:     # trying and trying and trying to get the course description.
 3734:     my %envhash=();
 3735:     my %returnhash=();
 3736:     
 3737:     my $expiretime=600;
 3738:     if ($env{'request.course.id'} eq $normalid) {
 3739: 	$expiretime=120;
 3740:     }
 3741: 
 3742:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3743:     if (!$args->{'freshen_cache'}
 3744: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3745: 	foreach my $key (keys(%env)) {
 3746: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3747: 	    my ($setting) = $1;
 3748: 	    $returnhash{$setting} = $env{$key};
 3749: 	}
 3750: 	return %returnhash;
 3751:     }
 3752: 
 3753:     # get the data agin
 3754:     if (!$args->{'one_time'}) {
 3755: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3756:     }
 3757: 
 3758:     if ($chome ne 'no_host') {
 3759:        %returnhash=&dump('environment',$cdomain,$cnum);
 3760:        if (!exists($returnhash{'con_lost'})) {
 3761:            $returnhash{'home'}= $chome;
 3762: 	   $returnhash{'domain'} = $cdomain;
 3763: 	   $returnhash{'num'} = $cnum;
 3764:            if (!defined($returnhash{'type'})) {
 3765:                $returnhash{'type'} = 'Course';
 3766:            }
 3767:            while (my ($name,$value) = each %returnhash) {
 3768:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3769:            }
 3770:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3771:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3772: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3773:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3774:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3775:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3776:        }
 3777:     }
 3778:     if (!$args->{'one_time'}) {
 3779: 	&appenv(\%envhash);
 3780:     }
 3781:     return %returnhash;
 3782: }
 3783: 
 3784: # -------------------------------------------------See if a user is privileged
 3785: 
 3786: sub privileged {
 3787:     my ($username,$domain)=@_;
 3788:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3789: 			&homeserver($username,$domain));
 3790:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3791:         ($rolesdump =~ /^error:/)) {
 3792:         return 0;
 3793:     }
 3794:     my $now=time;
 3795:     if ($rolesdump ne '') {
 3796:         foreach my $entry (split(/&/,$rolesdump)) {
 3797: 	    if ($entry!~/^rolesdef_/) {
 3798: 		my ($area,$role)=split(/=/,$entry);
 3799: 		$area=~s/\_\w\w$//;
 3800: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3801: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3802: 		    my $active=1;
 3803: 		    if ($tend) {
 3804: 			if ($tend<$now) { $active=0; }
 3805: 		    }
 3806: 		    if ($tstart) {
 3807: 			if ($tstart>$now) { $active=0; }
 3808: 		    }
 3809: 		    if ($active) { return 1; }
 3810: 		}
 3811: 	    }
 3812: 	}
 3813:     }
 3814:     return 0;
 3815: }
 3816: 
 3817: # -------------------------------------------------------- Get user privileges
 3818: 
 3819: sub rolesinit {
 3820:     my ($domain,$username,$authhost)=@_;
 3821:     my $now=time;
 3822:     my %userroles = ('user.login.time' => $now);
 3823:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3824:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3825:         ($rolesdump =~ /^error:/)) { 
 3826:         return \%userroles;
 3827:     }
 3828:     my %allroles=();
 3829:     my %allgroups=();   
 3830:     my $group_privs;
 3831: 
 3832:     if ($rolesdump ne '') {
 3833:         foreach my $entry (split(/&/,$rolesdump)) {
 3834: 	  if ($entry!~/^rolesdef_/) {
 3835:             my ($area,$role)=split(/=/,$entry);
 3836: 	    $area=~s/\_\w\w$//;
 3837:             my ($trole,$tend,$tstart,$group_privs);
 3838: 	    if ($role=~/^cr/) { 
 3839: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3840: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3841: 		    ($tend,$tstart)=split('_',$trest);
 3842: 		} else {
 3843: 		    $trole=$role;
 3844: 		}
 3845:             } elsif ($role =~ m|^gr/|) {
 3846:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3847:                 ($trole,$group_privs) = split(/\//,$trole);
 3848:                 $group_privs = &unescape($group_privs);
 3849: 	    } else {
 3850: 		($trole,$tend,$tstart)=split(/_/,$role);
 3851: 	    }
 3852: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3853: 					 $username);
 3854: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3855:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3856:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3857:             if (($area ne '') && ($trole ne '')) {
 3858: 		my $spec=$trole.'.'.$area;
 3859: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3860: 		if ($trole =~ /^cr\//) {
 3861:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3862:                 } elsif ($trole eq 'gr') {
 3863:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3864: 		} else {
 3865:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3866: 		}
 3867:             }
 3868:           }
 3869:         }
 3870:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3871:         $userroles{'user.adv'}    = $adv;
 3872: 	$userroles{'user.author'} = $author;
 3873:         $env{'user.adv'}=$adv;
 3874:     }
 3875:     return \%userroles;  
 3876: }
 3877: 
 3878: sub set_arearole {
 3879:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3880: # log the associated role with the area
 3881:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3882:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3883: }
 3884: 
 3885: sub custom_roleprivs {
 3886:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3887:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3888:     my $homsvr=homeserver($rauthor,$rdomain);
 3889:     if (&hostname($homsvr) ne '') {
 3890:         my ($rdummy,$roledef)=
 3891:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3892:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3893:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3894:             if (defined($syspriv)) {
 3895:                 if ($trest =~ /^$match_community$/) {
 3896:                     $syspriv =~ s/bre\&S//; 
 3897:                 }
 3898:                 $$allroles{'cm./'}.=':'.$syspriv;
 3899:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3900:             }
 3901:             if ($tdomain ne '') {
 3902:                 if (defined($dompriv)) {
 3903:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3904:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3905:                 }
 3906:                 if (($trest ne '') && (defined($coursepriv))) {
 3907:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3908:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3909:                 }
 3910:             }
 3911:         }
 3912:     }
 3913: }
 3914: 
 3915: sub group_roleprivs {
 3916:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3917:     my $access = 1;
 3918:     my $now = time;
 3919:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3920:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3921:     if ($access) {
 3922:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3923:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3924:     }
 3925: }
 3926: 
 3927: sub standard_roleprivs {
 3928:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3929:     if (defined($pr{$trole.':s'})) {
 3930:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3931:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3932:     }
 3933:     if ($tdomain ne '') {
 3934:         if (defined($pr{$trole.':d'})) {
 3935:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3936:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3937:         }
 3938:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3939:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3940:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3941:         }
 3942:     }
 3943: }
 3944: 
 3945: sub set_userprivs {
 3946:     my ($userroles,$allroles,$allgroups) = @_; 
 3947:     my $author=0;
 3948:     my $adv=0;
 3949:     my %grouproles = ();
 3950:     if (keys(%{$allgroups}) > 0) {
 3951:         foreach my $role (keys(%{$allroles})) {
 3952:             my ($trole,$area,$sec,$extendedarea);
 3953:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3954:                 $trole = $1;
 3955:                 $area = $2;
 3956:                 $sec = $3;
 3957:                 $extendedarea = $area.$sec;
 3958:                 if (exists($$allgroups{$area})) {
 3959:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3960:                         my $spec = $trole.'.'.$extendedarea;
 3961:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3962:                                                 $$allgroups{$area}{$group};
 3963:                     }
 3964:                 }
 3965:             }
 3966:         }
 3967:     }
 3968:     foreach my $group (keys(%grouproles)) {
 3969:         $$allroles{$group} = $grouproles{$group};
 3970:     }
 3971:     foreach my $role (keys(%{$allroles})) {
 3972:         my %thesepriv;
 3973:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3974:         foreach my $item (split(/:/,$$allroles{$role})) {
 3975:             if ($item ne '') {
 3976:                 my ($privilege,$restrictions)=split(/&/,$item);
 3977:                 if ($restrictions eq '') {
 3978:                     $thesepriv{$privilege}='F';
 3979:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3980:                     $thesepriv{$privilege}.=$restrictions;
 3981:                 }
 3982:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3983:             }
 3984:         }
 3985:         my $thesestr='';
 3986:         foreach my $priv (keys(%thesepriv)) {
 3987: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3988: 	}
 3989:         $userroles->{'user.priv.'.$role} = $thesestr;
 3990:     }
 3991:     return ($author,$adv);
 3992: }
 3993: 
 3994: sub role_status {
 3995:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 3996:     my @pwhere = ();
 3997:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 3998:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 3999:         unless (!defined($$role) || $$role eq '') {
 4000:             $$where=join('.',@pwhere);
 4001:             $$trolecode=$$role.'.'.$$where;
 4002:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4003:             $$tstatus='is';
 4004:             if ($$tstart && $$tstart>$then) {
 4005:                 $$tstatus='future';
 4006:                 if ($$tstart<$now) {
 4007:                     if ($$tstart && $$tstart>$refresh) {
 4008:                         if (($$where ne '') && ($$role ne '')) {
 4009:                             my (%allroles,%allgroups,$group_privs);
 4010:                             my %userroles = (
 4011:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4012:                             );
 4013:                             my $spec=$$role.'.'.$$where;
 4014:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4015:                             if ($$role =~ /^cr\//) {
 4016:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4017:                             } elsif ($$role eq 'gr') {
 4018:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4019:                                                     $env{'user.name'});
 4020:                                 my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
 4021:                                 (undef,my $group_privs) = split(/\//,$trole);
 4022:                                 $group_privs = &unescape($group_privs);
 4023:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4024:                             } else {
 4025:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4026:                             }
 4027:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4028:                             &appenv(\%userroles,[$$role,'cm']);
 4029:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4030:                         }
 4031:                     }
 4032:                     $$tstatus = 'is';
 4033:                 }
 4034:             }
 4035:             if ($$tend) {
 4036:                 if ($$tend<$then) {
 4037:                     $$tstatus='expired';
 4038:                 } elsif ($$tend<$now) {
 4039:                     $$tstatus='will_not';
 4040:                 }
 4041:             }
 4042:         }
 4043:     }
 4044: }
 4045: 
 4046: sub check_adhoc_privs {
 4047:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 4048:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4049:     if ($env{$cckey}) {
 4050:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4051:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4052:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4053:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4054:         }
 4055:     } else {
 4056:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4057:     }
 4058: }
 4059: 
 4060: sub set_adhoc_privileges {
 4061: # role can be cc or ca
 4062:     my ($dcdom,$pickedcourse,$role) = @_;
 4063:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4064:     my $spec = $role.'.'.$area;
 4065:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4066:                                   $env{'user.name'});
 4067:     my %ccrole = ();
 4068:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4069:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4070:     &appenv(\%userroles,[$role,'cm']);
 4071:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4072:     &appenv( {'request.role'        => $spec,
 4073:               'request.role.domain' => $dcdom,
 4074:               'request.course.sec'  => ''
 4075:              }
 4076:            );
 4077:     my $tadv=0;
 4078:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4079:     &appenv({'request.role.adv'    => $tadv});
 4080: }
 4081: 
 4082: # --------------------------------------------------------------- get interface
 4083: 
 4084: sub get {
 4085:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4086:    my $items='';
 4087:    foreach my $item (@$storearr) {
 4088:        $items.=&escape($item).'&';
 4089:    }
 4090:    $items=~s/\&$//;
 4091:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4092:    if (!$uname) { $uname=$env{'user.name'}; }
 4093:    my $uhome=&homeserver($uname,$udomain);
 4094: 
 4095:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4096:    my @pairs=split(/\&/,$rep);
 4097:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4098:      return @pairs;
 4099:    }
 4100:    my %returnhash=();
 4101:    my $i=0;
 4102:    foreach my $item (@$storearr) {
 4103:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4104:       $i++;
 4105:    }
 4106:    return %returnhash;
 4107: }
 4108: 
 4109: # --------------------------------------------------------------- del interface
 4110: 
 4111: sub del {
 4112:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4113:    my $items='';
 4114:    foreach my $item (@$storearr) {
 4115:        $items.=&escape($item).'&';
 4116:    }
 4117: 
 4118:    $items=~s/\&$//;
 4119:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4120:    if (!$uname) { $uname=$env{'user.name'}; }
 4121:    my $uhome=&homeserver($uname,$udomain);
 4122:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4123: }
 4124: 
 4125: # -------------------------------------------------------------- dump interface
 4126: 
 4127: sub dump {
 4128:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4129:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4130:     if (!$uname) { $uname=$env{'user.name'}; }
 4131:     my $uhome=&homeserver($uname,$udomain);
 4132:     if ($regexp) {
 4133: 	$regexp=&escape($regexp);
 4134:     } else {
 4135: 	$regexp='.';
 4136:     }
 4137:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4138:     my @pairs=split(/\&/,$rep);
 4139:     my %returnhash=();
 4140:     foreach my $item (@pairs) {
 4141: 	my ($key,$value)=split(/=/,$item,2);
 4142: 	$key = &unescape($key);
 4143: 	next if ($key =~ /^error: 2 /);
 4144: 	$returnhash{$key}=&thaw_unescape($value);
 4145:     }
 4146:     return %returnhash;
 4147: }
 4148: 
 4149: # --------------------------------------------------------- dumpstore interface
 4150: 
 4151: sub dumpstore {
 4152:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4153:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4154:    if (!$uname) { $uname=$env{'user.name'}; }
 4155:    my $uhome=&homeserver($uname,$udomain);
 4156:    if ($regexp) {
 4157:        $regexp=&escape($regexp);
 4158:    } else {
 4159:        $regexp='.';
 4160:    }
 4161:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4162:    my @pairs=split(/\&/,$rep);
 4163:    my %returnhash=();
 4164:    foreach my $item (@pairs) {
 4165:        my ($key,$value)=split(/=/,$item,2);
 4166:        next if ($key =~ /^error: 2 /);
 4167:        $returnhash{$key}=&thaw_unescape($value);
 4168:    }
 4169:    return %returnhash;
 4170: }
 4171: 
 4172: # -------------------------------------------------------------- keys interface
 4173: 
 4174: sub getkeys {
 4175:    my ($namespace,$udomain,$uname)=@_;
 4176:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4177:    if (!$uname) { $uname=$env{'user.name'}; }
 4178:    my $uhome=&homeserver($uname,$udomain);
 4179:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4180:    my @keyarray=();
 4181:    foreach my $key (split(/\&/,$rep)) {
 4182:       next if ($key =~ /^error: 2 /);
 4183:       push(@keyarray,&unescape($key));
 4184:    }
 4185:    return @keyarray;
 4186: }
 4187: 
 4188: # --------------------------------------------------------------- currentdump
 4189: sub currentdump {
 4190:    my ($courseid,$sdom,$sname)=@_;
 4191:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4192:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4193:    $sname    = $env{'user.name'}         if (! defined($sname));
 4194:    my $uhome = &homeserver($sname,$sdom);
 4195:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4196:    return if ($rep =~ /^(error:|no_such_host)/);
 4197:    #
 4198:    my %returnhash=();
 4199:    #
 4200:    if ($rep eq "unknown_cmd") { 
 4201:        # an old lond will not know currentdump
 4202:        # Do a dump and make it look like a currentdump
 4203:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4204:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4205:        my %hash = @tmp;
 4206:        @tmp=();
 4207:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4208:    } else {
 4209:        my @pairs=split(/\&/,$rep);
 4210:        foreach my $pair (@pairs) {
 4211:            my ($key,$value)=split(/=/,$pair,2);
 4212:            my ($symb,$param) = split(/:/,$key);
 4213:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4214:                                                         &thaw_unescape($value);
 4215:        }
 4216:    }
 4217:    return %returnhash;
 4218: }
 4219: 
 4220: sub convert_dump_to_currentdump{
 4221:     my %hash = %{shift()};
 4222:     my %returnhash;
 4223:     # Code ripped from lond, essentially.  The only difference
 4224:     # here is the unescaping done by lonnet::dump().  Conceivably
 4225:     # we might run in to problems with parameter names =~ /^v\./
 4226:     while (my ($key,$value) = each(%hash)) {
 4227:         my ($v,$symb,$param) = split(/:/,$key);
 4228: 	$symb  = &unescape($symb);
 4229: 	$param = &unescape($param);
 4230:         next if ($v eq 'version' || $symb eq 'keys');
 4231:         next if (exists($returnhash{$symb}) &&
 4232:                  exists($returnhash{$symb}->{$param}) &&
 4233:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4234:         $returnhash{$symb}->{$param}=$value;
 4235:         $returnhash{$symb}->{'v.'.$param}=$v;
 4236:     }
 4237:     #
 4238:     # Remove all of the keys in the hashes which keep track of
 4239:     # the version of the parameter.
 4240:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4241:         # use a foreach because we are going to delete from the hash.
 4242:         foreach my $key (keys(%$param_hash)) {
 4243:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4244:         }
 4245:     }
 4246:     return \%returnhash;
 4247: }
 4248: 
 4249: # ------------------------------------------------------ critical inc interface
 4250: 
 4251: sub cinc {
 4252:     return &inc(@_,'critical');
 4253: }
 4254: 
 4255: # --------------------------------------------------------------- inc interface
 4256: 
 4257: sub inc {
 4258:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4259:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4260:     if (!$uname) { $uname=$env{'user.name'}; }
 4261:     my $uhome=&homeserver($uname,$udomain);
 4262:     my $items='';
 4263:     if (! ref($store)) {
 4264:         # got a single value, so use that instead
 4265:         $items = &escape($store).'=&';
 4266:     } elsif (ref($store) eq 'SCALAR') {
 4267:         $items = &escape($$store).'=&';        
 4268:     } elsif (ref($store) eq 'ARRAY') {
 4269:         $items = join('=&',map {&escape($_);} @{$store});
 4270:     } elsif (ref($store) eq 'HASH') {
 4271:         while (my($key,$value) = each(%{$store})) {
 4272:             $items.= &escape($key).'='.&escape($value).'&';
 4273:         }
 4274:     }
 4275:     $items=~s/\&$//;
 4276:     if ($critical) {
 4277: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4278:     } else {
 4279: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4280:     }
 4281: }
 4282: 
 4283: # --------------------------------------------------------------- put interface
 4284: 
 4285: sub put {
 4286:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4287:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4288:    if (!$uname) { $uname=$env{'user.name'}; }
 4289:    my $uhome=&homeserver($uname,$udomain);
 4290:    my $items='';
 4291:    foreach my $item (keys(%$storehash)) {
 4292:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4293:    }
 4294:    $items=~s/\&$//;
 4295:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4296: }
 4297: 
 4298: # ------------------------------------------------------------ newput interface
 4299: 
 4300: sub newput {
 4301:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4302:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4303:    if (!$uname) { $uname=$env{'user.name'}; }
 4304:    my $uhome=&homeserver($uname,$udomain);
 4305:    my $items='';
 4306:    foreach my $key (keys(%$storehash)) {
 4307:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4308:    }
 4309:    $items=~s/\&$//;
 4310:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4311: }
 4312: 
 4313: # ---------------------------------------------------------  putstore interface
 4314: 
 4315: sub putstore {
 4316:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4317:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4318:    if (!$uname) { $uname=$env{'user.name'}; }
 4319:    my $uhome=&homeserver($uname,$udomain);
 4320:    my $items='';
 4321:    foreach my $key (keys(%$storehash)) {
 4322:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4323:    }
 4324:    $items=~s/\&$//;
 4325:    my $esc_symb=&escape($symb);
 4326:    my $esc_v=&escape($version);
 4327:    my $reply =
 4328:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4329: 	      $uhome);
 4330:    if ($reply eq 'unknown_cmd') {
 4331:        # gfall back to way things use to be done
 4332:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4333: 			    $uname);
 4334:    }
 4335:    return $reply;
 4336: }
 4337: 
 4338: sub old_putstore {
 4339:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4340:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4341:     if (!$uname) { $uname=$env{'user.name'}; }
 4342:     my $uhome=&homeserver($uname,$udomain);
 4343:     my %newstorehash;
 4344:     foreach my $item (keys(%$storehash)) {
 4345: 	my $key = $version.':'.&escape($symb).':'.$item;
 4346: 	$newstorehash{$key} = $storehash->{$item};
 4347:     }
 4348:     my $items='';
 4349:     my %allitems = ();
 4350:     foreach my $item (keys(%newstorehash)) {
 4351: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4352: 	    my $key = $1.':keys:'.$2;
 4353: 	    $allitems{$key} .= $3.':';
 4354: 	}
 4355: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4356:     }
 4357:     foreach my $item (keys(%allitems)) {
 4358: 	$allitems{$item} =~ s/\:$//;
 4359: 	$items.= $item.'='.$allitems{$item}.'&';
 4360:     }
 4361:     $items=~s/\&$//;
 4362:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4363: }
 4364: 
 4365: # ------------------------------------------------------ critical put interface
 4366: 
 4367: sub cput {
 4368:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4369:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4370:    if (!$uname) { $uname=$env{'user.name'}; }
 4371:    my $uhome=&homeserver($uname,$udomain);
 4372:    my $items='';
 4373:    foreach my $item (keys(%$storehash)) {
 4374:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4375:    }
 4376:    $items=~s/\&$//;
 4377:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4378: }
 4379: 
 4380: # -------------------------------------------------------------- eget interface
 4381: 
 4382: sub eget {
 4383:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4384:    my $items='';
 4385:    foreach my $item (@$storearr) {
 4386:        $items.=&escape($item).'&';
 4387:    }
 4388:    $items=~s/\&$//;
 4389:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4390:    if (!$uname) { $uname=$env{'user.name'}; }
 4391:    my $uhome=&homeserver($uname,$udomain);
 4392:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4393:    my @pairs=split(/\&/,$rep);
 4394:    my %returnhash=();
 4395:    my $i=0;
 4396:    foreach my $item (@$storearr) {
 4397:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4398:       $i++;
 4399:    }
 4400:    return %returnhash;
 4401: }
 4402: 
 4403: # ------------------------------------------------------------ tmpput interface
 4404: sub tmpput {
 4405:     my ($storehash,$server,$context)=@_;
 4406:     my $items='';
 4407:     foreach my $item (keys(%$storehash)) {
 4408: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4409:     }
 4410:     $items=~s/\&$//;
 4411:     if (defined($context)) {
 4412:         $items .= ':'.&escape($context);
 4413:     }
 4414:     return &reply("tmpput:$items",$server);
 4415: }
 4416: 
 4417: # ------------------------------------------------------------ tmpget interface
 4418: sub tmpget {
 4419:     my ($token,$server)=@_;
 4420:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4421:     my $rep=&reply("tmpget:$token",$server);
 4422:     my %returnhash;
 4423:     foreach my $item (split(/\&/,$rep)) {
 4424: 	my ($key,$value)=split(/=/,$item);
 4425:         next if ($key =~ /^error: 2 /);
 4426: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4427:     }
 4428:     return %returnhash;
 4429: }
 4430: 
 4431: # ------------------------------------------------------------ tmpget interface
 4432: sub tmpdel {
 4433:     my ($token,$server)=@_;
 4434:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4435:     return &reply("tmpdel:$token",$server);
 4436: }
 4437: 
 4438: # -------------------------------------------------- portfolio access checking
 4439: 
 4440: sub portfolio_access {
 4441:     my ($requrl) = @_;
 4442:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4443:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4444:     if ($result) {
 4445:         my %setters;
 4446:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4447:             my ($startblock,$endblock) =
 4448:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4449:             if ($startblock && $endblock) {
 4450:                 return 'B';
 4451:             }
 4452:         } else {
 4453:             my ($startblock,$endblock) =
 4454:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4455:             if ($startblock && $endblock) {
 4456:                 return 'B';
 4457:             }
 4458:         }
 4459:     }
 4460:     if ($result eq 'ok') {
 4461:        return 'F';
 4462:     } elsif ($result =~ /^[^:]+:guest_/) {
 4463:        return 'A';
 4464:     }
 4465:     return '';
 4466: }
 4467: 
 4468: sub get_portfolio_access {
 4469:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4470: 
 4471:     if (!ref($access_hash)) {
 4472: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4473: 	my %access_controls = &get_access_controls($current_perms,$group,
 4474: 						   $file_name);
 4475: 	$access_hash = $access_controls{$file_name};
 4476:     }
 4477: 
 4478:     my ($public,$guest,@domains,@users,@courses,@groups);
 4479:     my $now = time;
 4480:     if (ref($access_hash) eq 'HASH') {
 4481:         foreach my $key (keys(%{$access_hash})) {
 4482:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4483:             if ($start > $now) {
 4484:                 next;
 4485:             }
 4486:             if ($end && $end<$now) {
 4487:                 next;
 4488:             }
 4489:             if ($scope eq 'public') {
 4490:                 $public = $key;
 4491:                 last;
 4492:             } elsif ($scope eq 'guest') {
 4493:                 $guest = $key;
 4494:             } elsif ($scope eq 'domains') {
 4495:                 push(@domains,$key);
 4496:             } elsif ($scope eq 'users') {
 4497:                 push(@users,$key);
 4498:             } elsif ($scope eq 'course') {
 4499:                 push(@courses,$key);
 4500:             } elsif ($scope eq 'group') {
 4501:                 push(@groups,$key);
 4502:             }
 4503:         }
 4504:         if ($public) {
 4505:             return 'ok';
 4506:         }
 4507:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4508:             if ($guest) {
 4509:                 return $guest;
 4510:             }
 4511:         } else {
 4512:             if (@domains > 0) {
 4513:                 foreach my $domkey (@domains) {
 4514:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4515:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4516:                             return 'ok';
 4517:                         }
 4518:                     }
 4519:                 }
 4520:             }
 4521:             if (@users > 0) {
 4522:                 foreach my $userkey (@users) {
 4523:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4524:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4525:                             if (ref($item) eq 'HASH') {
 4526:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4527:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4528:                                     return 'ok';
 4529:                                 }
 4530:                             }
 4531:                         }
 4532:                     } 
 4533:                 }
 4534:             }
 4535:             my %roleshash;
 4536:             my @courses_and_groups = @courses;
 4537:             push(@courses_and_groups,@groups); 
 4538:             if (@courses_and_groups > 0) {
 4539:                 my (%allgroups,%allroles); 
 4540:                 my ($start,$end,$role,$sec,$group);
 4541:                 foreach my $envkey (%env) {
 4542:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4543:                         my $cid = $2.'_'.$3; 
 4544:                         if ($1 eq 'gr') {
 4545:                             $group = $4;
 4546:                             $allgroups{$cid}{$group} = $env{$envkey};
 4547:                         } else {
 4548:                             if ($4 eq '') {
 4549:                                 $sec = 'none';
 4550:                             } else {
 4551:                                 $sec = $4;
 4552:                             }
 4553:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4554:                         }
 4555:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4556:                         my $cid = $2.'_'.$3;
 4557:                         if ($4 eq '') {
 4558:                             $sec = 'none';
 4559:                         } else {
 4560:                             $sec = $4;
 4561:                         }
 4562:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4563:                     }
 4564:                 }
 4565:                 if (keys(%allroles) == 0) {
 4566:                     return;
 4567:                 }
 4568:                 foreach my $key (@courses_and_groups) {
 4569:                     my %content = %{$$access_hash{$key}};
 4570:                     my $cnum = $content{'number'};
 4571:                     my $cdom = $content{'domain'};
 4572:                     my $cid = $cdom.'_'.$cnum;
 4573:                     if (!exists($allroles{$cid})) {
 4574:                         next;
 4575:                     }    
 4576:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4577:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4578:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4579:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4580:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4581:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4582:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4583:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4584:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4585:                                         if (grep/^all$/,@sections) {
 4586:                                             return 'ok';
 4587:                                         } else {
 4588:                                             if (grep/^$sec$/,@sections) {
 4589:                                                 return 'ok';
 4590:                                             }
 4591:                                         }
 4592:                                     }
 4593:                                 }
 4594:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4595:                                     if (grep/^none$/,@groups) {
 4596:                                         return 'ok';
 4597:                                     }
 4598:                                 } else {
 4599:                                     if (grep/^all$/,@groups) {
 4600:                                         return 'ok';
 4601:                                     } 
 4602:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4603:                                         if (grep/^$group$/,@groups) {
 4604:                                             return 'ok';
 4605:                                         }
 4606:                                     }
 4607:                                 } 
 4608:                             }
 4609:                         }
 4610:                     }
 4611:                 }
 4612:             }
 4613:             if ($guest) {
 4614:                 return $guest;
 4615:             }
 4616:         }
 4617:     }
 4618:     return;
 4619: }
 4620: 
 4621: sub course_group_datechecker {
 4622:     my ($dates,$now,$status) = @_;
 4623:     my ($start,$end) = split(/\./,$dates);
 4624:     if (!$start && !$end) {
 4625:         return 'ok';
 4626:     }
 4627:     if (grep/^active$/,@{$status}) {
 4628:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4629:             return 'ok';
 4630:         }
 4631:     }
 4632:     if (grep/^previous$/,@{$status}) {
 4633:         if ($end > $now ) {
 4634:             return 'ok';
 4635:         }
 4636:     }
 4637:     if (grep/^future$/,@{$status}) {
 4638:         if ($start > $now) {
 4639:             return 'ok';
 4640:         }
 4641:     }
 4642:     return; 
 4643: }
 4644: 
 4645: sub parse_portfolio_url {
 4646:     my ($url) = @_;
 4647: 
 4648:     my ($type,$udom,$unum,$group,$file_name);
 4649:     
 4650:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4651: 	$type = 1;
 4652:         $udom = $1;
 4653:         $unum = $2;
 4654:         $file_name = $3;
 4655:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4656: 	$type = 2;
 4657:         $udom = $1;
 4658:         $unum = $2;
 4659:         $group = $3;
 4660:         $file_name = $3.'/'.$4;
 4661:     }
 4662:     if (wantarray) {
 4663: 	return ($type,$udom,$unum,$file_name,$group);
 4664:     }
 4665:     return $type;
 4666: }
 4667: 
 4668: sub is_portfolio_url {
 4669:     my ($url) = @_;
 4670:     return scalar(&parse_portfolio_url($url));
 4671: }
 4672: 
 4673: sub is_portfolio_file {
 4674:     my ($file) = @_;
 4675:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4676:         return 1;
 4677:     }
 4678:     return;
 4679: }
 4680: 
 4681: sub usertools_access {
 4682:     my ($uname,$udom,$tool,$action,$context) = @_;
 4683:     my ($access,%tools);
 4684:     if ($context eq '') {
 4685:         $context = 'tools';
 4686:     }
 4687:     if ($context eq 'requestcourses') {
 4688:         %tools = (
 4689:                       official   => 1,
 4690:                       unofficial => 1,
 4691:                       community  => 1,
 4692:                  );
 4693:     } else {
 4694:         %tools = (
 4695:                       aboutme   => 1,
 4696:                       blog      => 1,
 4697:                       portfolio => 1,
 4698:                  );
 4699:     }
 4700:     return if (!defined($tools{$tool}));
 4701: 
 4702:     if ((!defined($udom)) || (!defined($uname))) {
 4703:         $udom = $env{'user.domain'};
 4704:         $uname = $env{'user.name'};
 4705:     }
 4706: 
 4707:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4708:         if ($action ne 'reload') {
 4709:             if ($context eq 'requestcourses') {
 4710:                 return $env{'environment.canrequest.'.$tool};
 4711:             } else {
 4712:                 return $env{'environment.availabletools.'.$tool};
 4713:             }
 4714:         }
 4715:     }
 4716: 
 4717:     my ($toolstatus,$inststatus);
 4718: 
 4719:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4720:          ($action ne 'reload')) {
 4721:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4722:         $inststatus = $env{'environment.inststatus'};
 4723:     } else {
 4724:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 4725:         $toolstatus = $userenv{$context.'.'.$tool};
 4726:         $inststatus = $userenv{'inststatus'};
 4727:     }
 4728: 
 4729:     if ($toolstatus ne '') {
 4730:         if ($toolstatus) {
 4731:             $access = 1;
 4732:         } else {
 4733:             $access = 0;
 4734:         }
 4735:         return $access;
 4736:     }
 4737: 
 4738:     my $is_adv = &is_advanced_user($udom,$uname);
 4739:     my %domdef = &get_domain_defaults($udom);
 4740:     if (ref($domdef{$tool}) eq 'HASH') {
 4741:         if ($is_adv) {
 4742:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4743:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4744:                     $access = 1;
 4745:                 } else {
 4746:                     $access = 0;
 4747:                 }
 4748:                 return $access;
 4749:             }
 4750:         }
 4751:         if ($inststatus ne '') {
 4752:             my ($hasaccess,$hasnoaccess);
 4753:             foreach my $affiliation (split(/:/,$inststatus)) {
 4754:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4755:                     if ($domdef{$tool}{$affiliation}) {
 4756:                         $hasaccess = 1;
 4757:                     } else {
 4758:                         $hasnoaccess = 1;
 4759:                     }
 4760:                 }
 4761:             }
 4762:             if ($hasaccess || $hasnoaccess) {
 4763:                 if ($hasaccess) {
 4764:                     $access = 1;
 4765:                 } elsif ($hasnoaccess) {
 4766:                     $access = 0; 
 4767:                 }
 4768:                 return $access;
 4769:             }
 4770:         } else {
 4771:             if ($domdef{$tool}{'default'} ne '') {
 4772:                 if ($domdef{$tool}{'default'}) {
 4773:                     $access = 1;
 4774:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4775:                     $access = 0;
 4776:                 }
 4777:                 return $access;
 4778:             }
 4779:         }
 4780:     } else {
 4781:         if ($context eq 'tools') {
 4782:             $access = 1;
 4783:         } else {
 4784:             $access = 0;
 4785:         }
 4786:         return $access;
 4787:     }
 4788: }
 4789: 
 4790: sub is_course_owner {
 4791:     my ($cdom,$cnum,$udom,$uname) = @_;
 4792:     if (($udom eq '') || ($uname eq '')) {
 4793:         $udom = $env{'user.domain'};
 4794:         $uname = $env{'user.name'};
 4795:     }
 4796:     unless (($udom eq '') || ($uname eq '')) {
 4797:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 4798:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 4799:                 return 1;
 4800:             } else {
 4801:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 4802:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 4803:                     return 1;
 4804:                 }
 4805:             }
 4806:         }
 4807:     }
 4808:     return;
 4809: }
 4810: 
 4811: sub is_advanced_user {
 4812:     my ($udom,$uname) = @_;
 4813:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4814:     my %allroles;
 4815:     my $is_adv;
 4816:     foreach my $role (keys(%roleshash)) {
 4817:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4818:         my $area = '/'.$tdomain.'/'.$trest;
 4819:         if ($sec ne '') {
 4820:             $area .= '/'.$sec;
 4821:         }
 4822:         if (($area ne '') && ($trole ne '')) {
 4823:             my $spec=$trole.'.'.$area;
 4824:             if ($trole =~ /^cr\//) {
 4825:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4826:             } elsif ($trole ne 'gr') {
 4827:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4828:             }
 4829:         }
 4830:     }
 4831:     foreach my $role (keys(%allroles)) {
 4832:         last if ($is_adv);
 4833:         foreach my $item (split(/:/,$allroles{$role})) {
 4834:             if ($item ne '') {
 4835:                 my ($privilege,$restrictions)=split(/&/,$item);
 4836:                 if ($privilege eq 'adv') {
 4837:                     $is_adv = 1;
 4838:                     last;
 4839:                 }
 4840:             }
 4841:         }
 4842:     }
 4843:     return $is_adv;
 4844: }
 4845: 
 4846: sub check_can_request {
 4847:     my ($dom,$can_request,$request_domains) = @_;
 4848:     my $canreq = 0;
 4849:     my ($types,$typename) = &Apache::loncommon::course_types();
 4850:     my @options = ('approval','validate','autolimit');
 4851:     my $optregex = join('|',@options);
 4852:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 4853:         foreach my $type (@{$types}) {
 4854:             if (&usertools_access($env{'user.name'},
 4855:                                   $env{'user.domain'},
 4856:                                   $type,undef,'requestcourses')) {
 4857:                 $canreq ++;
 4858:                 if (ref($request_domains) eq 'HASH') {
 4859:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 4860:                 }
 4861:                 if ($dom eq $env{'user.domain'}) {
 4862:                     $can_request->{$type} = 1;
 4863:                 }
 4864:             }
 4865:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 4866:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 4867:                 if (@curr > 0) {
 4868:                     foreach my $item (@curr) {
 4869:                         if (ref($request_domains) eq 'HASH') {
 4870:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 4871:                             if ($otherdom ne '') {
 4872:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 4873:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 4874:                                         push(@{$request_domains->{$type}},$otherdom);
 4875:                                     }
 4876:                                 } else {
 4877:                                     push(@{$request_domains->{$type}},$otherdom);
 4878:                                 }
 4879:                             }
 4880:                         }
 4881:                     }
 4882:                     unless($dom eq $env{'user.domain'}) {
 4883:                         $canreq ++;
 4884:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 4885:                             $can_request->{$type} = 1;
 4886:                         }
 4887:                     }
 4888:                 }
 4889:             }
 4890:         }
 4891:     }
 4892:     return $canreq;
 4893: }
 4894: 
 4895: # ---------------------------------------------- Custom access rule evaluation
 4896: 
 4897: sub customaccess {
 4898:     my ($priv,$uri)=@_;
 4899:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4900:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4901:     $udom = &LONCAPA::clean_domain($udom);
 4902:     $ucrs = &LONCAPA::clean_username($ucrs);
 4903:     my $access=0;
 4904:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4905: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4906: 	if ($type eq 'user') {
 4907: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4908: 		my ($tdom,$tuname)=split(m{/},$scope);
 4909: 		if ($tdom) {
 4910: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4911: 		}
 4912: 		if ($tuname) {
 4913: 		    if ($tuname ne $env{'user.name'}) { next; }
 4914: 		}
 4915: 		$access=($effect eq 'allow');
 4916: 		last;
 4917: 	    }
 4918: 	} else {
 4919: 	    if ($role) {
 4920: 		if ($role ne $urole) { next; }
 4921: 	    }
 4922: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4923: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4924: 		if ($tdom) {
 4925: 		    if ($tdom ne $udom) { next; }
 4926: 		}
 4927: 		if ($tcrs) {
 4928: 		    if ($tcrs ne $ucrs) { next; }
 4929: 		}
 4930: 		if ($tsec) {
 4931: 		    if ($tsec ne $usec) { next; }
 4932: 		}
 4933: 		$access=($effect eq 'allow');
 4934: 		last;
 4935: 	    }
 4936: 	    if ($realm eq '' && $role eq '') {
 4937: 		$access=($effect eq 'allow');
 4938: 	    }
 4939: 	}
 4940:     }
 4941:     return $access;
 4942: }
 4943: 
 4944: # ------------------------------------------------- Check for a user privilege
 4945: 
 4946: sub allowed {
 4947:     my ($priv,$uri,$symb,$role)=@_;
 4948:     my $ver_orguri=$uri;
 4949:     $uri=&deversion($uri);
 4950:     my $orguri=$uri;
 4951:     $uri=&declutter($uri);
 4952: 
 4953:     if ($priv eq 'evb') {
 4954: # Evade communication block restrictions for specified role in a course
 4955:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4956:             return $1;
 4957:         } else {
 4958:             return;
 4959:         }
 4960:     }
 4961: 
 4962:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4963: # Free bre access to adm and meta resources
 4964:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4965: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4966: 	&& ($priv eq 'bre')) {
 4967: 	return 'F';
 4968:     }
 4969: 
 4970: # Free bre access to user's own portfolio contents
 4971:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4972:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4973: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4974:         my %setters;
 4975:         my ($startblock,$endblock) = 
 4976:             &Apache::loncommon::blockcheck(\%setters,'port');
 4977:         if ($startblock && $endblock) {
 4978:             return 'B';
 4979:         } else {
 4980:             return 'F';
 4981:         }
 4982:     }
 4983: 
 4984: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4985:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4986:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4987:         if (exists($env{'request.course.id'})) {
 4988:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4989:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4990:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4991:                 my $courseprivid=$env{'request.course.id'};
 4992:                 $courseprivid=~s/\_/\//;
 4993:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4994:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4995:                     return $1; 
 4996:                 } else {
 4997:                     if ($env{'request.course.sec'}) {
 4998:                         $courseprivid.='/'.$env{'request.course.sec'};
 4999:                     }
 5000:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5001:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5002:                         return $2;
 5003:                     }
 5004:                 }
 5005:             }
 5006:         }
 5007:     }
 5008: 
 5009: # Free bre to public access
 5010: 
 5011:     if ($priv eq 'bre') {
 5012:         my $copyright=&metadata($uri,'copyright');
 5013: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5014:            return 'F'; 
 5015:         }
 5016:         if ($copyright eq 'priv') {
 5017:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5018: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5019: 		return '';
 5020:             }
 5021:         }
 5022:         if ($copyright eq 'domain') {
 5023:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5024: 	    unless (($env{'user.domain'} eq $1) ||
 5025:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5026: 		return '';
 5027:             }
 5028:         }
 5029:         if ($env{'request.role'}=~ /li\.\//) {
 5030:             # Library role, so allow browsing of resources in this domain.
 5031:             return 'F';
 5032:         }
 5033:         if ($copyright eq 'custom') {
 5034: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5035:         }
 5036:     }
 5037:     # Domain coordinator is trying to create a course
 5038:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5039:         # uri is the requested domain in this case.
 5040:         # comparison to 'request.role.domain' shows if the user has selected
 5041:         # a role of dc for the domain in question.
 5042:         return 'F' if ($uri eq $env{'request.role.domain'});
 5043:     }
 5044: 
 5045:     my $thisallowed='';
 5046:     my $statecond=0;
 5047:     my $courseprivid='';
 5048: 
 5049:     my $ownaccess;
 5050:     # Community Coordinator or Assistant Co-author browsing resource space.
 5051:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5052:         if ($uri eq '') {
 5053:             $ownaccess = 1;
 5054:         } else {
 5055:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5056:                 my $udom = $env{'user.domain'};
 5057:                 my $uname = $env{'user.name'};
 5058:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5059:                     $ownaccess = 1;
 5060:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5061:                     unless ($uri =~ m{\.\./}) {
 5062:                         $ownaccess = 1;
 5063:                     }
 5064:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5065:                     my $now = time;
 5066:                     if ($uri =~ m{^([^/]+)/?$}) {
 5067:                         my $adom = $1;
 5068:                         foreach my $key (keys(%env)) {
 5069:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5070:                                 my ($start,$end) = split('.',$env{$key});
 5071:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5072:                                     $ownaccess = 1;
 5073:                                     last;
 5074:                                 }
 5075:                             }
 5076:                         }
 5077:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5078:                         my $adom = $1;
 5079:                         my $aname = $2;
 5080:                         foreach my $role ('ca','aa') { 
 5081:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5082:                                 my ($start,$end) =
 5083:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5084:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5085:                                     $ownaccess = 1;
 5086:                                     last;
 5087:                                 }
 5088:                             }
 5089:                         }
 5090:                     }
 5091:                 }
 5092:             }
 5093:         }
 5094:     }
 5095: 
 5096: # Course
 5097: 
 5098:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 5099:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5100:             $thisallowed.=$1;
 5101:         }
 5102:     }
 5103: 
 5104: # Domain
 5105: 
 5106:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 5107:        =~/\Q$priv\E\&([^\:]*)/) {
 5108:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5109:             $thisallowed.=$1;
 5110:         }
 5111:     }
 5112: 
 5113: # Course: uri itself is a course
 5114:     my $courseuri=$uri;
 5115:     $courseuri=~s/\_(\d)/\/$1/;
 5116:     $courseuri=~s/^([^\/])/\/$1/;
 5117: 
 5118:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5119:        =~/\Q$priv\E\&([^\:]*)/) {
 5120:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5121:             $thisallowed.=$1;
 5122:         }
 5123:     }
 5124: 
 5125: # URI is an uploaded document for this course, default permissions don't matter
 5126: # not allowing 'edit' access (editupload) to uploaded course docs
 5127:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5128: 	$thisallowed='';
 5129:         my ($match)=&is_on_map($uri);
 5130:         if ($match) {
 5131:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5132:                   =~/\Q$priv\E\&([^\:]*)/) {
 5133:                 $thisallowed.=$1;
 5134:             }
 5135:         } else {
 5136:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5137:             if ($refuri) {
 5138:                 if ($refuri =~ m|^/adm/|) {
 5139:                     $thisallowed='F';
 5140:                 } else {
 5141:                     $refuri=&declutter($refuri);
 5142:                     my ($match) = &is_on_map($refuri);
 5143:                     if ($match) {
 5144:                         $thisallowed='F';
 5145:                     }
 5146:                 }
 5147:             }
 5148:         }
 5149:     }
 5150: 
 5151:     if ($priv eq 'bre'
 5152: 	&& $thisallowed ne 'F' 
 5153: 	&& $thisallowed ne '2'
 5154: 	&& &is_portfolio_url($uri)) {
 5155: 	$thisallowed = &portfolio_access($uri);
 5156:     }
 5157:     
 5158: # Full access at system, domain or course-wide level? Exit.
 5159:     if ($thisallowed=~/F/) {
 5160: 	return 'F';
 5161:     }
 5162: 
 5163: # If this is generating or modifying users, exit with special codes
 5164: 
 5165:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 5166: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 5167: 	    my ($audom,$auname)=split('/',$uri);
 5168: # no author name given, so this just checks on the general right to make a co-author in this domain
 5169: 	    unless ($auname) { return $thisallowed; }
 5170: # an author name is given, so we are about to actually make a co-author for a certain account
 5171: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 5172: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5173: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5174: 	}
 5175: 	return $thisallowed;
 5176:     }
 5177: #
 5178: # Gathered so far: system, domain and course wide privileges
 5179: #
 5180: # Course: See if uri or referer is an individual resource that is part of 
 5181: # the course
 5182: 
 5183:     if ($env{'request.course.id'}) {
 5184: 
 5185:        $courseprivid=$env{'request.course.id'};
 5186:        if ($env{'request.course.sec'}) {
 5187:           $courseprivid.='/'.$env{'request.course.sec'};
 5188:        }
 5189:        $courseprivid=~s/\_/\//;
 5190:        my $checkreferer=1;
 5191:        my ($match,$cond)=&is_on_map($uri);
 5192:        if ($match) {
 5193:            $statecond=$cond;
 5194:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5195:                =~/\Q$priv\E\&([^\:]*)/) {
 5196:                $thisallowed.=$1;
 5197:                $checkreferer=0;
 5198:            }
 5199:        }
 5200:        
 5201:        if ($checkreferer) {
 5202: 	  my $refuri=$env{'httpref.'.$orguri};
 5203:             unless ($refuri) {
 5204:                 foreach my $key (keys(%env)) {
 5205: 		    if ($key=~/^httpref\..*\*/) {
 5206: 			my $pattern=$key;
 5207:                         $pattern=~s/^httpref\.\/res\///;
 5208:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5209:                         $pattern=~s/\//\\\//g;
 5210:                         if ($orguri=~/$pattern/) {
 5211: 			    $refuri=$env{$key};
 5212:                         }
 5213:                     }
 5214:                 }
 5215:             }
 5216: 
 5217:          if ($refuri) { 
 5218: 	  $refuri=&declutter($refuri);
 5219:           my ($match,$cond)=&is_on_map($refuri);
 5220:             if ($match) {
 5221:               my $refstatecond=$cond;
 5222:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5223:                   =~/\Q$priv\E\&([^\:]*)/) {
 5224:                   $thisallowed.=$1;
 5225:                   $uri=$refuri;
 5226:                   $statecond=$refstatecond;
 5227:               }
 5228:           }
 5229:         }
 5230:        }
 5231:    }
 5232: 
 5233: #
 5234: # Gathered now: all privileges that could apply, and condition number
 5235: # 
 5236: #
 5237: # Full or no access?
 5238: #
 5239: 
 5240:     if ($thisallowed=~/F/) {
 5241: 	return 'F';
 5242:     }
 5243: 
 5244:     unless ($thisallowed) {
 5245:         return '';
 5246:     }
 5247: 
 5248: # Restrictions exist, deal with them
 5249: #
 5250: #   C:according to course preferences
 5251: #   R:according to resource settings
 5252: #   L:unless locked
 5253: #   X:according to user session state
 5254: #
 5255: 
 5256: # Possibly locked functionality, check all courses
 5257: # Locks might take effect only after 10 minutes cache expiration for other
 5258: # courses, and 2 minutes for current course
 5259: 
 5260:     my $envkey;
 5261:     if ($thisallowed=~/L/) {
 5262:         foreach $envkey (keys(%env)) {
 5263:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5264:                my $courseid=$2;
 5265:                my $roleid=$1.'.'.$2;
 5266:                $courseid=~s/^\///;
 5267:                my $expiretime=600;
 5268:                if ($env{'request.role'} eq $roleid) {
 5269: 		  $expiretime=120;
 5270:                }
 5271: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5272:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5273:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5274: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5275:                }
 5276:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5277:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5278: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5279:                        &log($env{'user.domain'},$env{'user.name'},
 5280:                             $env{'user.home'},
 5281:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5282:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5283:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5284: 		       return '';
 5285:                    }
 5286:                }
 5287:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5288:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5289: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5290:                        &log($env{'user.domain'},$env{'user.name'},
 5291:                             $env{'user.home'},
 5292:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5293:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5294:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5295: 		       return '';
 5296:                    }
 5297:                }
 5298: 	   }
 5299:        }
 5300:     }
 5301:    
 5302: #
 5303: # Rest of the restrictions depend on selected course
 5304: #
 5305: 
 5306:     unless ($env{'request.course.id'}) {
 5307: 	if ($thisallowed eq 'A') {
 5308: 	    return 'A';
 5309:         } elsif ($thisallowed eq 'B') {
 5310:             return 'B';
 5311: 	} else {
 5312: 	    return '1';
 5313: 	}
 5314:     }
 5315: 
 5316: #
 5317: # Now user is definitely in a course
 5318: #
 5319: 
 5320: 
 5321: # Course preferences
 5322: 
 5323:    if ($thisallowed=~/C/) {
 5324:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5325:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5326:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5327: 	   =~/\Q$rolecode\E/) {
 5328: 	   if ($priv ne 'pch') { 
 5329: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5330: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5331: 			$env{'request.course.id'});
 5332: 	   }
 5333:            return '';
 5334:        }
 5335: 
 5336:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5337: 	   =~/\Q$unamedom\E/) {
 5338: 	   if ($priv ne 'pch') { 
 5339: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5340: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5341: 			$env{'request.course.id'});
 5342: 	   }
 5343:            return '';
 5344:        }
 5345:    }
 5346: 
 5347: # Resource preferences
 5348: 
 5349:    if ($thisallowed=~/R/) {
 5350:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5351:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5352: 	   if ($priv ne 'pch') { 
 5353: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5354: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5355: 	   }
 5356: 	   return '';
 5357:        }
 5358:    }
 5359: 
 5360: # Restricted by state or randomout?
 5361: 
 5362:    if ($thisallowed=~/X/) {
 5363:       if ($env{'acc.randomout'}) {
 5364: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5365:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5366:             return ''; 
 5367:          }
 5368:       }
 5369:       if (&condval($statecond)) {
 5370: 	 return '2';
 5371:       } else {
 5372:          return '';
 5373:       }
 5374:    }
 5375: 
 5376:     if ($thisallowed eq 'A') {
 5377: 	return 'A';
 5378:     } elsif ($thisallowed eq 'B') {
 5379:         return 'B';
 5380:     }
 5381:    return 'F';
 5382: }
 5383: 
 5384: sub split_uri_for_cond {
 5385:     my $uri=&deversion(&declutter(shift));
 5386:     my @uriparts=split(/\//,$uri);
 5387:     my $filename=pop(@uriparts);
 5388:     my $pathname=join('/',@uriparts);
 5389:     return ($pathname,$filename);
 5390: }
 5391: # --------------------------------------------------- Is a resource on the map?
 5392: 
 5393: sub is_on_map {
 5394:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5395:     #Trying to find the conditional for the file
 5396:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5397: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5398:     if ($match) {
 5399: 	return (1,$1);
 5400:     } else {
 5401: 	return (0,0);
 5402:     }
 5403: }
 5404: 
 5405: # --------------------------------------------------------- Get symb from alias
 5406: 
 5407: sub get_symb_from_alias {
 5408:     my $symb=shift;
 5409:     my ($map,$resid,$url)=&decode_symb($symb);
 5410: # Already is a symb
 5411:     if ($url) { return $symb; }
 5412: # Must be an alias
 5413:     my $aliassymb='';
 5414:     my %bighash;
 5415:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5416:                             &GDBM_READER(),0640)) {
 5417:         my $rid=$bighash{'mapalias_'.$symb};
 5418: 	if ($rid) {
 5419: 	    my ($mapid,$resid)=split(/\./,$rid);
 5420: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5421: 				    $resid,$bighash{'src_'.$rid});
 5422: 	}
 5423:         untie %bighash;
 5424:     }
 5425:     return $aliassymb;
 5426: }
 5427: 
 5428: # ----------------------------------------------------------------- Define Role
 5429: 
 5430: sub definerole {
 5431:   if (allowed('mcr','/')) {
 5432:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5433:     foreach my $role (split(':',$sysrole)) {
 5434: 	my ($crole,$cqual)=split(/\&/,$role);
 5435:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5436:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5437: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5438:                return "refused:s:$crole&$cqual"; 
 5439:             }
 5440:         }
 5441:     }
 5442:     foreach my $role (split(':',$domrole)) {
 5443: 	my ($crole,$cqual)=split(/\&/,$role);
 5444:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5445:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5446: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5447:                return "refused:d:$crole&$cqual"; 
 5448:             }
 5449:         }
 5450:     }
 5451:     foreach my $role (split(':',$courole)) {
 5452: 	my ($crole,$cqual)=split(/\&/,$role);
 5453:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5454:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5455: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5456:                return "refused:c:$crole&$cqual"; 
 5457:             }
 5458:         }
 5459:     }
 5460:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5461:                 "$env{'user.domain'}:$env{'user.name'}:".
 5462: 	        "rolesdef_$rolename=".
 5463:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5464:     return reply($command,$env{'user.home'});
 5465:   } else {
 5466:     return 'refused';
 5467:   }
 5468: }
 5469: 
 5470: # ---------------- Make a metadata query against the network of library servers
 5471: 
 5472: sub metadata_query {
 5473:     my ($query,$custom,$customshow,$server_array)=@_;
 5474:     my %rhash;
 5475:     my %libserv = &all_library();
 5476:     my @server_list = (defined($server_array) ? @$server_array
 5477:                                               : keys(%libserv) );
 5478:     for my $server (@server_list) {
 5479: 	unless ($custom or $customshow) {
 5480: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5481: 	    $rhash{$server}=$reply;
 5482: 	}
 5483: 	else {
 5484: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5485: 			     &escape($custom).':'.&escape($customshow),
 5486: 			     $server);
 5487: 	    $rhash{$server}=$reply;
 5488: 	}
 5489:     }
 5490:     return \%rhash;
 5491: }
 5492: 
 5493: # ----------------------------------------- Send log queries and wait for reply
 5494: 
 5495: sub log_query {
 5496:     my ($uname,$udom,$query,%filters)=@_;
 5497:     my $uhome=&homeserver($uname,$udom);
 5498:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5499:     my $uhost=&hostname($uhome);
 5500:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5501:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5502:                        $uhome);
 5503:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5504:     return get_query_reply($queryid);
 5505: }
 5506: 
 5507: # -------------------------- Update MySQL table for portfolio file
 5508: 
 5509: sub update_portfolio_table {
 5510:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5511:     if ($group ne '') {
 5512:         $file_name =~s /^\Q$group\E//;
 5513:     }
 5514:     my $homeserver = &homeserver($uname,$udom);
 5515:     my $queryid=
 5516:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5517:                ':'.&escape($file_name).':'.$action,$homeserver);
 5518:     my $reply = &get_query_reply($queryid);
 5519:     return $reply;
 5520: }
 5521: 
 5522: # -------------------------- Update MySQL allusers table
 5523: 
 5524: sub update_allusers_table {
 5525:     my ($uname,$udom,$names) = @_;
 5526:     my $homeserver = &homeserver($uname,$udom);
 5527:     my $queryid=
 5528:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5529:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5530:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5531:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5532:                'generation='.&escape($names->{'generation'}).'%%'.
 5533:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5534:                'id='.&escape($names->{'id'}),$homeserver);
 5535:     my $reply = &get_query_reply($queryid);
 5536:     return $reply;
 5537: }
 5538: 
 5539: # ------- Request retrieval of institutional classlists for course(s)
 5540: 
 5541: sub fetch_enrollment_query {
 5542:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5543:     my $homeserver;
 5544:     my $maxtries = 1;
 5545:     if ($context eq 'automated') {
 5546:         $homeserver = $perlvar{'lonHostID'};
 5547:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5548:     } else {
 5549:         $homeserver = &homeserver($cnum,$dom);
 5550:     }
 5551:     my $host=&hostname($homeserver);
 5552:     my $cmd = '';
 5553:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5554:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5555:     }
 5556:     $cmd =~ s/%%$//;
 5557:     $cmd = &escape($cmd);
 5558:     my $query = 'fetchenrollment';
 5559:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5560:     unless ($queryid=~/^\Q$host\E\_/) { 
 5561:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5562:         return 'error: '.$queryid;
 5563:     }
 5564:     my $reply = &get_query_reply($queryid);
 5565:     my $tries = 1;
 5566:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5567:         $reply = &get_query_reply($queryid);
 5568:         $tries ++;
 5569:     }
 5570:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5571:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5572:     } else {
 5573:         my @responses = split(/:/,$reply);
 5574:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5575:             foreach my $line (@responses) {
 5576:                 my ($key,$value) = split(/=/,$line,2);
 5577:                 $$replyref{$key} = $value;
 5578:             }
 5579:         } else {
 5580:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5581:             foreach my $line (@responses) {
 5582:                 my ($key,$value) = split(/=/,$line);
 5583:                 $$replyref{$key} = $value;
 5584:                 if ($value > 0) {
 5585:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5586:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5587:                         my $destname = $pathname.'/'.$filename;
 5588:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5589:                         if ($xml_classlist =~ /^error/) {
 5590:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5591:                         } else {
 5592:                             if ( open(FILE,">$destname") ) {
 5593:                                 print FILE &unescape($xml_classlist);
 5594:                                 close(FILE);
 5595:                             } else {
 5596:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5597:                             }
 5598:                         }
 5599:                     }
 5600:                 }
 5601:             }
 5602:         }
 5603:         return 'ok';
 5604:     }
 5605:     return 'error';
 5606: }
 5607: 
 5608: sub get_query_reply {
 5609:     my $queryid=shift;
 5610:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5611:     my $reply='';
 5612:     for (1..100) {
 5613: 	sleep 2;
 5614:         if (-e $replyfile.'.end') {
 5615: 	    if (open(my $fh,$replyfile)) {
 5616: 		$reply = join('',<$fh>);
 5617: 		close($fh);
 5618: 	   } else { return 'error: reply_file_error'; }
 5619:            return &unescape($reply);
 5620: 	}
 5621:     }
 5622:     return 'timeout:'.$queryid;
 5623: }
 5624: 
 5625: sub courselog_query {
 5626: #
 5627: # possible filters:
 5628: # url: url or symb
 5629: # username
 5630: # domain
 5631: # action: view, submit, grade
 5632: # start: timestamp
 5633: # end: timestamp
 5634: #
 5635:     my (%filters)=@_;
 5636:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5637:     if ($filters{'url'}) {
 5638: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5639:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5640:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5641:     }
 5642:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5643:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5644:     return &log_query($cname,$cdom,'courselog',%filters);
 5645: }
 5646: 
 5647: sub userlog_query {
 5648: #
 5649: # possible filters:
 5650: # action: log check role
 5651: # start: timestamp
 5652: # end: timestamp
 5653: #
 5654:     my ($uname,$udom,%filters)=@_;
 5655:     return &log_query($uname,$udom,'userlog',%filters);
 5656: }
 5657: 
 5658: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5659: 
 5660: sub auto_run {
 5661:     my ($cnum,$cdom) = @_;
 5662:     my $response = 0;
 5663:     my $settings;
 5664:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5665:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5666:         $settings = $domconfig{'autoenroll'};
 5667:         if ($settings->{'run'} eq '1') {
 5668:             $response = 1;
 5669:         }
 5670:     } else {
 5671:         my $homeserver;
 5672:         if (&is_course($cdom,$cnum)) {
 5673:             $homeserver = &homeserver($cnum,$cdom);
 5674:         } else {
 5675:             $homeserver = &domain($cdom,'primary');
 5676:         }
 5677:         if ($homeserver ne 'no_host') {
 5678:             $response = &reply('autorun:'.$cdom,$homeserver);
 5679:         }
 5680:     }
 5681:     return $response;
 5682: }
 5683: 
 5684: sub auto_get_sections {
 5685:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5686:     my $homeserver;
 5687:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 5688:         $homeserver = &homeserver($cnum,$cdom);
 5689:     }
 5690:     if (!defined($homeserver)) { 
 5691:         if ($cdom =~ /^$match_domain$/) {
 5692:             $homeserver = &domain($cdom,'primary');
 5693:         }
 5694:     }
 5695:     my @secs;
 5696:     if (defined($homeserver)) {
 5697:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5698:         unless ($response eq 'refused') {
 5699:             @secs = split(/:/,$response);
 5700:         }
 5701:     }
 5702:     return @secs;
 5703: }
 5704: 
 5705: sub auto_new_course {
 5706:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5707:     my $homeserver = &homeserver($cnum,$cdom);
 5708:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5709:     return $response;
 5710: }
 5711: 
 5712: sub auto_validate_courseID {
 5713:     my ($cnum,$cdom,$inst_course_id) = @_;
 5714:     my $homeserver = &homeserver($cnum,$cdom);
 5715:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5716:     return $response;
 5717: }
 5718: 
 5719: sub auto_validate_instcode {
 5720:     my ($cnum,$cdom,$instcode,$owner) = @_;
 5721:     my ($homeserver,$response);
 5722:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5723:         $homeserver = &homeserver($cnum,$cdom);
 5724:     }
 5725:     if (!defined($homeserver)) {
 5726:         if ($cdom =~ /^$match_domain$/) {
 5727:             $homeserver = &domain($cdom,'primary');
 5728:         }
 5729:     }
 5730:     my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 5731:                            &escape($instcode).':'.&escape($owner),$homeserver));
 5732:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 5733:     return ($outcome,$description);
 5734: }
 5735: 
 5736: sub auto_create_password {
 5737:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5738:     my ($homeserver,$response);
 5739:     my $create_passwd = 0;
 5740:     my $authchk = '';
 5741:     if ($udom =~ /^$match_domain$/) {
 5742:         $homeserver = &domain($udom,'primary');
 5743:     }
 5744:     if ($homeserver eq '') {
 5745:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5746:             $homeserver = &homeserver($cnum,$cdom);
 5747:         }
 5748:     }
 5749:     if ($homeserver eq '') {
 5750:         $authchk = 'nodomain';
 5751:     } else {
 5752:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5753:         if ($response eq 'refused') {
 5754:             $authchk = 'refused';
 5755:         } else {
 5756:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5757:         }
 5758:     }
 5759:     return ($authparam,$create_passwd,$authchk);
 5760: }
 5761: 
 5762: sub auto_photo_permission {
 5763:     my ($cnum,$cdom,$students) = @_;
 5764:     my $homeserver = &homeserver($cnum,$cdom);
 5765:     my ($outcome,$perm_reqd,$conditions) = 
 5766: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5767:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5768: 	return (undef,undef);
 5769:     }
 5770:     return ($outcome,$perm_reqd,$conditions);
 5771: }
 5772: 
 5773: sub auto_checkphotos {
 5774:     my ($uname,$udom,$pid) = @_;
 5775:     my $homeserver = &homeserver($uname,$udom);
 5776:     my ($result,$resulttype);
 5777:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5778: 				   &escape($uname).':'.&escape($pid),
 5779: 				   $homeserver));
 5780:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5781: 	return (undef,undef);
 5782:     }
 5783:     if ($outcome) {
 5784:         ($result,$resulttype) = split(/:/,$outcome);
 5785:     } 
 5786:     return ($result,$resulttype);
 5787: }
 5788: 
 5789: sub auto_photochoice {
 5790:     my ($cnum,$cdom) = @_;
 5791:     my $homeserver = &homeserver($cnum,$cdom);
 5792:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5793: 						       &escape($cdom),
 5794: 						       $homeserver)));
 5795:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5796: 	return (undef,undef);
 5797:     }
 5798:     return ($update,$comment);
 5799: }
 5800: 
 5801: sub auto_photoupdate {
 5802:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5803:     my $homeserver = &homeserver($cnum,$dom);
 5804:     my $host=&hostname($homeserver);
 5805:     my $cmd = '';
 5806:     my $maxtries = 1;
 5807:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5808:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5809:     }
 5810:     $cmd =~ s/%%$//;
 5811:     $cmd = &escape($cmd);
 5812:     my $query = 'institutionalphotos';
 5813:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5814:     unless ($queryid=~/^\Q$host\E\_/) {
 5815:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5816:         return 'error: '.$queryid;
 5817:     }
 5818:     my $reply = &get_query_reply($queryid);
 5819:     my $tries = 1;
 5820:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5821:         $reply = &get_query_reply($queryid);
 5822:         $tries ++;
 5823:     }
 5824:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5825:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5826:     } else {
 5827:         my @responses = split(/:/,$reply);
 5828:         my $outcome = shift(@responses); 
 5829:         foreach my $item (@responses) {
 5830:             my ($key,$value) = split(/=/,$item);
 5831:             $$photo{$key} = $value;
 5832:         }
 5833:         return $outcome;
 5834:     }
 5835:     return 'error';
 5836: }
 5837: 
 5838: sub auto_instcode_format {
 5839:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5840: 	$cat_order) = @_;
 5841:     my $courses = '';
 5842:     my @homeservers;
 5843:     if ($caller eq 'global') {
 5844: 	my %servers = &get_servers($codedom,'library');
 5845: 	foreach my $tryserver (keys(%servers)) {
 5846: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5847: 		push(@homeservers,$tryserver);
 5848: 	    }
 5849:         }
 5850:     } elsif ($caller eq 'requests') {
 5851:         if ($codedom =~ /^$match_domain$/) {
 5852:             my $chome = &domain($codedom,'primary');
 5853:             unless ($chome eq 'no_host') {
 5854:                 push(@homeservers,$chome);
 5855:             }
 5856:         }
 5857:     } else {
 5858:         push(@homeservers,&homeserver($caller,$codedom));
 5859:     }
 5860:     foreach my $code (keys(%{$instcodes})) {
 5861:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5862:     }
 5863:     chop($courses);
 5864:     my $ok_response = 0;
 5865:     my $response;
 5866:     while (@homeservers > 0 && $ok_response == 0) {
 5867:         my $server = shift(@homeservers); 
 5868:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5869:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5870:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5871: 		split(/:/,$response);
 5872:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5873:             push(@{$codetitles},&str2array($codetitles_str));
 5874:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5875:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5876:             $ok_response = 1;
 5877:         }
 5878:     }
 5879:     if ($ok_response) {
 5880:         return 'ok';
 5881:     } else {
 5882:         return $response;
 5883:     }
 5884: }
 5885: 
 5886: sub auto_instcode_defaults {
 5887:     my ($domain,$returnhash,$code_order) = @_;
 5888:     my @homeservers;
 5889: 
 5890:     my %servers = &get_servers($domain,'library');
 5891:     foreach my $tryserver (keys(%servers)) {
 5892: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5893: 	    push(@homeservers,$tryserver);
 5894: 	}
 5895:     }
 5896: 
 5897:     my $response;
 5898:     foreach my $server (@homeservers) {
 5899:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5900:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5901: 	
 5902: 	foreach my $pair (split(/\&/,$response)) {
 5903: 	    my ($name,$value)=split(/\=/,$pair);
 5904: 	    if ($name eq 'code_order') {
 5905: 		@{$code_order} = split(/\&/,&unescape($value));
 5906: 	    } else {
 5907: 		$returnhash->{&unescape($name)}=&unescape($value);
 5908: 	    }
 5909: 	}
 5910: 	return 'ok';
 5911:     }
 5912: 
 5913:     return $response;
 5914: }
 5915: 
 5916: sub auto_possible_instcodes {
 5917:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 5918:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 5919:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 5920:         return;
 5921:     }
 5922:     my (@homeservers,$uhome);
 5923:     if (defined(&domain($domain,'primary'))) {
 5924:         $uhome=&domain($domain,'primary');
 5925:         push(@homeservers,&domain($domain,'primary'));
 5926:     } else {
 5927:         my %servers = &get_servers($domain,'library');
 5928:         foreach my $tryserver (keys(%servers)) {
 5929:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5930:                 push(@homeservers,$tryserver);
 5931:             }
 5932:         }
 5933:     }
 5934:     my $response;
 5935:     foreach my $server (@homeservers) {
 5936:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 5937:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5938:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 5939:             split(':',$response);
 5940:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 5941:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 5942:         foreach my $item (split('&',$cat_title)) {   
 5943:             my ($name,$value)=split('=',$item);
 5944:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 5945:         }
 5946:         foreach my $item (split('&',$cat_order)) {
 5947:             my ($name,$value)=split('=',$item);
 5948:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 5949:         }
 5950:         return 'ok';
 5951:     }
 5952:     return $response;
 5953: }
 5954: 
 5955: sub auto_courserequest_checks {
 5956:     my ($dom) = @_;
 5957:     my ($homeserver,%validations);
 5958:     if ($dom =~ /^$match_domain$/) {
 5959:         $homeserver = &domain($dom,'primary');
 5960:     }
 5961:     unless ($homeserver eq 'no_host') {
 5962:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 5963:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 5964:             my @items = split(/&/,$response);
 5965:             foreach my $item (@items) {
 5966:                 my ($key,$value) = split('=',$item);
 5967:                 $validations{&unescape($key)} = &thaw_unescape($value);
 5968:             }
 5969:         }
 5970:     }
 5971:     return %validations; 
 5972: }
 5973: 
 5974: sub auto_courserequest_validation {
 5975:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 5976:     my ($homeserver,$response);
 5977:     if ($dom =~ /^$match_domain$/) {
 5978:         $homeserver = &domain($dom,'primary');
 5979:     }
 5980:     unless ($homeserver eq 'no_host') {  
 5981:           
 5982:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 5983:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 5984:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 5985:                                     $homeserver));
 5986:     }
 5987:     return $response;
 5988: }
 5989: 
 5990: sub auto_validate_class_sec {
 5991:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5992:     my $homeserver = &homeserver($cnum,$cdom);
 5993:     my $ownerlist;
 5994:     if (ref($owners) eq 'ARRAY') {
 5995:         $ownerlist = join(',',@{$owners});
 5996:     } else {
 5997:         $ownerlist = $owners;
 5998:     }
 5999:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 6000:                         &escape($ownerlist).':'.$cdom,$homeserver);
 6001:     return $response;
 6002: }
 6003: 
 6004: # ------------------------------------------------------- Course Group routines
 6005: 
 6006: sub get_coursegroups {
 6007:     my ($cdom,$cnum,$group,$namespace) = @_;
 6008:     return(&dump($namespace,$cdom,$cnum,$group));
 6009: }
 6010: 
 6011: sub modify_coursegroup {
 6012:     my ($cdom,$cnum,$groupsettings) = @_;
 6013:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 6014: }
 6015: 
 6016: sub toggle_coursegroup_status {
 6017:     my ($cdom,$cnum,$group,$action) = @_;
 6018:     my ($from_namespace,$to_namespace);
 6019:     if ($action eq 'delete') {
 6020:         $from_namespace = 'coursegroups';
 6021:         $to_namespace = 'deleted_groups';
 6022:     } else {
 6023:         $from_namespace = 'deleted_groups';
 6024:         $to_namespace = 'coursegroups';
 6025:     }
 6026:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 6027:     if (my $tmp = &error(%curr_group)) {
 6028:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 6029:         return ('read error',$tmp);
 6030:     } else {
 6031:         my %savedsettings = %curr_group; 
 6032:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 6033:         my $deloutcome;
 6034:         if ($result eq 'ok') {
 6035:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 6036:         } else {
 6037:             return ('write error',$result);
 6038:         }
 6039:         if ($deloutcome eq 'ok') {
 6040:             return 'ok';
 6041:         } else {
 6042:             return ('delete error',$deloutcome);
 6043:         }
 6044:     }
 6045: }
 6046: 
 6047: sub modify_group_roles {
 6048:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 6049:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 6050:     my $role = 'gr/'.&escape($userprivs);
 6051:     my ($uname,$udom) = split(/:/,$user);
 6052:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 6053:     if ($result eq 'ok') {
 6054:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 6055:     }
 6056:     return $result;
 6057: }
 6058: 
 6059: sub modify_coursegroup_membership {
 6060:     my ($cdom,$cnum,$membership) = @_;
 6061:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 6062:     return $result;
 6063: }
 6064: 
 6065: sub get_active_groups {
 6066:     my ($udom,$uname,$cdom,$cnum) = @_;
 6067:     my $now = time;
 6068:     my %groups = ();
 6069:     foreach my $key (keys(%env)) {
 6070:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 6071:             my ($start,$end) = split(/\./,$env{$key});
 6072:             if (($end!=0) && ($end<$now)) { next; }
 6073:             if (($start!=0) && ($start>$now)) { next; }
 6074:             if ($1 eq $cdom && $2 eq $cnum) {
 6075:                 $groups{$3} = $env{$key} ;
 6076:             }
 6077:         }
 6078:     }
 6079:     return %groups;
 6080: }
 6081: 
 6082: sub get_group_membership {
 6083:     my ($cdom,$cnum,$group) = @_;
 6084:     return(&dump('groupmembership',$cdom,$cnum,$group));
 6085: }
 6086: 
 6087: sub get_users_groups {
 6088:     my ($udom,$uname,$courseid) = @_;
 6089:     my @usersgroups;
 6090:     my $cachetime=1800;
 6091: 
 6092:     my $hashid="$udom:$uname:$courseid";
 6093:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 6094:     if (defined($cached)) {
 6095:         @usersgroups = split(/:/,$grouplist);
 6096:     } else {  
 6097:         $grouplist = '';
 6098:         my $courseurl = &courseid_to_courseurl($courseid);
 6099:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 6100:         my $access_end = $env{'course.'.$courseid.
 6101:                               '.default_enrollment_end_date'};
 6102:         my $now = time;
 6103:         foreach my $key (keys(%roleshash)) {
 6104:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 6105:                 my $group = $1;
 6106:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 6107:                     my $start = $2;
 6108:                     my $end = $1;
 6109:                     if ($start == -1) { next; } # deleted from group
 6110:                     if (($start!=0) && ($start>$now)) { next; }
 6111:                     if (($end!=0) && ($end<$now)) {
 6112:                         if ($access_end && $access_end < $now) {
 6113:                             if ($access_end - $end < 86400) {
 6114:                                 push(@usersgroups,$group);
 6115:                             }
 6116:                         }
 6117:                         next;
 6118:                     }
 6119:                     push(@usersgroups,$group);
 6120:                 }
 6121:             }
 6122:         }
 6123:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 6124:         $grouplist = join(':',@usersgroups);
 6125:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6126:     }
 6127:     return @usersgroups;
 6128: }
 6129: 
 6130: sub devalidate_getgroups_cache {
 6131:     my ($udom,$uname,$cdom,$cnum)=@_;
 6132:     my $courseid = $cdom.'_'.$cnum;
 6133: 
 6134:     my $hashid="$udom:$uname:$courseid";
 6135:     &devalidate_cache_new('getgroups',$hashid);
 6136: }
 6137: 
 6138: # ------------------------------------------------------------------ Plain Text
 6139: 
 6140: sub plaintext {
 6141:     my ($short,$type,$cid,$forcedefault) = @_;
 6142:     if ($short =~ m{^cr/}) {
 6143: 	return (split('/',$short))[-1];
 6144:     }
 6145:     if (!defined($cid)) {
 6146:         $cid = $env{'request.course.id'};
 6147:     }
 6148:     my %rolenames = (
 6149:                       Course    => 'std',
 6150:                       Community => 'alt1',
 6151:                     );
 6152:     if ($cid ne '') {
 6153:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 6154:             unless ($forcedefault) {
 6155:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 6156:                 &Apache::lonlocal::mt_escape(\$roletext);
 6157:                 return &Apache::lonlocal::mt($roletext);
 6158:             }
 6159:         }
 6160:     }
 6161:     if ((defined($type)) && (defined($rolenames{$type})) &&
 6162:         (defined($rolenames{$type})) && 
 6163:         (defined($prp{$short}{$rolenames{$type}}))) {
 6164:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 6165:     } elsif ($cid ne '') {
 6166:         my $crstype = $env{'course.'.$cid.'.type'};
 6167:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 6168:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 6169:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 6170:         }
 6171:     }
 6172:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 6173: }
 6174: 
 6175: # ----------------------------------------------------------------- Assign Role
 6176: 
 6177: sub assignrole {
 6178:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 6179:         $context)=@_;
 6180:     my $mrole;
 6181:     if ($role =~ /^cr\//) {
 6182:         my $cwosec=$url;
 6183:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6184: 	unless (&allowed('ccr',$cwosec)) {
 6185:            my $refused = 1;
 6186:            if ($context eq 'requestcourses') {
 6187:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 6188:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 6189:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 6190:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6191:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6192:                            if ($crsenv{'internal.courseowner'} eq
 6193:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 6194:                                $refused = '';
 6195:                            }
 6196:                        }
 6197:                    }
 6198:                }
 6199:            }
 6200:            if ($refused) {
 6201:                &logthis('Refused custom assignrole: '.
 6202:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 6203:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 6204:                return 'refused';
 6205:            }
 6206:         }
 6207:         $mrole='cr';
 6208:     } elsif ($role =~ /^gr\//) {
 6209:         my $cwogrp=$url;
 6210:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 6211:         unless (&allowed('mdg',$cwogrp)) {
 6212:             &logthis('Refused group assignrole: '.
 6213:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 6214:                     $env{'user.name'}.' at '.$env{'user.domain'});
 6215:             return 'refused';
 6216:         }
 6217:         $mrole='gr';
 6218:     } else {
 6219:         my $cwosec=$url;
 6220:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6221:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 6222:             my $refused;
 6223:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 6224:                 if (!(&allowed('c'.$role,$url))) {
 6225:                     $refused = 1;
 6226:                 }
 6227:             } else {
 6228:                 $refused = 1;
 6229:             }
 6230:             if ($refused) {
 6231:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6232:                 if (!$selfenroll && $context eq 'course') {
 6233:                     my %crsenv;
 6234:                     if ($role eq 'cc' || $role eq 'co') {
 6235:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6236:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 6237: 
 6238:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 6239:                                 if ($crsenv{'internal.courseowner'} eq 
 6240:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 6241:                                     $refused = '';
 6242:                                 }
 6243:                             }
 6244:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 6245:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 6246:                                 if ($crsenv{'internal.courseowner'} eq 
 6247:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 6248:                                     $refused = '';
 6249:                                 }
 6250:                             }
 6251:                         }
 6252:                     }
 6253:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6254:                     $refused = '';
 6255:                 } elsif ($context eq 'requestcourses') {
 6256:                     my @possroles = ('st','ta','ep','in','cc','co');
 6257:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 6258:                         my $wrongcc;
 6259:                         if ($cnum =~ /^$match_community$/) {
 6260:                             $wrongcc = 1 if ($role eq 'cc');
 6261:                         } else {
 6262:                             $wrongcc = 1 if ($role eq 'co');
 6263:                         }
 6264:                         unless ($wrongcc) {
 6265:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6266:                             if ($crsenv{'internal.courseowner'} eq 
 6267:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 6268:                                 $refused = '';
 6269:                             }
 6270:                         }
 6271:                     }
 6272:                 }
 6273:                 if ($refused) {
 6274:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 6275:                              ' '.$role.' '.$end.' '.$start.' by '.
 6276: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 6277:                     return 'refused';
 6278:                 }
 6279:             }
 6280:         }
 6281:         $mrole=$role;
 6282:     }
 6283:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6284:                 "$udom:$uname:$url".'_'."$mrole=$role";
 6285:     if ($end) { $command.='_'.$end; }
 6286:     if ($start) {
 6287: 	if ($end) { 
 6288:            $command.='_'.$start; 
 6289:         } else {
 6290:            $command.='_0_'.$start;
 6291:         }
 6292:     }
 6293:     my $origstart = $start;
 6294:     my $origend = $end;
 6295:     my $delflag;
 6296: # actually delete
 6297:     if ($deleteflag) {
 6298: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 6299: # modify command to delete the role
 6300:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 6301:                 "$udom:$uname:$url".'_'."$mrole";
 6302: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 6303: # set start and finish to negative values for userrolelog
 6304:            $start=-1;
 6305:            $end=-1;
 6306:            $delflag = 1;
 6307:         }
 6308:     }
 6309: # send command
 6310:     my $answer=&reply($command,&homeserver($uname,$udom));
 6311: # log new user role if status is ok
 6312:     if ($answer eq 'ok') {
 6313: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 6314: # for course roles, perform group memberships changes triggered by role change.
 6315:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 6316:         unless ($role =~ /^gr/) {
 6317:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 6318:                                              $origstart,$selfenroll,$context);
 6319:         }
 6320:         if ($role eq 'cc') {
 6321:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 6322:         }
 6323:     }
 6324:     return $answer;
 6325: }
 6326: 
 6327: sub autoupdate_coowners {
 6328:     my ($url,$end,$start,$uname,$udom) = @_;
 6329:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 6330:     if (($cdom ne '') && ($cnum ne '')) {
 6331:         my $now = time;
 6332:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 6333:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 6334:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 6335:             my $instcode = $coursehash{'internal.coursecode'};
 6336:             if ($instcode ne '') {
 6337:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 6338:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 6339:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 6340:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 6341:                         if ($result eq 'valid') {
 6342:                             if ($coursehash{'internal.co-owners'}) {
 6343:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 6344:                                     push(@newcoowners,$coowner);
 6345:                                 }
 6346:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 6347:                                     push(@newcoowners,$uname.':'.$udom);
 6348:                                 }
 6349:                                 @newcoowners = sort(@newcoowners);
 6350:                             } else {
 6351:                                 push(@newcoowners,$uname.':'.$udom);
 6352:                             }
 6353:                         } else {
 6354:                             if ($coursehash{'internal.co-owners'}) {
 6355:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 6356:                                     unless ($coowner eq $uname.':'.$udom) {
 6357:                                         push(@newcoowners,$coowner);
 6358:                                     }
 6359:                                 }
 6360:                                 unless (@newcoowners > 0) {
 6361:                                     $delcoowners = 1;
 6362:                                     $coowners = '';
 6363:                                 }
 6364:                             }
 6365:                         }
 6366:                         if (@newcoowners || $delcoowners) {
 6367:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 6368:                                             $delcoowners,@newcoowners);
 6369:                         }
 6370:                     }
 6371:                 }
 6372:             }
 6373:         }
 6374:     }
 6375: }
 6376: 
 6377: sub store_coowners {
 6378:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 6379:     my $cid = $cdom.'_'.$cnum;
 6380:     my ($coowners,$delresult,$putresult);
 6381:     if (@newcoowners) {
 6382:         $coowners = join(',',@newcoowners);
 6383:         my %coownershash = (
 6384:                             'internal.co-owners' => $coowners,
 6385:                            );
 6386:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 6387:         if ($putresult eq 'ok') {
 6388:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 6389:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 6390:             }
 6391:         }
 6392:     }
 6393:     if ($delcoowners) {
 6394:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 6395:         if ($delresult eq 'ok') {
 6396:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 6397:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 6398:             }
 6399:         }
 6400:     }
 6401:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 6402:         my %crsinfo =
 6403:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6404:         if (ref($crsinfo{$cid}) eq 'HASH') {
 6405:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 6406:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 6407:         }
 6408:     }
 6409: }
 6410: 
 6411: # -------------------------------------------------- Modify user authentication
 6412: # Overrides without validation
 6413: 
 6414: sub modifyuserauth {
 6415:     my ($udom,$uname,$umode,$upass)=@_;
 6416:     my $uhome=&homeserver($uname,$udom);
 6417:     unless (&allowed('mau',$udom)) { return 'refused'; }
 6418:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 6419:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6420:              ' in domain '.$env{'request.role.domain'});  
 6421:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 6422: 		     &escape($upass),$uhome);
 6423:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 6424:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 6425:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6426:     &log($udom,,$uname,$uhome,
 6427:         'Authentication changed by '.$env{'user.domain'}.', '.
 6428:                                      $env{'user.name'}.', '.$umode.
 6429:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6430:     unless ($reply eq 'ok') {
 6431:         &logthis('Authentication mode error: '.$reply);
 6432: 	return 'error: '.$reply;
 6433:     }   
 6434:     return 'ok';
 6435: }
 6436: 
 6437: # --------------------------------------------------------------- Modify a user
 6438: 
 6439: sub modifyuser {
 6440:     my ($udom,    $uname, $uid,
 6441:         $umode,   $upass, $first,
 6442:         $middle,  $last,  $gene,
 6443:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 6444:     $udom= &LONCAPA::clean_domain($udom);
 6445:     $uname=&LONCAPA::clean_username($uname);
 6446:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6447:              $umode.', '.$first.', '.$middle.', '.
 6448: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$candelete.')'.
 6449:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6450:                                      ' desiredhome not specified'). 
 6451:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6452:              ' in domain '.$env{'request.role.domain'});
 6453:     my $uhome=&homeserver($uname,$udom,'true');
 6454: # ----------------------------------------------------------------- Create User
 6455:     if (($uhome eq 'no_host') && 
 6456: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6457:         my $unhome='';
 6458:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6459:             $unhome = $desiredhome;
 6460: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6461: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6462:         } else { # load balancing routine for determining $unhome
 6463:             my $loadm=10000000;
 6464: 	    my %servers = &get_servers($udom,'library');
 6465: 	    foreach my $tryserver (keys(%servers)) {
 6466: 		my $answer=reply('load',$tryserver);
 6467: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6468: 		    $loadm=$answer;
 6469: 		    $unhome=$tryserver;
 6470: 		}
 6471: 	    }
 6472:         }
 6473:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6474: 	    return 'error: unable to find a home server for '.$uname.
 6475:                    ' in domain '.$udom;
 6476:         }
 6477:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6478:                          &escape($upass),$unhome);
 6479: 	unless ($reply eq 'ok') {
 6480:             return 'error: '.$reply;
 6481:         }   
 6482:         $uhome=&homeserver($uname,$udom,'true');
 6483:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6484: 	    return 'error: unable verify users home machine.';
 6485:         }
 6486:     }   # End of creation of new user
 6487: # ---------------------------------------------------------------------- Add ID
 6488:     if ($uid) {
 6489:        $uid=~tr/A-Z/a-z/;
 6490:        my %uidhash=&idrget($udom,$uname);
 6491:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6492:          && (!$forceid)) {
 6493: 	  unless ($uid eq $uidhash{$uname}) {
 6494: 	      return 'error: user id "'.$uid.'" does not match '.
 6495:                   'current user id "'.$uidhash{$uname}.'".';
 6496:           }
 6497:        } else {
 6498: 	  &idput($udom,($uname => $uid));
 6499:        }
 6500:     }
 6501: # -------------------------------------------------------------- Add names, etc
 6502:     my @tmp=&get('environment',
 6503: 		   ['firstname','middlename','lastname','generation','id',
 6504:                     'permanentemail','inststatus'],
 6505: 		   $udom,$uname);
 6506:     my %names;
 6507:     if ($tmp[0] =~ m/^error:.*/) { 
 6508:         %names=(); 
 6509:     } else {
 6510:         %names = @tmp;
 6511:     }
 6512: #
 6513: # If name, email and/or uid are blank (e.g., because an uploaded file
 6514: # of users did not contain them), do not overwrite existing values
 6515: # unless field is in $candelete array ref.  
 6516: #
 6517: 
 6518:     my @fields = ('firstname','middlename','lastname','generation',
 6519:                   'permanentemail','id');
 6520:     my %newvalues;
 6521:     if (ref($candelete) eq 'ARRAY') {
 6522:         foreach my $field (@fields) {
 6523:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 6524:                 if ($field eq 'firstname') {
 6525:                     $names{$field} = $first;
 6526:                 } elsif ($field eq 'middlename') {
 6527:                     $names{$field} = $middle;
 6528:                 } elsif ($field eq 'lastname') {
 6529:                     $names{$field} = $last;
 6530:                 } elsif ($field eq 'generation') { 
 6531:                     $names{$field} = $gene;
 6532:                 } elsif ($field eq 'permanentemail') {
 6533:                     $names{$field} = $email;
 6534:                 } elsif ($field eq 'id') {
 6535:                     $names{$field}  = $uid;
 6536:                 }
 6537:             }
 6538:         }
 6539:     }
 6540:     if ($first)  { $names{'firstname'}  = $first; }
 6541:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6542:     if ($last)   { $names{'lastname'}   = $last; }
 6543:     if (defined($gene))   { $names{'generation'} = $gene; }
 6544:     if ($email) {
 6545:        $email=~s/[^\w\@\.\-\,]//gs;
 6546:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6547:     }
 6548:     if ($uid) { $names{'id'}  = $uid; }
 6549:     if (defined($inststatus)) {
 6550:         $names{'inststatus'} = '';
 6551:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6552:         if (ref($usertypes) eq 'HASH') {
 6553:             my @okstatuses; 
 6554:             foreach my $item (split(/:/,$inststatus)) {
 6555:                 if (defined($usertypes->{$item})) {
 6556:                     push(@okstatuses,$item);  
 6557:                 }
 6558:             }
 6559:             if (@okstatuses) {
 6560:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6561:             }
 6562:         }
 6563:     }
 6564:     my $reply = &put('environment', \%names, $udom,$uname);
 6565:     if ($reply ne 'ok') { return 'error: '.$reply; }
 6566:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6567:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6568:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 6569:                  $umode.', '.$first.', '.$middle.', '.
 6570: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 6571:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6572:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6573:     } else {
 6574:         $logmsg .= ' during self creation';
 6575:     }
 6576:     &logthis($logmsg);
 6577:     return 'ok';
 6578: }
 6579: 
 6580: # -------------------------------------------------------------- Modify student
 6581: 
 6582: sub modifystudent {
 6583:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6584:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6585:         $selfenroll,$context,$inststatus)=@_;
 6586:     if (!$cid) {
 6587: 	unless ($cid=$env{'request.course.id'}) {
 6588: 	    return 'not_in_class';
 6589: 	}
 6590:     }
 6591: # --------------------------------------------------------------- Make the user
 6592:     my $reply=&modifyuser
 6593: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6594:          $desiredhome,$email,$inststatus);
 6595:     unless ($reply eq 'ok') { return $reply; }
 6596:     # This will cause &modify_student_enrollment to get the uid from the
 6597:     # students environment
 6598:     $uid = undef if (!$forceid);
 6599:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6600: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6601:     return $reply;
 6602: }
 6603: 
 6604: sub modify_student_enrollment {
 6605:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6606:     my ($cdom,$cnum,$chome);
 6607:     if (!$cid) {
 6608: 	unless ($cid=$env{'request.course.id'}) {
 6609: 	    return 'not_in_class';
 6610: 	}
 6611: 	$cdom=$env{'course.'.$cid.'.domain'};
 6612: 	$cnum=$env{'course.'.$cid.'.num'};
 6613:     } else {
 6614: 	($cdom,$cnum)=split(/_/,$cid);
 6615:     }
 6616:     $chome=$env{'course.'.$cid.'.home'};
 6617:     if (!$chome) {
 6618: 	$chome=&homeserver($cnum,$cdom);
 6619:     }
 6620:     if (!$chome) { return 'unknown_course'; }
 6621:     # Make sure the user exists
 6622:     my $uhome=&homeserver($uname,$udom);
 6623:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6624: 	return 'error: no such user';
 6625:     }
 6626:     # Get student data if we were not given enough information
 6627:     if (!defined($first)  || $first  eq '' || 
 6628:         !defined($last)   || $last   eq '' || 
 6629:         !defined($uid)    || $uid    eq '' || 
 6630:         !defined($middle) || $middle eq '' || 
 6631:         !defined($gene)   || $gene   eq '') {
 6632:         # They did not supply us with enough data to enroll the student, so
 6633:         # we need to pick up more information.
 6634:         my %tmp = &get('environment',
 6635:                        ['firstname','middlename','lastname', 'generation','id']
 6636:                        ,$udom,$uname);
 6637: 
 6638:         #foreach my $key (keys(%tmp)) {
 6639:         #    &logthis("key $key = ".$tmp{$key});
 6640:         #}
 6641:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6642:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6643:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6644:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6645:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6646:     }
 6647:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6648:     my $reply=cput('classlist',
 6649: 		   {"$uname:$udom" => 
 6650: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6651: 		   $cdom,$cnum);
 6652:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6653: 	return 'error: '.$reply;
 6654:     } else {
 6655: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6656:     }
 6657:     # Add student role to user
 6658:     my $uurl='/'.$cid;
 6659:     $uurl=~s/\_/\//g;
 6660:     if ($usec) {
 6661: 	$uurl.='/'.$usec;
 6662:     }
 6663:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6664: }
 6665: 
 6666: sub format_name {
 6667:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6668:     my $name;
 6669:     if ($first ne 'lastname') {
 6670: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6671:     } else {
 6672: 	if ($lastname=~/\S/) {
 6673: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6674: 	    $name=~s/\s+,/,/;
 6675: 	} else {
 6676: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6677: 	}
 6678:     }
 6679:     $name=~s/^\s+//;
 6680:     $name=~s/\s+$//;
 6681:     $name=~s/\s+/ /g;
 6682:     return $name;
 6683: }
 6684: 
 6685: # ------------------------------------------------- Write to course preferences
 6686: 
 6687: sub writecoursepref {
 6688:     my ($courseid,%prefs)=@_;
 6689:     $courseid=~s/^\///;
 6690:     $courseid=~s/\_/\//g;
 6691:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6692:     my $chome=homeserver($cnum,$cdomain);
 6693:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6694: 	return 'error: no such course';
 6695:     }
 6696:     my $cstring='';
 6697:     foreach my $pref (keys(%prefs)) {
 6698: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6699:     }
 6700:     $cstring=~s/\&$//;
 6701:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6702: }
 6703: 
 6704: # ---------------------------------------------------------- Make/modify course
 6705: 
 6706: sub createcourse {
 6707:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6708:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 6709:     $url=&declutter($url);
 6710:     my $cid='';
 6711:     if ($context eq 'requestcourses') {
 6712:         my $can_create = 0;
 6713:         my ($ownername,$ownerdom) = split(':',$course_owner);
 6714:         if ($udom eq $ownerdom) {
 6715:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 6716:                                   $context)) {
 6717:                 $can_create = 1;
 6718:             }
 6719:         } else {
 6720:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 6721:                                            $category);
 6722:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 6723:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 6724:                 if (@curr > 0) {
 6725:                     my @options = qw(approval validate autolimit);
 6726:                     my $optregex = join('|',@options);
 6727:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 6728:                         $can_create = 1;
 6729:                     }
 6730:                 }
 6731:             }
 6732:         }
 6733:         if ($can_create) {
 6734:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 6735:                 unless (&allowed('ccc',$udom)) {
 6736:                     return 'refused'; 
 6737:                 }
 6738:             }
 6739:         } else {
 6740:             return 'refused';
 6741:         }
 6742:     } elsif (!&allowed('ccc',$udom)) {
 6743:         return 'refused';
 6744:     }
 6745: # --------------------------------------------------------------- Get Unique ID
 6746:     my $uname;
 6747:     if ($cnum =~ /^$match_courseid$/) {
 6748:         my $chome=&homeserver($cnum,$udom,'true');
 6749:         if (($chome eq '') || ($chome eq 'no_host')) {
 6750:             $uname = $cnum;
 6751:         } else {
 6752:             $uname = &generate_coursenum($udom,$crstype);
 6753:         }
 6754:     } else {
 6755:         $uname = &generate_coursenum($udom,$crstype);
 6756:     }
 6757:     return $uname if ($uname =~ /^error/);
 6758: # -------------------------------------------------- Check supplied server name
 6759:     if (!defined($course_server)) {
 6760:         if (defined(&domain($udom,'primary'))) {
 6761:             $course_server = &domain($udom,'primary');
 6762:         } else {
 6763:             $course_server = $env{'user.home'}; 
 6764:         }
 6765:     }
 6766:     my %host_servers =
 6767:         &Apache::lonnet::get_servers($udom,'library');
 6768:     unless ($host_servers{$course_server}) {
 6769:         return 'error: invalid home server for course: '.$course_server;
 6770:     }
 6771: # ------------------------------------------------------------- Make the course
 6772:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6773:                       $course_server);
 6774:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6775:     my $uhome=&homeserver($uname,$udom,'true');
 6776:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6777: 	return 'error: no such course';
 6778:     }
 6779: # ----------------------------------------------------------------- Course made
 6780: # log existence
 6781:     my $now = time;
 6782:     my $newcourse = {
 6783:                     $udom.'_'.$uname => {
 6784:                                      description => $description,
 6785:                                      inst_code   => $inst_code,
 6786:                                      owner       => $course_owner,
 6787:                                      type        => $crstype,
 6788:                                      creator     => $env{'user.name'}.':'.
 6789:                                                     $env{'user.domain'},
 6790:                                      created     => $now,
 6791:                                      context     => $context,
 6792:                                                 },
 6793:                     };
 6794:     &courseidput($udom,$newcourse,$uhome,'notime');
 6795: # set toplevel url
 6796:     my $topurl=$url;
 6797:     unless ($nonstandard) {
 6798: # ------------------------------------------ For standard courses, make top url
 6799:         my $mapurl=&clutter($url);
 6800:         if ($mapurl eq '/res/') { $mapurl=''; }
 6801:         $env{'form.initmap'}=(<<ENDINITMAP);
 6802: <map>
 6803: <resource id="1" type="start"></resource>
 6804: <resource id="2" src="$mapurl"></resource>
 6805: <resource id="3" type="finish"></resource>
 6806: <link index="1" from="1" to="2"></link>
 6807: <link index="2" from="2" to="3"></link>
 6808: </map>
 6809: ENDINITMAP
 6810:         $topurl=&declutter(
 6811:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6812:                           );
 6813:     }
 6814: # ----------------------------------------------------------- Write preferences
 6815:     &writecoursepref($udom.'_'.$uname,
 6816:                      ('description'              => $description,
 6817:                       'url'                      => $topurl,
 6818:                       'internal.creator'         => $env{'user.name'}.':'.
 6819:                                                     $env{'user.domain'},
 6820:                       'internal.created'         => $now,
 6821:                       'internal.creationcontext' => $context)
 6822:                     );
 6823:     return '/'.$udom.'/'.$uname;
 6824: }
 6825: 
 6826: # ------------------------------------------------------------------- Create ID
 6827: sub generate_coursenum {
 6828:     my ($udom,$crstype) = @_;
 6829:     my $domdesc = &domain($udom);
 6830:     return 'error: invalid domain' if ($domdesc eq '');
 6831:     my $first;
 6832:     if ($crstype eq 'Community') {
 6833:         $first = '0';
 6834:     } else {
 6835:         $first = int(1+rand(9)); 
 6836:     } 
 6837:     my $uname=$first.
 6838:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6839:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6840:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6841: # ----------------------------------------------- Make sure that does not exist
 6842:     my $uhome=&homeserver($uname,$udom,'true');
 6843:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6844:         if ($crstype eq 'Community') {
 6845:             $first = '0';
 6846:         } else {
 6847:             $first = int(1+rand(9));
 6848:         }
 6849:         $uname=$first.
 6850:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 6851:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 6852:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 6853:         $uhome=&homeserver($uname,$udom,'true');
 6854:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6855:             return 'error: unable to generate unique course-ID';
 6856:         }
 6857:     }
 6858:     return $uname;
 6859: }
 6860: 
 6861: sub is_course {
 6862:     my ($cdom,$cnum) = @_;
 6863:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6864: 				undef,'.');
 6865:     if (exists($courses{$cdom.'_'.$cnum})) {
 6866:         return 1;
 6867:     }
 6868:     return 0;
 6869: }
 6870: 
 6871: sub store_userdata {
 6872:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 6873:     my $result;
 6874:     if ($datakey ne '') {
 6875:         if (ref($storehash) eq 'HASH') {
 6876:             if ($udom eq '' || $uname eq '') {
 6877:                 $udom = $env{'user.domain'};
 6878:                 $uname = $env{'user.name'};
 6879:             }
 6880:             my $uhome=&homeserver($uname,$udom);
 6881:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 6882:                 $result = 'error: no_host';
 6883:             } else {
 6884:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 6885:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 6886: 
 6887:                 my $namevalue='';
 6888:                 foreach my $key (keys(%{$storehash})) {
 6889:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6890:                 }
 6891:                 $namevalue=~s/\&$//;
 6892:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
 6893:                                   "$namespace:$datakey:$namevalue",$uhome);
 6894:             }
 6895:         } else {
 6896:             $result = 'error: data to store was not a hash reference'; 
 6897:         }
 6898:     } else {
 6899:         $result= 'error: invalid requestkey'; 
 6900:     }
 6901:     return $result;
 6902: }
 6903: 
 6904: # ---------------------------------------------------------- Assign Custom Role
 6905: 
 6906: sub assigncustomrole {
 6907:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6908:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6909:                        $end,$start,$deleteflag,$selfenroll,$context);
 6910: }
 6911: 
 6912: # ----------------------------------------------------------------- Revoke Role
 6913: 
 6914: sub revokerole {
 6915:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6916:     my $now=time;
 6917:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6918: }
 6919: 
 6920: # ---------------------------------------------------------- Revoke Custom Role
 6921: 
 6922: sub revokecustomrole {
 6923:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6924:     my $now=time;
 6925:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6926:            $deleteflag,$selfenroll,$context);
 6927: }
 6928: 
 6929: # ------------------------------------------------------------ Disk usage
 6930: sub diskusage {
 6931:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6932:     $directorypath =~ s/\/$//;
 6933:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6934:                        .&escape($getpropath).':'.&escape($uname).':'
 6935:                        .&escape($udom),homeserver($uname,$udom));
 6936:     if ($listing eq 'unknown_cmd') {
 6937:         if ($getpropath) {
 6938:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6939:         }
 6940:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6941:     }
 6942:     return $listing;
 6943: }
 6944: 
 6945: sub is_locked {
 6946:     my ($file_name, $domain, $user) = @_;
 6947:     my @check;
 6948:     my $is_locked;
 6949:     push @check, $file_name;
 6950:     my %locked = &get('file_permissions',\@check,
 6951: 		      $env{'user.domain'},$env{'user.name'});
 6952:     my ($tmp)=keys(%locked);
 6953:     if ($tmp=~/^error:/) { undef(%locked); }
 6954:     
 6955:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6956:         $is_locked = 'false';
 6957:         foreach my $entry (@{$locked{$file_name}}) {
 6958:            if (ref($entry) eq 'ARRAY') { 
 6959:                $is_locked = 'true';
 6960:                last;
 6961:            }
 6962:        }
 6963:     } else {
 6964:         $is_locked = 'false';
 6965:     }
 6966: }
 6967: 
 6968: sub declutter_portfile {
 6969:     my ($file) = @_;
 6970:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6971:     return $file;
 6972: }
 6973: 
 6974: # ------------------------------------------------------------- Mark as Read Only
 6975: 
 6976: sub mark_as_readonly {
 6977:     my ($domain,$user,$files,$what) = @_;
 6978:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6979:     my ($tmp)=keys(%current_permissions);
 6980:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6981:     foreach my $file (@{$files}) {
 6982: 	$file = &declutter_portfile($file);
 6983:         push(@{$current_permissions{$file}},$what);
 6984:     }
 6985:     &put('file_permissions',\%current_permissions,$domain,$user);
 6986:     return;
 6987: }
 6988: 
 6989: # ------------------------------------------------------------Save Selected Files
 6990: 
 6991: sub save_selected_files {
 6992:     my ($user, $path, @files) = @_;
 6993:     my $filename = $user."savedfiles";
 6994:     my @other_files = &files_not_in_path($user, $path);
 6995:     open (OUT, '>'.$tmpdir.$filename);
 6996:     foreach my $file (@files) {
 6997:         print (OUT $env{'form.currentpath'}.$file."\n");
 6998:     }
 6999:     foreach my $file (@other_files) {
 7000:         print (OUT $file."\n");
 7001:     }
 7002:     close (OUT);
 7003:     return 'ok';
 7004: }
 7005: 
 7006: sub clear_selected_files {
 7007:     my ($user) = @_;
 7008:     my $filename = $user."savedfiles";
 7009:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 7010:     print (OUT undef);
 7011:     close (OUT);
 7012:     return ("ok");    
 7013: }
 7014: 
 7015: sub files_in_path {
 7016:     my ($user, $path) = @_;
 7017:     my $filename = $user."savedfiles";
 7018:     my %return_files;
 7019:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 7020:     while (my $line_in = <IN>) {
 7021:         chomp ($line_in);
 7022:         my @paths_and_file = split (m!/!, $line_in);
 7023:         my $file_part = pop (@paths_and_file);
 7024:         my $path_part = join ('/', @paths_and_file);
 7025:         $path_part.='/';
 7026:         my $path_and_file = $path_part.$file_part;
 7027:         if ($path_part eq $path) {
 7028:             $return_files{$file_part}= 'selected';
 7029:         }
 7030:     }
 7031:     close (IN);
 7032:     return (\%return_files);
 7033: }
 7034: 
 7035: # called in portfolio select mode, to show files selected NOT in current directory
 7036: sub files_not_in_path {
 7037:     my ($user, $path) = @_;
 7038:     my $filename = $user."savedfiles";
 7039:     my @return_files;
 7040:     my $path_part;
 7041:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 7042:     while (my $line = <IN>) {
 7043:         #ok, I know it's clunky, but I want it to work
 7044:         my @paths_and_file = split(m|/|, $line);
 7045:         my $file_part = pop(@paths_and_file);
 7046:         chomp($file_part);
 7047:         my $path_part = join('/', @paths_and_file);
 7048:         $path_part .= '/';
 7049:         my $path_and_file = $path_part.$file_part;
 7050:         if ($path_part ne $path) {
 7051:             push(@return_files, ($path_and_file));
 7052:         }
 7053:     }
 7054:     close(OUT);
 7055:     return (@return_files);
 7056: }
 7057: 
 7058: #----------------------------------------------Get portfolio file permissions
 7059: 
 7060: sub get_portfile_permissions {
 7061:     my ($domain,$user) = @_;
 7062:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7063:     my ($tmp)=keys(%current_permissions);
 7064:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7065:     return \%current_permissions;
 7066: }
 7067: 
 7068: #---------------------------------------------Get portfolio file access controls
 7069: 
 7070: sub get_access_controls {
 7071:     my ($current_permissions,$group,$file) = @_;
 7072:     my %access;
 7073:     my $real_file = $file;
 7074:     $file =~ s/\.meta$//;
 7075:     if (defined($file)) {
 7076:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 7077:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 7078:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 7079:             }
 7080:         }
 7081:     } else {
 7082:         foreach my $key (keys(%{$current_permissions})) {
 7083:             if ($key =~ /\0accesscontrol$/) {
 7084:                 if (defined($group)) {
 7085:                     if ($key !~ m-^\Q$group\E/-) {
 7086:                         next;
 7087:                     }
 7088:                 }
 7089:                 my ($fullpath) = split(/\0/,$key);
 7090:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 7091:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 7092:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 7093:                     }
 7094:                 }
 7095:             }
 7096:         }
 7097:     }
 7098:     return %access;
 7099: }
 7100: 
 7101: sub modify_access_controls {
 7102:     my ($file_name,$changes,$domain,$user)=@_;
 7103:     my ($outcome,$deloutcome);
 7104:     my %store_permissions;
 7105:     my %new_values;
 7106:     my %new_control;
 7107:     my %translation;
 7108:     my @deletions = ();
 7109:     my $now = time;
 7110:     if (exists($$changes{'activate'})) {
 7111:         if (ref($$changes{'activate'}) eq 'HASH') {
 7112:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 7113:             my $numnew = scalar(@newitems);
 7114:             for (my $i=0; $i<$numnew; $i++) {
 7115:                 my $newkey = $newitems[$i];
 7116:                 my $newid = &Apache::loncommon::get_cgi_id();
 7117:                 if ($newkey =~ /^\d+:/) { 
 7118:                     $newkey =~ s/^(\d+)/$newid/;
 7119:                     $translation{$1} = $newid;
 7120:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 7121:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 7122:                     $translation{$1} = $newid;
 7123:                 }
 7124:                 $new_values{$file_name."\0".$newkey} = 
 7125:                                           $$changes{'activate'}{$newitems[$i]};
 7126:                 $new_control{$newkey} = $now;
 7127:             }
 7128:         }
 7129:     }
 7130:     my %todelete;
 7131:     my %changed_items;
 7132:     foreach my $action ('delete','update') {
 7133:         if (exists($$changes{$action})) {
 7134:             if (ref($$changes{$action}) eq 'HASH') {
 7135:                 foreach my $key (keys(%{$$changes{$action}})) {
 7136:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 7137:                     if ($action eq 'delete') { 
 7138:                         $todelete{$itemnum} = 1;
 7139:                     } else {
 7140:                         $changed_items{$itemnum} = $key;
 7141:                     }
 7142:                 }
 7143:             }
 7144:         }
 7145:     }
 7146:     # get lock on access controls for file.
 7147:     my $lockhash = {
 7148:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 7149:                                                        ':'.$env{'user.domain'},
 7150:                    }; 
 7151:     my $tries = 0;
 7152:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7153:    
 7154:     while (($gotlock ne 'ok') && $tries <3) {
 7155:         $tries ++;
 7156:         sleep 1;
 7157:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7158:     }
 7159:     if ($gotlock eq 'ok') {
 7160:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 7161:         my ($tmp)=keys(%curr_permissions);
 7162:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 7163:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 7164:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 7165:             if (ref($curr_controls) eq 'HASH') {
 7166:                 foreach my $control_item (keys(%{$curr_controls})) {
 7167:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 7168:                     if (defined($todelete{$itemnum})) {
 7169:                         push(@deletions,$file_name."\0".$control_item);
 7170:                     } else {
 7171:                         if (defined($changed_items{$itemnum})) {
 7172:                             $new_control{$changed_items{$itemnum}} = $now;
 7173:                             push(@deletions,$file_name."\0".$control_item);
 7174:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 7175:                         } else {
 7176:                             $new_control{$control_item} = $$curr_controls{$control_item};
 7177:                         }
 7178:                     }
 7179:                 }
 7180:             }
 7181:         }
 7182:         my ($group);
 7183:         if (&is_course($domain,$user)) {
 7184:             ($group,my $file) = split(/\//,$file_name,2);
 7185:         }
 7186:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 7187:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 7188:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 7189:         #  remove lock
 7190:         my @del_lock = ($file_name."\0".'locked_access_records');
 7191:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 7192:         my $sqlresult =
 7193:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 7194:                                     $group);
 7195:     } else {
 7196:         $outcome = "error: could not obtain lockfile\n";  
 7197:     }
 7198:     return ($outcome,$deloutcome,\%new_values,\%translation);
 7199: }
 7200: 
 7201: sub make_public_indefinitely {
 7202:     my ($requrl) = @_;
 7203:     my $now = time;
 7204:     my $action = 'activate';
 7205:     my $aclnum = 0;
 7206:     if (&is_portfolio_url($requrl)) {
 7207:         my (undef,$udom,$unum,$file_name,$group) =
 7208:             &parse_portfolio_url($requrl);
 7209:         my $current_perms = &get_portfile_permissions($udom,$unum);
 7210:         my %access_controls = &get_access_controls($current_perms,
 7211:                                                    $group,$file_name);
 7212:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 7213:             my ($num,$scope,$end,$start) = 
 7214:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7215:             if ($scope eq 'public') {
 7216:                 if ($start <= $now && $end == 0) {
 7217:                     $action = 'none';
 7218:                 } else {
 7219:                     $action = 'update';
 7220:                     $aclnum = $num;
 7221:                 }
 7222:                 last;
 7223:             }
 7224:         }
 7225:         if ($action eq 'none') {
 7226:              return 'ok';
 7227:         } else {
 7228:             my %changes;
 7229:             my $newend = 0;
 7230:             my $newstart = $now;
 7231:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 7232:             $changes{$action}{$newkey} = {
 7233:                 type => 'public',
 7234:                 time => {
 7235:                     start => $newstart,
 7236:                     end   => $newend,
 7237:                 },
 7238:             };
 7239:             my ($outcome,$deloutcome,$new_values,$translation) =
 7240:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 7241:             return $outcome;
 7242:         }
 7243:     } else {
 7244:         return 'invalid';
 7245:     }
 7246: }
 7247: 
 7248: #------------------------------------------------------Get Marked as Read Only
 7249: 
 7250: sub get_marked_as_readonly {
 7251:     my ($domain,$user,$what,$group) = @_;
 7252:     my $current_permissions = &get_portfile_permissions($domain,$user);
 7253:     my @readonly_files;
 7254:     my $cmp1=$what;
 7255:     if (ref($what)) { $cmp1=join('',@{$what}) };
 7256:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7257:         if (defined($group)) {
 7258:             if ($file_name !~ m-^\Q$group\E/-) {
 7259:                 next;
 7260:             }
 7261:         }
 7262:         if (ref($value) eq "ARRAY"){
 7263:             foreach my $stored_what (@{$value}) {
 7264:                 my $cmp2=$stored_what;
 7265:                 if (ref($stored_what) eq 'ARRAY') {
 7266:                     $cmp2=join('',@{$stored_what});
 7267:                 }
 7268:                 if ($cmp1 eq $cmp2) {
 7269:                     push(@readonly_files, $file_name);
 7270:                     last;
 7271:                 } elsif (!defined($what)) {
 7272:                     push(@readonly_files, $file_name);
 7273:                     last;
 7274:                 }
 7275:             }
 7276:         }
 7277:     }
 7278:     return @readonly_files;
 7279: }
 7280: #-----------------------------------------------------------Get Marked as Read Only Hash
 7281: 
 7282: sub get_marked_as_readonly_hash {
 7283:     my ($current_permissions,$group,$what) = @_;
 7284:     my %readonly_files;
 7285:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7286:         if (defined($group)) {
 7287:             if ($file_name !~ m-^\Q$group\E/-) {
 7288:                 next;
 7289:             }
 7290:         }
 7291:         if (ref($value) eq "ARRAY"){
 7292:             foreach my $stored_what (@{$value}) {
 7293:                 if (ref($stored_what) eq 'ARRAY') {
 7294:                     foreach my $lock_descriptor(@{$stored_what}) {
 7295:                         if ($lock_descriptor eq 'graded') {
 7296:                             $readonly_files{$file_name} = 'graded';
 7297:                         } elsif ($lock_descriptor eq 'handback') {
 7298:                             $readonly_files{$file_name} = 'handback';
 7299:                         } else {
 7300:                             if (!exists($readonly_files{$file_name})) {
 7301:                                 $readonly_files{$file_name} = 'locked';
 7302:                             }
 7303:                         }
 7304:                     }
 7305:                 } 
 7306:             }
 7307:         } 
 7308:     }
 7309:     return %readonly_files;
 7310: }
 7311: # ------------------------------------------------------------ Unmark as Read Only
 7312: 
 7313: sub unmark_as_readonly {
 7314:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 7315:     # for portfolio submissions, $what contains [$symb,$crsid] 
 7316:     my ($domain,$user,$what,$file_name,$group) = @_;
 7317:     $file_name = &declutter_portfile($file_name);
 7318:     my $symb_crs = $what;
 7319:     if (ref($what)) { $symb_crs=join('',@$what); }
 7320:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 7321:     my ($tmp)=keys(%current_permissions);
 7322:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7323:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 7324:     foreach my $file (@readonly_files) {
 7325: 	my $clean_file = &declutter_portfile($file);
 7326: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 7327: 	my $current_locks = $current_permissions{$file};
 7328:         my @new_locks;
 7329:         my @del_keys;
 7330:         if (ref($current_locks) eq "ARRAY"){
 7331:             foreach my $locker (@{$current_locks}) {
 7332:                 my $compare=$locker;
 7333:                 if (ref($locker) eq 'ARRAY') {
 7334:                     $compare=join('',@{$locker});
 7335:                     if ($compare ne $symb_crs) {
 7336:                         push(@new_locks, $locker);
 7337:                     }
 7338:                 }
 7339:             }
 7340:             if (scalar(@new_locks) > 0) {
 7341:                 $current_permissions{$file} = \@new_locks;
 7342:             } else {
 7343:                 push(@del_keys, $file);
 7344:                 &del('file_permissions',\@del_keys, $domain, $user);
 7345:                 delete($current_permissions{$file});
 7346:             }
 7347:         }
 7348:     }
 7349:     &put('file_permissions',\%current_permissions,$domain,$user);
 7350:     return;
 7351: }
 7352: 
 7353: # ------------------------------------------------------------ Directory lister
 7354: 
 7355: sub dirlist {
 7356:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 7357:     $uri=~s/^\///;
 7358:     $uri=~s/\/$//;
 7359:     my ($udom, $uname);
 7360:     if ($getuserdir) {
 7361:         $udom = $userdomain;
 7362:         $uname = $username;
 7363:     } else {
 7364:         (undef,$udom,$uname)=split(/\//,$uri);
 7365:         if(defined($userdomain)) {
 7366:             $udom = $userdomain;
 7367:         }
 7368:         if(defined($username)) {
 7369:             $uname = $username;
 7370:         }
 7371:     }
 7372:     my ($dirRoot,$listing,@listing_results);
 7373: 
 7374:     $dirRoot = $perlvar{'lonDocRoot'};
 7375:     if (defined($getpropath)) {
 7376:         $dirRoot = &propath($udom,$uname);
 7377:         $dirRoot =~ s/\/$//;
 7378:     } elsif (defined($getuserdir)) {
 7379:         my $subdir=$uname.'__';
 7380:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 7381:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 7382:                    ."/$udom/$subdir/$uname";
 7383:     } elsif (defined($alternateRoot)) {
 7384:         $dirRoot = $alternateRoot;
 7385:     }
 7386: 
 7387:     if($udom) {
 7388:         if($uname) {
 7389:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 7390:                               .$getuserdir.':'.&escape($dirRoot)
 7391:                               .':'.&escape($uname).':'.&escape($udom),
 7392:                               &homeserver($uname,$udom));
 7393:             if ($listing eq 'unknown_cmd') {
 7394:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 7395:                                   &homeserver($uname,$udom));
 7396:             } else {
 7397:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7398:             }
 7399:             if ($listing eq 'unknown_cmd') {
 7400:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 7401: 				  &homeserver($uname,$udom));
 7402:                 @listing_results = split(/:/,$listing);
 7403:             } else {
 7404:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7405:             }
 7406:             return @listing_results;
 7407:         } elsif(!$alternateRoot) {
 7408:             my %allusers;
 7409: 	    my %servers = &get_servers($udom,'library');
 7410:  	    foreach my $tryserver (keys(%servers)) {
 7411:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 7412:                                   &escape($udom),$tryserver);
 7413:                 if ($listing eq 'unknown_cmd') {
 7414: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 7415: 				      $udom, $tryserver);
 7416:                 } else {
 7417:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 7418:                 }
 7419: 		if ($listing eq 'unknown_cmd') {
 7420: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 7421: 				      $udom, $tryserver);
 7422: 		    @listing_results = split(/:/,$listing);
 7423: 		} else {
 7424: 		    @listing_results =
 7425: 			map { &unescape($_); } split(/:/,$listing);
 7426: 		}
 7427: 		if ($listing_results[0] ne 'no_such_dir' && 
 7428: 		    $listing_results[0] ne 'empty'       &&
 7429: 		    $listing_results[0] ne 'con_lost') {
 7430: 		    foreach my $line (@listing_results) {
 7431: 			my ($entry) = split(/&/,$line,2);
 7432: 			$allusers{$entry} = 1;
 7433: 		    }
 7434: 		}
 7435:             }
 7436:             my $alluserstr='';
 7437:             foreach my $user (sort(keys(%allusers))) {
 7438:                 $alluserstr.=$user.'&user:';
 7439:             }
 7440:             $alluserstr=~s/:$//;
 7441:             return split(/:/,$alluserstr);
 7442:         } else {
 7443:             return ('missing user name');
 7444:         }
 7445:     } elsif(!defined($getpropath)) {
 7446:         my @all_domains = sort(&all_domains());
 7447:         foreach my $domain (@all_domains) {
 7448:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 7449:         }
 7450:         return @all_domains;
 7451:     } else {
 7452:         return ('missing domain');
 7453:     }
 7454: }
 7455: 
 7456: # --------------------------------------------- GetFileTimestamp
 7457: # This function utilizes dirlist and returns the date stamp for
 7458: # when it was last modified.  It will also return an error of -1
 7459: # if an error occurs
 7460: 
 7461: sub GetFileTimestamp {
 7462:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 7463:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 7464:     $studentName   = &LONCAPA::clean_username($studentName);
 7465:     my ($fileStat) = 
 7466:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 7467:                                  undef,$getuserdir);
 7468:     my @stats = split('&', $fileStat);
 7469:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7470:         # @stats contains first the filename, then the stat output
 7471:         return $stats[10]; # so this is 10 instead of 9.
 7472:     } else {
 7473:         return -1;
 7474:     }
 7475: }
 7476: 
 7477: sub stat_file {
 7478:     my ($uri) = @_;
 7479:     $uri = &clutter_with_no_wrapper($uri);
 7480: 
 7481:     my ($udom,$uname,$file);
 7482:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 7483: 	($udom,$uname,$file) =
 7484: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 7485: 	$file = 'userfiles/'.$file;
 7486:     }
 7487:     if ($uri =~ m-^/res/-) {
 7488: 	($udom,$uname) = 
 7489: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 7490: 	$file = $uri;
 7491:     }
 7492: 
 7493:     if (!$udom || !$uname || !$file) {
 7494: 	# unable to handle the uri
 7495: 	return ();
 7496:     }
 7497:     my $getpropath;
 7498:     if ($file =~ /^userfiles\//) {
 7499:         $getpropath = 1;
 7500:     }
 7501:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 7502:     my @stats = split('&', $result);
 7503:     
 7504:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7505: 	shift(@stats); #filename is first
 7506: 	return @stats;
 7507:     }
 7508:     return ();
 7509: }
 7510: 
 7511: # -------------------------------------------------------- Value of a Condition
 7512: 
 7513: # gets the value of a specific preevaluated condition
 7514: #    stored in the string  $env{user.state.<cid>}
 7515: # or looks up a condition reference in the bighash and if if hasn't
 7516: # already been evaluated recurses into docondval to get the value of
 7517: # the condition, then memoizing it to 
 7518: #   $env{user.state.<cid>.<condition>}
 7519: sub directcondval {
 7520:     my $number=shift;
 7521:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 7522: 	&Apache::lonuserstate::evalstate();
 7523:     }
 7524:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 7525: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 7526:     } elsif ($number =~ /^_/) {
 7527: 	my $sub_condition;
 7528: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7529: 		&GDBM_READER(),0640)) {
 7530: 	    $sub_condition=$bighash{'conditions'.$number};
 7531: 	    untie(%bighash);
 7532: 	}
 7533: 	my $value = &docondval($sub_condition);
 7534: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 7535: 	return $value;
 7536:     }
 7537:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 7538:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 7539:     } else {
 7540:        return 2;
 7541:     }
 7542: }
 7543: 
 7544: # get the collection of conditions for this resource
 7545: sub condval {
 7546:     my $condidx=shift;
 7547:     my $allpathcond='';
 7548:     foreach my $cond (split(/\|/,$condidx)) {
 7549: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 7550: 	    $allpathcond.=
 7551: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 7552: 	}
 7553:     }
 7554:     $allpathcond=~s/\|$//;
 7555:     return &docondval($allpathcond);
 7556: }
 7557: 
 7558: #evaluates an expression of conditions
 7559: sub docondval {
 7560:     my ($allpathcond) = @_;
 7561:     my $result=0;
 7562:     if ($env{'request.course.id'}
 7563: 	&& defined($allpathcond)) {
 7564: 	my $operand='|';
 7565: 	my @stack;
 7566: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 7567: 	    if ($chunk eq '(') {
 7568: 		push @stack,($operand,$result);
 7569: 	    } elsif ($chunk eq ')') {
 7570: 		my $before=pop @stack;
 7571: 		if (pop @stack eq '&') {
 7572: 		    $result=$result>$before?$before:$result;
 7573: 		} else {
 7574: 		    $result=$result>$before?$result:$before;
 7575: 		}
 7576: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7577: 		$operand=$chunk;
 7578: 	    } else {
 7579: 		my $new=directcondval($chunk);
 7580: 		if ($operand eq '&') {
 7581: 		    $result=$result>$new?$new:$result;
 7582: 		} else {
 7583: 		    $result=$result>$new?$result:$new;
 7584: 		}
 7585: 	    }
 7586: 	}
 7587:     }
 7588:     return $result;
 7589: }
 7590: 
 7591: # ---------------------------------------------------- Devalidate courseresdata
 7592: 
 7593: sub devalidatecourseresdata {
 7594:     my ($coursenum,$coursedomain)=@_;
 7595:     my $hashid=$coursenum.':'.$coursedomain;
 7596:     &devalidate_cache_new('courseres',$hashid);
 7597: }
 7598: 
 7599: 
 7600: # --------------------------------------------------- Course Resourcedata Query
 7601: #
 7602: #  Parameters:
 7603: #      $coursenum    - Number of the course.
 7604: #      $coursedomain - Domain at which the course was created.
 7605: #  Returns:
 7606: #     A hash of the course parameters along (I think) with timestamps
 7607: #     and version info.
 7608: 
 7609: sub get_courseresdata {
 7610:     my ($coursenum,$coursedomain)=@_;
 7611:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7612:     my $hashid=$coursenum.':'.$coursedomain;
 7613:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7614:     my %dumpreply;
 7615:     unless (defined($cached)) {
 7616: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7617: 	$result=\%dumpreply;
 7618: 	my ($tmp) = keys(%dumpreply);
 7619: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7620: 	    &do_cache_new('courseres',$hashid,$result,600);
 7621: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7622: 	    return $tmp;
 7623: 	} elsif ($tmp =~ /^(error)/) {
 7624: 	    $result=undef;
 7625: 	    &do_cache_new('courseres',$hashid,$result,600);
 7626: 	}
 7627:     }
 7628:     return $result;
 7629: }
 7630: 
 7631: sub devalidateuserresdata {
 7632:     my ($uname,$udom)=@_;
 7633:     my $hashid="$udom:$uname";
 7634:     &devalidate_cache_new('userres',$hashid);
 7635: }
 7636: 
 7637: sub get_userresdata {
 7638:     my ($uname,$udom)=@_;
 7639:     #most student don\'t have any data set, check if there is some data
 7640:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7641: 
 7642:     my $hashid="$udom:$uname";
 7643:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7644:     if (!defined($cached)) {
 7645: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7646: 	$result=\%resourcedata;
 7647: 	&do_cache_new('userres',$hashid,$result,600);
 7648:     }
 7649:     my ($tmp)=keys(%$result);
 7650:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7651: 	return $result;
 7652:     }
 7653:     #error 2 occurs when the .db doesn't exist
 7654:     if ($tmp!~/error: 2 /) {
 7655: 	&logthis("<font color=\"blue\">WARNING:".
 7656: 		 " Trying to get resource data for ".
 7657: 		 $uname." at ".$udom.": ".
 7658: 		 $tmp."</font>");
 7659:     } elsif ($tmp=~/error: 2 /) {
 7660: 	#&EXT_cache_set($udom,$uname);
 7661: 	&do_cache_new('userres',$hashid,undef,600);
 7662: 	undef($tmp); # not really an error so don't send it back
 7663:     }
 7664:     return $tmp;
 7665: }
 7666: #----------------------------------------------- resdata - return resource data
 7667: #  Purpose:
 7668: #    Return resource data for either users or for a course.
 7669: #  Parameters:
 7670: #     $name      - Course/user name.
 7671: #     $domain    - Name of the domain the user/course is registered on.
 7672: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7673: #     @which     - Array of names of resources desired.
 7674: #  Returns:
 7675: #     The value of the first reasource in @which that is found in the
 7676: #     resource hash.
 7677: #  Exceptional Conditions:
 7678: #     If the $type passed in is not valid (not the string 'course' or 
 7679: #     'user', an undefined  reference is returned.
 7680: #     If none of the resources are found, an undef is returned
 7681: sub resdata {
 7682:     my ($name,$domain,$type,@which)=@_;
 7683:     my $result;
 7684:     if ($type eq 'course') {
 7685: 	$result=&get_courseresdata($name,$domain);
 7686:     } elsif ($type eq 'user') {
 7687: 	$result=&get_userresdata($name,$domain);
 7688:     }
 7689:     if (!ref($result)) { return $result; }    
 7690:     foreach my $item (@which) {
 7691: 	if (defined($result->{$item->[0]})) {
 7692: 	    return [$result->{$item->[0]},$item->[1]];
 7693: 	}
 7694:     }
 7695:     return undef;
 7696: }
 7697: 
 7698: #
 7699: # EXT resource caching routines
 7700: #
 7701: 
 7702: sub clear_EXT_cache_status {
 7703:     &delenv('cache.EXT.');
 7704: }
 7705: 
 7706: sub EXT_cache_status {
 7707:     my ($target_domain,$target_user) = @_;
 7708:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7709:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7710:         # We know already the user has no data
 7711:         return 1;
 7712:     } else {
 7713:         return 0;
 7714:     }
 7715: }
 7716: 
 7717: sub EXT_cache_set {
 7718:     my ($target_domain,$target_user) = @_;
 7719:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7720:     #&appenv({$cachename => time});
 7721: }
 7722: 
 7723: # --------------------------------------------------------- Value of a Variable
 7724: sub EXT {
 7725: 
 7726:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7727:     unless ($varname) { return ''; }
 7728:     #get real user name/domain, courseid and symb
 7729:     my $courseid;
 7730:     my $publicuser;
 7731:     if ($symbparm) {
 7732: 	$symbparm=&get_symb_from_alias($symbparm);
 7733:     }
 7734:     if (!($uname && $udom)) {
 7735:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7736:       if (!$symbparm) {	$symbparm=$cursymb; }
 7737:     } else {
 7738: 	$courseid=$env{'request.course.id'};
 7739:     }
 7740:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7741:     my $rest;
 7742:     if (defined($therest[0])) {
 7743:        $rest=join('.',@therest);
 7744:     } else {
 7745:        $rest='';
 7746:     }
 7747: 
 7748:     my $qualifierrest=$qualifier;
 7749:     if ($rest) { $qualifierrest.='.'.$rest; }
 7750:     my $spacequalifierrest=$space;
 7751:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7752:     if ($realm eq 'user') {
 7753: # --------------------------------------------------------------- user.resource
 7754: 	if ($space eq 'resource') {
 7755: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7756: 		  || defined($Apache::lonhomework::parsing_a_task))
 7757: 		 &&
 7758: 		 ($symbparm eq &symbread()) ) {	
 7759: 		# if we are in the middle of processing the resource the
 7760: 		# get the value we are planning on committing
 7761:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7762:                     return $Apache::lonhomework::results{$qualifierrest};
 7763:                 } else {
 7764:                     return $Apache::lonhomework::history{$qualifierrest};
 7765:                 }
 7766: 	    } else {
 7767: 		my %restored;
 7768: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7769: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7770: 		} else {
 7771: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7772: 		}
 7773: 		return $restored{$qualifierrest};
 7774: 	    }
 7775: # ----------------------------------------------------------------- user.access
 7776:         } elsif ($space eq 'access') {
 7777: 	    # FIXME - not supporting calls for a specific user
 7778:             return &allowed($qualifier,$rest);
 7779: # ------------------------------------------ user.preferences, user.environment
 7780:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7781: 	    if (($uname eq $env{'user.name'}) &&
 7782: 		($udom eq $env{'user.domain'})) {
 7783: 		return $env{join('.',('environment',$qualifierrest))};
 7784: 	    } else {
 7785: 		my %returnhash;
 7786: 		if (!$publicuser) {
 7787: 		    %returnhash=&userenvironment($udom,$uname,
 7788: 						 $qualifierrest);
 7789: 		}
 7790: 		return $returnhash{$qualifierrest};
 7791: 	    }
 7792: # ----------------------------------------------------------------- user.course
 7793:         } elsif ($space eq 'course') {
 7794: 	    # FIXME - not supporting calls for a specific user
 7795:             return $env{join('.',('request.course',$qualifier))};
 7796: # ------------------------------------------------------------------- user.role
 7797:         } elsif ($space eq 'role') {
 7798: 	    # FIXME - not supporting calls for a specific user
 7799:             my ($role,$where)=split(/\./,$env{'request.role'});
 7800:             if ($qualifier eq 'value') {
 7801: 		return $role;
 7802:             } elsif ($qualifier eq 'extent') {
 7803:                 return $where;
 7804:             }
 7805: # ----------------------------------------------------------------- user.domain
 7806:         } elsif ($space eq 'domain') {
 7807:             return $udom;
 7808: # ------------------------------------------------------------------- user.name
 7809:         } elsif ($space eq 'name') {
 7810:             return $uname;
 7811: # ---------------------------------------------------- Any other user namespace
 7812:         } else {
 7813: 	    my %reply;
 7814: 	    if (!$publicuser) {
 7815: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 7816: 	    }
 7817: 	    return $reply{$qualifierrest};
 7818:         }
 7819:     } elsif ($realm eq 'query') {
 7820: # ---------------------------------------------- pull stuff out of query string
 7821:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 7822: 						[$spacequalifierrest]);
 7823: 	return $env{'form.'.$spacequalifierrest}; 
 7824:    } elsif ($realm eq 'request') {
 7825: # ------------------------------------------------------------- request.browser
 7826:         if ($space eq 'browser') {
 7827: 	    if ($qualifier eq 'textremote') {
 7828: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 7829: 		    return 1;
 7830: 		} else {
 7831: 		    return 0;
 7832: 		}
 7833: 	    } else {
 7834: 		return $env{'browser.'.$qualifier};
 7835: 	    }
 7836: # ------------------------------------------------------------ request.filename
 7837:         } else {
 7838:             return $env{'request.'.$spacequalifierrest};
 7839:         }
 7840:     } elsif ($realm eq 'course') {
 7841: # ---------------------------------------------------------- course.description
 7842:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7843:     } elsif ($realm eq 'resource') {
 7844: 
 7845: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7846: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7847: 	}
 7848: 
 7849: 	if ($space eq 'title') {
 7850: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7851: 	    return &gettitle($symbparm);
 7852: 	}
 7853: 	
 7854: 	if ($space eq 'map') {
 7855: 	    my ($map) = &decode_symb($symbparm);
 7856: 	    return &symbread($map);
 7857: 	}
 7858: 	if ($space eq 'filename') {
 7859: 	    if ($symbparm) {
 7860: 		return &clutter((&decode_symb($symbparm))[2]);
 7861: 	    }
 7862: 	    return &hreflocation('',$env{'request.filename'});
 7863: 	}
 7864: 
 7865: 	my ($section, $group, @groups);
 7866: 	my ($courselevelm,$courselevel);
 7867: 	if ($symbparm && defined($courseid) && 
 7868: 	    $courseid eq $env{'request.course.id'}) {
 7869: 
 7870: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7871: 
 7872: # ----------------------------------------------------- Cascading lookup scheme
 7873: 	    my $symbp=$symbparm;
 7874: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7875: 
 7876: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7877: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7878: 
 7879: 	    if (($env{'user.name'} eq $uname) &&
 7880: 		($env{'user.domain'} eq $udom)) {
 7881: 		$section=$env{'request.course.sec'};
 7882:                 @groups = split(/:/,$env{'request.course.groups'});  
 7883:                 @groups=&sort_course_groups($courseid,@groups); 
 7884: 	    } else {
 7885: 		if (! defined($usection)) {
 7886: 		    $section=&getsection($udom,$uname,$courseid);
 7887: 		} else {
 7888: 		    $section = $usection;
 7889: 		}
 7890:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7891: 	    }
 7892: 
 7893: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7894: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7895: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7896: 
 7897: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7898: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7899: 	    $courselevelm=$courseid.'.'.$mapparm;
 7900: 
 7901: # ----------------------------------------------------------- first, check user
 7902: 
 7903: 	    my $userreply=&resdata($uname,$udom,'user',
 7904: 				       ([$courselevelr,'resource'],
 7905: 					[$courselevelm,'map'     ],
 7906: 					[$courselevel, 'course'  ]));
 7907: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7908: 
 7909: # ------------------------------------------------ second, check some of course
 7910:             my $coursereply;
 7911:             if (@groups > 0) {
 7912:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7913:                                        $mapparm,$spacequalifierrest);
 7914:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7915:             }
 7916: 
 7917: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7918: 				  $env{'course.'.$courseid.'.domain'},
 7919: 				  'course',
 7920: 				  ([$seclevelr,   'resource'],
 7921: 				   [$seclevelm,   'map'     ],
 7922: 				   [$seclevel,    'course'  ],
 7923: 				   [$courselevelr,'resource']));
 7924: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7925: 
 7926: # ------------------------------------------------------ third, check map parms
 7927: 	    my %parmhash=();
 7928: 	    my $thisparm='';
 7929: 	    if (tie(%parmhash,'GDBM_File',
 7930: 		    $env{'request.course.fn'}.'_parms.db',
 7931: 		    &GDBM_READER(),0640)) {
 7932: 		$thisparm=$parmhash{$symbparm};
 7933: 		untie(%parmhash);
 7934: 	    }
 7935: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7936: 	}
 7937: # ------------------------------------------ fourth, look in resource metadata
 7938: 
 7939: 	$spacequalifierrest=~s/\./\_/;
 7940: 	my $filename;
 7941: 	if (!$symbparm) { $symbparm=&symbread(); }
 7942: 	if ($symbparm) {
 7943: 	    $filename=(&decode_symb($symbparm))[2];
 7944: 	} else {
 7945: 	    $filename=$env{'request.filename'};
 7946: 	}
 7947: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7948: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7949: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7950: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7951: 
 7952: # ---------------------------------------------- fourth, look in rest of course
 7953: 	if ($symbparm && defined($courseid) && 
 7954: 	    $courseid eq $env{'request.course.id'}) {
 7955: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7956: 				     $env{'course.'.$courseid.'.domain'},
 7957: 				     'course',
 7958: 				     ([$courselevelm,'map'   ],
 7959: 				      [$courselevel, 'course']));
 7960: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7961: 	}
 7962: # ------------------------------------------------------------------ Cascade up
 7963: 	unless ($space eq '0') {
 7964: 	    my @parts=split(/_/,$space);
 7965: 	    my $id=pop(@parts);
 7966: 	    my $part=join('_',@parts);
 7967: 	    if ($part eq '') { $part='0'; }
 7968: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7969: 				 $symbparm,$udom,$uname,$section,1);
 7970: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7971: 	}
 7972: 	if ($recurse) { return undef; }
 7973: 	my $pack_def=&packages_tab_default($filename,$varname);
 7974: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7975: # ---------------------------------------------------- Any other user namespace
 7976:     } elsif ($realm eq 'environment') {
 7977: # ----------------------------------------------------------------- environment
 7978: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7979: 	    return $env{'environment.'.$spacequalifierrest};
 7980: 	} else {
 7981: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7982: 		return '';
 7983: 	    }
 7984: 	    my %returnhash=&userenvironment($udom,$uname,
 7985: 					    $spacequalifierrest);
 7986: 	    return $returnhash{$spacequalifierrest};
 7987: 	}
 7988:     } elsif ($realm eq 'system') {
 7989: # ----------------------------------------------------------------- system.time
 7990: 	if ($space eq 'time') {
 7991: 	    return time;
 7992:         }
 7993:     } elsif ($realm eq 'server') {
 7994: # ----------------------------------------------------------------- system.time
 7995: 	if ($space eq 'name') {
 7996: 	    return $ENV{'SERVER_NAME'};
 7997:         }
 7998:     }
 7999:     return '';
 8000: }
 8001: 
 8002: sub get_reply {
 8003:     my ($reply_value) = @_;
 8004:     if (ref($reply_value) eq 'ARRAY') {
 8005:         if (wantarray) {
 8006: 	    return @$reply_value;
 8007:         }
 8008:         return $reply_value->[0];
 8009:     } else {
 8010:         return $reply_value;
 8011:     }
 8012: }
 8013: 
 8014: sub check_group_parms {
 8015:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 8016:     my @groupitems = ();
 8017:     my $resultitem;
 8018:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 8019:     foreach my $group (@{$groups}) {
 8020:         foreach my $level (@levels) {
 8021:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 8022:              push(@groupitems,[$item,$level->[1]]);
 8023:         }
 8024:     }
 8025:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 8026:                             $env{'course.'.$courseid.'.domain'},
 8027:                                      'course',@groupitems);
 8028:     return $coursereply;
 8029: }
 8030: 
 8031: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 8032:     my ($courseid,@groups) = @_;
 8033:     @groups = sort(@groups);
 8034:     return @groups;
 8035: }
 8036: 
 8037: sub packages_tab_default {
 8038:     my ($uri,$varname)=@_;
 8039:     my (undef,$part,$name)=split(/\./,$varname);
 8040: 
 8041:     my (@extension,@specifics,$do_default);
 8042:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 8043: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 8044: 	if ($pack_type eq 'default') {
 8045: 	    $do_default=1;
 8046: 	} elsif ($pack_type eq 'extension') {
 8047: 	    push(@extension,[$package,$pack_type,$pack_part]);
 8048: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 8049: 	    # only look at packages defaults for packages that this id is
 8050: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 8051: 	}
 8052:     }
 8053:     # first look for a package that matches the requested part id
 8054:     foreach my $package (@specifics) {
 8055: 	my (undef,$pack_type,$pack_part)=@{$package};
 8056: 	next if ($pack_part ne $part);
 8057: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8058: 	    return $packagetab{"$pack_type&$name&default"};
 8059: 	}
 8060:     }
 8061:     # look for any possible matching non extension_ package
 8062:     foreach my $package (@specifics) {
 8063: 	my (undef,$pack_type,$pack_part)=@{$package};
 8064: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8065: 	    return $packagetab{"$pack_type&$name&default"};
 8066: 	}
 8067: 	if ($pack_type eq 'part') { $pack_part='0'; }
 8068: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 8069: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 8070: 	}
 8071:     }
 8072:     # look for any posible extension_ match
 8073:     foreach my $package (@extension) {
 8074: 	my ($package,$pack_type)=@{$package};
 8075: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8076: 	    return $packagetab{"$pack_type&$name&default"};
 8077: 	}
 8078: 	if (defined($packagetab{$package."&$name&default"})) {
 8079: 	    return $packagetab{$package."&$name&default"};
 8080: 	}
 8081:     }
 8082:     # look for a global default setting
 8083:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 8084: 	return $packagetab{"default&$name&default"};
 8085:     }
 8086:     return undef;
 8087: }
 8088: 
 8089: sub add_prefix_and_part {
 8090:     my ($prefix,$part)=@_;
 8091:     my $keyroot;
 8092:     if (defined($prefix) && $prefix !~ /^__/) {
 8093: 	# prefix that has a part already
 8094: 	$keyroot=$prefix;
 8095:     } elsif (defined($prefix)) {
 8096: 	# prefix that is missing a part
 8097: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 8098:     } else {
 8099: 	# no prefix at all
 8100: 	if (defined($part)) { $keyroot='_'.$part; }
 8101:     }
 8102:     return $keyroot;
 8103: }
 8104: 
 8105: # ---------------------------------------------------------------- Get metadata
 8106: 
 8107: my %metaentry;
 8108: sub metadata {
 8109:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 8110:     $uri=&declutter($uri);
 8111:     # if it is a non metadata possible uri return quickly
 8112:     if (($uri eq '') || 
 8113: 	(($uri =~ m|^/*adm/|) && 
 8114: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 8115:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 8116: 	return undef;
 8117:     }
 8118:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 8119: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 8120: 	return undef;
 8121:     }
 8122:     my $filename=$uri;
 8123:     $uri=~s/\.meta$//;
 8124: #
 8125: # Is the metadata already cached?
 8126: # Look at timestamp of caching
 8127: # Everything is cached by the main uri, libraries are never directly cached
 8128: #
 8129:     if (!defined($liburi)) {
 8130: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 8131: 	if (defined($cached)) { return $result->{':'.$what}; }
 8132:     }
 8133:     {
 8134: #
 8135: # Is this a recursive call for a library?
 8136: #
 8137: #	if (! exists($metacache{$uri})) {
 8138: #	    $metacache{$uri}={};
 8139: #	}
 8140: 	my $cachetime = 60*60;
 8141:         if ($liburi) {
 8142: 	    $liburi=&declutter($liburi);
 8143:             $filename=$liburi;
 8144:         } else {
 8145: 	    &devalidate_cache_new('meta',$uri);
 8146: 	    undef(%metaentry);
 8147: 	}
 8148:         my %metathesekeys=();
 8149:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 8150: 	my $metastring;
 8151: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 8152: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 8153: 	    $metastring = 
 8154: 		&Apache::lonnet::ssi_body($which,
 8155: 					  ('grade_target' => 'meta'));
 8156: 	    $cachetime = 1; # only want this cached in the child not long term
 8157: 	} elsif ($uri !~ m -^(editupload)/-) {
 8158: 	    my $file=&filelocation('',&clutter($filename));
 8159: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 8160: 	    $metastring=&getfile($file);
 8161: 	}
 8162:         my $parser=HTML::LCParser->new(\$metastring);
 8163:         my $token;
 8164:         undef %metathesekeys;
 8165:         while ($token=$parser->get_token) {
 8166: 	    if ($token->[0] eq 'S') {
 8167: 		if (defined($token->[2]->{'package'})) {
 8168: #
 8169: # This is a package - get package info
 8170: #
 8171: 		    my $package=$token->[2]->{'package'};
 8172: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8173: 		    if (defined($token->[2]->{'id'})) { 
 8174: 			$keyroot.='_'.$token->[2]->{'id'}; 
 8175: 		    }
 8176: 		    if ($metaentry{':packages'}) {
 8177: 			$metaentry{':packages'}.=','.$package.$keyroot;
 8178: 		    } else {
 8179: 			$metaentry{':packages'}=$package.$keyroot;
 8180: 		    }
 8181: 		    foreach my $pack_entry (keys(%packagetab)) {
 8182: 			my $part=$keyroot;
 8183: 			$part=~s/^\_//;
 8184: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 8185: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 8186: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 8187: 			    # ignore package.tab specified default values
 8188:                             # here &package_tab_default() will fetch those
 8189: 			    if ($subp eq 'default') { next; }
 8190: 			    my $value=$packagetab{$pack_entry};
 8191: 			    my $unikey;
 8192: 			    if ($pack =~ /_0$/) {
 8193: 				$unikey='parameter_0_'.$name;
 8194: 				$part=0;
 8195: 			    } else {
 8196: 				$unikey='parameter'.$keyroot.'_'.$name;
 8197: 			    }
 8198: 			    if ($subp eq 'display') {
 8199: 				$value.=' [Part: '.$part.']';
 8200: 			    }
 8201: 			    $metaentry{':'.$unikey.'.part'}=$part;
 8202: 			    $metathesekeys{$unikey}=1;
 8203: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8204: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 8205: 			    }
 8206: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 8207: 				$metaentry{':'.$unikey}=
 8208: 				    $metaentry{':'.$unikey.'.default'};
 8209: 			    }
 8210: 			}
 8211: 		    }
 8212: 		} else {
 8213: #
 8214: # This is not a package - some other kind of start tag
 8215: #
 8216: 		    my $entry=$token->[1];
 8217: 		    my $unikey;
 8218: 		    if ($entry eq 'import') {
 8219: 			$unikey='';
 8220: 		    } else {
 8221: 			$unikey=$entry;
 8222: 		    }
 8223: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8224: 
 8225: 		    if (defined($token->[2]->{'id'})) { 
 8226: 			$unikey.='_'.$token->[2]->{'id'}; 
 8227: 		    }
 8228: 
 8229: 		    if ($entry eq 'import') {
 8230: #
 8231: # Importing a library here
 8232: #
 8233: 			if ($depthcount<20) {
 8234: 			    my $location=$parser->get_text('/import');
 8235: 			    my $dir=$filename;
 8236: 			    $dir=~s|[^/]*$||;
 8237: 			    $location=&filelocation($dir,$location);
 8238: 			    my $metadata = 
 8239: 				&metadata($uri,'keys', $location,$unikey,
 8240: 					  $depthcount+1);
 8241: 			    foreach my $meta (split(',',$metadata)) {
 8242: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 8243: 				$metathesekeys{$meta}=1;
 8244: 			    }
 8245: 			}
 8246: 		    } else { 
 8247: 			
 8248: 			if (defined($token->[2]->{'name'})) { 
 8249: 			    $unikey.='_'.$token->[2]->{'name'}; 
 8250: 			}
 8251: 			$metathesekeys{$unikey}=1;
 8252: 			foreach my $param (@{$token->[3]}) {
 8253: 			    $metaentry{':'.$unikey.'.'.$param} =
 8254: 				$token->[2]->{$param};
 8255: 			}
 8256: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 8257: 			my $default=$metaentry{':'.$unikey.'.default'};
 8258: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 8259: 		 # only ws inside the tag, and not in default, so use default
 8260: 		 # as value
 8261: 			    $metaentry{':'.$unikey}=$default;
 8262: 			} elsif ( $internaltext =~ /\S/ ) {
 8263: 		  # something interesting inside the tag
 8264: 			    $metaentry{':'.$unikey}=$internaltext;
 8265: 			} else {
 8266: 		  # no interesting values, don't set a default
 8267: 			}
 8268: # end of not-a-package not-a-library import
 8269: 		    }
 8270: # end of not-a-package start tag
 8271: 		}
 8272: # the next is the end of "start tag"
 8273: 	    }
 8274: 	}
 8275: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 8276: 	$extension = lc($extension);
 8277: 	if ($extension eq 'htm') { $extension='html'; }
 8278: 
 8279: 	foreach my $key (keys(%packagetab)) {
 8280: 	    #no specific packages #how's our extension
 8281: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 8282: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 8283: 					 \%metathesekeys);
 8284: 	}
 8285: 
 8286: 	if (!exists($metaentry{':packages'})
 8287: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 8288: 	    foreach my $key (keys(%packagetab)) {
 8289: 		#no specific packages well let's get default then
 8290: 		if ($key!~/^default&/) { next; }
 8291: 		&metadata_create_package_def($uri,$key,'default',
 8292: 					     \%metathesekeys);
 8293: 	    }
 8294: 	}
 8295: # are there custom rights to evaluate
 8296: 	if ($metaentry{':copyright'} eq 'custom') {
 8297: 
 8298:     #
 8299:     # Importing a rights file here
 8300:     #
 8301: 	    unless ($depthcount) {
 8302: 		my $location=$metaentry{':customdistributionfile'};
 8303: 		my $dir=$filename;
 8304: 		$dir=~s|[^/]*$||;
 8305: 		$location=&filelocation($dir,$location);
 8306: 		my $rights_metadata =
 8307: 		    &metadata($uri,'keys',$location,'_rights',
 8308: 			      $depthcount+1);
 8309: 		foreach my $rights (split(',',$rights_metadata)) {
 8310: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 8311: 		    $metathesekeys{$rights}=1;
 8312: 		}
 8313: 	    }
 8314: 	}
 8315: 	# uniqifiy package listing
 8316: 	my %seen;
 8317: 	my @uniq_packages =
 8318: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 8319: 	$metaentry{':packages'} = join(',',@uniq_packages);
 8320: 
 8321: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 8322: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 8323: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 8324: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 8325: # this is the end of "was not already recently cached
 8326:     }
 8327:     return $metaentry{':'.$what};
 8328: }
 8329: 
 8330: sub metadata_create_package_def {
 8331:     my ($uri,$key,$package,$metathesekeys)=@_;
 8332:     my ($pack,$name,$subp)=split(/\&/,$key);
 8333:     if ($subp eq 'default') { next; }
 8334:     
 8335:     if (defined($metaentry{':packages'})) {
 8336: 	$metaentry{':packages'}.=','.$package;
 8337:     } else {
 8338: 	$metaentry{':packages'}=$package;
 8339:     }
 8340:     my $value=$packagetab{$key};
 8341:     my $unikey;
 8342:     $unikey='parameter_0_'.$name;
 8343:     $metaentry{':'.$unikey.'.part'}=0;
 8344:     $$metathesekeys{$unikey}=1;
 8345:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8346: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 8347:     }
 8348:     if (defined($metaentry{':'.$unikey.'.default'})) {
 8349: 	$metaentry{':'.$unikey}=
 8350: 	    $metaentry{':'.$unikey.'.default'};
 8351:     }
 8352: }
 8353: 
 8354: sub metadata_generate_part0 {
 8355:     my ($metadata,$metacache,$uri) = @_;
 8356:     my %allnames;
 8357:     foreach my $metakey (keys(%$metadata)) {
 8358: 	if ($metakey=~/^parameter\_(.*)/) {
 8359: 	  my $part=$$metacache{':'.$metakey.'.part'};
 8360: 	  my $name=$$metacache{':'.$metakey.'.name'};
 8361: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 8362: 	    $allnames{$name}=$part;
 8363: 	  }
 8364: 	}
 8365:     }
 8366:     foreach my $name (keys(%allnames)) {
 8367:       $$metadata{"parameter_0_$name"}=1;
 8368:       my $key=":parameter_0_$name";
 8369:       $$metacache{"$key.part"}='0';
 8370:       $$metacache{"$key.name"}=$name;
 8371:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 8372: 					   $allnames{$name}.'_'.$name.
 8373: 					   '.type'};
 8374:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 8375: 			     '.display'};
 8376:       my $expr='[Part: '.$allnames{$name}.']';
 8377:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 8378:       $$metacache{"$key.display"}=$olddis;
 8379:     }
 8380: }
 8381: 
 8382: # ------------------------------------------------------ Devalidate title cache
 8383: 
 8384: sub devalidate_title_cache {
 8385:     my ($url)=@_;
 8386:     if (!$env{'request.course.id'}) { return; }
 8387:     my $symb=&symbread($url);
 8388:     if (!$symb) { return; }
 8389:     my $key=$env{'request.course.id'}."\0".$symb;
 8390:     &devalidate_cache_new('title',$key);
 8391: }
 8392: 
 8393: # ------------------------------------------------- Get the title of a course
 8394: 
 8395: sub current_course_title {
 8396:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 8397: }
 8398: # ------------------------------------------------- Get the title of a resource
 8399: 
 8400: sub gettitle {
 8401:     my $urlsymb=shift;
 8402:     my $symb=&symbread($urlsymb);
 8403:     if ($symb) {
 8404: 	my $key=$env{'request.course.id'}."\0".$symb;
 8405: 	my ($result,$cached)=&is_cached_new('title',$key);
 8406: 	if (defined($cached)) { 
 8407: 	    return $result;
 8408: 	}
 8409: 	my ($map,$resid,$url)=&decode_symb($symb);
 8410: 	my $title='';
 8411: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 8412: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 8413: 	} else {
 8414: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8415: 		    &GDBM_READER(),0640)) {
 8416: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 8417: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 8418: 		untie(%bighash);
 8419: 	    }
 8420: 	}
 8421: 	$title=~s/\&colon\;/\:/gs;
 8422: 	if ($title) {
 8423: 	    return &do_cache_new('title',$key,$title,600);
 8424: 	}
 8425: 	$urlsymb=$url;
 8426:     }
 8427:     my $title=&metadata($urlsymb,'title');
 8428:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 8429:     return $title;
 8430: }
 8431: 
 8432: sub get_slot {
 8433:     my ($which,$cnum,$cdom)=@_;
 8434:     if (!$cnum || !$cdom) {
 8435: 	(undef,my $courseid)=&whichuser();
 8436: 	$cdom=$env{'course.'.$courseid.'.domain'};
 8437: 	$cnum=$env{'course.'.$courseid.'.num'};
 8438:     }
 8439:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 8440:     my %slotinfo;
 8441:     if (exists($remembered{$key})) {
 8442: 	$slotinfo{$which} = $remembered{$key};
 8443:     } else {
 8444: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 8445: 	&Apache::lonhomework::showhash(%slotinfo);
 8446: 	my ($tmp)=keys(%slotinfo);
 8447: 	if ($tmp=~/^error:/) { return (); }
 8448: 	$remembered{$key} = $slotinfo{$which};
 8449:     }
 8450:     if (ref($slotinfo{$which}) eq 'HASH') {
 8451: 	return %{$slotinfo{$which}};
 8452:     }
 8453:     return $slotinfo{$which};
 8454: }
 8455: # ------------------------------------------------- Update symbolic store links
 8456: 
 8457: sub symblist {
 8458:     my ($mapname,%newhash)=@_;
 8459:     $mapname=&deversion(&declutter($mapname));
 8460:     my %hash;
 8461:     if (($env{'request.course.fn'}) && (%newhash)) {
 8462:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8463:                       &GDBM_WRCREAT(),0640)) {
 8464: 	    foreach my $url (keys(%newhash)) {
 8465: 		next if ($url eq 'last_known'
 8466: 			 && $env{'form.no_update_last_known'});
 8467: 		$hash{declutter($url)}=&encode_symb($mapname,
 8468: 						    $newhash{$url}->[1],
 8469: 						    $newhash{$url}->[0]);
 8470:             }
 8471:             if (untie(%hash)) {
 8472: 		return 'ok';
 8473:             }
 8474:         }
 8475:     }
 8476:     return 'error';
 8477: }
 8478: 
 8479: # --------------------------------------------------------------- Verify a symb
 8480: 
 8481: sub symbverify {
 8482:     my ($symb,$thisurl)=@_;
 8483:     my $thisfn=$thisurl;
 8484:     $thisfn=&declutter($thisfn);
 8485: # direct jump to resource in page or to a sequence - will construct own symbs
 8486:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 8487: # check URL part
 8488:     my ($map,$resid,$url)=&decode_symb($symb);
 8489: 
 8490:     unless ($url eq $thisfn) { return 0; }
 8491: 
 8492:     $symb=&symbclean($symb);
 8493:     $thisurl=&deversion($thisurl);
 8494:     $thisfn=&deversion($thisfn);
 8495: 
 8496:     my %bighash;
 8497:     my $okay=0;
 8498: 
 8499:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8500:                             &GDBM_READER(),0640)) {
 8501:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 8502:             $thisurl =~ s/\?.+$//;
 8503:         }
 8504:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 8505:         unless ($ids) { 
 8506:            $ids=$bighash{'ids_/'.$thisurl};
 8507:         }
 8508:         if ($ids) {
 8509: # ------------------------------------------------------------------- Has ID(s)
 8510: 	    foreach my $id (split(/\,/,$ids)) {
 8511: 	       my ($mapid,$resid)=split(/\./,$id);
 8512:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 8513:                    $symb =~ s/\?.+$//;
 8514:                }
 8515:                if (
 8516:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 8517:    eq $symb) { 
 8518: 		   if (($env{'request.role.adv'}) ||
 8519: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 8520: 		       $okay=1; 
 8521: 		   }
 8522: 	       }
 8523: 	   }
 8524:         }
 8525: 	untie(%bighash);
 8526:     }
 8527:     return $okay;
 8528: }
 8529: 
 8530: # --------------------------------------------------------------- Clean-up symb
 8531: 
 8532: sub symbclean {
 8533:     my $symb=shift;
 8534:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8535: # remove version from map
 8536:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 8537: 
 8538: # remove version from URL
 8539:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 8540: 
 8541: # remove wrapper
 8542: 
 8543:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 8544:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 8545:     return $symb;
 8546: }
 8547: 
 8548: # ---------------------------------------------- Split symb to find map and url
 8549: 
 8550: sub encode_symb {
 8551:     my ($map,$resid,$url)=@_;
 8552:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 8553: }
 8554: 
 8555: sub decode_symb {
 8556:     my $symb=shift;
 8557:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8558:     my ($map,$resid,$url)=split(/___/,$symb);
 8559:     return (&fixversion($map),$resid,&fixversion($url));
 8560: }
 8561: 
 8562: sub fixversion {
 8563:     my $fn=shift;
 8564:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 8565:     my %bighash;
 8566:     my $uri=&clutter($fn);
 8567:     my $key=$env{'request.course.id'}.'_'.$uri;
 8568: # is this cached?
 8569:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 8570:     if (defined($cached)) { return $result; }
 8571: # unfortunately not cached, or expired
 8572:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8573: 	    &GDBM_READER(),0640)) {
 8574:  	if ($bighash{'version_'.$uri}) {
 8575:  	    my $version=$bighash{'version_'.$uri};
 8576:  	    unless (($version eq 'mostrecent') || 
 8577: 		    ($version==&getversion($uri))) {
 8578:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 8579:  	    }
 8580:  	}
 8581:  	untie %bighash;
 8582:     }
 8583:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 8584: }
 8585: 
 8586: sub deversion {
 8587:     my $url=shift;
 8588:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8589:     return $url;
 8590: }
 8591: 
 8592: # ------------------------------------------------------ Return symb list entry
 8593: 
 8594: sub symbread {
 8595:     my ($thisfn,$donotrecurse)=@_;
 8596:     my $cache_str='request.symbread.cached.'.$thisfn;
 8597:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8598: # no filename provided? try from environment
 8599:     unless ($thisfn) {
 8600:         if ($env{'request.symb'}) {
 8601: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8602: 	}
 8603: 	$thisfn=$env{'request.filename'};
 8604:     }
 8605:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8606: # is that filename actually a symb? Verify, clean, and return
 8607:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8608: 	if (&symbverify($thisfn,$1)) {
 8609: 	    return $env{$cache_str}=&symbclean($thisfn);
 8610: 	}
 8611:     }
 8612:     $thisfn=declutter($thisfn);
 8613:     my %hash;
 8614:     my %bighash;
 8615:     my $syval='';
 8616:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8617:         my $targetfn = $thisfn;
 8618:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8619:             $targetfn = 'adm/wrapper/'.$thisfn;
 8620:         }
 8621: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8622: 	    $targetfn=$1;
 8623: 	}
 8624:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8625:                       &GDBM_READER(),0640)) {
 8626: 	    $syval=$hash{$targetfn};
 8627:             untie(%hash);
 8628:         }
 8629: # ---------------------------------------------------------- There was an entry
 8630:         if ($syval) {
 8631: 	    #unless ($syval=~/\_\d+$/) {
 8632: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8633: 		    #&appenv({'request.ambiguous' => $thisfn});
 8634: 		    #return $env{$cache_str}='';
 8635: 		#}    
 8636: 		#$syval.=$1;
 8637: 	    #}
 8638:         } else {
 8639: # ------------------------------------------------------- Was not in symb table
 8640:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8641:                             &GDBM_READER(),0640)) {
 8642: # ---------------------------------------------- Get ID(s) for current resource
 8643:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8644:               unless ($ids) { 
 8645:                  $ids=$bighash{'ids_/'.$thisfn};
 8646:               }
 8647:               unless ($ids) {
 8648: # alias?
 8649: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8650:               }
 8651:               if ($ids) {
 8652: # ------------------------------------------------------------------- Has ID(s)
 8653:                  my @possibilities=split(/\,/,$ids);
 8654:                  if ($#possibilities==0) {
 8655: # ----------------------------------------------- There is only one possibility
 8656: 		     my ($mapid,$resid)=split(/\./,$ids);
 8657: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8658: 						    $resid,$thisfn);
 8659:                  } elsif (!$donotrecurse) {
 8660: # ------------------------------------------ There is more than one possibility
 8661:                      my $realpossible=0;
 8662:                      foreach my $id (@possibilities) {
 8663: 			 my $file=$bighash{'src_'.$id};
 8664:                          if (&allowed('bre',$file)) {
 8665:          		    my ($mapid,$resid)=split(/\./,$id);
 8666:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8667: 				$realpossible++;
 8668:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8669: 						    $resid,$thisfn);
 8670:                             }
 8671: 			 }
 8672:                      }
 8673: 		     if ($realpossible!=1) { $syval=''; }
 8674:                  } else {
 8675:                      $syval='';
 8676:                  }
 8677: 	      }
 8678:               untie(%bighash)
 8679:            }
 8680:         }
 8681:         if ($syval) {
 8682: 	    return $env{$cache_str}=$syval;
 8683:         }
 8684:     }
 8685:     &appenv({'request.ambiguous' => $thisfn});
 8686:     return $env{$cache_str}='';
 8687: }
 8688: 
 8689: # ---------------------------------------------------------- Return random seed
 8690: 
 8691: sub numval {
 8692:     my $txt=shift;
 8693:     $txt=~tr/A-J/0-9/;
 8694:     $txt=~tr/a-j/0-9/;
 8695:     $txt=~tr/K-T/0-9/;
 8696:     $txt=~tr/k-t/0-9/;
 8697:     $txt=~tr/U-Z/0-5/;
 8698:     $txt=~tr/u-z/0-5/;
 8699:     $txt=~s/\D//g;
 8700:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8701:     return int($txt);
 8702: }
 8703: 
 8704: sub numval2 {
 8705:     my $txt=shift;
 8706:     $txt=~tr/A-J/0-9/;
 8707:     $txt=~tr/a-j/0-9/;
 8708:     $txt=~tr/K-T/0-9/;
 8709:     $txt=~tr/k-t/0-9/;
 8710:     $txt=~tr/U-Z/0-5/;
 8711:     $txt=~tr/u-z/0-5/;
 8712:     $txt=~s/\D//g;
 8713:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8714:     my $total;
 8715:     foreach my $val (@txts) { $total+=$val; }
 8716:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8717:     return int($total);
 8718: }
 8719: 
 8720: sub numval3 {
 8721:     use integer;
 8722:     my $txt=shift;
 8723:     $txt=~tr/A-J/0-9/;
 8724:     $txt=~tr/a-j/0-9/;
 8725:     $txt=~tr/K-T/0-9/;
 8726:     $txt=~tr/k-t/0-9/;
 8727:     $txt=~tr/U-Z/0-5/;
 8728:     $txt=~tr/u-z/0-5/;
 8729:     $txt=~s/\D//g;
 8730:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8731:     my $total;
 8732:     foreach my $val (@txts) { $total+=$val; }
 8733:     if ($_64bit) { $total=(($total<<32)>>32); }
 8734:     return $total;
 8735: }
 8736: 
 8737: sub digest {
 8738:     my ($data)=@_;
 8739:     my $digest=&Digest::MD5::md5($data);
 8740:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8741:     my ($e,$f);
 8742:     {
 8743:         use integer;
 8744:         $e=($a+$b);
 8745:         $f=($c+$d);
 8746:         if ($_64bit) {
 8747:             $e=(($e<<32)>>32);
 8748:             $f=(($f<<32)>>32);
 8749:         }
 8750:     }
 8751:     if (wantarray) {
 8752: 	return ($e,$f);
 8753:     } else {
 8754: 	my $g;
 8755: 	{
 8756: 	    use integer;
 8757: 	    $g=($e+$f);
 8758: 	    if ($_64bit) {
 8759: 		$g=(($g<<32)>>32);
 8760: 	    }
 8761: 	}
 8762: 	return $g;
 8763:     }
 8764: }
 8765: 
 8766: sub latest_rnd_algorithm_id {
 8767:     return '64bit5';
 8768: }
 8769: 
 8770: sub get_rand_alg {
 8771:     my ($courseid)=@_;
 8772:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 8773:     if ($courseid) {
 8774: 	return $env{"course.$courseid.rndseed"};
 8775:     }
 8776:     return &latest_rnd_algorithm_id();
 8777: }
 8778: 
 8779: sub validCODE {
 8780:     my ($CODE)=@_;
 8781:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 8782:     return 0;
 8783: }
 8784: 
 8785: sub getCODE {
 8786:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 8787:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 8788: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 8789: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 8790: 	return $Apache::lonhomework::history{'resource.CODE'};
 8791:     }
 8792:     return undef;
 8793: }
 8794: 
 8795: sub rndseed {
 8796:     my ($symb,$courseid,$domain,$username)=@_;
 8797:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 8798:     if (!defined($symb)) {
 8799: 	unless ($symb=$wsymb) { return time; }
 8800:     }
 8801:     if (!$courseid) { $courseid=$wcourseid; }
 8802:     if (!$domain) { $domain=$wdomain; }
 8803:     if (!$username) { $username=$wusername }
 8804:     my $which=&get_rand_alg();
 8805: 
 8806:     if (defined(&getCODE())) {
 8807: 	if ($which eq '64bit5') {
 8808: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 8809: 	} elsif ($which eq '64bit4') {
 8810: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 8811: 	} else {
 8812: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 8813: 	}
 8814:     } elsif ($which eq '64bit5') {
 8815: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 8816:     } elsif ($which eq '64bit4') {
 8817: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 8818:     } elsif ($which eq '64bit3') {
 8819: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 8820:     } elsif ($which eq '64bit2') {
 8821: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 8822:     } elsif ($which eq '64bit') {
 8823: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 8824:     }
 8825:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 8826: }
 8827: 
 8828: sub rndseed_32bit {
 8829:     my ($symb,$courseid,$domain,$username)=@_;
 8830:     {
 8831: 	use integer;
 8832: 	my $symbchck=unpack("%32C*",$symb) << 27;
 8833: 	my $symbseed=numval($symb) << 22;
 8834: 	my $namechck=unpack("%32C*",$username) << 17;
 8835: 	my $nameseed=numval($username) << 12;
 8836: 	my $domainseed=unpack("%32C*",$domain) << 7;
 8837: 	my $courseseed=unpack("%32C*",$courseid);
 8838: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 8839: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8840: 	#&logthis("rndseed :$num:$symb");
 8841: 	if ($_64bit) { $num=(($num<<32)>>32); }
 8842: 	return $num;
 8843:     }
 8844: }
 8845: 
 8846: sub rndseed_64bit {
 8847:     my ($symb,$courseid,$domain,$username)=@_;
 8848:     {
 8849: 	use integer;
 8850: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8851: 	my $symbseed=numval($symb) << 10;
 8852: 	my $namechck=unpack("%32S*",$username);
 8853: 	
 8854: 	my $nameseed=numval($username) << 21;
 8855: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8856: 	my $courseseed=unpack("%32S*",$courseid);
 8857: 	
 8858: 	my $num1=$symbchck+$symbseed+$namechck;
 8859: 	my $num2=$nameseed+$domainseed+$courseseed;
 8860: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8861: 	#&logthis("rndseed :$num:$symb");
 8862: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8863: 	return "$num1,$num2";
 8864:     }
 8865: }
 8866: 
 8867: sub rndseed_64bit2 {
 8868:     my ($symb,$courseid,$domain,$username)=@_;
 8869:     {
 8870: 	use integer;
 8871: 	# strings need to be an even # of cahracters long, it it is odd the
 8872:         # last characters gets thrown away
 8873: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8874: 	my $symbseed=numval($symb) << 10;
 8875: 	my $namechck=unpack("%32S*",$username.' ');
 8876: 	
 8877: 	my $nameseed=numval($username) << 21;
 8878: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8879: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8880: 	
 8881: 	my $num1=$symbchck+$symbseed+$namechck;
 8882: 	my $num2=$nameseed+$domainseed+$courseseed;
 8883: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8884: 	#&logthis("rndseed :$num:$symb");
 8885: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8886: 	return "$num1,$num2";
 8887:     }
 8888: }
 8889: 
 8890: sub rndseed_64bit3 {
 8891:     my ($symb,$courseid,$domain,$username)=@_;
 8892:     {
 8893: 	use integer;
 8894: 	# strings need to be an even # of cahracters long, it it is odd the
 8895:         # last characters gets thrown away
 8896: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8897: 	my $symbseed=numval2($symb) << 10;
 8898: 	my $namechck=unpack("%32S*",$username.' ');
 8899: 	
 8900: 	my $nameseed=numval2($username) << 21;
 8901: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8902: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8903: 	
 8904: 	my $num1=$symbchck+$symbseed+$namechck;
 8905: 	my $num2=$nameseed+$domainseed+$courseseed;
 8906: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8907: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8908: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8909: 	
 8910: 	return "$num1:$num2";
 8911:     }
 8912: }
 8913: 
 8914: sub rndseed_64bit4 {
 8915:     my ($symb,$courseid,$domain,$username)=@_;
 8916:     {
 8917: 	use integer;
 8918: 	# strings need to be an even # of cahracters long, it it is odd the
 8919:         # last characters gets thrown away
 8920: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8921: 	my $symbseed=numval3($symb) << 10;
 8922: 	my $namechck=unpack("%32S*",$username.' ');
 8923: 	
 8924: 	my $nameseed=numval3($username) << 21;
 8925: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8926: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8927: 	
 8928: 	my $num1=$symbchck+$symbseed+$namechck;
 8929: 	my $num2=$nameseed+$domainseed+$courseseed;
 8930: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8931: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8932: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8933: 	
 8934: 	return "$num1:$num2";
 8935:     }
 8936: }
 8937: 
 8938: sub rndseed_64bit5 {
 8939:     my ($symb,$courseid,$domain,$username)=@_;
 8940:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8941:     return "$num1:$num2";
 8942: }
 8943: 
 8944: sub rndseed_CODE_64bit {
 8945:     my ($symb,$courseid,$domain,$username)=@_;
 8946:     {
 8947: 	use integer;
 8948: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8949: 	my $symbseed=numval2($symb);
 8950: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8951: 	my $CODEseed=numval(&getCODE());
 8952: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8953: 	my $num1=$symbseed+$CODEchck;
 8954: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8955: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8956: 	#&logthis("rndseed :$num1:$num2:$symb");
 8957: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8958: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8959: 	return "$num1:$num2";
 8960:     }
 8961: }
 8962: 
 8963: sub rndseed_CODE_64bit4 {
 8964:     my ($symb,$courseid,$domain,$username)=@_;
 8965:     {
 8966: 	use integer;
 8967: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8968: 	my $symbseed=numval3($symb);
 8969: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8970: 	my $CODEseed=numval3(&getCODE());
 8971: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8972: 	my $num1=$symbseed+$CODEchck;
 8973: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8974: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8975: 	#&logthis("rndseed :$num1:$num2:$symb");
 8976: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8977: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8978: 	return "$num1:$num2";
 8979:     }
 8980: }
 8981: 
 8982: sub rndseed_CODE_64bit5 {
 8983:     my ($symb,$courseid,$domain,$username)=@_;
 8984:     my $code = &getCODE();
 8985:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8986:     return "$num1:$num2";
 8987: }
 8988: 
 8989: sub setup_random_from_rndseed {
 8990:     my ($rndseed)=@_;
 8991:     if ($rndseed =~/([,:])/) {
 8992: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8993: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8994:     } else {
 8995: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8996:     }
 8997: }
 8998: 
 8999: sub latest_receipt_algorithm_id {
 9000:     return 'receipt3';
 9001: }
 9002: 
 9003: sub recunique {
 9004:     my $fucourseid=shift;
 9005:     my $unique;
 9006:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 9007: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9008: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 9009:     } else {
 9010: 	$unique=$perlvar{'lonReceipt'};
 9011:     }
 9012:     return unpack("%32C*",$unique);
 9013: }
 9014: 
 9015: sub recprefix {
 9016:     my $fucourseid=shift;
 9017:     my $prefix;
 9018:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 9019: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9020: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 9021:     } else {
 9022: 	$prefix=$perlvar{'lonHostID'};
 9023:     }
 9024:     return unpack("%32C*",$prefix);
 9025: }
 9026: 
 9027: sub ireceipt {
 9028:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 9029: 
 9030:     my $return =&recprefix($fucourseid).'-';
 9031: 
 9032:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 9033: 	$env{'request.state'} eq 'construct') {
 9034: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 9035: 	return $return;
 9036:     }
 9037: 
 9038:     my $cuname=unpack("%32C*",$funame);
 9039:     my $cudom=unpack("%32C*",$fudom);
 9040:     my $cucourseid=unpack("%32C*",$fucourseid);
 9041:     my $cusymb=unpack("%32C*",$fusymb);
 9042:     my $cunique=&recunique($fucourseid);
 9043:     my $cpart=unpack("%32S*",$part);
 9044:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 9045: 
 9046: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 9047: 			       
 9048: 	$return.= ($cunique%$cuname+
 9049: 		   $cunique%$cudom+
 9050: 		   $cusymb%$cuname+
 9051: 		   $cusymb%$cudom+
 9052: 		   $cucourseid%$cuname+
 9053: 		   $cucourseid%$cudom+
 9054: 		   $cpart%$cuname+
 9055: 		   $cpart%$cudom);
 9056:     } else {
 9057: 	$return.= ($cunique%$cuname+
 9058: 		   $cunique%$cudom+
 9059: 		   $cusymb%$cuname+
 9060: 		   $cusymb%$cudom+
 9061: 		   $cucourseid%$cuname+
 9062: 		   $cucourseid%$cudom);
 9063:     }
 9064:     return $return;
 9065: }
 9066: 
 9067: sub receipt {
 9068:     my ($part)=@_;
 9069:     my ($symb,$courseid,$domain,$name) = &whichuser();
 9070:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 9071: }
 9072: 
 9073: sub whichuser {
 9074:     my ($passedsymb)=@_;
 9075:     my ($symb,$courseid,$domain,$name,$publicuser);
 9076:     if (defined($env{'form.grade_symb'})) {
 9077: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 9078: 	my $allowed=&allowed('vgr',$tmp_courseid);
 9079: 	if (!$allowed &&
 9080: 	    exists($env{'request.course.sec'}) &&
 9081: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 9082: 	    $allowed=&allowed('vgr',$tmp_courseid.
 9083: 			      '/'.$env{'request.course.sec'});
 9084: 	}
 9085: 	if ($allowed) {
 9086: 	    ($symb)=&get_env_multiple('form.grade_symb');
 9087: 	    $courseid=$tmp_courseid;
 9088: 	    ($domain)=&get_env_multiple('form.grade_domain');
 9089: 	    ($name)=&get_env_multiple('form.grade_username');
 9090: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 9091: 	}
 9092:     }
 9093:     if (!$passedsymb) {
 9094: 	$symb=&symbread();
 9095:     } else {
 9096: 	$symb=$passedsymb;
 9097:     }
 9098:     $courseid=$env{'request.course.id'};
 9099:     $domain=$env{'user.domain'};
 9100:     $name=$env{'user.name'};
 9101:     if ($name eq 'public' && $domain eq 'public') {
 9102: 	if (!defined($env{'form.username'})) {
 9103: 	    $env{'form.username'}.=time.rand(10000000);
 9104: 	}
 9105: 	$name.=$env{'form.username'};
 9106:     }
 9107:     return ($symb,$courseid,$domain,$name,$publicuser);
 9108: 
 9109: }
 9110: 
 9111: # ------------------------------------------------------------ Serves up a file
 9112: # returns either the contents of the file or 
 9113: # -1 if the file doesn't exist
 9114: #
 9115: # if the target is a file that was uploaded via DOCS, 
 9116: # a check will be made to see if a current copy exists on the local server,
 9117: # if it does this will be served, otherwise a copy will be retrieved from
 9118: # the home server for the course and stored in /home/httpd/html/userfiles on
 9119: # the local server.   
 9120: 
 9121: sub getfile {
 9122:     my ($file) = @_;
 9123:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 9124:     &repcopy($file);
 9125:     return &readfile($file);
 9126: }
 9127: 
 9128: sub repcopy_userfile {
 9129:     my ($file)=@_;
 9130:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 9131:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 9132:     my ($cdom,$cnum,$filename) = 
 9133: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 9134:     my $uri="/uploaded/$cdom/$cnum/$filename";
 9135:     if (-e "$file") {
 9136: # we already have a local copy, check it out
 9137: 	my @fileinfo = stat($file);
 9138: 	my $rtncode;
 9139: 	my $info;
 9140: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 9141: 	if ($lwpresp ne 'ok') {
 9142: # there is no such file anymore, even though we had a local copy
 9143: 	    if ($rtncode eq '404') {
 9144: 		unlink($file);
 9145: 	    }
 9146: 	    return -1;
 9147: 	}
 9148: 	if ($info < $fileinfo[9]) {
 9149: # nice, the file we have is up-to-date, just say okay
 9150: 	    return 'ok';
 9151: 	} else {
 9152: # the file is outdated, get rid of it
 9153: 	    unlink($file);
 9154: 	}
 9155:     }
 9156: # one way or the other, at this point, we don't have the file
 9157: # construct the correct path for the file
 9158:     my @parts = ($cdom,$cnum); 
 9159:     if ($filename =~ m|^(.+)/[^/]+$|) {
 9160: 	push @parts, split(/\//,$1);
 9161:     }
 9162:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 9163:     foreach my $part (@parts) {
 9164: 	$path .= '/'.$part;
 9165: 	if (!-e $path) {
 9166: 	    mkdir($path,0770);
 9167: 	}
 9168:     }
 9169: # now the path exists for sure
 9170: # get a user agent
 9171:     my $ua=new LWP::UserAgent;
 9172:     my $transferfile=$file.'.in.transfer';
 9173: # FIXME: this should flock
 9174:     if (-e $transferfile) { return 'ok'; }
 9175:     my $request;
 9176:     $uri=~s/^\///;
 9177:     my $homeserver = &homeserver($cnum,$cdom);
 9178:     my $protocol = $protocol{$homeserver};
 9179:     $protocol = 'http' if ($protocol ne 'https');
 9180:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 9181:     my $response=$ua->request($request,$transferfile);
 9182: # did it work?
 9183:     if ($response->is_error()) {
 9184: 	unlink($transferfile);
 9185: 	&logthis("Userfile repcopy failed for $uri");
 9186: 	return -1;
 9187:     }
 9188: # worked, rename the transfer file
 9189:     rename($transferfile,$file);
 9190:     return 'ok';
 9191: }
 9192: 
 9193: sub tokenwrapper {
 9194:     my $uri=shift;
 9195:     $uri=~s|^https?\://([^/]+)||;
 9196:     $uri=~s|^/||;
 9197:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 9198:     my $token=$1;
 9199:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 9200:     if ($udom && $uname && $file) {
 9201: 	$file=~s|(\?\.*)*$||;
 9202:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 9203:         my $homeserver = &homeserver($uname,$udom);
 9204:         my $protocol = $protocol{$homeserver};
 9205:         $protocol = 'http' if ($protocol ne 'https');
 9206:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 9207:                (($uri=~/\?/)?'&':'?').'token='.$token.
 9208:                                '&tokenissued='.$perlvar{'lonHostID'};
 9209:     } else {
 9210:         return '/adm/notfound.html';
 9211:     }
 9212: }
 9213: 
 9214: # call with reqtype HEAD: get last modification time
 9215: # call with reqtype GET: get the file contents
 9216: # Do not call this with reqtype GET for large files! It loads everything into memory
 9217: #
 9218: sub getuploaded {
 9219:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 9220:     $uri=~s/^\///;
 9221:     my $homeserver = &homeserver($cnum,$cdom);
 9222:     my $protocol = $protocol{$homeserver};
 9223:     $protocol = 'http' if ($protocol ne 'https');
 9224:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 9225:     my $ua=new LWP::UserAgent;
 9226:     my $request=new HTTP::Request($reqtype,$uri);
 9227:     my $response=$ua->request($request);
 9228:     $$rtncode = $response->code;
 9229:     if (! $response->is_success()) {
 9230: 	return 'failed';
 9231:     }      
 9232:     if ($reqtype eq 'HEAD') {
 9233: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 9234:     } elsif ($reqtype eq 'GET') {
 9235: 	$$info = $response->content;
 9236:     }
 9237:     return 'ok';
 9238: }
 9239: 
 9240: sub readfile {
 9241:     my $file = shift;
 9242:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 9243:     my $fh;
 9244:     open($fh,"<$file");
 9245:     my $a='';
 9246:     while (my $line = <$fh>) { $a .= $line; }
 9247:     return $a;
 9248: }
 9249: 
 9250: sub filelocation {
 9251:     my ($dir,$file) = @_;
 9252:     my $location;
 9253:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 9254: 
 9255:     if ($file =~ m-^/adm/-) {
 9256: 	$file=~s-^/adm/wrapper/-/-;
 9257: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9258:     }
 9259: 
 9260:     if ($file=~m:^/~:) { # is a contruction space reference
 9261:         $location = $file;
 9262:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 9263:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 9264: 	# is a correct contruction space reference
 9265:         $location = $file;
 9266:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 9267:         $location = $file;
 9268:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 9269:         my ($udom,$uname,$filename)=
 9270:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 9271:         my $home=&homeserver($uname,$udom);
 9272:         my $is_me=0;
 9273:         my @ids=&current_machine_ids();
 9274:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 9275:         if ($is_me) {
 9276:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 9277:         } else {
 9278:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 9279:   	      $udom.'/'.$uname.'/'.$filename;
 9280:         }
 9281:     } elsif ($file =~ m-^/adm/-) {
 9282: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 9283:     } else {
 9284:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9285:         $file=~s:^/res/:/:;
 9286:         if ( !( $file =~ m:^/:) ) {
 9287:             $location = $dir. '/'.$file;
 9288:         } else {
 9289:             $location = '/home/httpd/html/res'.$file;
 9290:         }
 9291:     }
 9292:     $location=~s://+:/:g; # remove duplicate /
 9293:     while ($location=~m{/\.\./}) {
 9294: 	if ($location =~ m{/[^/]+/\.\./}) {
 9295: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 9296: 	} else {
 9297: 	    $location=~ s{/\.\./}{/}g;
 9298: 	}
 9299:     } #remove dir/..
 9300:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 9301:     return $location;
 9302: }
 9303: 
 9304: sub hreflocation {
 9305:     my ($dir,$file)=@_;
 9306:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 9307: 	$file=filelocation($dir,$file);
 9308:     } elsif ($file=~m-^/adm/-) {
 9309: 	$file=~s-^/adm/wrapper/-/-;
 9310: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9311:     }
 9312:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 9313: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 9314:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 9315: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 9316:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 9317: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 9318: 	    -/uploaded/$1/$2/-x;
 9319:     }
 9320:     if ($file=~ m{^/userfiles/}) {
 9321: 	$file =~ s{^/userfiles/}{/uploaded/};
 9322:     }
 9323:     return $file;
 9324: }
 9325: 
 9326: sub current_machine_domains {
 9327:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 9328: }
 9329: 
 9330: sub machine_domains {
 9331:     my ($hostname) = @_;
 9332:     my @domains;
 9333:     my %hostname = &all_hostnames();
 9334:     while( my($id, $name) = each(%hostname)) {
 9335: #	&logthis("-$id-$name-$hostname-");
 9336: 	if ($hostname eq $name) {
 9337: 	    push(@domains,&host_domain($id));
 9338: 	}
 9339:     }
 9340:     return @domains;
 9341: }
 9342: 
 9343: sub current_machine_ids {
 9344:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 9345: }
 9346: 
 9347: sub machine_ids {
 9348:     my ($hostname) = @_;
 9349:     $hostname ||= &hostname($perlvar{'lonHostID'});
 9350:     my @ids;
 9351:     my %name_to_host = &all_names();
 9352:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 9353: 	return @{ $name_to_host{$hostname} };
 9354:     }
 9355:     return;
 9356: }
 9357: 
 9358: sub additional_machine_domains {
 9359:     my @domains;
 9360:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 9361:     while( my $line = <$fh>) {
 9362:         $line =~ s/\s//g;
 9363:         push(@domains,$line);
 9364:     }
 9365:     return @domains;
 9366: }
 9367: 
 9368: sub default_login_domain {
 9369:     my $domain = $perlvar{'lonDefDomain'};
 9370:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 9371:     foreach my $posdom (&current_machine_domains(),
 9372:                         &additional_machine_domains()) {
 9373:         if (lc($posdom) eq lc($testdomain)) {
 9374:             $domain=$posdom;
 9375:             last;
 9376:         }
 9377:     }
 9378:     return $domain;
 9379: }
 9380: 
 9381: # ------------------------------------------------------------- Declutters URLs
 9382: 
 9383: sub declutter {
 9384:     my $thisfn=shift;
 9385:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9386:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9387:     $thisfn=~s/^\///;
 9388:     $thisfn=~s|^adm/wrapper/||;
 9389:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 9390:     $thisfn=~s/^res\///;
 9391:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
 9392:         $thisfn=~s/\?.+$//;
 9393:     }
 9394:     return $thisfn;
 9395: }
 9396: 
 9397: # ------------------------------------------------------------- Clutter up URLs
 9398: 
 9399: sub clutter {
 9400:     my $thisfn='/'.&declutter(shift);
 9401:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 9402: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 9403:        $thisfn='/res'.$thisfn; 
 9404:     }
 9405:     if ($thisfn !~m|^/adm|) {
 9406: 	if ($thisfn =~ m|^/ext/|) {
 9407: 	    $thisfn='/adm/wrapper'.$thisfn;
 9408: 	} else {
 9409: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 9410: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 9411: 	    if ($embstyle eq 'ssi'
 9412: 		|| ($embstyle eq 'hdn')
 9413: 		|| ($embstyle eq 'rat')
 9414: 		|| ($embstyle eq 'prv')
 9415: 		|| ($embstyle eq 'ign')) {
 9416: 		#do nothing with these
 9417: 	    } elsif (($embstyle eq 'img') 
 9418: 		|| ($embstyle eq 'emb')
 9419: 		|| ($embstyle eq 'wrp')) {
 9420: 		$thisfn='/adm/wrapper'.$thisfn;
 9421: 	    } elsif ($embstyle eq 'unk'
 9422: 		     && $thisfn!~/\.(sequence|page)$/) {
 9423: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 9424: 	    } else {
 9425: #		&logthis("Got a blank emb style");
 9426: 	    }
 9427: 	}
 9428:     }
 9429:     return $thisfn;
 9430: }
 9431: 
 9432: sub clutter_with_no_wrapper {
 9433:     my $uri = &clutter(shift);
 9434:     if ($uri =~ m-^/adm/-) {
 9435: 	$uri =~ s-^/adm/wrapper/-/-;
 9436: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 9437:     }
 9438:     return $uri;
 9439: }
 9440: 
 9441: sub freeze_escape {
 9442:     my ($value)=@_;
 9443:     if (ref($value)) {
 9444: 	$value=&nfreeze($value);
 9445: 	return '__FROZEN__'.&escape($value);
 9446:     }
 9447:     return &escape($value);
 9448: }
 9449: 
 9450: 
 9451: sub thaw_unescape {
 9452:     my ($value)=@_;
 9453:     if ($value =~ /^__FROZEN__/) {
 9454: 	substr($value,0,10,undef);
 9455: 	$value=&unescape($value);
 9456: 	return &thaw($value);
 9457:     }
 9458:     return &unescape($value);
 9459: }
 9460: 
 9461: sub correct_line_ends {
 9462:     my ($result)=@_;
 9463:     $$result =~s/\r\n/\n/mg;
 9464:     $$result =~s/\r/\n/mg;
 9465: }
 9466: # ================================================================ Main Program
 9467: 
 9468: sub goodbye {
 9469:    &logthis("Starting Shut down");
 9470: #not converted to using infrastruture and probably shouldn't be
 9471:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 9472: #converted
 9473: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 9474:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 9475: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 9476: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 9477: #1.1 only
 9478: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 9479: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 9480: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 9481: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 9482:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 9483:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 9484:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 9485:    &flushcourselogs();
 9486:    &logthis("Shutting down");
 9487: }
 9488: 
 9489: sub get_dns {
 9490:     my ($url,$func,$ignore_cache) = @_;
 9491:     if (!$ignore_cache) {
 9492: 	my ($content,$cached)=
 9493: 	    &Apache::lonnet::is_cached_new('dns',$url);
 9494: 	if ($cached) {
 9495: 	    &$func($content);
 9496: 	    return;
 9497: 	}
 9498:     }
 9499: 
 9500:     my %alldns;
 9501:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9502:     foreach my $dns (<$config>) {
 9503: 	next if ($dns !~ /^\^(\S*)/x);
 9504:         my $line = $1;
 9505:         my ($host,$protocol) = split(/:/,$line);
 9506:         if ($protocol ne 'https') {
 9507:             $protocol = 'http';
 9508:         }
 9509: 	$alldns{$host} = $protocol;
 9510:     }
 9511:     while (%alldns) {
 9512: 	my ($dns) = keys(%alldns);
 9513: 	my $ua=new LWP::UserAgent;
 9514: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 9515: 	my $response=$ua->request($request);
 9516:         delete($alldns{$dns});
 9517: 	next if ($response->is_error());
 9518: 	my @content = split("\n",$response->content);
 9519: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 9520: 	&$func(\@content);
 9521: 	return;
 9522:     }
 9523:     close($config);
 9524:     my $which = (split('/',$url))[3];
 9525:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 9526:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 9527:     my @content = <$config>;
 9528:     &$func(\@content);
 9529:     return;
 9530: }
 9531: # ------------------------------------------------------------ Read domain file
 9532: {
 9533:     my $loaded;
 9534:     my %domain;
 9535: 
 9536:     sub parse_domain_tab {
 9537: 	my ($lines) = @_;
 9538: 	foreach my $line (@$lines) {
 9539: 	    next if ($line =~ /^(\#|\s*$ )/x);
 9540: 
 9541: 	    chomp($line);
 9542: 	    my ($name,@elements) = split(/:/,$line,9);
 9543: 	    my %this_domain;
 9544: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 9545: 			       'lang_def', 'city', 'longi', 'lati',
 9546: 			       'primary') {
 9547: 		$this_domain{$field} = shift(@elements);
 9548: 	    }
 9549: 	    $domain{$name} = \%this_domain;
 9550: 	}
 9551:     }
 9552: 
 9553:     sub reset_domain_info {
 9554: 	undef($loaded);
 9555: 	undef(%domain);
 9556:     }
 9557: 
 9558:     sub load_domain_tab {
 9559: 	my ($ignore_cache) = @_;
 9560: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 9561: 	my $fh;
 9562: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 9563: 	    my @lines = <$fh>;
 9564: 	    &parse_domain_tab(\@lines);
 9565: 	}
 9566: 	close($fh);
 9567: 	$loaded = 1;
 9568:     }
 9569: 
 9570:     sub domain {
 9571: 	&load_domain_tab() if (!$loaded);
 9572: 
 9573: 	my ($name,$what) = @_;
 9574: 	return if ( !exists($domain{$name}) );
 9575: 
 9576: 	if (!$what) {
 9577: 	    return $domain{$name}{'description'};
 9578: 	}
 9579: 	return $domain{$name}{$what};
 9580:     }
 9581: 
 9582:     sub domain_info {
 9583:         &load_domain_tab() if (!$loaded);
 9584:         return %domain;
 9585:     }
 9586: 
 9587: }
 9588: 
 9589: 
 9590: # ------------------------------------------------------------- Read hosts file
 9591: {
 9592:     my %hostname;
 9593:     my %hostdom;
 9594:     my %libserv;
 9595:     my $loaded;
 9596:     my %name_to_host;
 9597: 
 9598:     sub parse_hosts_tab {
 9599: 	my ($file) = @_;
 9600: 	foreach my $configline (@$file) {
 9601: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9602: 	    next if ($configline =~ /^\^/);
 9603: 	    chomp($configline);
 9604: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 9605: 	    $name=~s/\s//g;
 9606: 	    if ($id && $domain && $role && $name) {
 9607: 		$hostname{$id}=$name;
 9608: 		push(@{$name_to_host{$name}}, $id);
 9609: 		$hostdom{$id}=$domain;
 9610: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9611:                 if (defined($protocol)) {
 9612:                     if ($protocol eq 'https') {
 9613:                         $protocol{$id} = $protocol;
 9614:                     } else {
 9615:                         $protocol{$id} = 'http'; 
 9616:                     }
 9617:                 } else {
 9618:                     $protocol{$id} = 'http';
 9619:                 }
 9620: 	    }
 9621: 	}
 9622:     }
 9623:     
 9624:     sub reset_hosts_info {
 9625: 	&purge_remembered();
 9626: 	&reset_domain_info();
 9627: 	&reset_hosts_ip_info();
 9628: 	undef(%name_to_host);
 9629: 	undef(%hostname);
 9630: 	undef(%hostdom);
 9631: 	undef(%libserv);
 9632: 	undef($loaded);
 9633:     }
 9634: 
 9635:     sub load_hosts_tab {
 9636: 	my ($ignore_cache) = @_;
 9637: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9638: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9639: 	my @config = <$config>;
 9640: 	&parse_hosts_tab(\@config);
 9641: 	close($config);
 9642: 	$loaded=1;
 9643:     }
 9644: 
 9645:     sub hostname {
 9646: 	&load_hosts_tab() if (!$loaded);
 9647: 
 9648: 	my ($lonid) = @_;
 9649: 	return $hostname{$lonid};
 9650:     }
 9651: 
 9652:     sub all_hostnames {
 9653: 	&load_hosts_tab() if (!$loaded);
 9654: 
 9655: 	return %hostname;
 9656:     }
 9657: 
 9658:     sub all_names {
 9659: 	&load_hosts_tab() if (!$loaded);
 9660: 
 9661: 	return %name_to_host;
 9662:     }
 9663: 
 9664:     sub all_host_domain {
 9665:         &load_hosts_tab() if (!$loaded);
 9666:         return %hostdom;
 9667:     }
 9668: 
 9669:     sub is_library {
 9670: 	&load_hosts_tab() if (!$loaded);
 9671: 
 9672: 	return exists($libserv{$_[0]});
 9673:     }
 9674: 
 9675:     sub all_library {
 9676: 	&load_hosts_tab() if (!$loaded);
 9677: 
 9678: 	return %libserv;
 9679:     }
 9680: 
 9681:     sub get_servers {
 9682: 	&load_hosts_tab() if (!$loaded);
 9683: 
 9684: 	my ($domain,$type) = @_;
 9685: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9686: 	                                          : %hostname;
 9687: 	my %result;
 9688: 	if (ref($domain) eq 'ARRAY') {
 9689: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9690: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9691: 		    $result{$host} = $hostname;
 9692: 		}
 9693: 	    }
 9694: 	} else {
 9695: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9696: 		if ($hostdom{$host} eq $domain) {
 9697: 		    $result{$host} = $hostname;
 9698: 		}
 9699: 	    }
 9700: 	}
 9701: 	return %result;
 9702:     }
 9703: 
 9704:     sub host_domain {
 9705: 	&load_hosts_tab() if (!$loaded);
 9706: 
 9707: 	my ($lonid) = @_;
 9708: 	return $hostdom{$lonid};
 9709:     }
 9710: 
 9711:     sub all_domains {
 9712: 	&load_hosts_tab() if (!$loaded);
 9713: 
 9714: 	my %seen;
 9715: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9716: 	return @uniq;
 9717:     }
 9718: }
 9719: 
 9720: { 
 9721:     my %iphost;
 9722:     my %name_to_ip;
 9723:     my %lonid_to_ip;
 9724: 
 9725:     sub get_hosts_from_ip {
 9726: 	my ($ip) = @_;
 9727: 	my %iphosts = &get_iphost();
 9728: 	if (ref($iphosts{$ip})) {
 9729: 	    return @{$iphosts{$ip}};
 9730: 	}
 9731: 	return;
 9732:     }
 9733:     
 9734:     sub reset_hosts_ip_info {
 9735: 	undef(%iphost);
 9736: 	undef(%name_to_ip);
 9737: 	undef(%lonid_to_ip);
 9738:     }
 9739: 
 9740:     sub get_host_ip {
 9741: 	my ($lonid) = @_;
 9742: 	if (exists($lonid_to_ip{$lonid})) {
 9743: 	    return $lonid_to_ip{$lonid};
 9744: 	}
 9745: 	my $name=&hostname($lonid);
 9746:    	my $ip = gethostbyname($name);
 9747: 	return if (!$ip || length($ip) ne 4);
 9748: 	$ip=inet_ntoa($ip);
 9749: 	$name_to_ip{$name}   = $ip;
 9750: 	$lonid_to_ip{$lonid} = $ip;
 9751: 	return $ip;
 9752:     }
 9753:     
 9754:     sub get_iphost {
 9755: 	my ($ignore_cache) = @_;
 9756: 
 9757: 	if (!$ignore_cache) {
 9758: 	    if (%iphost) {
 9759: 		return %iphost;
 9760: 	    }
 9761: 	    my ($ip_info,$cached)=
 9762: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 9763: 	    if ($cached) {
 9764: 		%iphost      = %{$ip_info->[0]};
 9765: 		%name_to_ip  = %{$ip_info->[1]};
 9766: 		%lonid_to_ip = %{$ip_info->[2]};
 9767: 		return %iphost;
 9768: 	    }
 9769: 	}
 9770: 
 9771: 	# get yesterday's info for fallback
 9772: 	my %old_name_to_ip;
 9773: 	my ($ip_info,$cached)=
 9774: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 9775: 	if ($cached) {
 9776: 	    %old_name_to_ip = %{$ip_info->[1]};
 9777: 	}
 9778: 
 9779: 	my %name_to_host = &all_names();
 9780: 	foreach my $name (keys(%name_to_host)) {
 9781: 	    my $ip;
 9782: 	    if (!exists($name_to_ip{$name})) {
 9783: 		$ip = gethostbyname($name);
 9784: 		if (!$ip || length($ip) ne 4) {
 9785: 		    if (defined($old_name_to_ip{$name})) {
 9786: 			$ip = $old_name_to_ip{$name};
 9787: 			&logthis("Can't find $name defaulting to old $ip");
 9788: 		    } else {
 9789: 			&logthis("Name $name no IP found");
 9790: 			next;
 9791: 		    }
 9792: 		} else {
 9793: 		    $ip=inet_ntoa($ip);
 9794: 		}
 9795: 		$name_to_ip{$name} = $ip;
 9796: 	    } else {
 9797: 		$ip = $name_to_ip{$name};
 9798: 	    }
 9799: 	    foreach my $id (@{ $name_to_host{$name} }) {
 9800: 		$lonid_to_ip{$id} = $ip;
 9801: 	    }
 9802: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 9803: 	}
 9804: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 9805: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 9806: 				      48*60*60);
 9807: 
 9808: 	return %iphost;
 9809:     }
 9810: 
 9811:     #
 9812:     #  Given a DNS returns the loncapa host name for that DNS 
 9813:     # 
 9814:     sub host_from_dns {
 9815:         my ($dns) = @_;
 9816:         my @hosts;
 9817:         my $ip;
 9818: 
 9819:         if (exists($name_to_ip{$dns})) {
 9820:             $ip = $name_to_ip{$dns};
 9821:         }
 9822:         if (!$ip) {
 9823:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
 9824:             if (length($ip) == 4) { 
 9825: 	        $ip   = &IO::Socket::inet_ntoa($ip);
 9826:             }
 9827:         }
 9828:         if ($ip) {
 9829: 	    @hosts = get_hosts_from_ip($ip);
 9830: 	    return $hosts[0];
 9831:         }
 9832:         return undef;
 9833:     }
 9834: 
 9835: }
 9836: 
 9837: BEGIN {
 9838: 
 9839: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 9840:     unless ($readit) {
 9841: {
 9842:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 9843:     %perlvar = (%perlvar,%{$configvars});
 9844: }
 9845: 
 9846: 
 9847: # ------------------------------------------------------ Read spare server file
 9848: {
 9849:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 9850: 
 9851:     while (my $configline=<$config>) {
 9852:        chomp($configline);
 9853:        if ($configline) {
 9854: 	   my ($host,$type) = split(':',$configline,2);
 9855: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 9856: 	   push(@{ $spareid{$type} }, $host);
 9857:        }
 9858:     }
 9859:     close($config);
 9860: }
 9861: # ------------------------------------------------------------ Read permissions
 9862: {
 9863:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 9864: 
 9865:     while (my $configline=<$config>) {
 9866: 	chomp($configline);
 9867: 	if ($configline) {
 9868: 	    my ($role,$perm)=split(/ /,$configline);
 9869: 	    if ($perm ne '') { $pr{$role}=$perm; }
 9870: 	}
 9871:     }
 9872:     close($config);
 9873: }
 9874: 
 9875: # -------------------------------------------- Read plain texts for permissions
 9876: {
 9877:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9878: 
 9879:     while (my $configline=<$config>) {
 9880: 	chomp($configline);
 9881: 	if ($configline) {
 9882: 	    my ($short,@plain)=split(/:/,$configline);
 9883:             %{$prp{$short}} = ();
 9884: 	    if (@plain > 0) {
 9885:                 $prp{$short}{'std'} = $plain[0];
 9886:                 for (my $i=1; $i<@plain; $i++) {
 9887:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9888:                 }
 9889:             }
 9890: 	}
 9891:     }
 9892:     close($config);
 9893: }
 9894: 
 9895: # ---------------------------------------------------------- Read package table
 9896: {
 9897:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9898: 
 9899:     while (my $configline=<$config>) {
 9900: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9901: 	chomp($configline);
 9902: 	my ($short,$plain)=split(/:/,$configline);
 9903: 	my ($pack,$name)=split(/\&/,$short);
 9904: 	if ($plain ne '') {
 9905: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9906: 	    $packagetab{$short}=$plain; 
 9907: 	}
 9908:     }
 9909:     close($config);
 9910: }
 9911: 
 9912: # ------------- set up temporary directory
 9913: {
 9914:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9915: 
 9916: }
 9917: 
 9918: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9919: 				'compress_threshold'=> 20_000,
 9920:  			        });
 9921: 
 9922: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9923: $dumpcount=0;
 9924: $locknum=0;
 9925: 
 9926: &logtouch();
 9927: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9928: $readit=1;
 9929:     {
 9930: 	use integer;
 9931: 	my $test=(2**32)+1;
 9932: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9933: 	&logthis(" Detected 64bit platform ($_64bit)");
 9934:     }
 9935: }
 9936: }
 9937: 
 9938: 1;
 9939: __END__
 9940: 
 9941: =pod
 9942: 
 9943: =head1 NAME
 9944: 
 9945: Apache::lonnet - Subroutines to ask questions about things in the network.
 9946: 
 9947: =head1 SYNOPSIS
 9948: 
 9949: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9950: 
 9951:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9952: 
 9953: Common parameters:
 9954: 
 9955: =over 4
 9956: 
 9957: =item *
 9958: 
 9959: $uname : an internal username (if $cname expecting a course Id specifically)
 9960: 
 9961: =item *
 9962: 
 9963: $udom : a domain (if $cdom expecting a course's domain specifically)
 9964: 
 9965: =item *
 9966: 
 9967: $symb : a resource instance identifier
 9968: 
 9969: =item *
 9970: 
 9971: $namespace : the name of a .db file that contains the data needed or
 9972: being set.
 9973: 
 9974: =back
 9975: 
 9976: =head1 OVERVIEW
 9977: 
 9978: lonnet provides subroutines which interact with the
 9979: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9980: about classes, users, and resources.
 9981: 
 9982: For many of these objects you can also use this to store data about
 9983: them or modify them in various ways.
 9984: 
 9985: =head2 Symbs
 9986: 
 9987: To identify a specific instance of a resource, LON-CAPA uses symbols
 9988: or "symbs"X<symb>. These identifiers are built from the URL of the
 9989: map, the resource number of the resource in the map, and the URL of
 9990: the resource itself. The latter is somewhat redundant, but might help
 9991: if maps change.
 9992: 
 9993: An example is
 9994: 
 9995:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9996: 
 9997: The respective map entry is
 9998: 
 9999:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
10000:   title="Problem 2">
10001:  </resource>
10002: 
10003: Symbs are used by the random number generator, as well as to store and
10004: restore data specific to a certain instance of for example a problem.
10005: 
10006: =head2 Storing And Retrieving Data
10007: 
10008: X<store()>X<cstore()>X<restore()>Three of the most important functions
10009: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10010: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10011: is is the non-critical message twin of cstore. These functions are for
10012: handlers to store a perl hash to a user's permanent data space in an
10013: easy manner, and to retrieve it again on another call. It is expected
10014: that a handler would use this once at the beginning to retrieve data,
10015: and then again once at the end to send only the new data back.
10016: 
10017: The data is stored in the user's data directory on the user's
10018: homeserver under the ID of the course.
10019: 
10020: The hash that is returned by restore will have all of the previous
10021: value for all of the elements of the hash.
10022: 
10023: Example:
10024: 
10025:  #creating a hash
10026:  my %hash;
10027:  $hash{'foo'}='bar';
10028: 
10029:  #storing it
10030:  &Apache::lonnet::cstore(\%hash);
10031: 
10032:  #changing a value
10033:  $hash{'foo'}='notbar';
10034: 
10035:  #adding a new value
10036:  $hash{'bar'}='foo';
10037:  &Apache::lonnet::cstore(\%hash);
10038: 
10039:  #retrieving the hash
10040:  my %history=&Apache::lonnet::restore();
10041: 
10042:  #print the hash
10043:  foreach my $key (sort(keys(%history))) {
10044:    print("\%history{$key} = $history{$key}");
10045:  }
10046: 
10047: Will print out:
10048: 
10049:  %history{1:foo} = bar
10050:  %history{1:keys} = foo:timestamp
10051:  %history{1:timestamp} = 990455579
10052:  %history{2:bar} = foo
10053:  %history{2:foo} = notbar
10054:  %history{2:keys} = foo:bar:timestamp
10055:  %history{2:timestamp} = 990455580
10056:  %history{bar} = foo
10057:  %history{foo} = notbar
10058:  %history{timestamp} = 990455580
10059:  %history{version} = 2
10060: 
10061: Note that the special hash entries C<keys>, C<version> and
10062: C<timestamp> were added to the hash. C<version> will be equal to the
10063: total number of versions of the data that have been stored. The
10064: C<timestamp> attribute will be the UNIX time the hash was
10065: stored. C<keys> is available in every historical section to list which
10066: keys were added or changed at a specific historical revision of a
10067: hash.
10068: 
10069: B<Warning>: do not store the hash that restore returns directly. This
10070: will cause a mess since it will restore the historical keys as if the
10071: were new keys. I.E. 1:foo will become 1:1:foo etc.
10072: 
10073: Calling convention:
10074: 
10075:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10076:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
10077: 
10078: For more detailed information, see lonnet specific documentation.
10079: 
10080: =head1 RETURN MESSAGES
10081: 
10082: =over 4
10083: 
10084: =item * B<con_lost>: unable to contact remote host
10085: 
10086: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10087: when the connection is brought back up
10088: 
10089: =item * B<con_failed>: unable to contact remote host and unable to save message
10090: for later delivery
10091: 
10092: =item * B<error:>: an error a occurred, a description of the error follows the :
10093: 
10094: =item * B<no_such_host>: unable to fund a host associated with the user/domain
10095: that was requested
10096: 
10097: =back
10098: 
10099: =head1 PUBLIC SUBROUTINES
10100: 
10101: =head2 Session Environment Functions
10102: 
10103: =over 4
10104: 
10105: =item * 
10106: X<appenv()>
10107: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
10108: the user envirnoment file, and will be restored for each access this
10109: user makes during this session, also modifies the %env for the current
10110: process. Optional rolesarrayref - if defined contains a reference to an array
10111: of roles which are exempt from the restriction on modifying user.role entries 
10112: in the user's environment.db and in %env.    
10113: 
10114: =item *
10115: X<delenv()>
10116: B<delenv($delthis,$regexp)>: removes all items from the session
10117: environment file that begin with $delthis. If the 
10118: optional second arg - $regexp - is true, $delthis is treated as a 
10119: regular expression, otherwise \Q$delthis\E is used. 
10120: The values are also deleted from the current processes %env.
10121: 
10122: =item * get_env_multiple($name) 
10123: 
10124: gets $name from the %env hash, it seemlessly handles the cases where multiple
10125: values may be defined and end up as an array ref.
10126: 
10127: returns an array of values
10128: 
10129: =back
10130: 
10131: =head2 User Information
10132: 
10133: =over 4
10134: 
10135: =item *
10136: X<queryauthenticate()>
10137: B<queryauthenticate($uname,$udom)>: try to determine user's current 
10138: authentication scheme
10139: 
10140: =item *
10141: X<authenticate()>
10142: B<authenticate($uname,$upass,$udom)>: try to
10143: authenticate user from domain's lib servers (first use the current
10144: one). C<$upass> should be the users password.
10145: 
10146: =item *
10147: X<homeserver()>
10148: B<homeserver($uname,$udom)>: find the server which has
10149: the user's directory and files (there must be only one), this caches
10150: the answer, and also caches if there is a borken connection.
10151: 
10152: =item *
10153: X<idget()>
10154: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10155: (IDs are a unique resource in a domain, there must be only 1 ID per
10156: username, and only 1 username per ID in a specific domain) (returns
10157: hash: id=>name,id=>name)
10158: 
10159: =item *
10160: X<idrget()>
10161: B<idrget($udom,@unames)>: find the IDs behind a list of
10162: usernames (returns hash: name=>id,name=>id)
10163: 
10164: =item *
10165: X<idput()>
10166: B<idput($udom,%ids)>: store away a list of names and associated IDs
10167: 
10168: =item *
10169: X<rolesinit()>
10170: B<rolesinit($udom,$username,$authhost)>: get user privileges
10171: 
10172: =item *
10173: X<getsection()>
10174: B<getsection($udom,$uname,$cname)>: finds the section of student in the
10175: course $cname, return section name/number or '' for "not in course"
10176: and '-1' for "no section"
10177: 
10178: =item *
10179: X<userenvironment()>
10180: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
10181: passed in @what from the requested user's environment, returns a hash
10182: 
10183: =item * 
10184: X<userlog_query()>
10185: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10186: activity.log file. %filters defines filters applied when parsing the
10187: log file. These can be start or end timestamps, or the type of action
10188: - log to look for Login or Logout events, check for Checkin or
10189: Checkout, role for role selection. The response is in the form
10190: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
10191: escaped strings of the action recorded in the activity.log file.
10192: 
10193: =back
10194: 
10195: =head2 User Roles
10196: 
10197: =over 4
10198: 
10199: =item *
10200: 
10201: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
10202:  F: full access
10203:  U,I,K: authentication modes (cxx only)
10204:  '': forbidden
10205:  1: user needs to choose course
10206:  2: browse allowed
10207:  A: passphrase authentication needed
10208: 
10209: =item *
10210: 
10211: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10212: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10213: and course level
10214: 
10215: =item *
10216: 
10217: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
10218: (rolesplain.tab); plain text explanation of a user role term.
10219: $type is Course (default) or Community.
10220: If $forcedefault evaluates to true, text returned will be default 
10221: text for $type. Otherwise, if this is a course, the text returned 
10222: will be a custom name for the role (if defined in the course's 
10223: environment).  If no custom name is defined the default is returned.
10224:    
10225: =item *
10226: 
10227: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
10228: All arguments are optional. Returns a hash of a roles, either for
10229: co-author/assistant author roles for a user's Construction Space
10230: (default), or if $context is 'userroles', roles for the user himself,
10231: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10232: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10233: For each key, value is set to colon-separated start and end times for
10234: the role.  If no username and domain are specified, will default to
10235: current user/domain. Types, roles, and roledoms are references to arrays
10236: of role statuses (active, future or previous), roles 
10237: (e.g., cc,in, st etc.) and domains of the roles which can be used
10238: to restrict the list of roles reported. If no array ref is 
10239: provided for types, will default to return only active roles.
10240: 
10241: =back
10242: 
10243: =head2 User Modification
10244: 
10245: =over 4
10246: 
10247: =item *
10248: 
10249: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
10250: user for the level given by URL.  Optional start and end dates (leave empty
10251: string or zero for "no date")
10252: 
10253: =item *
10254: 
10255: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10256: change a users, password, possible return values are: ok,
10257: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10258: refused
10259: 
10260: =item *
10261: 
10262: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
10263: 
10264: =item *
10265: 
10266: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10267:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
10268: 
10269: will update user information (firstname,middlename,lastname,generation,
10270: permanentemail), and if forceid is true, student/employee ID also.
10271: A user's institutional affiliation(s) can also be updated.
10272: User information fields will not be overwritten with empty entries 
10273: unless the field is included in the $candelete array reference.
10274: This array is included when a single user is modified via "Manage Users",
10275: or when Autoupdate.pl is run by cron in a domain.
10276: 
10277: =item *
10278: 
10279: modifystudent
10280: 
10281: modify a student's enrollment and identification information.
10282: The course id is resolved based on the current users environment.  
10283: This means the envoking user must be a course coordinator or otherwise
10284: associated with a course.
10285: 
10286: This call is essentially a wrapper for lonnet::modifyuser and
10287: lonnet::modify_student_enrollment
10288: 
10289: Inputs: 
10290: 
10291: =over 4
10292: 
10293: =item B<$udom> Student's loncapa domain
10294: 
10295: =item B<$uname> Student's loncapa login name
10296: 
10297: =item B<$uid> Student/Employee ID
10298: 
10299: =item B<$umode> Student's authentication mode
10300: 
10301: =item B<$upass> Student's password
10302: 
10303: =item B<$first> Student's first name
10304: 
10305: =item B<$middle> Student's middle name
10306: 
10307: =item B<$last> Student's last name
10308: 
10309: =item B<$gene> Student's generation
10310: 
10311: =item B<$usec> Student's section in course
10312: 
10313: =item B<$end> Unix time of the roles expiration
10314: 
10315: =item B<$start> Unix time of the roles start date
10316: 
10317: =item B<$forceid> If defined, allow $uid to be changed
10318: 
10319: =item B<$desiredhome> server to use as home server for student
10320: 
10321: =item B<$email> Student's permanent e-mail address
10322: 
10323: =item B<$type> Type of enrollment (auto or manual)
10324: 
10325: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
10326: 
10327: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10328: 
10329: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10330: 
10331: =item B<$context> role change context (shown in User Management Logs display in a course)
10332: 
10333: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
10334: 
10335: =back
10336: 
10337: =item *
10338: 
10339: modify_student_enrollment
10340: 
10341: Change a students enrollment status in a class.  The environment variable
10342: 'role.request.course' must be defined for this function to proceed.
10343: 
10344: Inputs:
10345: 
10346: =over 4
10347: 
10348: =item $udom, students domain
10349: 
10350: =item $uname, students name
10351: 
10352: =item $uid, students user id
10353: 
10354: =item $first, students first name
10355: 
10356: =item $middle
10357: 
10358: =item $last
10359: 
10360: =item $gene
10361: 
10362: =item $usec
10363: 
10364: =item $end
10365: 
10366: =item $start
10367: 
10368: =item $type
10369: 
10370: =item $locktype
10371: 
10372: =item $cid
10373: 
10374: =item $selfenroll
10375: 
10376: =item $context
10377: 
10378: =back
10379: 
10380: 
10381: =item *
10382: 
10383: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10384: custom role; give a custom role to a user for the level given by URL.  Specify
10385: name and domain of role author, and role name
10386: 
10387: =item *
10388: 
10389: revokerole($udom,$uname,$url,$role) : revoke a role for url
10390: 
10391: =item *
10392: 
10393: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10394: 
10395: =back
10396: 
10397: =head2 Course Infomation
10398: 
10399: =over 4
10400: 
10401: =item *
10402: 
10403: coursedescription($courseid) : returns a hash of information about the
10404: specified course id, including all environment settings for the
10405: course, the description of the course will be in the hash under the
10406: key 'description'
10407: 
10408: =item *
10409: 
10410: resdata($name,$domain,$type,@which) : request for current parameter
10411: setting for a specific $type, where $type is either 'course' or 'user',
10412: @what should be a list of parameters to ask about. This routine caches
10413: answers for 5 minutes.
10414: 
10415: =item *
10416: 
10417: get_courseresdata($courseid, $domain) : dump the entire course resource
10418: data base, returning a hash that is keyed by the resource name and has
10419: values that are the resource value.  I believe that the timestamps and
10420: versions are also returned.
10421: 
10422: 
10423: =back
10424: 
10425: =head2 Course Modification
10426: 
10427: =over 4
10428: 
10429: =item *
10430: 
10431: writecoursepref($courseid,%prefs) : write preferences (environment
10432: database) for a course
10433: 
10434: =item *
10435: 
10436: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10437: 
10438: =item *
10439: 
10440: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
10441: 
10442: =back
10443: 
10444: =head2 Resource Subroutines
10445: 
10446: =over 4
10447: 
10448: =item *
10449: 
10450: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10451: 
10452: =item *
10453: 
10454: repcopy($filename) : subscribes to the requested file, and attempts to
10455: replicate from the owning library server, Might return
10456: 'unavailable', 'not_found', 'forbidden', 'ok', or
10457: 'bad_request', also attempts to grab the metadata for the
10458: resource. Expects the local filesystem pathname
10459: (/home/httpd/html/res/....)
10460: 
10461: =back
10462: 
10463: =head2 Resource Information
10464: 
10465: =over 4
10466: 
10467: =item *
10468: 
10469: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10470: a vairety of different possible values, $varname should be a request
10471: string, and the other parameters can be used to specify who and what
10472: one is asking about.
10473: 
10474: Possible values for $varname are environment.lastname (or other item
10475: from the envirnment hash), user.name (or someother aspect about the
10476: user), resource.0.maxtries (or some other part and parameter of a
10477: resource)
10478: 
10479: =item *
10480: 
10481: directcondval($number) : get current value of a condition; reads from a state
10482: string
10483: 
10484: =item *
10485: 
10486: condval($condidx) : value of condition index based on state
10487: 
10488: =item *
10489: 
10490: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10491: resource's metadata, $what should be either a specific key, or either
10492: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10493: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10494: 
10495: this function automatically caches all requests
10496: 
10497: =item *
10498: 
10499: metadata_query($query,$custom,$customshow) : make a metadata query against the
10500: network of library servers; returns file handle of where SQL and regex results
10501: will be stored for query
10502: 
10503: =item *
10504: 
10505: symbread($filename) : return symbolic list entry (filename argument optional);
10506: returns the data handle
10507: 
10508: =item *
10509: 
10510: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10511: a possible symb for the URL in $thisfn, and if is an encryypted
10512: resource that the user accessed using /enc/ returns a 1 on success, 0
10513: on failure, user must be in a course, as it assumes the existance of
10514: the course initial hash, and uses $env('request.course.id'}
10515: 
10516: 
10517: =item *
10518: 
10519: symbclean($symb) : removes versions numbers from a symb, returns the
10520: cleaned symb
10521: 
10522: =item *
10523: 
10524: is_on_map($uri) : checks if the $uri is somewhere on the current
10525: course map, user must be in a course for it to work.
10526: 
10527: =item *
10528: 
10529: numval($salt) : return random seed value (addend for rndseed)
10530: 
10531: =item *
10532: 
10533: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10534: a random seed, all arguments are optional, if they aren't sent it uses the
10535: environment to derive them. Note: if symb isn't sent and it can't get one
10536: from &symbread it will use the current time as its return value
10537: 
10538: =item *
10539: 
10540: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10541: unfakeable, receipt
10542: 
10543: =item *
10544: 
10545: receipt() : API to ireceipt working off of env values; given out to users
10546: 
10547: =item *
10548: 
10549: countacc($url) : count the number of accesses to a given URL
10550: 
10551: =item *
10552: 
10553: 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
10554: 
10555: =item *
10556: 
10557: 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)
10558: 
10559: =item *
10560: 
10561: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10562: 
10563: =item *
10564: 
10565: devalidate($symb) : devalidate temporary spreadsheet calculations,
10566: forcing spreadsheet to reevaluate the resource scores next time.
10567: 
10568: =back
10569: 
10570: =head2 Storing/Retreiving Data
10571: 
10572: =over 4
10573: 
10574: =item *
10575: 
10576: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10577: for this url; hashref needs to be given and should be a \%hashname; the
10578: remaining args aren't required and if they aren't passed or are '' they will
10579: be derived from the env
10580: 
10581: =item *
10582: 
10583: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10584: uses critical subroutine
10585: 
10586: =item *
10587: 
10588: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10589: all args are optional
10590: 
10591: =item *
10592: 
10593: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
10594: dumps the complete (or key matching regexp) namespace into a hash
10595: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10596: normally &store()ed into
10597: 
10598: $range should be either an integer '100' (give me the first 100
10599:                                            matching records)
10600:               or be  two integers sperated by a - with no spaces
10601:                  '30-50' (give me the 30th through the 50th matching
10602:                           records)
10603: 
10604: 
10605: =item *
10606: 
10607: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10608: replaces a &store() version of data with a replacement set of data
10609: for a particular resource in a namespace passed in the $storehash hash 
10610: reference
10611: 
10612: =item *
10613: 
10614: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10615: works very similar to store/cstore, but all data is stored in a
10616: temporary location and can be reset using tmpreset, $storehash should
10617: be a hash reference, returns nothing on success
10618: 
10619: =item *
10620: 
10621: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10622: similar to restore, but all data is stored in a temporary location and
10623: can be reset using tmpreset. Returns a hash of values on success,
10624: error string otherwise.
10625: 
10626: =item *
10627: 
10628: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10629: deltes all keys for $symb form the temporary storage hash.
10630: 
10631: =item *
10632: 
10633: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10634: reference filled in from namesp ($udom and $uname are optional)
10635: 
10636: =item *
10637: 
10638: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10639: namesp ($udom and $uname are optional)
10640: 
10641: =item *
10642: 
10643: dump($namespace,$udom,$uname,$regexp,$range) : 
10644: dumps the complete (or key matching regexp) namespace into a hash
10645: ($udom, $uname, $regexp, $range are optional)
10646: 
10647: $range should be either an integer '100' (give me the first 100
10648:                                            matching records)
10649:               or be  two integers sperated by a - with no spaces
10650:                  '30-50' (give me the 30th through the 50th matching
10651:                           records)
10652: =item *
10653: 
10654: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10655: $store can be a scalar, an array reference, or if the amount to be 
10656: incremented is > 1, a hash reference.
10657: 
10658: ($udom and $uname are optional)
10659: 
10660: =item *
10661: 
10662: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10663: ($udom and $uname are optional)
10664: 
10665: =item *
10666: 
10667: cput($namespace,$storehash,$udom,$uname) : critical put
10668: ($udom and $uname are optional)
10669: 
10670: =item *
10671: 
10672: newput($namespace,$storehash,$udom,$uname) :
10673: 
10674: Attempts to store the items in the $storehash, but only if they don't
10675: currently exist, if this succeeds you can be certain that you have 
10676: successfully created a new key value pair in the $namespace db.
10677: 
10678: 
10679: Args:
10680:  $namespace: name of database to store values to
10681:  $storehash: hashref to store to the db
10682:  $udom: (optional) domain of user containing the db
10683:  $uname: (optional) name of user caontaining the db
10684: 
10685: Returns:
10686:  'ok' -> succeeded in storing all keys of $storehash
10687:  'key_exists: <key>' -> failed to anything out of $storehash, as at
10688:                         least <key> already existed in the db (other
10689:                         requested keys may also already exist)
10690:  'error: <msg>' -> unable to tie the DB or other error occurred
10691:  'con_lost' -> unable to contact request server
10692:  'refused' -> action was not allowed by remote machine
10693: 
10694: 
10695: =item *
10696: 
10697: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10698: reference filled in from namesp (encrypts the return communication)
10699: ($udom and $uname are optional)
10700: 
10701: =item *
10702: 
10703: log($udom,$name,$home,$message) : write to permanent log for user; use
10704: critical subroutine
10705: 
10706: =item *
10707: 
10708: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10709: array reference filled in from namespace found in domain level on either
10710: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10711: 
10712: =item *
10713: 
10714: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
10715: domain level either on specified domain server ($uhome) or primary domain 
10716: server ($udom and $uhome are optional)
10717: 
10718: =item * 
10719: 
10720: get_domain_defaults($target_domain) : returns hash with defaults for
10721: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10722: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10723: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10724: Values are retrieved from cache (if current), or from domain's configuration.db
10725: (if available), or lastly from values in lonTabs/dns_domain,tab, 
10726: or lonTabs/domain.tab. 
10727: 
10728: %domdefaults = &get_auth_defaults($target_domain);
10729: 
10730: =back
10731: 
10732: =head2 Network Status Functions
10733: 
10734: =over 4
10735: 
10736: =item *
10737: 
10738: dirlist($uri) : return directory list based on URI
10739: 
10740: =item *
10741: 
10742: spareserver() : find server with least workload from spare.tab
10743: 
10744: 
10745: =item *
10746: 
10747: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10748: if there is no corresponding loncapa host.
10749: 
10750: =back
10751: 
10752: 
10753: =head2 Apache Request
10754: 
10755: =over 4
10756: 
10757: =item *
10758: 
10759: ssi($url,%hash) : server side include, does a complete request cycle on url to
10760: localhost, posts hash
10761: 
10762: =back
10763: 
10764: =head2 Data to String to Data
10765: 
10766: =over 4
10767: 
10768: =item *
10769: 
10770: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10771: and '&' separators, supports elements that are arrayrefs and hashrefs
10772: 
10773: =item *
10774: 
10775: hashref2str($hashref) : convert a hashref into a string complete with
10776: escaping and '=' and '&' separators, supports elements that are
10777: arrayrefs and hashrefs
10778: 
10779: =item *
10780: 
10781: arrayref2str($arrayref) : convert an arrayref into a string complete
10782: with escaping and '&' separators, supports elements that are arrayrefs
10783: and hashrefs
10784: 
10785: =item *
10786: 
10787: str2hash($string) : convert string to hash using unescaping and
10788: splitting on '=' and '&', supports elements that are arrayrefs and
10789: hashrefs
10790: 
10791: =item *
10792: 
10793: str2array($string) : convert string to hash using unescaping and
10794: splitting on '&', supports elements that are arrayrefs and hashrefs
10795: 
10796: =back
10797: 
10798: =head2 Logging Routines
10799: 
10800: =over 4
10801: 
10802: These routines allow one to make log messages in the lonnet.log and
10803: lonnet.perm logfiles.
10804: 
10805: =item *
10806: 
10807: logtouch() : make sure the logfile, lonnet.log, exists
10808: 
10809: =item *
10810: 
10811: logthis() : append message to the normal lonnet.log file, it gets
10812: preiodically rolled over and deleted.
10813: 
10814: =item *
10815: 
10816: logperm() : append a permanent message to lonnet.perm.log, this log
10817: file never gets deleted by any automated portion of the system, only
10818: messages of critical importance should go in here.
10819: 
10820: =back
10821: 
10822: =head2 General File Helper Routines
10823: 
10824: =over 4
10825: 
10826: =item *
10827: 
10828: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10829: (a) files in /uploaded
10830:   (i) If a local copy of the file exists - 
10831:       compares modification date of local copy with last-modified date for 
10832:       definitive version stored on home server for course. If local copy is 
10833:       stale, requests a new version from the home server and stores it. 
10834:       If the original has been removed from the home server, then local copy 
10835:       is unlinked.
10836:   (ii) If local copy does not exist -
10837:       requests the file from the home server and stores it. 
10838:   
10839:   If $caller is 'uploadrep':  
10840:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10841:     for request for files originally uploaded via DOCS. 
10842:      - returns 'ok' if fresh local copy now available, -1 otherwise.
10843:   
10844:   Otherwise:
10845:      This indicates a call from the content generation phase of the request.
10846:      -  returns the entire contents of the file or -1.
10847:      
10848: (b) files in /res
10849:    - returns the entire contents of a file or -1; 
10850:    it properly subscribes to and replicates the file if neccessary.
10851: 
10852: 
10853: =item *
10854: 
10855: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10856:                   reference
10857: 
10858: returns either a stat() list of data about the file or an empty list
10859: if the file doesn't exist or couldn't find out about it (connection
10860: problems or user unknown)
10861: 
10862: =item *
10863: 
10864: filelocation($dir,$file) : returns file system location of a file
10865: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10866: directory that relative $file lookups are to looked in ($dir of /a/dir
10867: and a file of ../bob will become /a/bob)
10868: 
10869: =item *
10870: 
10871: hreflocation($dir,$file) : returns file system location or a URL; same as
10872: filelocation except for hrefs
10873: 
10874: =item *
10875: 
10876: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10877: 
10878: =back
10879: 
10880: =head2 Usererfile file routines (/uploaded*)
10881: 
10882: =over 4
10883: 
10884: =item *
10885: 
10886: userfileupload(): main rotine for putting a file in a user or course's
10887:                   filespace, arguments are,
10888: 
10889:  formname - required - this is the name of the element in $env where the
10890:            filename, and the contents of the file to create/modifed exist
10891:            the filename is in $env{'form.'.$formname.'.filename'} and the
10892:            contents of the file is located in $env{'form.'.$formname}
10893:  coursedoc - if true, store the file in the course of the active role
10894:              of the current user
10895:  subdir - required - subdirectory to put the file in under ../userfiles/
10896:          if undefined, it will be placed in "unknown"
10897: 
10898:  (This routine calls clean_filename() to remove any dangerous
10899:  characters from the filename, and then calls finuserfileupload() to
10900:  complete the transaction)
10901: 
10902:  returns either the url of the uploaded file (/uploaded/....) if successful
10903:  and /adm/notfound.html if unsuccessful
10904: 
10905: =item *
10906: 
10907: clean_filename(): routine for cleaing a filename up for storage in
10908:                  userfile space, argument is:
10909: 
10910:  filename - proposed filename
10911: 
10912: returns: the new clean filename
10913: 
10914: =item *
10915: 
10916: finishuserfileupload(): routine that creaes and sends the file to
10917: userspace, probably shouldn't be called directly
10918: 
10919:   docuname: username or courseid of destination for the file
10920:   docudom: domain of user/course of destination for the file
10921:   formname: same as for userfileupload()
10922:   fname: filename (inculding subdirectories) for the file
10923: 
10924:  returns either the url of the uploaded file (/uploaded/....) if successful
10925:  and /adm/notfound.html if unsuccessful
10926: 
10927: =item *
10928: 
10929: renameuserfile(): renames an existing userfile to a new name
10930: 
10931:   Args:
10932:    docuname: username or courseid of destination for the file
10933:    docudom: domain of user/course of destination for the file
10934:    old: current file name (including any subdirs under userfiles)
10935:    new: desired file name (including any subdirs under userfiles)
10936: 
10937: =item *
10938: 
10939: mkdiruserfile(): creates a directory is a userfiles dir
10940: 
10941:   Args:
10942:    docuname: username or courseid of destination for the file
10943:    docudom: domain of user/course of destination for the file
10944:    dir: dir to create (including any subdirs under userfiles)
10945: 
10946: =item *
10947: 
10948: removeuserfile(): removes a file that exists in userfiles
10949: 
10950:   Args:
10951:    docuname: username or courseid of destination for the file
10952:    docudom: domain of user/course of destination for the file
10953:    fname: filname to delete (including any subdirs under userfiles)
10954: 
10955: =item *
10956: 
10957: removeuploadedurl(): convience function for removeuserfile()
10958: 
10959:   Args:
10960:    url:  a full /uploaded/... url to delete
10961: 
10962: =item * 
10963: 
10964: get_portfile_permissions():
10965:   Args:
10966:     domain: domain of user or course contain the portfolio files
10967:     user: name of user or num of course contain the portfolio files
10968:   Returns:
10969:     hashref of a dump of the proper file_permissions.db
10970:    
10971: 
10972: =item * 
10973: 
10974: get_access_controls():
10975: 
10976: Args:
10977:   current_permissions: the hash ref returned from get_portfile_permissions()
10978:   group: (optional) the group you want the files associated with
10979:   file: (optional) the file you want access info on
10980: 
10981: Returns:
10982:     a hash (keys are file names) of hashes containing
10983:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10984:         values are XML containing access control settings (see below) 
10985: 
10986: Internal notes:
10987: 
10988:  access controls are stored in file_permissions.db as key=value pairs.
10989:     key -> path to file/file_name\0uniqueID:scope_end_start
10990:         where scope -> public,guest,course,group,domains or users.
10991:               end -> UNIX time for end of access (0 -> no end date)
10992:               start -> UNIX time for start of access
10993: 
10994:     value -> XML description of access control
10995:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10996:             <start></start>
10997:             <end></end>
10998: 
10999:             <password></password>  for scope type = guest
11000: 
11001:             <domain></domain>     for scope type = course or group
11002:             <number></number>
11003:             <roles id="">
11004:              <role></role>
11005:              <access></access>
11006:              <section></section>
11007:              <group></group>
11008:             </roles>
11009: 
11010:             <dom></dom>         for scope type = domains
11011: 
11012:             <users>             for scope type = users
11013:              <user>
11014:               <uname></uname>
11015:               <udom></udom>
11016:              </user>
11017:             </users>
11018:            </scope> 
11019:               
11020:  Access data is also aggregated for each file in an additional key=value pair:
11021:  key -> path to file/file_name\0accesscontrol 
11022:  value -> reference to hash
11023:           hash contains key = value pairs
11024:           where key = uniqueID:scope_end_start
11025:                 value = UNIX time record was last updated
11026: 
11027:           Used to improve speed of look-ups of access controls for each file.  
11028:  
11029:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11030: 
11031: modify_access_controls():
11032: 
11033: Modifies access controls for a portfolio file
11034: Args
11035: 1. file name
11036: 2. reference to hash of required changes,
11037: 3. domain
11038: 4. username
11039:   where domain,username are the domain of the portfolio owner 
11040:   (either a user or a course) 
11041: 
11042: Returns:
11043: 1. result of additions or updates ('ok' or 'error', with error message). 
11044: 2. result of deletions ('ok' or 'error', with error message).
11045: 3. reference to hash of any new or updated access controls.
11046: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11047:    key = integer (inbound ID)
11048:    value = uniqueID  
11049: 
11050: =back
11051: 
11052: =head2 HTTP Helper Routines
11053: 
11054: =over 4
11055: 
11056: =item *
11057: 
11058: escape() : unpack non-word characters into CGI-compatible hex codes
11059: 
11060: =item *
11061: 
11062: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11063: 
11064: =back
11065: 
11066: =head1 PRIVATE SUBROUTINES
11067: 
11068: =head2 Underlying communication routines (Shouldn't call)
11069: 
11070: =over 4
11071: 
11072: =item *
11073: 
11074: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11075: 
11076: =item *
11077: 
11078: reply() : uses subreply to send a message to remote machine, logs all failures
11079: 
11080: =item *
11081: 
11082: critical() : passes a critical message to another server; if cannot
11083: get through then place message in connection buffer directory and
11084: returns con_delayed, if incapable of saving message, returns
11085: con_failed
11086: 
11087: =item *
11088: 
11089: reconlonc() : tries to reconnect lonc client processes.
11090: 
11091: =back
11092: 
11093: =head2 Resource Access Logging
11094: 
11095: =over 4
11096: 
11097: =item *
11098: 
11099: flushcourselogs() : flush (save) buffer logs and access logs
11100: 
11101: =item *
11102: 
11103: courselog($what) : save message for course in hash
11104: 
11105: =item *
11106: 
11107: courseacclog($what) : save message for course using &courselog().  Perform
11108: special processing for specific resource types (problems, exams, quizzes, etc).
11109: 
11110: =item *
11111: 
11112: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11113: as a PerlChildExitHandler
11114: 
11115: =back
11116: 
11117: =head2 Other
11118: 
11119: =over 4
11120: 
11121: =item *
11122: 
11123: symblist($mapname,%newhash) : update symbolic storage links
11124: 
11125: =back
11126: 
11127: =cut
11128: 

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