File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1205: download - view: text, annotated - select for diffs
Mon Dec 3 14:47:37 2012 UTC (11 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Eliminate use of pagepath and pagesymb.
- Information about current map hierarchy found in $env{'form.folderpath'}
  for both .page and .sequence in /uploaded.
- Container type (.sequence or .page) appears in additional fifth colon
  separated field appended to map title. (1 if page, blank otherwise).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1205 2012/12/03 14:47:37 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: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$name,$id) = @_;
  360:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  361:     return $response;
  362: }
  363: 
  364: # -------------------------------------------------- Non-critical communication
  365: sub subreply {
  366:     my ($cmd,$server)=@_;
  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  368:     #
  369:     #  With loncnew process trimming, there's a timing hole between lonc server
  370:     #  process exit and the master server picking up the listen on the AF_UNIX
  371:     #  socket.  In that time interval, a lock file will exist:
  372: 
  373:     my $lockfile=$peerfile.".lock";
  374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  375: 	sleep(1);
  376:     }
  377:     # At this point, either a loncnew parent is listening or an old lonc
  378:     # or loncnew child is listening so we can connect or everything's dead.
  379:     #
  380:     #   We'll give the connection a few tries before abandoning it.  If
  381:     #   connection is not possible, we'll con_lost back to the client.
  382:     #   
  383:     my $client;
  384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  386: 				      Type    => SOCK_STREAM,
  387: 				      Timeout => 10);
  388: 	if ($client) {
  389: 	    last;		# Connected!
  390: 	} else {
  391: 	    &create_connection(&hostname($server),$server);
  392: 	}
  393:         sleep(1);		# Try again later if failed connection.
  394:     }
  395:     my $answer;
  396:     if ($client) {
  397: 	print $client "sethost:$server:$cmd\n";
  398: 	$answer=<$client>;
  399: 	if (!$answer) { $answer="con_lost"; }
  400: 	chomp($answer);
  401:     } else {
  402: 	$answer = 'con_lost';	# Failed connection.
  403:     }
  404:     return $answer;
  405: }
  406: 
  407: sub reply {
  408:     my ($cmd,$server)=@_;
  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  410:     my $answer=subreply($cmd,$server);
  411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  412:        &logthis("<font color=\"blue\">WARNING:".
  413:                 " $cmd to $server returned $answer</font>");
  414:     }
  415:     return $answer;
  416: }
  417: 
  418: # ----------------------------------------------------------- Send USR1 to lonc
  419: 
  420: sub reconlonc {
  421:     my ($lonid) = @_;
  422:     my $hostname = &hostname($lonid);
  423:     if ($lonid) {
  424: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  425: 	if ($hostname && -e $peerfile) {
  426: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  427: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  428: 					     Type    => SOCK_STREAM,
  429: 					     Timeout => 10);
  430: 	    if ($client) {
  431: 		print $client ("reset_retries\n");
  432: 		my $answer=<$client>;
  433: 		#reset just this one.
  434: 	    }
  435: 	}
  436: 	return;
  437:     }
  438: 
  439:     &logthis("Trying to reconnect lonc");
  440:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  441:     if (open(my $fh,"<$loncfile")) {
  442: 	my $loncpid=<$fh>;
  443:         chomp($loncpid);
  444:         if (kill 0 => $loncpid) {
  445: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  446:             kill USR1 => $loncpid;
  447:             sleep 1;
  448:          } else {
  449: 	    &logthis(
  450:                "<font color=\"blue\">WARNING:".
  451:                " lonc at pid $loncpid not responding, giving up</font>");
  452:         }
  453:     } else {
  454: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  455:     }
  456: }
  457: 
  458: # ------------------------------------------------------ Critical communication
  459: 
  460: sub critical {
  461:     my ($cmd,$server)=@_;
  462:     unless (&hostname($server)) {
  463:         &logthis("<font color=\"blue\">WARNING:".
  464:                " Critical message to unknown server ($server)</font>");
  465:         return 'no_such_host';
  466:     }
  467:     my $answer=reply($cmd,$server);
  468:     if ($answer eq 'con_lost') {
  469: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  470: 	my $answer=reply($cmd,$server);
  471:         if ($answer eq 'con_lost') {
  472:             my $now=time;
  473:             my $middlename=$cmd;
  474:             $middlename=substr($middlename,0,16);
  475:             $middlename=~s/\W//g;
  476:             my $dfilename=
  477:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  478:             $dumpcount++;
  479:             {
  480: 		my $dfh;
  481: 		if (open($dfh,">$dfilename")) {
  482: 		    print $dfh "$cmd\n"; 
  483: 		    close($dfh);
  484: 		}
  485:             }
  486:             sleep 2;
  487:             my $wcmd='';
  488:             {
  489: 		my $dfh;
  490: 		if (open($dfh,"<$dfilename")) {
  491: 		    $wcmd=<$dfh>; 
  492: 		    close($dfh);
  493: 		}
  494:             }
  495:             chomp($wcmd);
  496:             if ($wcmd eq $cmd) {
  497: 		&logthis("<font color=\"blue\">WARNING: ".
  498:                          "Connection buffer $dfilename: $cmd</font>");
  499:                 &logperm("D:$server:$cmd");
  500: 	        return 'con_delayed';
  501:             } else {
  502:                 &logthis("<font color=\"red\">CRITICAL:"
  503:                         ." Critical connection failed: $server $cmd</font>");
  504:                 &logperm("F:$server:$cmd");
  505:                 return 'con_failed';
  506:             }
  507:         }
  508:     }
  509:     return $answer;
  510: }
  511: 
  512: # ------------------------------------------- check if return value is an error
  513: 
  514: sub error {
  515:     my ($result) = @_;
  516:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  517: 	if ($2 == 2) { return undef; }
  518: 	return $1;
  519:     }
  520:     return undef;
  521: }
  522: 
  523: sub convert_and_load_session_env {
  524:     my ($lonidsdir,$handle)=@_;
  525:     my @profile;
  526:     {
  527: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  528: 	if (!$opened) {
  529: 	    return 0;
  530: 	}
  531: 	flock($idf,LOCK_SH);
  532: 	@profile=<$idf>;
  533: 	close($idf);
  534:     }
  535:     my %temp_env;
  536:     foreach my $line (@profile) {
  537: 	if ($line !~ m/=/) {
  538: 	    return 0;
  539: 	}
  540: 	chomp($line);
  541: 	my ($envname,$envvalue)=split(/=/,$line,2);
  542: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  543:     }
  544:     unlink("$lonidsdir/$handle.id");
  545:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  546: 	    0640)) {
  547: 	%disk_env = %temp_env;
  548: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  549: 	untie(%disk_env);
  550:     }
  551:     return 1;
  552: }
  553: 
  554: # ------------------------------------------- Transfer profile into environment
  555: my $env_loaded;
  556: sub transfer_profile_to_env {
  557:     my ($lonidsdir,$handle,$force_transfer) = @_;
  558:     if (!$force_transfer && $env_loaded) { return; } 
  559: 
  560:     if (!defined($lonidsdir)) {
  561: 	$lonidsdir = $perlvar{'lonIDsDir'};
  562:     }
  563:     if (!defined($handle)) {
  564:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  565:     }
  566: 
  567:     my $convert;
  568:     {
  569:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  570: 	if (!$opened) {
  571: 	    return;
  572: 	}
  573: 	flock($idf,LOCK_SH);
  574: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  575: 		&GDBM_READER(),0640)) {
  576: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  577: 	    untie(%disk_env);
  578: 	} else {
  579: 	    $convert = 1;
  580: 	}
  581:     }
  582:     if ($convert) {
  583: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  584: 	    &logthis("Failed to load session, or convert session.");
  585: 	}
  586:     }
  587: 
  588:     my %remove;
  589:     while ( my $envname = each(%env) ) {
  590:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  591:             if ($time < time-300) {
  592:                 $remove{$key}++;
  593:             }
  594:         }
  595:     }
  596: 
  597:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  598:     $env_loaded=1;
  599:     foreach my $expired_key (keys(%remove)) {
  600:         &delenv($expired_key);
  601:     }
  602: }
  603: 
  604: # ---------------------------------------------------- Check for valid session 
  605: sub check_for_valid_session {
  606:     my ($r,$name) = @_;
  607:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  608:     if ($name eq '') {
  609:         $name = 'lonID';
  610:     }
  611:     my $lonid=$cookies{$name};
  612:     return undef if (!$lonid);
  613: 
  614:     my $handle=&LONCAPA::clean_handle($lonid->value);
  615:     my $lonidsdir;
  616:     if ($name eq 'lonDAV') {
  617:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  618:     } else {
  619:         $lonidsdir=$r->dir_config('lonIDsDir');
  620:     }
  621:     return undef if (!-e "$lonidsdir/$handle.id");
  622: 
  623:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  624:     return undef if (!$opened);
  625: 
  626:     flock($idf,LOCK_SH);
  627:     my %disk_env;
  628:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  629: 	    &GDBM_READER(),0640)) {
  630: 	return undef;	
  631:     }
  632: 
  633:     if (!defined($disk_env{'user.name'})
  634: 	|| !defined($disk_env{'user.domain'})) {
  635: 	return undef;
  636:     }
  637:     return $handle;
  638: }
  639: 
  640: sub timed_flock {
  641:     my ($file,$lock_type) = @_;
  642:     my $failed=0;
  643:     eval {
  644: 	local $SIG{__DIE__}='DEFAULT';
  645: 	local $SIG{ALRM}=sub {
  646: 	    $failed=1;
  647: 	    die("failed lock");
  648: 	};
  649: 	alarm(13);
  650: 	flock($file,$lock_type);
  651: 	alarm(0);
  652:     };
  653:     if ($failed) {
  654: 	return undef;
  655:     } else {
  656: 	return 1;
  657:     }
  658: }
  659: 
  660: # ---------------------------------------------------------- Append Environment
  661: 
  662: sub appenv {
  663:     my ($newenv,$roles) = @_;
  664:     if (ref($newenv) eq 'HASH') {
  665:         foreach my $key (keys(%{$newenv})) {
  666:             my $refused = 0;
  667: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  668:                 $refused = 1;
  669:                 if (ref($roles) eq 'ARRAY') {
  670:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  671:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  672:                         $refused = 0;
  673:                     }
  674:                 }
  675:             }
  676:             if ($refused) {
  677:                 &logthis("<font color=\"blue\">WARNING: ".
  678:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  679:                          .'</font>');
  680: 	        delete($newenv->{$key});
  681:             } else {
  682:                 $env{$key}=$newenv->{$key};
  683:             }
  684:         }
  685:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  686:         if ($opened
  687: 	    && &timed_flock($env_file,LOCK_EX)
  688: 	    &&
  689: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  690: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  691: 	    while (my ($key,$value) = each(%{$newenv})) {
  692: 	        $disk_env{$key} = $value;
  693: 	    }
  694: 	    untie(%disk_env);
  695:         }
  696:     }
  697:     return 'ok';
  698: }
  699: # ----------------------------------------------------- Delete from Environment
  700: 
  701: sub delenv {
  702:     my ($delthis,$regexp,$roles) = @_;
  703:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  704:         my $refused = 1;
  705:         if (ref($roles) eq 'ARRAY') {
  706:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  707:             if (grep(/^\Q$role\E$/,@{$roles})) {
  708:                 $refused = 0;
  709:             }
  710:         }
  711:         if ($refused) {
  712:             &logthis("<font color=\"blue\">WARNING: ".
  713:                      "Attempt to delete from environment ".$delthis);
  714:             return 'error';
  715:         }
  716:     }
  717:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  718:     if ($opened
  719: 	&& &timed_flock($env_file,LOCK_EX)
  720: 	&&
  721: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  722: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  723: 	foreach my $key (keys(%disk_env)) {
  724: 	    if ($regexp) {
  725:                 if ($key=~/^$delthis/) {
  726:                     delete($env{$key});
  727:                     delete($disk_env{$key});
  728:                 } 
  729:             } else {
  730:                 if ($key=~/^\Q$delthis\E/) {
  731: 		    delete($env{$key});
  732: 		    delete($disk_env{$key});
  733: 	        }
  734:             }
  735: 	}
  736: 	untie(%disk_env);
  737:     }
  738:     return 'ok';
  739: }
  740: 
  741: sub get_env_multiple {
  742:     my ($name) = @_;
  743:     my @values;
  744:     if (defined($env{$name})) {
  745:         # exists is it an array
  746:         if (ref($env{$name})) {
  747:             @values=@{ $env{$name} };
  748:         } else {
  749:             $values[0]=$env{$name};
  750:         }
  751:     }
  752:     return(@values);
  753: }
  754: 
  755: # ------------------------------------------------------------------- Locking
  756: 
  757: sub set_lock {
  758:     my ($text)=@_;
  759:     $locknum++;
  760:     my $id=$$.'-'.$locknum;
  761:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  762:              'session.lock.'.$id => $text});
  763:     return $id;
  764: }
  765: 
  766: sub get_locks {
  767:     my $num=0;
  768:     my %texts=();
  769:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  770:        if ($lock=~/\w/) {
  771:           $num++;
  772:           $texts{$lock}=$env{'session.lock.'.$lock};
  773:        }
  774:    }
  775:    return ($num,%texts);
  776: }
  777: 
  778: sub remove_lock {
  779:     my ($id)=@_;
  780:     my $newlocks='';
  781:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  782:        if (($lock=~/\w/) && ($lock ne $id)) {
  783:           $newlocks.=','.$lock;
  784:        }
  785:     }
  786:     &appenv({'session.locks' => $newlocks});
  787:     &delenv('session.lock.'.$id);
  788: }
  789: 
  790: sub remove_all_locks {
  791:     my $activelocks=$env{'session.locks'};
  792:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  793:        if ($lock=~/\w/) {
  794:           &remove_lock($lock);
  795:        }
  796:     }
  797: }
  798: 
  799: 
  800: # ------------------------------------------ Find out current server userload
  801: sub userload {
  802:     my $numusers=0;
  803:     {
  804: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  805: 	my $filename;
  806: 	my $curtime=time;
  807: 	while ($filename=readdir(LONIDS)) {
  808: 	    next if ($filename eq '.' || $filename eq '..');
  809: 	    next if ($filename =~ /publicuser_\d+\.id/);
  810: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  811: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  812: 	}
  813: 	closedir(LONIDS);
  814:     }
  815:     my $userloadpercent=0;
  816:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  817:     if ($maxuserload) {
  818: 	$userloadpercent=100*$numusers/$maxuserload;
  819:     }
  820:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  821:     return $userloadpercent;
  822: }
  823: 
  824: # ------------------------------ Find server with least workload from spare.tab
  825: 
  826: sub spareserver {
  827:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  828:     my $spare_server;
  829:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  830:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  831:                                                      :  $userloadpercent;
  832:     my ($uint_dom,$remotesessions);
  833:     if (($udom ne '') && (&domain($udom) ne '')) {
  834:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  835:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  836:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  837:         $remotesessions = $udomdefaults{'remotesessions'};
  838:     }
  839:     my $spareshash = &this_host_spares($udom);
  840:     if (ref($spareshash) eq 'HASH') {
  841:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  842:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  843:                 if ($uint_dom) {
  844:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  845:                                                  $try_server));
  846:                 }
  847: 	        ($spare_server, $lowest_load) =
  848: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  849:             }
  850:         }
  851: 
  852:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  853: 
  854:         if (!$found_server) {
  855:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  856: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  857:                     if ($uint_dom) {
  858:                         next unless (&spare_can_host($udom,$uint_dom,
  859:                                                      $remotesessions,$try_server));
  860:                     }
  861: 	            ($spare_server, $lowest_load) =
  862: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  863:                 }
  864: 	    }
  865:         }
  866:     }
  867: 
  868:     if (!$want_server_name) {
  869:         my $protocol = 'http';
  870:         if ($protocol{$spare_server} eq 'https') {
  871:             $protocol = $protocol{$spare_server};
  872:         }
  873:         if (defined($spare_server)) {
  874:             my $hostname = &hostname($spare_server);
  875:             if (defined($hostname)) {
  876: 	        $spare_server = $protocol.'://'.$hostname;
  877:             }
  878:         }
  879:     }
  880:     return $spare_server;
  881: }
  882: 
  883: sub compare_server_load {
  884:     my ($try_server, $spare_server, $lowest_load) = @_;
  885: 
  886:     my $loadans     = &reply('load',    $try_server);
  887:     my $userloadans = &reply('userload',$try_server);
  888: 
  889:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  890: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  891:     }
  892: 
  893:     my $load;
  894:     if ($loadans =~ /\d/) {
  895: 	if ($userloadans =~ /\d/) {
  896: 	    #both are numbers, pick the bigger one
  897: 	    $load = ($loadans > $userloadans) ? $loadans 
  898: 		                              : $userloadans;
  899: 	} else {
  900: 	    $load = $loadans;
  901: 	}
  902:     } else {
  903: 	$load = $userloadans;
  904:     }
  905: 
  906:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  907: 	$spare_server = $try_server;
  908: 	$lowest_load  = $load;
  909:     }
  910:     return ($spare_server,$lowest_load);
  911: }
  912: 
  913: # --------------------------- ask offload servers if user already has a session
  914: sub find_existing_session {
  915:     my ($udom,$uname) = @_;
  916:     my $spareshash = &this_host_spares($udom);
  917:     if (ref($spareshash) eq 'HASH') {
  918:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  919:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  920:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  921:             }
  922:         }
  923:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  924:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  925:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  926:             }
  927:         }
  928:     }
  929:     return;
  930: }
  931: 
  932: # -------------------------------- ask if server already has a session for user
  933: sub has_user_session {
  934:     my ($lonid,$udom,$uname) = @_;
  935:     my $result = &reply(join(':','userhassession',
  936: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  937:     return 1 if ($result eq 'ok');
  938: 
  939:     return 0;
  940: }
  941: 
  942: # --------- determine least loaded server in a user's domain which allows login
  943: 
  944: sub choose_server {
  945:     my ($udom,$checkloginvia) = @_;
  946:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  947:     my %servers = &get_servers($udom);
  948:     my $lowest_load = 30000;
  949:     my ($login_host,$hostname,$portal_path,$isredirect);
  950:     foreach my $lonhost (keys(%servers)) {
  951:         my $loginvia;
  952:         if ($checkloginvia) {
  953:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  954:             if ($loginvia) {
  955:                 my ($server,$path) = split(/:/,$loginvia);
  956:                 ($login_host, $lowest_load) =
  957:                     &compare_server_load($server, $login_host, $lowest_load);
  958:                 if ($login_host eq $server) {
  959:                     $portal_path = $path;
  960:                     $isredirect = 1;
  961:                 }
  962:             } else {
  963:                 ($login_host, $lowest_load) =
  964:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  965:                 if ($login_host eq $lonhost) {
  966:                     $portal_path = '';
  967:                     $isredirect = ''; 
  968:                 }
  969:             }
  970:         } else {
  971:             ($login_host, $lowest_load) =
  972:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  973:         }
  974:     }
  975:     if ($login_host ne '') {
  976:         $hostname = &hostname($login_host);
  977:     }
  978:     return ($login_host,$hostname,$portal_path,$isredirect);
  979: }
  980: 
  981: # --------------------------------------------- Try to change a user's password
  982: 
  983: sub changepass {
  984:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  985:     $currentpass = &escape($currentpass);
  986:     $newpass     = &escape($newpass);
  987:     my $lonhost = $perlvar{'lonHostID'};
  988:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  989: 		       $server);
  990:     if (! $answer) {
  991: 	&logthis("No reply on password change request to $server ".
  992: 		 "by $uname in domain $udom.");
  993:     } elsif ($answer =~ "^ok") {
  994:         &logthis("$uname in $udom successfully changed their password ".
  995: 		 "on $server.");
  996:     } elsif ($answer =~ "^pwchange_failure") {
  997: 	&logthis("$uname in $udom was unable to change their password ".
  998: 		 "on $server.  The action was blocked by either lcpasswd ".
  999: 		 "or pwchange");
 1000:     } elsif ($answer =~ "^non_authorized") {
 1001:         &logthis("$uname in $udom did not get their password correct when ".
 1002: 		 "attempting to change it on $server.");
 1003:     } elsif ($answer =~ "^auth_mode_error") {
 1004:         &logthis("$uname in $udom attempted to change their password despite ".
 1005: 		 "not being locally or internally authenticated on $server.");
 1006:     } elsif ($answer =~ "^unknown_user") {
 1007:         &logthis("$uname in $udom attempted to change their password ".
 1008: 		 "on $server but were unable to because $server is not ".
 1009: 		 "their home server.");
 1010:     } elsif ($answer =~ "^refused") {
 1011: 	&logthis("$server refused to change $uname in $udom password because ".
 1012: 		 "it was sent an unencrypted request to change the password.");
 1013:     } elsif ($answer =~ "invalid_client") {
 1014:         &logthis("$server refused to change $uname in $udom password because ".
 1015:                  "it was a reset by e-mail originating from an invalid server.");
 1016:     }
 1017:     return $answer;
 1018: }
 1019: 
 1020: # ----------------------- Try to determine user's current authentication scheme
 1021: 
 1022: sub queryauthenticate {
 1023:     my ($uname,$udom)=@_;
 1024:     my $uhome=&homeserver($uname,$udom);
 1025:     if (!$uhome) {
 1026: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1027: 	return 'no_host';
 1028:     }
 1029:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1030:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1031: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1032:     }
 1033:     return $answer;
 1034: }
 1035: 
 1036: # --------- Try to authenticate user from domain's lib servers (first this one)
 1037: 
 1038: sub authenticate {
 1039:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1040:     $upass=&escape($upass);
 1041:     $uname= &LONCAPA::clean_username($uname);
 1042:     my $uhome=&homeserver($uname,$udom,1);
 1043:     my $newhome;
 1044:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1045: # Maybe the machine was offline and only re-appeared again recently?
 1046:         &reconlonc();
 1047: # One more
 1048: 	$uhome=&homeserver($uname,$udom,1);
 1049:         if (($uhome eq 'no_host') && $checkdefauth) {
 1050:             if (defined(&domain($udom,'primary'))) {
 1051:                 $newhome=&domain($udom,'primary');
 1052:             }
 1053:             if ($newhome ne '') {
 1054:                 $uhome = $newhome;
 1055:             }
 1056:         }
 1057: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1058: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1059: 	    return 'no_host';
 1060:         }
 1061:     }
 1062:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1063:     if ($answer eq 'authorized') {
 1064:         if ($newhome) {
 1065:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1066:             return 'no_account_on_host'; 
 1067:         } else {
 1068:             &logthis("User $uname at $udom authorized by $uhome");
 1069:             return $uhome;
 1070:         }
 1071:     }
 1072:     if ($answer eq 'non_authorized') {
 1073: 	&logthis("User $uname at $udom rejected by $uhome");
 1074: 	return 'no_host'; 
 1075:     }
 1076:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1077:     return 'no_host';
 1078: }
 1079: 
 1080: sub can_host_session {
 1081:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1082:     my $canhost = 1;
 1083:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1084:     if (ref($remotesessions) eq 'HASH') {
 1085:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1086:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1087:                 $canhost = 0;
 1088:             } else {
 1089:                 $canhost = 1;
 1090:             }
 1091:         }
 1092:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1094:                 $canhost = 1;
 1095:             } else {
 1096:                 $canhost = 0;
 1097:             }
 1098:         }
 1099:         if ($canhost) {
 1100:             if ($remotesessions->{'version'} ne '') {
 1101:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1102:                 if ($reqmajor ne '' && $reqminor ne '') {
 1103:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1104:                         my $major = $1;
 1105:                         my $minor = $2;
 1106:                         if (($major < $reqmajor ) ||
 1107:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1108:                             $canhost = 0;
 1109:                         }
 1110:                     } else {
 1111:                         $canhost = 0;
 1112:                     }
 1113:                 }
 1114:             }
 1115:         }
 1116:     }
 1117:     if ($canhost) {
 1118:         if (ref($hostedsessions) eq 'HASH') {
 1119:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1120:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1121:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1122:                 if (($uint_dom ne '') && 
 1123:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1124:                     $canhost = 0;
 1125:                 } else {
 1126:                     $canhost = 1;
 1127:                 }
 1128:             }
 1129:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1130:                 if (($uint_dom ne '') && 
 1131:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1132:                     $canhost = 1;
 1133:                 } else {
 1134:                     $canhost = 0;
 1135:                 }
 1136:             }
 1137:         }
 1138:     }
 1139:     return $canhost;
 1140: }
 1141: 
 1142: sub spare_can_host {
 1143:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1144:     my $canhost=1;
 1145:     my @intdoms;
 1146:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1147:     if (ref($internet_names) eq 'ARRAY') {
 1148:         @intdoms = @{$internet_names};
 1149:     }
 1150:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1151:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1152:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1153:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1154:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1155:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1156:                                      $remotesessions,
 1157:                                      $defdomdefaults{'hostedsessions'});
 1158:     }
 1159:     return $canhost;
 1160: }
 1161: 
 1162: sub this_host_spares {
 1163:     my ($dom) = @_;
 1164:     my ($dom_in_use,$lonhost_in_use,$result);
 1165:     my @hosts = &current_machine_ids();
 1166:     foreach my $lonhost (@hosts) {
 1167:         if (&host_domain($lonhost) eq $dom) {
 1168:             $dom_in_use = $dom;
 1169:             $lonhost_in_use = $lonhost;
 1170:             last;
 1171:         }
 1172:     }
 1173:     if ($dom_in_use ne '') {
 1174:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1175:     }
 1176:     if (ref($result) ne 'HASH') {
 1177:         $lonhost_in_use = $perlvar{'lonHostID'};
 1178:         $dom_in_use = &host_domain($lonhost_in_use);
 1179:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1180:         if (ref($result) ne 'HASH') {
 1181:             $result = \%spareid;
 1182:         }
 1183:     }
 1184:     return $result;
 1185: }
 1186: 
 1187: sub spares_for_offload  {
 1188:     my ($dom_in_use,$lonhost_in_use) = @_;
 1189:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1190:     if (defined($cached)) {
 1191:         return $result;
 1192:     } else {
 1193:         my $cachetime = 60*60*24;
 1194:         my %domconfig =
 1195:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1196:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1197:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1198:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1199:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1200:                 }
 1201:             }
 1202:         }
 1203:     }
 1204:     return;
 1205: }
 1206: 
 1207: sub get_lonbalancer_config {
 1208:     my ($servers) = @_;
 1209:     my ($currbalancer,$currtargets);
 1210:     if (ref($servers) eq 'HASH') {
 1211:         foreach my $server (keys(%{$servers})) {
 1212:             my %what = (
 1213:                          spareid => 1,
 1214:                          perlvar => 1,
 1215:                        );
 1216:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1217:             if ($result eq 'ok') {
 1218:                 if (ref($returnhash) eq 'HASH') {
 1219:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1220:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1221:                             $currbalancer = $server;
 1222:                             $currtargets = {};
 1223:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1224:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1225:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1226:                                 }
 1227:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1228:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1229:                                 }
 1230:                             }
 1231:                             last;
 1232:                         }
 1233:                     }
 1234:                 }
 1235:             }
 1236:         }
 1237:     }
 1238:     return ($currbalancer,$currtargets);
 1239: }
 1240: 
 1241: sub check_loadbalancing {
 1242:     my ($uname,$udom) = @_;
 1243:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1244:         $rule_in_effect,$offloadto,$otherserver);
 1245:     my $lonhost = $perlvar{'lonHostID'};
 1246:     my @hosts = &current_machine_ids();
 1247:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1248:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1249:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1250:     my $serverhomedom = &host_domain($lonhost);
 1251: 
 1252:     my $cachetime = 60*60*24;
 1253: 
 1254:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1255:         $dom_in_use = $udom;
 1256:         $homeintdom = 1;
 1257:     } else {
 1258:         $dom_in_use = $serverhomedom;
 1259:     }
 1260:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1261:     unless (defined($cached)) {
 1262:         my %domconfig =
 1263:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1264:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1265:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1266:         }
 1267:     }
 1268:     if (ref($result) eq 'HASH') {
 1269:         ($is_balancer,$currtargets,$currrules) = 
 1270:             &check_balancer_result($result,@hosts);
 1271:         if ($is_balancer) {
 1272:             if (ref($currrules) eq 'HASH') {
 1273:                 if ($homeintdom) {
 1274:                     if ($uname ne '') {
 1275:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1276:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1277:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1278:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1279:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1280:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1281:                             }
 1282:                         }
 1283:                         if ($rule_in_effect eq '') {
 1284:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1285:                             if ($userenv{'inststatus'} ne '') {
 1286:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1287:                                 my ($othertitle,$usertypes,$types) =
 1288:                                     &Apache::loncommon::sorted_inst_types($udom);
 1289:                                 if (ref($types) eq 'ARRAY') {
 1290:                                     foreach my $type (@{$types}) {
 1291:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1292:                                             if (exists($currrules->{$type})) {
 1293:                                                 $rule_in_effect = $currrules->{$type};
 1294:                                             }
 1295:                                         }
 1296:                                     }
 1297:                                 }
 1298:                             } else {
 1299:                                 if (exists($currrules->{'default'})) {
 1300:                                     $rule_in_effect = $currrules->{'default'};
 1301:                                 }
 1302:                             }
 1303:                         }
 1304:                     } else {
 1305:                         if (exists($currrules->{'default'})) {
 1306:                             $rule_in_effect = $currrules->{'default'};
 1307:                         }
 1308:                     }
 1309:                 } else {
 1310:                     if ($currrules->{'_LC_external'} ne '') {
 1311:                         $rule_in_effect = $currrules->{'_LC_external'};
 1312:                     }
 1313:                 }
 1314:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1315:                                                        $uname,$udom);
 1316:             }
 1317:         }
 1318:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1319:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1320:         unless (defined($cached)) {
 1321:             my %domconfig =
 1322:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1323:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1324:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1325:             }
 1326:         }
 1327:         if (ref($result) eq 'HASH') {
 1328:             ($is_balancer,$currtargets,$currrules) = 
 1329:                 &check_balancer_result($result,@hosts);
 1330:             if ($is_balancer) {
 1331:                 if (ref($currrules) eq 'HASH') {
 1332:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1333:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1334:                     }
 1335:                 }
 1336:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1337:                                                        $uname,$udom);
 1338:             }
 1339:         } else {
 1340:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1341:                 $is_balancer = 1;
 1342:                 $offloadto = &this_host_spares($dom_in_use);
 1343:             }
 1344:         }
 1345:     } else {
 1346:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1347:             $is_balancer = 1;
 1348:             $offloadto = &this_host_spares($dom_in_use);
 1349:         }
 1350:     }
 1351:     if ($is_balancer) {
 1352:         my $lowest_load = 30000;
 1353:         if (ref($offloadto) eq 'HASH') {
 1354:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1355:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1356:                     ($otherserver,$lowest_load) =
 1357:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1358:                 }
 1359:             }
 1360:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1361: 
 1362:             if (!$found_server) {
 1363:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1364:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1365:                         ($otherserver,$lowest_load) =
 1366:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1367:                     }
 1368:                 }
 1369:             }
 1370:         } elsif (ref($offloadto) eq 'ARRAY') {
 1371:             if (@{$offloadto} == 1) {
 1372:                 $otherserver = $offloadto->[0];
 1373:             } elsif (@{$offloadto} > 1) {
 1374:                 foreach my $try_server (@{$offloadto}) {
 1375:                     ($otherserver,$lowest_load) =
 1376:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1377:                 }
 1378:             }
 1379:         }
 1380:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1381:             $is_balancer = 0;
 1382:             if ($uname ne '' && $udom ne '') {
 1383:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1384:                     
 1385:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1386:                              'user.loadbalcheck.time' => time});
 1387:                 }
 1388:             }
 1389:         }
 1390:     }
 1391:     return ($is_balancer,$otherserver);
 1392: }
 1393: 
 1394: sub check_balancer_result {
 1395:     my ($result,@hosts) = @_;
 1396:     my ($is_balancer,$currtargets,$currrules);
 1397:     if (ref($result) eq 'HASH') {
 1398:         if ($result->{'lonhost'} ne '') {
 1399:             my $currbalancer = $result->{'lonhost'};
 1400:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1401:                 $is_balancer = 1;
 1402:                 $currtargets = $result->{'targets'};
 1403:                 $currrules = $result->{'rules'};
 1404:             }
 1405:         } else {
 1406:             foreach my $key (keys(%{$result})) {
 1407:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1408:                     (ref($result->{$key}) eq 'HASH')) {
 1409:                     $is_balancer = 1;
 1410:                     $currrules = $result->{$key}{'rules'};
 1411:                     $currtargets = $result->{$key}{'targets'};
 1412:                     last;
 1413:                 }
 1414:             }
 1415:         }
 1416:     }
 1417:     return ($is_balancer,$currtargets,$currrules);
 1418: }
 1419: 
 1420: sub get_loadbalancer_targets {
 1421:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1422:     my $offloadto;
 1423:     if ($rule_in_effect eq 'none') {
 1424:         return [$perlvar{'lonHostID'}];
 1425:     } elsif ($rule_in_effect eq '') {
 1426:         $offloadto = $currtargets;
 1427:     } else {
 1428:         if ($rule_in_effect eq 'homeserver') {
 1429:             my $homeserver = &homeserver($uname,$udom);
 1430:             if ($homeserver ne 'no_host') {
 1431:                 $offloadto = [$homeserver];
 1432:             }
 1433:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1434:             my %domconfig =
 1435:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1436:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1437:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1438:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1439:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1440:                     }
 1441:                 }
 1442:             } else {
 1443:                 my %servers = &internet_dom_servers($udom);
 1444:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1445:                 if (&hostname($remotebalancer) ne '') {
 1446:                     $offloadto = [$remotebalancer];
 1447:                 }
 1448:             }
 1449:         } elsif (&hostname($rule_in_effect) ne '') {
 1450:             $offloadto = [$rule_in_effect];
 1451:         }
 1452:     }
 1453:     return $offloadto;
 1454: }
 1455: 
 1456: sub internet_dom_servers {
 1457:     my ($dom) = @_;
 1458:     my (%uniqservers,%servers);
 1459:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1460:     my @machinedoms = &machine_domains($primaryserver);
 1461:     foreach my $mdom (@machinedoms) {
 1462:         my %currservers = %servers;
 1463:         my %server = &get_servers($mdom);
 1464:         %servers = (%currservers,%server);
 1465:     }
 1466:     my %by_hostname;
 1467:     foreach my $id (keys(%servers)) {
 1468:         push(@{$by_hostname{$servers{$id}}},$id);
 1469:     }
 1470:     foreach my $hostname (sort(keys(%by_hostname))) {
 1471:         if (@{$by_hostname{$hostname}} > 1) {
 1472:             my $match = 0;
 1473:             foreach my $id (@{$by_hostname{$hostname}}) {
 1474:                 if (&host_domain($id) eq $dom) {
 1475:                     $uniqservers{$id} = $hostname;
 1476:                     $match = 1;
 1477:                 }
 1478:             }
 1479:             unless ($match) {
 1480:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1481:             }
 1482:         } else {
 1483:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1484:         }
 1485:     }
 1486:     return %uniqservers;
 1487: }
 1488: 
 1489: # ---------------------- Find the homebase for a user from domain's lib servers
 1490: 
 1491: my %homecache;
 1492: sub homeserver {
 1493:     my ($uname,$udom,$ignoreBadCache)=@_;
 1494:     my $index="$uname:$udom";
 1495: 
 1496:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1497: 
 1498:     my %servers = &get_servers($udom,'library');
 1499:     foreach my $tryserver (keys(%servers)) {
 1500:         next if ($ignoreBadCache ne 'true' && 
 1501: 		 exists($badServerCache{$tryserver}));
 1502: 
 1503: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1504: 	if ($answer eq 'found') {
 1505: 	    delete($badServerCache{$tryserver}); 
 1506: 	    return $homecache{$index}=$tryserver;
 1507: 	} elsif ($answer eq 'no_host') {
 1508: 	    $badServerCache{$tryserver}=1;
 1509: 	}
 1510:     }    
 1511:     return 'no_host';
 1512: }
 1513: 
 1514: # ------------------------------------- Find the usernames behind a list of IDs
 1515: 
 1516: sub idget {
 1517:     my ($udom,@ids)=@_;
 1518:     my %returnhash=();
 1519:     
 1520:     my %servers = &get_servers($udom,'library');
 1521:     foreach my $tryserver (keys(%servers)) {
 1522: 	my $idlist=join('&',@ids);
 1523: 	$idlist=~tr/A-Z/a-z/; 
 1524: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1525: 	my @answer=();
 1526: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1527: 	    @answer=split(/\&/,$reply);
 1528: 	}                    ;
 1529: 	my $i;
 1530: 	for ($i=0;$i<=$#ids;$i++) {
 1531: 	    if ($answer[$i]) {
 1532: 		$returnhash{$ids[$i]}=$answer[$i];
 1533: 	    } 
 1534: 	}
 1535:     } 
 1536:     return %returnhash;
 1537: }
 1538: 
 1539: # ------------------------------------- Find the IDs behind a list of usernames
 1540: 
 1541: sub idrget {
 1542:     my ($udom,@unames)=@_;
 1543:     my %returnhash=();
 1544:     foreach my $uname (@unames) {
 1545:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1546:     }
 1547:     return %returnhash;
 1548: }
 1549: 
 1550: # ------------------------------- Store away a list of names and associated IDs
 1551: 
 1552: sub idput {
 1553:     my ($udom,%ids)=@_;
 1554:     my %servers=();
 1555:     foreach my $uname (keys(%ids)) {
 1556: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1557:         my $uhom=&homeserver($uname,$udom);
 1558:         if ($uhom ne 'no_host') {
 1559:             my $id=&escape($ids{$uname});
 1560:             $id=~tr/A-Z/a-z/;
 1561:             my $esc_unam=&escape($uname);
 1562: 	    if ($servers{$uhom}) {
 1563: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1564:             } else {
 1565:                 $servers{$uhom}=$id.'='.$esc_unam;
 1566:             }
 1567:         }
 1568:     }
 1569:     foreach my $server (keys(%servers)) {
 1570:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1571:     }
 1572: }
 1573: 
 1574: # ------------------------------dump from db file owned by domainconfig user
 1575: sub dump_dom {
 1576:     my ($namespace, $udom, $regexp) = @_;
 1577: 
 1578:     $udom ||= $env{'user.domain'};
 1579: 
 1580:     return () unless $udom;
 1581: 
 1582:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1583: }
 1584: 
 1585: # ------------------------------------------ get items from domain db files   
 1586: 
 1587: sub get_dom {
 1588:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1589:     my $items='';
 1590:     foreach my $item (@$storearr) {
 1591:         $items.=&escape($item).'&';
 1592:     }
 1593:     $items=~s/\&$//;
 1594:     if (!$udom) {
 1595:         $udom=$env{'user.domain'};
 1596:         if (defined(&domain($udom,'primary'))) {
 1597:             $uhome=&domain($udom,'primary');
 1598:         } else {
 1599:             undef($uhome);
 1600:         }
 1601:     } else {
 1602:         if (!$uhome) {
 1603:             if (defined(&domain($udom,'primary'))) {
 1604:                 $uhome=&domain($udom,'primary');
 1605:             }
 1606:         }
 1607:     }
 1608:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1609:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1610:         my %returnhash;
 1611:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1612:             return %returnhash;
 1613:         }
 1614:         my @pairs=split(/\&/,$rep);
 1615:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1616:             return @pairs;
 1617:         }
 1618:         my $i=0;
 1619:         foreach my $item (@$storearr) {
 1620:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1621:             $i++;
 1622:         }
 1623:         return %returnhash;
 1624:     } else {
 1625:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1626:     }
 1627: }
 1628: 
 1629: # -------------------------------------------- put items in domain db files 
 1630: 
 1631: sub put_dom {
 1632:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1633:     if (!$udom) {
 1634:         $udom=$env{'user.domain'};
 1635:         if (defined(&domain($udom,'primary'))) {
 1636:             $uhome=&domain($udom,'primary');
 1637:         } else {
 1638:             undef($uhome);
 1639:         }
 1640:     } else {
 1641:         if (!$uhome) {
 1642:             if (defined(&domain($udom,'primary'))) {
 1643:                 $uhome=&domain($udom,'primary');
 1644:             }
 1645:         }
 1646:     } 
 1647:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1648:         my $items='';
 1649:         foreach my $item (keys(%$storehash)) {
 1650:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1651:         }
 1652:         $items=~s/\&$//;
 1653:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1654:     } else {
 1655:         &logthis("put_dom failed - no homeserver and/or domain");
 1656:     }
 1657: }
 1658: 
 1659: # --------------------- newput for items in db file owned by domainconfig user
 1660: sub newput_dom {
 1661:     my ($namespace,$storehash,$udom) = @_;
 1662:     my $result;
 1663:     if (!$udom) {
 1664:         $udom=$env{'user.domain'};
 1665:     }
 1666:     if ($udom) {
 1667:         my $uname = &get_domainconfiguser($udom);
 1668:         $result = &newput($namespace,$storehash,$udom,$uname);
 1669:     }
 1670:     return $result;
 1671: }
 1672: 
 1673: # --------------------- delete for items in db file owned by domainconfig user
 1674: sub del_dom {
 1675:     my ($namespace,$storearr,$udom)=@_;
 1676:     if (ref($storearr) eq 'ARRAY') {
 1677:         if (!$udom) {
 1678:             $udom=$env{'user.domain'};
 1679:         }
 1680:         if ($udom) {
 1681:             my $uname = &get_domainconfiguser($udom); 
 1682:             return &del($namespace,$storearr,$udom,$uname);
 1683:         }
 1684:     }
 1685: }
 1686: 
 1687: # ----------------------------------construct domainconfig user for a domain 
 1688: sub get_domainconfiguser {
 1689:     my ($udom) = @_;
 1690:     return $udom.'-domainconfig';
 1691: }
 1692: 
 1693: sub retrieve_inst_usertypes {
 1694:     my ($udom) = @_;
 1695:     my (%returnhash,@order);
 1696:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1697:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1698:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1699:         %returnhash = %{$domdefs{'inststatustypes'}};
 1700:         @order = @{$domdefs{'inststatusorder'}};
 1701:     } else {
 1702:         if (defined(&domain($udom,'primary'))) {
 1703:             my $uhome=&domain($udom,'primary');
 1704:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1705:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1706:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1707:                 return (\%returnhash,\@order);
 1708:             }
 1709:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1710:             my @pairs=split(/\&/,$hashitems);
 1711:             foreach my $item (@pairs) {
 1712:                 my ($key,$value)=split(/=/,$item,2);
 1713:                 $key = &unescape($key);
 1714:                 next if ($key =~ /^error: 2 /);
 1715:                 $returnhash{$key}=&thaw_unescape($value);
 1716:             }
 1717:             my @esc_order = split(/\&/,$orderitems);
 1718:             foreach my $item (@esc_order) {
 1719:                 push(@order,&unescape($item));
 1720:             }
 1721:         } else {
 1722:             &logthis("get_dom failed - no primary domain server for $udom");
 1723:         }
 1724:     }
 1725:     return (\%returnhash,\@order);
 1726: }
 1727: 
 1728: sub is_domainimage {
 1729:     my ($url) = @_;
 1730:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1731:         if (&domain($1) ne '') {
 1732:             return '1';
 1733:         }
 1734:     }
 1735:     return;
 1736: }
 1737: 
 1738: sub inst_directory_query {
 1739:     my ($srch) = @_;
 1740:     my $udom = $srch->{'srchdomain'};
 1741:     my %results;
 1742:     my $homeserver = &domain($udom,'primary');
 1743:     my $outcome;
 1744:     if ($homeserver ne '') {
 1745: 	my $queryid=&reply("querysend:instdirsearch:".
 1746: 			   &escape($srch->{'srchby'}).':'.
 1747: 			   &escape($srch->{'srchterm'}).':'.
 1748: 			   &escape($srch->{'srchtype'}),$homeserver);
 1749: 	my $host=&hostname($homeserver);
 1750: 	if ($queryid !~/^\Q$host\E\_/) {
 1751: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1752: 	    return;
 1753: 	}
 1754: 	my $response = &get_query_reply($queryid);
 1755: 	my $maxtries = 5;
 1756: 	my $tries = 1;
 1757: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1758: 	    $response = &get_query_reply($queryid);
 1759: 	    $tries ++;
 1760: 	}
 1761: 
 1762:         if (!&error($response) && $response ne 'refused') {
 1763:             if ($response eq 'unavailable') {
 1764:                 $outcome = $response;
 1765:             } else {
 1766:                 $outcome = 'ok';
 1767:                 my @matches = split(/\n/,$response);
 1768:                 foreach my $match (@matches) {
 1769:                     my ($key,$value) = split(/=/,$match);
 1770:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1771:                 }
 1772:             }
 1773:         }
 1774:     }
 1775:     return ($outcome,%results);
 1776: }
 1777: 
 1778: sub usersearch {
 1779:     my ($srch) = @_;
 1780:     my $dom = $srch->{'srchdomain'};
 1781:     my %results;
 1782:     my %libserv = &all_library();
 1783:     my $query = 'usersearch';
 1784:     foreach my $tryserver (keys(%libserv)) {
 1785:         if (&host_domain($tryserver) eq $dom) {
 1786:             my $host=&hostname($tryserver);
 1787:             my $queryid=
 1788:                 &reply("querysend:".&escape($query).':'.
 1789:                        &escape($srch->{'srchby'}).':'.
 1790:                        &escape($srch->{'srchtype'}).':'.
 1791:                        &escape($srch->{'srchterm'}),$tryserver);
 1792:             if ($queryid !~/^\Q$host\E\_/) {
 1793:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1794:                 next;
 1795:             }
 1796:             my $reply = &get_query_reply($queryid);
 1797:             my $maxtries = 1;
 1798:             my $tries = 1;
 1799:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1800:                 $reply = &get_query_reply($queryid);
 1801:                 $tries ++;
 1802:             }
 1803:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1804:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1805:             } else {
 1806:                 my @matches;
 1807:                 if ($reply =~ /\n/) {
 1808:                     @matches = split(/\n/,$reply);
 1809:                 } else {
 1810:                     @matches = split(/\&/,$reply);
 1811:                 }
 1812:                 foreach my $match (@matches) {
 1813:                     my ($uname,$udom,%userhash);
 1814:                     foreach my $entry (split(/:/,$match)) {
 1815:                         my ($key,$value) =
 1816:                             map {&unescape($_);} split(/=/,$entry);
 1817:                         $userhash{$key} = $value;
 1818:                         if ($key eq 'username') {
 1819:                             $uname = $value;
 1820:                         } elsif ($key eq 'domain') {
 1821:                             $udom = $value;
 1822:                         }
 1823:                     }
 1824:                     $results{$uname.':'.$udom} = \%userhash;
 1825:                 }
 1826:             }
 1827:         }
 1828:     }
 1829:     return %results;
 1830: }
 1831: 
 1832: sub get_instuser {
 1833:     my ($udom,$uname,$id) = @_;
 1834:     my $homeserver = &domain($udom,'primary');
 1835:     my ($outcome,%results);
 1836:     if ($homeserver ne '') {
 1837:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1838:                            &escape($id).':'.&escape($udom),$homeserver);
 1839:         my $host=&hostname($homeserver);
 1840:         if ($queryid !~/^\Q$host\E\_/) {
 1841:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1842:             return;
 1843:         }
 1844:         my $response = &get_query_reply($queryid);
 1845:         my $maxtries = 5;
 1846:         my $tries = 1;
 1847:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1848:             $response = &get_query_reply($queryid);
 1849:             $tries ++;
 1850:         }
 1851:         if (!&error($response) && $response ne 'refused') {
 1852:             if ($response eq 'unavailable') {
 1853:                 $outcome = $response;
 1854:             } else {
 1855:                 $outcome = 'ok';
 1856:                 my @matches = split(/\n/,$response);
 1857:                 foreach my $match (@matches) {
 1858:                     my ($key,$value) = split(/=/,$match);
 1859:                     $results{&unescape($key)} = &thaw_unescape($value);
 1860:                 }
 1861:             }
 1862:         }
 1863:     }
 1864:     my %userinfo;
 1865:     if (ref($results{$uname}) eq 'HASH') {
 1866:         %userinfo = %{$results{$uname}};
 1867:     } 
 1868:     return ($outcome,%userinfo);
 1869: }
 1870: 
 1871: sub inst_rulecheck {
 1872:     my ($udom,$uname,$id,$item,$rules) = @_;
 1873:     my %returnhash;
 1874:     if ($udom ne '') {
 1875:         if (ref($rules) eq 'ARRAY') {
 1876:             @{$rules} = map {&escape($_);} (@{$rules});
 1877:             my $rulestr = join(':',@{$rules});
 1878:             my $homeserver=&domain($udom,'primary');
 1879:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1880:                 my $response;
 1881:                 if ($item eq 'username') {                
 1882:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1883:                                               ':'.&escape($uname).':'.$rulestr,
 1884:                                               $homeserver));
 1885:                 } elsif ($item eq 'id') {
 1886:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1887:                                               ':'.&escape($id).':'.$rulestr,
 1888:                                               $homeserver));
 1889:                 } elsif ($item eq 'selfcreate') {
 1890:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1891:                                                &escape($udom).':'.&escape($uname).
 1892:                                               ':'.$rulestr,$homeserver));
 1893:                 }
 1894:                 if ($response ne 'refused') {
 1895:                     my @pairs=split(/\&/,$response);
 1896:                     foreach my $item (@pairs) {
 1897:                         my ($key,$value)=split(/=/,$item,2);
 1898:                         $key = &unescape($key);
 1899:                         next if ($key =~ /^error: 2 /);
 1900:                         $returnhash{$key}=&thaw_unescape($value);
 1901:                     }
 1902:                 }
 1903:             }
 1904:         }
 1905:     }
 1906:     return %returnhash;
 1907: }
 1908: 
 1909: sub inst_userrules {
 1910:     my ($udom,$check) = @_;
 1911:     my (%ruleshash,@ruleorder);
 1912:     if ($udom ne '') {
 1913:         my $homeserver=&domain($udom,'primary');
 1914:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1915:             my $response;
 1916:             if ($check eq 'id') {
 1917:                 $response=&reply('instidrules:'.&escape($udom),
 1918:                                  $homeserver);
 1919:             } elsif ($check eq 'email') {
 1920:                 $response=&reply('instemailrules:'.&escape($udom),
 1921:                                  $homeserver);
 1922:             } else {
 1923:                 $response=&reply('instuserrules:'.&escape($udom),
 1924:                                  $homeserver);
 1925:             }
 1926:             if (($response ne 'refused') && ($response ne 'error') && 
 1927:                 ($response ne 'unknown_cmd') && 
 1928:                 ($response ne 'no_such_host')) {
 1929:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1930:                 my @pairs=split(/\&/,$hashitems);
 1931:                 foreach my $item (@pairs) {
 1932:                     my ($key,$value)=split(/=/,$item,2);
 1933:                     $key = &unescape($key);
 1934:                     next if ($key =~ /^error: 2 /);
 1935:                     $ruleshash{$key}=&thaw_unescape($value);
 1936:                 }
 1937:                 my @esc_order = split(/\&/,$orderitems);
 1938:                 foreach my $item (@esc_order) {
 1939:                     push(@ruleorder,&unescape($item));
 1940:                 }
 1941:             }
 1942:         }
 1943:     }
 1944:     return (\%ruleshash,\@ruleorder);
 1945: }
 1946: 
 1947: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1948: 
 1949: sub get_domain_defaults {
 1950:     my ($domain) = @_;
 1951:     my $cachetime = 60*60*24;
 1952:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1953:     if (defined($cached)) {
 1954:         if (ref($result) eq 'HASH') {
 1955:             return %{$result};
 1956:         }
 1957:     }
 1958:     my %domdefaults;
 1959:     my %domconfig =
 1960:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1961:                                   'requestcourses','inststatus',
 1962:                                   'coursedefaults','usersessions',
 1963:                                   'requestauthor'],$domain);
 1964:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1965:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1966:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1967:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1968:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1969:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1970:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1971:     } else {
 1972:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1973:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1974:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1975:     }
 1976:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1977:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1978:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1979:         } else {
 1980:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1981:         } 
 1982:         my @usertools = ('aboutme','blog','webdav','portfolio');
 1983:         foreach my $item (@usertools) {
 1984:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1985:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1986:             }
 1987:         }
 1988:     }
 1989:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1990:         foreach my $item ('official','unofficial','community') {
 1991:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1992:         }
 1993:     }
 1994:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 1995:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 1996:     }
 1997:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1998:         foreach my $item ('inststatustypes','inststatusorder') {
 1999:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2000:         }
 2001:     }
 2002:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2003:         foreach my $item ('canuse_pdfforms') {
 2004:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 2005:         }
 2006:     }
 2007:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2008:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2009:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2010:         }
 2011:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2012:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2013:         }
 2014:     }
 2015:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 2016:                                   $cachetime);
 2017:     return %domdefaults;
 2018: }
 2019: 
 2020: # --------------------------------------------------- Assign a key to a student
 2021: 
 2022: sub assign_access_key {
 2023: #
 2024: # a valid key looks like uname:udom#comments
 2025: # comments are being appended
 2026: #
 2027:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2028:     $kdom=
 2029:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2030:     $knum=
 2031:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2032:     $cdom=
 2033:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2034:     $cnum=
 2035:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2036:     $udom=$env{'user.name'} unless (defined($udom));
 2037:     $uname=$env{'user.domain'} unless (defined($uname));
 2038:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2039:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2040:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2041:                                                   # assigned to this person
 2042:                                                   # - this should not happen,
 2043:                                                   # unless something went wrong
 2044:                                                   # the first time around
 2045: # ready to assign
 2046:         $logentry=$1.'; '.$logentry;
 2047:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2048:                                                  $kdom,$knum) eq 'ok') {
 2049: # key now belongs to user
 2050: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2051:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2052:                 &appenv({'environment.'.$envkey => $ckey});
 2053:                 return 'ok';
 2054:             } else {
 2055:                 return 
 2056:   'error: Count not permanently assign key, will need to be re-entered later.';
 2057: 	    }
 2058:         } else {
 2059:             return 'error: Could not assign key, try again later.';
 2060:         }
 2061:     } elsif (!$existing{$ckey}) {
 2062: # the key does not exist
 2063: 	return 'error: The key does not exist';
 2064:     } else {
 2065: # the key is somebody else's
 2066: 	return 'error: The key is already in use';
 2067:     }
 2068: }
 2069: 
 2070: # ------------------------------------------ put an additional comment on a key
 2071: 
 2072: sub comment_access_key {
 2073: #
 2074: # a valid key looks like uname:udom#comments
 2075: # comments are being appended
 2076: #
 2077:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2078:     $cdom=
 2079:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2080:     $cnum=
 2081:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2082:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2083:     if ($existing{$ckey}) {
 2084:         $existing{$ckey}.='; '.$logentry;
 2085: # ready to assign
 2086:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2087:                                                  $cdom,$cnum) eq 'ok') {
 2088: 	    return 'ok';
 2089:         } else {
 2090: 	    return 'error: Count not store comment.';
 2091:         }
 2092:     } else {
 2093: # the key does not exist
 2094: 	return 'error: The key does not exist';
 2095:     }
 2096: }
 2097: 
 2098: # ------------------------------------------------------ Generate a set of keys
 2099: 
 2100: sub generate_access_keys {
 2101:     my ($number,$cdom,$cnum,$logentry)=@_;
 2102:     $cdom=
 2103:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2104:     $cnum=
 2105:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2106:     unless (&allowed('mky',$cdom)) { return 0; }
 2107:     unless (($cdom) && ($cnum)) { return 0; }
 2108:     if ($number>10000) { return 0; }
 2109:     sleep(2); # make sure don't get same seed twice
 2110:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2111:     my $total=0;
 2112:     for (my $i=1;$i<=$number;$i++) {
 2113:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2114:                   sprintf("%lx",int(100000*rand)).'-'.
 2115:                   sprintf("%lx",int(100000*rand));
 2116:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2117:        $newkey=~s/0/h/g; # and also 0 and O
 2118:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2119:        if ($existing{$newkey}) {
 2120:            $i--;
 2121:        } else {
 2122: 	  if (&put('accesskeys',
 2123:               { $newkey => '# generated '.localtime().
 2124:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2125:                            '; '.$logentry },
 2126: 		   $cdom,$cnum) eq 'ok') {
 2127:               $total++;
 2128: 	  }
 2129:        }
 2130:     }
 2131:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2132:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2133:     return $total;
 2134: }
 2135: 
 2136: # ------------------------------------------------------- Validate an accesskey
 2137: 
 2138: sub validate_access_key {
 2139:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2140:     $cdom=
 2141:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2142:     $cnum=
 2143:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2144:     $udom=$env{'user.domain'} unless (defined($udom));
 2145:     $uname=$env{'user.name'} unless (defined($uname));
 2146:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2147:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2148: }
 2149: 
 2150: # ------------------------------------- Find the section of student in a course
 2151: sub devalidate_getsection_cache {
 2152:     my ($udom,$unam,$courseid)=@_;
 2153:     my $hashid="$udom:$unam:$courseid";
 2154:     &devalidate_cache_new('getsection',$hashid);
 2155: }
 2156: 
 2157: sub courseid_to_courseurl {
 2158:     my ($courseid) = @_;
 2159:     #already url style courseid
 2160:     return $courseid if ($courseid =~ m{^/});
 2161: 
 2162:     if (exists($env{'course.'.$courseid.'.num'})) {
 2163: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2164: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2165: 	return "/$cdom/$cnum";
 2166:     }
 2167: 
 2168:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2169:     if (exists($courseinfo{'num'})) {
 2170: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2171:     }
 2172: 
 2173:     return undef;
 2174: }
 2175: 
 2176: sub getsection {
 2177:     my ($udom,$unam,$courseid)=@_;
 2178:     my $cachetime=1800;
 2179: 
 2180:     my $hashid="$udom:$unam:$courseid";
 2181:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2182:     if (defined($cached)) { return $result; }
 2183: 
 2184:     my %Pending; 
 2185:     my %Expired;
 2186:     #
 2187:     # Each role can either have not started yet (pending), be active, 
 2188:     #    or have expired.
 2189:     #
 2190:     # If there is an active role, we are done.
 2191:     #
 2192:     # If there is more than one role which has not started yet, 
 2193:     #     choose the one which will start sooner
 2194:     # If there is one role which has not started yet, return it.
 2195:     #
 2196:     # If there is more than one expired role, choose the one which ended last.
 2197:     # If there is a role which has expired, return it.
 2198:     #
 2199:     $courseid = &courseid_to_courseurl($courseid);
 2200:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2201:     foreach my $key (keys(%roleshash)) {
 2202:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2203:         my $section=$1;
 2204:         if ($key eq $courseid.'_st') { $section=''; }
 2205:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2206:         my $now=time;
 2207:         if (defined($end) && $end && ($now > $end)) {
 2208:             $Expired{$end}=$section;
 2209:             next;
 2210:         }
 2211:         if (defined($start) && $start && ($now < $start)) {
 2212:             $Pending{$start}=$section;
 2213:             next;
 2214:         }
 2215:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2216:     }
 2217:     #
 2218:     # Presumedly there will be few matching roles from the above
 2219:     # loop and the sorting time will be negligible.
 2220:     if (scalar(keys(%Pending))) {
 2221:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2222:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2223:     } 
 2224:     if (scalar(keys(%Expired))) {
 2225:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2226:         my $time = pop(@sorted);
 2227:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2228:     }
 2229:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2230: }
 2231: 
 2232: sub save_cache {
 2233:     &purge_remembered();
 2234:     #&Apache::loncommon::validate_page();
 2235:     undef(%env);
 2236:     undef($env_loaded);
 2237: }
 2238: 
 2239: my $to_remember=-1;
 2240: my %remembered;
 2241: my %accessed;
 2242: my $kicks=0;
 2243: my $hits=0;
 2244: sub make_key {
 2245:     my ($name,$id) = @_;
 2246:     if (length($id) > 65 
 2247: 	&& length(&escape($id)) > 200) {
 2248: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2249:     }
 2250:     return &escape($name.':'.$id);
 2251: }
 2252: 
 2253: sub devalidate_cache_new {
 2254:     my ($name,$id,$debug) = @_;
 2255:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2256:     $id=&make_key($name,$id);
 2257:     $memcache->delete($id);
 2258:     delete($remembered{$id});
 2259:     delete($accessed{$id});
 2260: }
 2261: 
 2262: sub is_cached_new {
 2263:     my ($name,$id,$debug) = @_;
 2264:     $id=&make_key($name,$id);
 2265:     if (exists($remembered{$id})) {
 2266: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2267: 	$accessed{$id}=[&gettimeofday()];
 2268: 	$hits++;
 2269: 	return ($remembered{$id},1);
 2270:     }
 2271:     my $value = $memcache->get($id);
 2272:     if (!(defined($value))) {
 2273: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2274: 	return (undef,undef);
 2275:     }
 2276:     if ($value eq '__undef__') {
 2277: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2278: 	$value=undef;
 2279:     }
 2280:     &make_room($id,$value,$debug);
 2281:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2282:     return ($value,1);
 2283: }
 2284: 
 2285: sub do_cache_new {
 2286:     my ($name,$id,$value,$time,$debug) = @_;
 2287:     $id=&make_key($name,$id);
 2288:     my $setvalue=$value;
 2289:     if (!defined($setvalue)) {
 2290: 	$setvalue='__undef__';
 2291:     }
 2292:     if (!defined($time) ) {
 2293: 	$time=600;
 2294:     }
 2295:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2296:     my $result = $memcache->set($id,$setvalue,$time);
 2297:     if (! $result) {
 2298: 	&logthis("caching of id -> $id  failed");
 2299: 	$memcache->disconnect_all();
 2300:     }
 2301:     # need to make a copy of $value
 2302:     &make_room($id,$value,$debug);
 2303:     return $value;
 2304: }
 2305: 
 2306: sub make_room {
 2307:     my ($id,$value,$debug)=@_;
 2308: 
 2309:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2310:                                     : $value;
 2311:     if ($to_remember<0) { return; }
 2312:     $accessed{$id}=[&gettimeofday()];
 2313:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2314:     my $to_kick;
 2315:     my $max_time=0;
 2316:     foreach my $other (keys(%accessed)) {
 2317: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2318: 	    $to_kick=$other;
 2319: 	    $max_time=&tv_interval($accessed{$other});
 2320: 	}
 2321:     }
 2322:     delete($remembered{$to_kick});
 2323:     delete($accessed{$to_kick});
 2324:     $kicks++;
 2325:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2326:     return;
 2327: }
 2328: 
 2329: sub purge_remembered {
 2330:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2331:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2332:     undef(%remembered);
 2333:     undef(%accessed);
 2334: }
 2335: # ------------------------------------- Read an entry from a user's environment
 2336: 
 2337: sub userenvironment {
 2338:     my ($udom,$unam,@what)=@_;
 2339:     my $items;
 2340:     foreach my $item (@what) {
 2341:         $items.=&escape($item).'&';
 2342:     }
 2343:     $items=~s/\&$//;
 2344:     my %returnhash=();
 2345:     my $uhome = &homeserver($unam,$udom);
 2346:     unless ($uhome eq 'no_host') {
 2347:         my @answer=split(/\&/, 
 2348:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2349:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2350:             return %returnhash;
 2351:         }
 2352:         my $i;
 2353:         for ($i=0;$i<=$#what;$i++) {
 2354: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2355:         }
 2356:     }
 2357:     return %returnhash;
 2358: }
 2359: 
 2360: # ---------------------------------------------------------- Get a studentphoto
 2361: sub studentphoto {
 2362:     my ($udom,$unam,$ext) = @_;
 2363:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2364:     if (defined($env{'request.course.id'})) {
 2365:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2366:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2367:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2368:             } else {
 2369:                 my ($result,$perm_reqd)=
 2370: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2371:                 if ($result eq 'ok') {
 2372:                     if (!($perm_reqd eq 'yes')) {
 2373:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2374:                     }
 2375:                 }
 2376:             }
 2377:         }
 2378:     } else {
 2379:         my ($result,$perm_reqd) = 
 2380: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2381:         if ($result eq 'ok') {
 2382:             if (!($perm_reqd eq 'yes')) {
 2383:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2384:             }
 2385:         }
 2386:     }
 2387:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2388: }
 2389: 
 2390: sub retrievestudentphoto {
 2391:     my ($udom,$unam,$ext,$type) = @_;
 2392:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2393:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2394:     if ($ret eq 'ok') {
 2395:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2396:         if ($type eq 'thumbnail') {
 2397:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2398:         }
 2399:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2400:         return $tokenurl;
 2401:     } else {
 2402:         if ($type eq 'thumbnail') {
 2403:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2404:         } else { 
 2405:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2406:         }
 2407:     }
 2408: }
 2409: 
 2410: # -------------------------------------------------------------------- New chat
 2411: 
 2412: sub chatsend {
 2413:     my ($newentry,$anon,$group)=@_;
 2414:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2415:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2416:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2417:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2418: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2419: 		   &escape($newentry)).':'.$group,$chome);
 2420: }
 2421: 
 2422: # ------------------------------------------ Find current version of a resource
 2423: 
 2424: sub getversion {
 2425:     my $fname=&clutter(shift);
 2426:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2427:     return &currentversion(&filelocation('',$fname));
 2428: }
 2429: 
 2430: sub currentversion {
 2431:     my $fname=shift;
 2432:     my $author=$fname;
 2433:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2434:     my ($udom,$uname)=split(/\//,$author);
 2435:     my $home=&homeserver($uname,$udom);
 2436:     if ($home eq 'no_host') { 
 2437:         return -1; 
 2438:     }
 2439:     my $answer=&reply("currentversion:$fname",$home);
 2440:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2441: 	return -1;
 2442:     }
 2443:     return $answer;
 2444: }
 2445: 
 2446: #
 2447: # Return special version number of resource if set by override, empty otherwise
 2448: #
 2449: sub usedversion {
 2450:     my $fname=shift;
 2451:     unless ($fname) { $fname=$env{'request.uri'}; }
 2452:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2453:     if ($urlversion) { return $urlversion; }
 2454:     return '';
 2455: }
 2456: 
 2457: # ----------------------------- Subscribe to a resource, return URL if possible
 2458: 
 2459: sub subscribe {
 2460:     my $fname=shift;
 2461:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2462:     $fname=~s/[\n\r]//g;
 2463:     my $author=$fname;
 2464:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2465:     my ($udom,$uname)=split(/\//,$author);
 2466:     my $home=homeserver($uname,$udom);
 2467:     if ($home eq 'no_host') {
 2468:         return 'not_found';
 2469:     }
 2470:     my $answer=reply("sub:$fname",$home);
 2471:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2472: 	$answer.=' by '.$home;
 2473:     }
 2474:     return $answer;
 2475: }
 2476:     
 2477: # -------------------------------------------------------------- Replicate file
 2478: 
 2479: sub repcopy {
 2480:     my $filename=shift;
 2481:     $filename=~s/\/+/\//g;
 2482:     my $londocroot = $perlvar{'lonDocRoot'};
 2483:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2484:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2485:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2486: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2487: 	return &repcopy_userfile($filename);
 2488:     }
 2489:     $filename=~s/[\n\r]//g;
 2490:     my $transname="$filename.in.transfer";
 2491: # FIXME: this should flock
 2492:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2493:     my $remoteurl=subscribe($filename);
 2494:     if ($remoteurl =~ /^con_lost by/) {
 2495: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2496:            return 'unavailable';
 2497:     } elsif ($remoteurl eq 'not_found') {
 2498: 	   #&logthis("Subscribe returned not_found: $filename");
 2499: 	   return 'not_found';
 2500:     } elsif ($remoteurl =~ /^rejected by/) {
 2501: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2502:            return 'forbidden';
 2503:     } elsif ($remoteurl eq 'directory') {
 2504:            return 'ok';
 2505:     } else {
 2506:         my $author=$filename;
 2507:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2508:         my ($udom,$uname)=split(/\//,$author);
 2509:         my $home=homeserver($uname,$udom);
 2510:         unless ($home eq $perlvar{'lonHostID'}) {
 2511:            my @parts=split(/\//,$filename);
 2512:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2513:            if ($path ne "$londocroot/res") {
 2514:                &logthis("Malconfiguration for replication: $filename");
 2515: 	       return 'bad_request';
 2516:            }
 2517:            my $count;
 2518:            for ($count=5;$count<$#parts;$count++) {
 2519:                $path.="/$parts[$count]";
 2520:                if ((-e $path)!=1) {
 2521: 		   mkdir($path,0777);
 2522:                }
 2523:            }
 2524:            my $ua=new LWP::UserAgent;
 2525:            my $request=new HTTP::Request('GET',"$remoteurl");
 2526:            my $response=$ua->request($request,$transname);
 2527:            if ($response->is_error()) {
 2528: 	       unlink($transname);
 2529:                my $message=$response->status_line;
 2530:                &logthis("<font color=\"blue\">WARNING:"
 2531:                        ." LWP get: $message: $filename</font>");
 2532:                return 'unavailable';
 2533:            } else {
 2534: 	       if ($remoteurl!~/\.meta$/) {
 2535:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2536:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2537:                   if ($mresponse->is_error()) {
 2538: 		      unlink($filename.'.meta');
 2539:                       &logthis(
 2540:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2541:                   }
 2542: 	       }
 2543:                rename($transname,$filename);
 2544:                return 'ok';
 2545:            }
 2546:        }
 2547:     }
 2548: }
 2549: 
 2550: # ------------------------------------------------ Get server side include body
 2551: sub ssi_body {
 2552:     my ($filelink,%form)=@_;
 2553:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2554:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2555:     }
 2556:     my $output='';
 2557:     my $response;
 2558:     if ($filelink=~/^https?\:/) {
 2559:        ($output,$response)=&externalssi($filelink);
 2560:     } else {
 2561:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2562:        $filelink .= 'inhibitmenu=yes';
 2563:        ($output,$response)=&ssi($filelink,%form);
 2564:     }
 2565:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2566:     $output=~s/^.*?\<body[^\>]*\>//si;
 2567:     $output=~s/\<\/body\s*\>.*?$//si;
 2568:     if (wantarray) {
 2569:         return ($output, $response);
 2570:     } else {
 2571:         return $output;
 2572:     }
 2573: }
 2574: 
 2575: # --------------------------------------------------------- Server Side Include
 2576: 
 2577: sub absolute_url {
 2578:     my ($host_name) = @_;
 2579:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2580:     if ($host_name eq '') {
 2581: 	$host_name = $ENV{'SERVER_NAME'};
 2582:     }
 2583:     return $protocol.$host_name;
 2584: }
 2585: 
 2586: #
 2587: #   Server side include.
 2588: # Parameters:
 2589: #  fn     Possibly encrypted resource name/id.
 2590: #  form   Hash that describes how the rendering should be done
 2591: #         and other things.
 2592: # Returns:
 2593: #   Scalar context: The content of the response.
 2594: #   Array context:  2 element list of the content and the full response object.
 2595: #     
 2596: sub ssi {
 2597: 
 2598:     my ($fn,%form)=@_;
 2599:     my $ua=new LWP::UserAgent;
 2600:     my $request;
 2601: 
 2602:     $form{'no_update_last_known'}=1;
 2603:     &Apache::lonenc::check_encrypt(\$fn);
 2604:     if (%form) {
 2605:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2606:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2607:     } else {
 2608:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2609:     }
 2610: 
 2611:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2612:     my $response= $ua->request($request);
 2613:     my $content = $response->content;
 2614: 
 2615: 
 2616:     if (wantarray) {
 2617: 	return ($content, $response);
 2618:     } else {
 2619: 	return $content;
 2620:     }
 2621: }
 2622: 
 2623: sub externalssi {
 2624:     my ($url)=@_;
 2625:     my $ua=new LWP::UserAgent;
 2626:     my $request=new HTTP::Request('GET',$url);
 2627:     my $response=$ua->request($request);
 2628:     if (wantarray) {
 2629:         return ($response->content, $response);
 2630:     } else {
 2631:         return $response->content;
 2632:     }
 2633: }
 2634: 
 2635: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2636: 
 2637: sub allowuploaded {
 2638:     my ($srcurl,$url)=@_;
 2639:     $url=&clutter(&declutter($url));
 2640:     my $dir=$url;
 2641:     $dir=~s/\/[^\/]+$//;
 2642:     my %httpref=();
 2643:     my $httpurl=&hreflocation('',$url);
 2644:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2645:     &Apache::lonnet::appenv(\%httpref);
 2646: }
 2647: 
 2648: #
 2649: # Determine if the current user should be able to edit a particular resource,
 2650: # when viewing in course context.
 2651: # (a) When viewing resource used to determine if "Edit" item is included in 
 2652: #     Functions.
 2653: # (b) When displaying folder contents in course editor, used to determine if
 2654: #     "Edit" link will be displayed alongside resource.
 2655: #
 2656: #  input: six args -- filename (decluttered), course number, course domain,
 2657: #                   url, symb (if registered) and group (if this is a group
 2658: #                   item -- e.g., bulletin board, group page etc.).
 2659: #  output: array of five scalars -- 
 2660: #          $cfile -- url for file editing if editable on current server
 2661: #          $home -- homeserver of resource (i.e., for author if published,
 2662: #                                           or course if uploaded.).
 2663: #          $switchserver --  1 if server switch will be needed.
 2664: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2665: #          $forceview -- 1 if icon/link should be to go to view mode
 2666: #
 2667: 
 2668: sub can_edit_resource {
 2669:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2670:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2671: #
 2672: # For aboutme pages user can only edit his/her own.
 2673: #
 2674:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2675:         my ($sdom,$sname) = ($1,$2);
 2676:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2677:             $home = $env{'user.home'};
 2678:             $cfile = $resurl;
 2679:             if ($env{'form.forceedit'}) {
 2680:                 $forceview = 1;
 2681:             } else {
 2682:                 $forceedit = 1;
 2683:             }
 2684:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2685:         } else {
 2686:             return;
 2687:         }
 2688:     }
 2689: 
 2690:     if ($env{'request.course.id'}) {
 2691:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2692:         if ($group ne '') {
 2693: # if this is a group homepage or group bulletin board, check group privs
 2694:             my $allowed = 0;
 2695:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2696:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2697:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2698:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2699:                     $allowed = 1;
 2700:                 }
 2701:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2702:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2703:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2704:                     $allowed = 1;
 2705:                 }
 2706:             }
 2707:             if ($allowed) {
 2708:                 $home=&homeserver($cnum,$cdom);
 2709:                 if ($env{'form.forceedit'}) {
 2710:                     $forceview = 1;
 2711:                 } else {
 2712:                     $forceedit = 1;
 2713:                 }
 2714:                 $cfile = $resurl;
 2715:             } else {
 2716:                 return;
 2717:             }
 2718:         } else {
 2719: #
 2720: # No edit allowed where CC has switched to student role.
 2721: #
 2722:             unless ($crsedit) {
 2723:                 return;
 2724:             }
 2725:         }
 2726:     }
 2727: 
 2728:     if ($file ne '') {
 2729:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2730:             if (&is_course_upload($file,$cnum,$cdom)) {
 2731:                 $uploaded = 1;
 2732:                 $incourse = 1;
 2733:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2734:                     $cfile = &hreflocation('',$file);
 2735:                     if ($env{'form.forceedit'}) {
 2736:                         $forceview = 1;
 2737:                     } else {
 2738:                         $forceedit = 1;
 2739:                     }
 2740:                 }
 2741:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2742:                 $incourse = 1;
 2743:                 if ($env{'form.forceedit'}) {
 2744:                     $forceview = 1;
 2745:                 } else {
 2746:                     $forceedit = 1;
 2747:                 }
 2748:                 $cfile = $resurl;
 2749:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2750:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2751:                     $incourse = 1;
 2752:                     if ($env{'form.forceedit'}) {
 2753:                         $forceview = 1;
 2754:                     } else {
 2755:                         $forceedit = 1;
 2756:                     }
 2757:                     $cfile = $resurl;
 2758:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2759:                     $incourse = 1;
 2760:                     $cfile = $resurl.'/smpedit';
 2761:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2762:                     $incourse = 1;
 2763:                     if ($env{'form.forceedit'}) {
 2764:                         $forceview = 1;
 2765:                     } else {
 2766:                         $forceedit = 1;
 2767:                     }
 2768:                     $cfile = $resurl;
 2769:                 }
 2770:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2771:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2772:                 if (&is_on_map($template)) { 
 2773:                     $incourse = 1;
 2774:                     $forceview = 1;
 2775:                     $cfile = $template;
 2776:                 }
 2777:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2778:                     $incourse = 1;
 2779:                     if ($env{'form.forceedit'}) {
 2780:                         $forceview = 1;
 2781:                     } else {
 2782:                         $forceedit = 1;
 2783:                     }
 2784:                     $cfile = $resurl;
 2785:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2786:                 $incourse = 1;
 2787:                 $forceview = 1;
 2788:                 if ($symb) {
 2789:                     my ($map,$id,$res)=&decode_symb($symb);
 2790:                     $env{'request.symb'} = $symb;
 2791:                     $cfile = &clutter($res);
 2792:                 } else {
 2793:                     $cfile = $env{'form.suppurl'};
 2794:                     $cfile =~ s{^http://}{};
 2795:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2796:                 }
 2797:             }
 2798:         }
 2799:         if ($uploaded || $incourse) {
 2800:             $home=&homeserver($cnum,$cdom);
 2801:         } else {
 2802:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2803:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2804:             # Check that the user has permission to edit this resource
 2805:             my $setpriv = 1;
 2806:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2807:             if (defined($cfudom)) {
 2808:                 $home=&homeserver($cfuname,$cfudom);
 2809:                 $cfile=$file;
 2810:             }
 2811:         }
 2812:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2813:             (($home ne '') && ($home ne 'no_host'))) {
 2814:             my @ids=&current_machine_ids();
 2815:             unless (grep(/^\Q$home\E$/,@ids)) {
 2816:                 $switchserver=1;
 2817:             }
 2818:         }
 2819:     }
 2820:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2821: }
 2822: 
 2823: sub is_course_upload {
 2824:     my ($file,$cnum,$cdom) = @_;
 2825:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2826:     $uploadpath =~ s{^\/}{};
 2827:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2828:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2829:         return 1;
 2830:     }
 2831:     return;
 2832: }
 2833: 
 2834: sub in_course {
 2835:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2836:     if ($hideprivileged) {
 2837:         my $skipuser;
 2838:         if (&privileged($uname,$udom)) {
 2839:             $skipuser = 1;
 2840:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2841:             if ($coursehash{'nothideprivileged'}) {
 2842:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2843:                     my $user;
 2844:                     if ($item =~ /:/) {
 2845:                         $user = $item;
 2846:                     } else {
 2847:                         $user = join(':',split(/[\@]/,$item));
 2848:                     }
 2849:                     if ($user eq $uname.':'.$udom) {
 2850:                         undef($skipuser);
 2851:                         last;
 2852:                     }
 2853:                 }
 2854:             }
 2855:             if ($skipuser) {
 2856:                 return 0;
 2857:             }
 2858:         }
 2859:     }
 2860:     $type ||= 'any';
 2861:     if (!defined($cdom) || !defined($cnum)) {
 2862:         my $cid  = $env{'request.course.id'};
 2863:         $cdom = $env{'course.'.$cid.'.domain'};
 2864:         $cnum = $env{'course.'.$cid.'.num'};
 2865:     }
 2866:     my $typesref;
 2867:     if (($type eq 'any') || ($type eq 'all')) {
 2868:         $typesref = ['active','previous','future'];
 2869:     } elsif ($type eq 'previous' || $type eq 'future') {
 2870:         $typesref = [$type];
 2871:     }
 2872:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2873:                               $typesref,undef,[$cdom]);
 2874:     my ($tmp) = keys(%roles);
 2875:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2876:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2877:     if (@course_roles > 0) {
 2878:         return 1;
 2879:     }
 2880:     return 0;
 2881: }
 2882: 
 2883: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2884: # input: action, courseID, current domain, intended
 2885: #        path to file, source of file, instruction to parse file for objects,
 2886: #        ref to hash for embedded objects,
 2887: #        ref to hash for codebase of java objects.
 2888: #        reference to scalar to accommodate mime type determined
 2889: #          from File::MMagic if $parser = parse.
 2890: #
 2891: # output: url to file (if action was uploaddoc), 
 2892: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2893: #
 2894: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2895: # course.
 2896: #
 2897: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2898: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2899: #          course's home server.
 2900: #
 2901: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2902: #          be copied from $source (current location) to 
 2903: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2904: #         and will then be copied to
 2905: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2906: #         course's home server.
 2907: #
 2908: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2909: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2910: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2911: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2912: #         in course's home server.
 2913: #
 2914: 
 2915: sub process_coursefile {
 2916:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2917:         $mimetype)=@_;
 2918:     my $fetchresult;
 2919:     my $home=&homeserver($docuname,$docudom);
 2920:     if ($action eq 'propagate') {
 2921:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2922: 			     $home);
 2923:     } else {
 2924:         my $fpath = '';
 2925:         my $fname = $file;
 2926:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2927:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2928:         my $filepath = &build_filepath($fpath);
 2929:         if ($action eq 'copy') {
 2930:             if ($source eq '') {
 2931:                 $fetchresult = 'no source file';
 2932:                 return $fetchresult;
 2933:             } else {
 2934:                 my $destination = $filepath.'/'.$fname;
 2935:                 rename($source,$destination);
 2936:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2937:                                  $home);
 2938:             }
 2939:         } elsif ($action eq 'uploaddoc') {
 2940:             open(my $fh,'>'.$filepath.'/'.$fname);
 2941:             print $fh $env{'form.'.$source};
 2942:             close($fh);
 2943:             if ($parser eq 'parse') {
 2944:                 my $mm = new File::MMagic;
 2945:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2946:                 if ($type eq 'text/html') {
 2947:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2948:                     unless ($parse_result eq 'ok') {
 2949:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2950:                     }
 2951:                 }
 2952:                 if (ref($mimetype)) {
 2953:                     $$mimetype = $type;
 2954:                 } 
 2955:             }
 2956:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2957:                                  $home);
 2958:             if ($fetchresult eq 'ok') {
 2959:                 return '/uploaded/'.$fpath.'/'.$fname;
 2960:             } else {
 2961:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2962:                         ' to host '.$home.': '.$fetchresult);
 2963:                 return '/adm/notfound.html';
 2964:             }
 2965:         }
 2966:     }
 2967:     unless ( $fetchresult eq 'ok') {
 2968:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2969:              ' to host '.$home.': '.$fetchresult);
 2970:     }
 2971:     return $fetchresult;
 2972: }
 2973: 
 2974: sub build_filepath {
 2975:     my ($fpath) = @_;
 2976:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2977:     unless ($fpath eq '') {
 2978:         my @parts=split('/',$fpath);
 2979:         foreach my $part (@parts) {
 2980:             $filepath.= '/'.$part;
 2981:             if ((-e $filepath)!=1) {
 2982:                 mkdir($filepath,0777);
 2983:             }
 2984:         }
 2985:     }
 2986:     return $filepath;
 2987: }
 2988: 
 2989: sub store_edited_file {
 2990:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2991:     my $file = $primary_url;
 2992:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2993:     my $fpath = '';
 2994:     my $fname = $file;
 2995:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2996:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2997:     my $filepath = &build_filepath($fpath);
 2998:     open(my $fh,'>'.$filepath.'/'.$fname);
 2999:     print $fh $content;
 3000:     close($fh);
 3001:     my $home=&homeserver($docuname,$docudom);
 3002:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3003: 			  $home);
 3004:     if ($$fetchresult eq 'ok') {
 3005:         return '/uploaded/'.$fpath.'/'.$fname;
 3006:     } else {
 3007:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3008: 		 ' to host '.$home.': '.$$fetchresult);
 3009:         return '/adm/notfound.html';
 3010:     }
 3011: }
 3012: 
 3013: sub clean_filename {
 3014:     my ($fname,$args)=@_;
 3015: # Replace Windows backslashes by forward slashes
 3016:     $fname=~s/\\/\//g;
 3017:     if (!$args->{'keep_path'}) {
 3018:         # Get rid of everything but the actual filename
 3019: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3020:     }
 3021: # Replace spaces by underscores
 3022:     $fname=~s/\s+/\_/g;
 3023: # Replace all other weird characters by nothing
 3024:     $fname=~s{[^/\w\.\-]}{}g;
 3025: # Replace all .\d. sequences with _\d. so they no longer look like version
 3026: # numbers
 3027:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3028:     return $fname;
 3029: }
 3030: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3031: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3032: # image with the same aspect ratio as the original, but with dimensions which do 
 3033: # not exceed $resizewidth and $resizeheight.
 3034:  
 3035: sub resizeImage {
 3036:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3037:     my $ima = Image::Magick->new;
 3038:     my $resized;
 3039:     if (-e $img_path) {
 3040:         $ima->Read($img_path);
 3041:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3042:             my $width = $ima->Get('width');
 3043:             my $height = $ima->Get('height');
 3044:             if ($width > $resizewidth) {
 3045: 	        my $factor = $width/$resizewidth;
 3046:                 my $newheight = $height/$factor;
 3047:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3048:                 $resized = 1;
 3049:             }
 3050:         }
 3051:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3052:             my $width = $ima->Get('width');
 3053:             my $height = $ima->Get('height');
 3054:             if ($height > $resizeheight) {
 3055:                 my $factor = $height/$resizeheight;
 3056:                 my $newwidth = $width/$factor;
 3057:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3058:                 $resized = 1;
 3059:             }
 3060:         }
 3061:         if ($resized) {
 3062:             $ima->Write($img_path);
 3063:         }
 3064:     }
 3065:     return;
 3066: }
 3067: 
 3068: # --------------- Take an uploaded file and put it into the userfiles directory
 3069: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3070: #                    the desired filename is in $env{"form.$formname.filename"}
 3071: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3072: #                                    canceloverwrite, or ''. 
 3073: #                   if 'coursedoc': upload to the current course
 3074: #                   if 'existingfile': write file to tmp/overwrites directory 
 3075: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3076: #                   $context is passed as argument to &finishuserfileupload
 3077: #        $subdir - directory in userfile to store the file into
 3078: #        $parser - instruction to parse file for objects ($parser = parse)    
 3079: #        $allfiles - reference to hash for embedded objects
 3080: #        $codebase - reference to hash for codebase of java objects
 3081: #        $desuname - username for permanent storage of uploaded file
 3082: #        $dsetudom - domain for permanaent storage of uploaded file
 3083: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3084: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3085: #        $resizewidth - width (pixels) to which to resize uploaded image
 3086: #        $resizeheight - height (pixels) to which to resize uploaded image
 3087: #        $mimetype - reference to scalar to accommodate mime type determined
 3088: #                    from File::MMagic.
 3089: # 
 3090: # output: url of file in userspace, or error: <message> 
 3091: #             or /adm/notfound.html if failure to upload occurse
 3092: 
 3093: sub userfileupload {
 3094:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3095:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3096:     if (!defined($subdir)) { $subdir='unknown'; }
 3097:     my $fname=$env{'form.'.$formname.'.filename'};
 3098:     $fname=&clean_filename($fname);
 3099:     # See if there is anything left
 3100:     unless ($fname) { return 'error: no uploaded file'; }
 3101:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3102:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3103:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3104:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3105:         my $now = time;
 3106:         my $filepath;
 3107:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3108:              $filepath = 'tmp/helprequests/'.$now;
 3109:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3110:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3111:                          '_'.$env{'user.domain'}.'/pending';
 3112:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3113:             my ($docuname,$docudom);
 3114:             if ($destudom) {
 3115:                 $docudom = $destudom;
 3116:             } else {
 3117:                 $docudom = $env{'user.domain'};
 3118:             }
 3119:             if ($destuname) {
 3120:                 $docuname = $destuname;
 3121:             } else {
 3122:                 $docuname = $env{'user.name'};
 3123:             }
 3124:             if (exists($env{'form.group'})) {
 3125:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3126:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3127:             }
 3128:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3129:             if ($context eq 'canceloverwrite') {
 3130:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3131:                 if (-e  $tempfile) {
 3132:                     my @info = stat($tempfile);
 3133:                     if ($info[9] eq $env{'form.timestamp'}) {
 3134:                         unlink($tempfile);
 3135:                     }
 3136:                 }
 3137:                 return;
 3138:             }
 3139:         }
 3140:         # Create the directory if not present
 3141:         my @parts=split(/\//,$filepath);
 3142:         my $fullpath = $perlvar{'lonDaemons'};
 3143:         for (my $i=0;$i<@parts;$i++) {
 3144:             $fullpath .= '/'.$parts[$i];
 3145:             if ((-e $fullpath)!=1) {
 3146:                 mkdir($fullpath,0777);
 3147:             }
 3148:         }
 3149:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3150:         print $fh $env{'form.'.$formname};
 3151:         close($fh);
 3152:         if ($context eq 'existingfile') {
 3153:             my @info = stat($fullpath.'/'.$fname);
 3154:             return ($fullpath.'/'.$fname,$info[9]);
 3155:         } else {
 3156:             return $fullpath.'/'.$fname;
 3157:         }
 3158:     }
 3159:     if ($subdir eq 'scantron') {
 3160:         $fname = 'scantron_orig_'.$fname;
 3161:     } else {
 3162:         $fname="$subdir/$fname";
 3163:     }
 3164:     if ($context eq 'coursedoc') {
 3165: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3166: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3167:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3168:             return &finishuserfileupload($docuname,$docudom,
 3169: 					 $formname,$fname,$parser,$allfiles,
 3170: 					 $codebase,$thumbwidth,$thumbheight,
 3171:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3172:         } else {
 3173:             $fname=$env{'form.folder'}.'/'.$fname;
 3174:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3175: 				       $fname,$formname,$parser,
 3176: 				       $allfiles,$codebase,$mimetype);
 3177:         }
 3178:     } elsif (defined($destuname)) {
 3179:         my $docuname=$destuname;
 3180:         my $docudom=$destudom;
 3181: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3182: 				     $parser,$allfiles,$codebase,
 3183:                                      $thumbwidth,$thumbheight,
 3184:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3185:     } else {
 3186:         my $docuname=$env{'user.name'};
 3187:         my $docudom=$env{'user.domain'};
 3188:         if (exists($env{'form.group'})) {
 3189:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3190:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3191:         }
 3192: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3193: 				     $parser,$allfiles,$codebase,
 3194:                                      $thumbwidth,$thumbheight,
 3195:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3196:     }
 3197: }
 3198: 
 3199: sub finishuserfileupload {
 3200:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3201:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3202:     my $path=$docudom.'/'.$docuname.'/';
 3203:     my $filepath=$perlvar{'lonDocRoot'};
 3204:   
 3205:     my ($fnamepath,$file,$fetchthumb);
 3206:     $file=$fname;
 3207:     if ($fname=~m|/|) {
 3208:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3209: 	$path.=$fnamepath.'/';
 3210:     }
 3211:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3212:     my $count;
 3213:     for ($count=4;$count<=$#parts;$count++) {
 3214:         $filepath.="/$parts[$count]";
 3215:         if ((-e $filepath)!=1) {
 3216: 	    mkdir($filepath,0777);
 3217:         }
 3218:     }
 3219: 
 3220: # Save the file
 3221:     {
 3222: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3223: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3224: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3225: 	    return '/adm/notfound.html';
 3226: 	}
 3227:         if ($context eq 'overwrite') {
 3228:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3229:             my $target = $filepath.'/'.$file;
 3230:             if (-e $source) {
 3231:                 my @info = stat($source);
 3232:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3233:                     unless (&File::Copy::move($source,$target)) {
 3234:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3235:                         return "Moving from $source failed";
 3236:                     }
 3237:                 } else {
 3238:                     return "Temporary file: $source had unexpected date/time for last modification";
 3239:                 }
 3240:             } else {
 3241:                 return "Temporary file: $source missing";
 3242:             }
 3243:         } elsif (!print FH ($env{'form.'.$formname})) {
 3244: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3245: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3246: 	    return '/adm/notfound.html';
 3247: 	}
 3248: 	close(FH);
 3249:         if ($resizewidth && $resizeheight) {
 3250:             my $mm = new File::MMagic;
 3251:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3252:             if ($mime_type =~ m{^image/}) {
 3253: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3254:             }  
 3255: 	}
 3256:     }
 3257:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3258:         if (ref($mimetype)) {
 3259:             if ($$mimetype eq '') {
 3260:                 my $mm = new File::MMagic;
 3261:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3262:                 $$mimetype = $type;
 3263:             }
 3264:         }
 3265:     }
 3266:     if ($parser eq 'parse') {
 3267:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3268:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3269:                                                        $allfiles,$codebase);
 3270:             unless ($parse_result eq 'ok') {
 3271:                 &logthis('Failed to parse '.$filepath.$file.
 3272: 	   	         ' for embedded media: '.$parse_result); 
 3273:             }
 3274:         }
 3275:     }
 3276:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3277:         my $input = $filepath.'/'.$file;
 3278:         my $output = $filepath.'/'.'tn-'.$file;
 3279:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3280:         system("convert -sample $thumbsize $input $output");
 3281:         if (-e $filepath.'/'.'tn-'.$file) {
 3282:             $fetchthumb  = 1; 
 3283:         }
 3284:     }
 3285:  
 3286: # Notify homeserver to grep it
 3287: #
 3288:     my $docuhome=&homeserver($docuname,$docudom);	
 3289:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3290:     if ($fetchresult eq 'ok') {
 3291:         if ($fetchthumb) {
 3292:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3293:             if ($thumbresult ne 'ok') {
 3294:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3295:                          $docuhome.': '.$thumbresult);
 3296:             }
 3297:         }
 3298: #
 3299: # Return the URL to it
 3300:         return '/uploaded/'.$path.$file;
 3301:     } else {
 3302:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3303: 		 ': '.$fetchresult);
 3304:         return '/adm/notfound.html';
 3305:     }
 3306: }
 3307: 
 3308: sub extract_embedded_items {
 3309:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3310:     my @state = ();
 3311:     my (%lastids,%related,%shockwave,%flashvars);
 3312:     my %javafiles = (
 3313:                       codebase => '',
 3314:                       code => '',
 3315:                       archive => ''
 3316:                     );
 3317:     my %mediafiles = (
 3318:                       src => '',
 3319:                       movie => '',
 3320:                      );
 3321:     my $p;
 3322:     if ($content) {
 3323:         $p = HTML::LCParser->new($content);
 3324:     } else {
 3325:         $p = HTML::LCParser->new($fullpath);
 3326:     }
 3327:     while (my $t=$p->get_token()) {
 3328: 	if ($t->[0] eq 'S') {
 3329: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3330: 	    push(@state, $tagname);
 3331:             if (lc($tagname) eq 'allow') {
 3332:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3333:             }
 3334: 	    if (lc($tagname) eq 'img') {
 3335: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3336: 	    }
 3337: 	    if (lc($tagname) eq 'a') {
 3338: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3339: 	    }
 3340:             if (lc($tagname) eq 'script') {
 3341:                 my $src;
 3342:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3343:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3344:                 } else {
 3345:                     if ($attr->{'src'} ne '') {
 3346:                         $src = $attr->{'src'};
 3347:                         &add_filetype($allfiles,$src,'src');
 3348:                     }
 3349:                 }
 3350:                 my $text = $p->get_trimmed_text();
 3351:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3352:                     my @swfargs = split(/,/,$1);
 3353:                     foreach my $item (@swfargs) {
 3354:                         $item =~ s/["']//g;
 3355:                         $item =~ s/^\s+//;
 3356:                         $item =~ s/\s+$//;
 3357:                     }
 3358:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3359:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3360:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3361:                         } else {
 3362:                             $related{$swfargs[0]} = [$swfargs[2]];
 3363:                         }
 3364:                     }
 3365:                 }
 3366:             }
 3367:             if (lc($tagname) eq 'link') {
 3368:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3369:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3370:                 }
 3371:             }
 3372: 	    if (lc($tagname) eq 'object' ||
 3373: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3374: 		foreach my $item (keys(%javafiles)) {
 3375: 		    $javafiles{$item} = '';
 3376: 		}
 3377:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3378:                     $lastids{lc($tagname)} = $attr->{'id'};
 3379:                 }
 3380: 	    }
 3381: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3382: 		my $name = lc($attr->{'name'});
 3383: 		foreach my $item (keys(%javafiles)) {
 3384: 		    if ($name eq $item) {
 3385: 			$javafiles{$item} = $attr->{'value'};
 3386: 			last;
 3387: 		    }
 3388: 		}
 3389:                 my $pathfrom;
 3390: 		foreach my $item (keys(%mediafiles)) {
 3391: 		    if ($name eq $item) {
 3392:                         $pathfrom = $attr->{'value'};
 3393:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3394: 			&add_filetype($allfiles,$pathfrom,$name);
 3395: 			last;
 3396: 		    }
 3397: 		}
 3398:                 if ($name eq 'flashvars') {
 3399:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3400:                 }
 3401:                 if ($pathfrom ne '') {
 3402:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3403:                                          $pathfrom);
 3404:                 }
 3405: 	    }
 3406: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3407: 		foreach my $item (keys(%javafiles)) {
 3408: 		    if ($attr->{$item}) {
 3409: 			$javafiles{$item} = $attr->{$item};
 3410: 			last;
 3411: 		    }
 3412: 		}
 3413: 		foreach my $item (keys(%mediafiles)) {
 3414: 		    if ($attr->{$item}) {
 3415: 			&add_filetype($allfiles,$attr->{$item},$item);
 3416: 			last;
 3417: 		    }
 3418: 		}
 3419:                 if (lc($tagname) eq 'embed') {
 3420:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3421:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3422:                                              $attr->{'src'});
 3423:                     }
 3424:                 }
 3425: 	    }
 3426:             if ($t->[4] =~ m{/>$}) {
 3427:                 pop(@state);  
 3428:             }
 3429: 	} elsif ($t->[0] eq 'E') {
 3430: 	    my ($tagname) = ($t->[1]);
 3431: 	    if ($javafiles{'codebase'} ne '') {
 3432: 		$javafiles{'codebase'} .= '/';
 3433: 	    }  
 3434: 	    if (lc($tagname) eq 'applet' ||
 3435: 		lc($tagname) eq 'object' ||
 3436: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3437: 		) {
 3438: 		foreach my $item (keys(%javafiles)) {
 3439: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3440: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3441: 			&add_filetype($allfiles,$file,$item);
 3442: 		    }
 3443: 		}
 3444: 	    } 
 3445: 	    pop @state;
 3446: 	}
 3447:     }
 3448:     foreach my $id (sort(keys(%flashvars))) {
 3449:         if ($shockwave{$id} ne '') {
 3450:             my @pairs = split(/\&/,$flashvars{$id});
 3451:             foreach my $pair (@pairs) {
 3452:                 my ($key,$value) = split(/\=/,$pair);
 3453:                 if ($key eq 'thumb') {
 3454:                     &add_filetype($allfiles,$value,$key);
 3455:                 } elsif ($key eq 'content') {
 3456:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3457:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3458:                     if ($ext ne '') {
 3459:                         &add_filetype($allfiles,$path.$value,$ext);
 3460:                     }
 3461:                 }
 3462:             }
 3463:         }
 3464:     }
 3465:     return 'ok';
 3466: }
 3467: 
 3468: sub add_filetype {
 3469:     my ($allfiles,$file,$type)=@_;
 3470:     if (exists($allfiles->{$file})) {
 3471: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3472: 	    push(@{$allfiles->{$file}}, &escape($type));
 3473: 	}
 3474:     } else {
 3475: 	@{$allfiles->{$file}} = (&escape($type));
 3476:     }
 3477: }
 3478: 
 3479: sub embedded_dependency {
 3480:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3481:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3482:         if (($identifier ne '') &&
 3483:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3484:             ($pathfrom ne '')) {
 3485:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3486:             foreach my $dep (@{$related->{$identifier}}) {
 3487:                 &add_filetype($allfiles,$path.$dep,'object');
 3488:             }
 3489:         }
 3490:     }
 3491:     return;
 3492: }
 3493: 
 3494: sub removeuploadedurl {
 3495:     my ($url)=@_;	
 3496:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3497:     return &removeuserfile($uname,$udom,$fname);
 3498: }
 3499: 
 3500: sub removeuserfile {
 3501:     my ($docuname,$docudom,$fname)=@_;
 3502:     my $home=&homeserver($docuname,$docudom);    
 3503:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3504:     if ($result eq 'ok') {	
 3505:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3506:             my $metafile = $fname.'.meta';
 3507:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3508: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3509:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3510:             my $sqlresult = 
 3511:                 &update_portfolio_table($docuname,$docudom,$file,
 3512:                                         'portfolio_metadata',$group,
 3513:                                         'delete');
 3514:         }
 3515:     }
 3516:     return $result;
 3517: }
 3518: 
 3519: sub mkdiruserfile {
 3520:     my ($docuname,$docudom,$dir)=@_;
 3521:     my $home=&homeserver($docuname,$docudom);
 3522:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3523: }
 3524: 
 3525: sub renameuserfile {
 3526:     my ($docuname,$docudom,$old,$new)=@_;
 3527:     my $home=&homeserver($docuname,$docudom);
 3528:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3529:                         &escape("$old").':'.&escape("$new"),$home);
 3530:     if ($result eq 'ok') {
 3531:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3532:             my $oldmeta = $old.'.meta';
 3533:             my $newmeta = $new.'.meta';
 3534:             my $metaresult = 
 3535:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3536: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3537:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3538:             my $sqlresult = 
 3539:                 &update_portfolio_table($docuname,$docudom,$file,
 3540:                                         'portfolio_metadata',$group,
 3541:                                         'delete');
 3542:         }
 3543:     }
 3544:     return $result;
 3545: }
 3546: 
 3547: # ------------------------------------------------------------------------- Log
 3548: 
 3549: sub log {
 3550:     my ($dom,$nam,$hom,$what)=@_;
 3551:     return critical("log:$dom:$nam:$what",$hom);
 3552: }
 3553: 
 3554: # ------------------------------------------------------------------ Course Log
 3555: #
 3556: # This routine flushes several buffers of non-mission-critical nature
 3557: #
 3558: 
 3559: sub flushcourselogs {
 3560:     &logthis('Flushing log buffers');
 3561: #
 3562: # course logs
 3563: # This is a log of all transactions in a course, which can be used
 3564: # for data mining purposes
 3565: #
 3566: # It also collects the courseid database, which lists last transaction
 3567: # times and course titles for all courseids
 3568: #
 3569:     my %courseidbuffer=();
 3570:     foreach my $crsid (keys(%courselogs)) {
 3571:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3572: 		          &escape($courselogs{$crsid}),
 3573: 		          $coursehombuf{$crsid}) eq 'ok') {
 3574: 	    delete $courselogs{$crsid};
 3575:         } else {
 3576:             &logthis('Failed to flush log buffer for '.$crsid);
 3577:             if (length($courselogs{$crsid})>40000) {
 3578:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3579:                         " exceeded maximum size, deleting.</font>");
 3580:                delete $courselogs{$crsid};
 3581:             }
 3582:         }
 3583:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3584:             'description' => $coursedescrbuf{$crsid},
 3585:             'inst_code'    => $courseinstcodebuf{$crsid},
 3586:             'type'        => $coursetypebuf{$crsid},
 3587:             'owner'       => $courseownerbuf{$crsid},
 3588:         };
 3589:     }
 3590: #
 3591: # Write course id database (reverse lookup) to homeserver of courses 
 3592: # Is used in pickcourse
 3593: #
 3594:     foreach my $crs_home (keys(%courseidbuffer)) {
 3595:         my $response = &courseidput(&host_domain($crs_home),
 3596:                                     $courseidbuffer{$crs_home},
 3597:                                     $crs_home,'timeonly');
 3598:     }
 3599: #
 3600: # File accesses
 3601: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3602: #
 3603:     foreach my $entry (keys(%accesshash)) {
 3604:         if ($entry =~ /___count$/) {
 3605:             my ($dom,$name);
 3606:             ($dom,$name,undef)=
 3607: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3608:             if (! defined($dom) || $dom eq '' || 
 3609:                 ! defined($name) || $name eq '') {
 3610:                 my $cid = $env{'request.course.id'};
 3611:                 $dom  = $env{'request.'.$cid.'.domain'};
 3612:                 $name = $env{'request.'.$cid.'.num'};
 3613:             }
 3614:             my $value = $accesshash{$entry};
 3615:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3616:             my %temphash=($url => $value);
 3617:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3618:             if ($result eq 'ok') {
 3619:                 delete $accesshash{$entry};
 3620:             }
 3621:         } else {
 3622:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3623:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3624:             my %temphash=($entry => $accesshash{$entry});
 3625:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3626:                 delete $accesshash{$entry};
 3627:             }
 3628:         }
 3629:     }
 3630: #
 3631: # Roles
 3632: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3633: #
 3634:     foreach my $entry (keys(%userrolehash)) {
 3635:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3636: 	    split(/\:/,$entry);
 3637:         if (&Apache::lonnet::put('nohist_userroles',
 3638:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3639:                 $rudom,$runame) eq 'ok') {
 3640: 	    delete $userrolehash{$entry};
 3641:         }
 3642:     }
 3643: #
 3644: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3645: #
 3646:     my %domrolebuffer = ();
 3647:     foreach my $entry (keys(%domainrolehash)) {
 3648:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3649:         if ($domrolebuffer{$rudom}) {
 3650:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3651:                       '='.&escape($domainrolehash{$entry});
 3652:         } else {
 3653:             $domrolebuffer{$rudom}.=&escape($entry).
 3654:                       '='.&escape($domainrolehash{$entry});
 3655:         }
 3656:         delete $domainrolehash{$entry};
 3657:     }
 3658:     foreach my $dom (keys(%domrolebuffer)) {
 3659: 	my %servers = &get_servers($dom,'library');
 3660: 	foreach my $tryserver (keys(%servers)) {
 3661: 	    unless (&reply('domroleput:'.$dom.':'.
 3662: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3663: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3664: 	    }
 3665:         }
 3666:     }
 3667:     $dumpcount++;
 3668: }
 3669: 
 3670: sub courselog {
 3671:     my $what=shift;
 3672:     $what=time.':'.$what;
 3673:     unless ($env{'request.course.id'}) { return ''; }
 3674:     $coursedombuf{$env{'request.course.id'}}=
 3675:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3676:     $coursenumbuf{$env{'request.course.id'}}=
 3677:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3678:     $coursehombuf{$env{'request.course.id'}}=
 3679:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3680:     $coursedescrbuf{$env{'request.course.id'}}=
 3681:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3682:     $courseinstcodebuf{$env{'request.course.id'}}=
 3683:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3684:     $courseownerbuf{$env{'request.course.id'}}=
 3685:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3686:     $coursetypebuf{$env{'request.course.id'}}=
 3687:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3688:     if (defined $courselogs{$env{'request.course.id'}}) {
 3689: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3690:     } else {
 3691: 	$courselogs{$env{'request.course.id'}}.=$what;
 3692:     }
 3693:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3694: 	&flushcourselogs();
 3695:     }
 3696: }
 3697: 
 3698: sub courseacclog {
 3699:     my $fnsymb=shift;
 3700:     unless ($env{'request.course.id'}) { return ''; }
 3701:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3702:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3703:         $what.=':POST';
 3704:         # FIXME: Probably ought to escape things....
 3705: 	foreach my $key (keys(%env)) {
 3706:             if ($key=~/^form\.(.*)/) {
 3707:                 my $formitem = $1;
 3708:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3709:                     $what.=':'.$formitem.'='.$env{$key};
 3710:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3711:                     $what.=':'.$formitem.'='.$env{$key};
 3712:                 }
 3713:             }
 3714:         }
 3715:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3716:         # FIXME: We should not be depending on a form parameter that someone
 3717:         # editing lonsearchcat.pm might change in the future.
 3718:         if ($env{'form.phase'} eq 'course_search') {
 3719:             $what.= ':POST';
 3720:             # FIXME: Probably ought to escape things....
 3721:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3722:                                  'crsdiscuss') {
 3723:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3724:             }
 3725:         }
 3726:     }
 3727:     &courselog($what);
 3728: }
 3729: 
 3730: sub countacc {
 3731:     my $url=&declutter(shift);
 3732:     return if (! defined($url) || $url eq '');
 3733:     unless ($env{'request.course.id'}) { return ''; }
 3734: #
 3735: # Mark that this url was used in this course
 3736: #
 3737:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3738: #
 3739: # Increase the access count for this resource in this child process
 3740: #
 3741:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3742:     $accesshash{$key}++;
 3743: }
 3744: 
 3745: sub linklog {
 3746:     my ($from,$to)=@_;
 3747:     $from=&declutter($from);
 3748:     $to=&declutter($to);
 3749:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3750:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3751: }
 3752: 
 3753: sub statslog {
 3754:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3755:     if ($users<2) { return; }
 3756:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3757:             'course'       => $env{'request.course.id'},
 3758:             'sections'     => '"all"',
 3759:             'num_students' => $users,
 3760:             'part'         => $part,
 3761:             'symb'         => $symb,
 3762:             'mean_tries'   => $av_attempts,
 3763:             'deg_of_diff'  => $degdiff});
 3764:     foreach my $key (keys(%dynstore)) {
 3765:         $accesshash{$key}=$dynstore{$key};
 3766:     }
 3767: }
 3768:   
 3769: sub userrolelog {
 3770:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3771:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3772:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3773:        $userrolehash
 3774:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3775:                     =$tend.':'.$tstart;
 3776:     }
 3777:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3778:        $userrolehash
 3779:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3780:                     =$tend.':'.$tstart;
 3781:     }
 3782:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3783:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3784:        $domainrolehash
 3785:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3786:                     = $tend.':'.$tstart;
 3787:     }
 3788: }
 3789: 
 3790: sub courserolelog {
 3791:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3792:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3793:         my $cdom = $1;
 3794:         my $cnum = $2;
 3795:         my $sec = $3;
 3796:         my $namespace = 'rolelog';
 3797:         my %storehash = (
 3798:                            role    => $trole,
 3799:                            start   => $tstart,
 3800:                            end     => $tend,
 3801:                            selfenroll => $selfenroll,
 3802:                            context    => $context,
 3803:                         );
 3804:         if ($trole eq 'gr') {
 3805:             $namespace = 'groupslog';
 3806:             $storehash{'group'} = $sec;
 3807:         } else {
 3808:             $storehash{'section'} = $sec;
 3809:         }
 3810:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3811:                    $domain,$cnum,$cdom);
 3812:         if (($trole ne 'st') || ($sec ne '')) {
 3813:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3814:         }
 3815:     }
 3816:     return;
 3817: }
 3818: 
 3819: sub domainrolelog {
 3820:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3821:     if ($area =~ m{^/($match_domain)/$}) {
 3822:         my $cdom = $1;
 3823:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3824:         my $namespace = 'rolelog';
 3825:         my %storehash = (
 3826:                            role    => $trole,
 3827:                            start   => $tstart,
 3828:                            end     => $tend,
 3829:                            context => $context,
 3830:                         );
 3831:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3832:                    $domain,$domconfiguser,$cdom);
 3833:     }
 3834:     return;
 3835: 
 3836: }
 3837: 
 3838: sub coauthorrolelog {
 3839:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3840:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3841:         my $audom = $1;
 3842:         my $auname = $2;
 3843:         my $namespace = 'rolelog';
 3844:         my %storehash = (
 3845:                            role    => $trole,
 3846:                            start   => $tstart,
 3847:                            end     => $tend,
 3848:                            context => $context,
 3849:                         );
 3850:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3851:                    $domain,$auname,$audom);
 3852:     }
 3853:     return;
 3854: }
 3855: 
 3856: sub get_course_adv_roles {
 3857:     my ($cid,$codes) = @_;
 3858:     $cid=$env{'request.course.id'} unless (defined($cid));
 3859:     my %coursehash=&coursedescription($cid);
 3860:     my $crstype = &Apache::loncommon::course_type($cid);
 3861:     my %nothide=();
 3862:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3863:         if ($user !~ /:/) {
 3864: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3865:         } else {
 3866:             $nothide{$user}=1;
 3867:         }
 3868:     }
 3869:     my %returnhash=();
 3870:     my %dumphash=
 3871:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3872:     my $now=time;
 3873:     my %privileged;
 3874:     foreach my $entry (keys(%dumphash)) {
 3875: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3876:         if (($tstart) && ($tstart<0)) { next; }
 3877:         if (($tend) && ($tend<$now)) { next; }
 3878:         if (($tstart) && ($now<$tstart)) { next; }
 3879:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3880: 	if ($username eq '' || $domain eq '') { next; }
 3881:         unless (ref($privileged{$domain}) eq 'HASH') {
 3882:             my %dompersonnel =
 3883:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3884:             $privileged{$domain} = {};
 3885:             foreach my $server (keys(%dompersonnel)) {
 3886:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3887:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3888:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3889:                         $privileged{$udom}{$uname} = 1;
 3890:                     }
 3891:                 }
 3892:             }
 3893:         }
 3894:         if ((exists($privileged{$domain}{$username})) && 
 3895:             (!$nothide{$username.':'.$domain})) { next; }
 3896: 	if ($role eq 'cr') { next; }
 3897:         if ($codes) {
 3898:             if ($section) { $role .= ':'.$section; }
 3899:             if ($returnhash{$role}) {
 3900:                 $returnhash{$role}.=','.$username.':'.$domain;
 3901:             } else {
 3902:                 $returnhash{$role}=$username.':'.$domain;
 3903:             }
 3904:         } else {
 3905:             my $key=&plaintext($role,$crstype);
 3906:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3907:             if ($returnhash{$key}) {
 3908: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3909:             } else {
 3910:                 $returnhash{$key}=$username.':'.$domain;
 3911:             }
 3912:         }
 3913:     }
 3914:     return %returnhash;
 3915: }
 3916: 
 3917: sub get_my_roles {
 3918:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3919:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3920:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3921:     my (%dumphash,%nothide);
 3922:     if ($context eq 'userroles') {
 3923:         %dumphash = &dump('roles',$udom,$uname);
 3924:     } else {
 3925:         %dumphash=
 3926:             &dump('nohist_userroles',$udom,$uname);
 3927:         if ($hidepriv) {
 3928:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3929:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3930:                 if ($user !~ /:/) {
 3931:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3932:                 } else {
 3933:                     $nothide{$user} = 1;
 3934:                 }
 3935:             }
 3936:         }
 3937:     }
 3938:     my %returnhash=();
 3939:     my $now=time;
 3940:     my %privileged;
 3941:     foreach my $entry (keys(%dumphash)) {
 3942:         my ($role,$tend,$tstart);
 3943:         if ($context eq 'userroles') {
 3944:             next if ($entry =~ /^rolesdef/);
 3945: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3946:         } else {
 3947:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3948:         }
 3949:         if (($tstart) && ($tstart<0)) { next; }
 3950:         my $status = 'active';
 3951:         if (($tend) && ($tend<=$now)) {
 3952:             $status = 'previous';
 3953:         } 
 3954:         if (($tstart) && ($now<$tstart)) {
 3955:             $status = 'future';
 3956:         }
 3957:         if (ref($types) eq 'ARRAY') {
 3958:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3959:                 next;
 3960:             } 
 3961:         } else {
 3962:             if ($status ne 'active') {
 3963:                 next;
 3964:             }
 3965:         }
 3966:         my ($rolecode,$username,$domain,$section,$area);
 3967:         if ($context eq 'userroles') {
 3968:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 3969:             (undef,$domain,$username,$section) = split(/\//,$area);
 3970:         } else {
 3971:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3972:         }
 3973:         if (ref($roledoms) eq 'ARRAY') {
 3974:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3975:                 next;
 3976:             }
 3977:         }
 3978:         if (ref($roles) eq 'ARRAY') {
 3979:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3980:                 if ($role =~ /^cr\//) {
 3981:                     if (!grep(/^cr$/,@{$roles})) {
 3982:                         next;
 3983:                     }
 3984:                 } elsif ($role =~ /^gr\//) {
 3985:                     if (!grep(/^gr$/,@{$roles})) {
 3986:                         next;
 3987:                     }
 3988:                 } else {
 3989:                     next;
 3990:                 }
 3991:             }
 3992:         }
 3993:         if ($hidepriv) {
 3994:             if ($context eq 'userroles') {
 3995:                 if ((&privileged($username,$domain)) &&
 3996:                     (!$nothide{$username.':'.$domain})) {
 3997:                     next;
 3998:                 }
 3999:             } else {
 4000:                 unless (ref($privileged{$domain}) eq 'HASH') {
 4001:                     my %dompersonnel =
 4002:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 4003:                     $privileged{$domain} = {};
 4004:                     if (keys(%dompersonnel)) {
 4005:                         foreach my $server (keys(%dompersonnel)) {
 4006:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 4007:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 4008:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 4009:                                     $privileged{$udom}{$uname} = $trole;
 4010:                                 }
 4011:                             }
 4012:                         }
 4013:                     }
 4014:                 }
 4015:                 if (exists($privileged{$domain}{$username})) {
 4016:                     if (!$nothide{$username.':'.$domain}) {
 4017:                         next;
 4018:                     }
 4019:                 }
 4020:             }
 4021:         }
 4022:         if ($withsec) {
 4023:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4024:                 $tstart.':'.$tend;
 4025:         } else {
 4026:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4027:         }
 4028:     }
 4029:     return %returnhash;
 4030: }
 4031: 
 4032: # ----------------------------------------------------- Frontpage Announcements
 4033: #
 4034: #
 4035: 
 4036: sub postannounce {
 4037:     my ($server,$text)=@_;
 4038:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4039:     unless ($text=~/\w/) { $text=''; }
 4040:     return &reply('setannounce:'.&escape($text),$server);
 4041: }
 4042: 
 4043: sub getannounce {
 4044: 
 4045:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4046: 	my $announcement='';
 4047: 	while (my $line = <$fh>) { $announcement .= $line; }
 4048: 	close($fh);
 4049: 	if ($announcement=~/\w/) { 
 4050: 	    return 
 4051:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4052:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4053: 	} else {
 4054: 	    return '';
 4055: 	}
 4056:     } else {
 4057: 	return '';
 4058:     }
 4059: }
 4060: 
 4061: # ---------------------------------------------------------- Course ID routines
 4062: # Deal with domain's nohist_courseid.db files
 4063: #
 4064: 
 4065: sub courseidput {
 4066:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4067:     return unless (ref($storehash) eq 'HASH');
 4068:     my $outcome;
 4069:     if ($caller eq 'timeonly') {
 4070:         my $cids = '';
 4071:         foreach my $item (keys(%$storehash)) {
 4072:             $cids.=&escape($item).'&';
 4073:         }
 4074:         $cids=~s/\&$//;
 4075:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4076:                           $coursehome);       
 4077:     } else {
 4078:         my $items = '';
 4079:         foreach my $item (keys(%$storehash)) {
 4080:             $items.= &escape($item).'='.
 4081:                      &freeze_escape($$storehash{$item}).'&';
 4082:         }
 4083:         $items=~s/\&$//;
 4084:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4085:                           $coursehome);
 4086:     }
 4087:     if ($outcome eq 'unknown_cmd') {
 4088:         my $what;
 4089:         foreach my $cid (keys(%$storehash)) {
 4090:             $what .= &escape($cid).'=';
 4091:             foreach my $item ('description','inst_code','owner','type') {
 4092:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4093:             }
 4094:             $what =~ s/\:$/&/;
 4095:         }
 4096:         $what =~ s/\&$//;  
 4097:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4098:     } else {
 4099:         return $outcome;
 4100:     }
 4101: }
 4102: 
 4103: sub courseiddump {
 4104:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4105:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4106:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4107:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4108:     my $as_hash = 1;
 4109:     my %returnhash;
 4110:     if (!$domfilter) { $domfilter=''; }
 4111:     my %libserv = &all_library();
 4112:     foreach my $tryserver (keys(%libserv)) {
 4113:         if ( (  $hostidflag == 1 
 4114: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4115: 	     || (!defined($hostidflag)) ) {
 4116: 
 4117: 	    if (($domfilter eq '') ||
 4118: 		(&host_domain($tryserver) eq $domfilter)) {
 4119:                 my $rep;
 4120:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4121:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4122:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4123:                                 &escape($descfilter), &escape($instcodefilter), 
 4124:                                 &escape($ownerfilter), &escape($coursefilter),
 4125:                                 &escape($typefilter), &escape($regexp_ok), 
 4126:                                 $as_hash, &escape($selfenrollonly), 
 4127:                                 &escape($catfilter), $showhidden, $caller, 
 4128:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4129:                                 &escape($createdbefore), &escape($createdafter), 
 4130:                                 &escape($creationcontext), $domcloner)));
 4131:                 } else {
 4132:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4133:                              $sincefilter.':'.&escape($descfilter).':'.
 4134:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4135:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4136:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4137:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4138:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4139:                              &escape($cc_clone).':'.$cloneonly.':'.
 4140:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4141:                              &escape($creationcontext).':'.$domcloner,
 4142:                              $tryserver);
 4143:                 }
 4144:                      
 4145:                 my @pairs=split(/\&/,$rep);
 4146:                 foreach my $item (@pairs) {
 4147:                     my ($key,$value)=split(/\=/,$item,2);
 4148:                     $key = &unescape($key);
 4149:                     next if ($key =~ /^error: 2 /);
 4150:                     my $result = &thaw_unescape($value);
 4151:                     if (ref($result) eq 'HASH') {
 4152:                         $returnhash{$key}=$result;
 4153:                     } else {
 4154:                         my @responses = split(/:/,$value);
 4155:                         my @items = ('description','inst_code','owner','type');
 4156:                         for (my $i=0; $i<@responses; $i++) {
 4157:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4158:                         }
 4159:                     }
 4160:                 }
 4161:             }
 4162:         }
 4163:     }
 4164:     return %returnhash;
 4165: }
 4166: 
 4167: sub courselastaccess {
 4168:     my ($cdom,$cnum,$hostidref) = @_;
 4169:     my %returnhash;
 4170:     if ($cdom && $cnum) {
 4171:         my $chome = &homeserver($cnum,$cdom);
 4172:         if ($chome ne 'no_host') {
 4173:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4174:             &extract_lastaccess(\%returnhash,$rep);
 4175:         }
 4176:     } else {
 4177:         if (!$cdom) { $cdom=''; }
 4178:         my %libserv = &all_library();
 4179:         foreach my $tryserver (keys(%libserv)) {
 4180:             if (ref($hostidref) eq 'ARRAY') {
 4181:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4182:             } 
 4183:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4184:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4185:                 &extract_lastaccess(\%returnhash,$rep);
 4186:             }
 4187:         }
 4188:     }
 4189:     return %returnhash;
 4190: }
 4191: 
 4192: sub extract_lastaccess {
 4193:     my ($returnhash,$rep) = @_;
 4194:     if (ref($returnhash) eq 'HASH') {
 4195:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4196:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4197:                  $rep eq '') {
 4198:             my @pairs=split(/\&/,$rep);
 4199:             foreach my $item (@pairs) {
 4200:                 my ($key,$value)=split(/\=/,$item,2);
 4201:                 $key = &unescape($key);
 4202:                 next if ($key =~ /^error: 2 /);
 4203:                 $returnhash->{$key} = &thaw_unescape($value);
 4204:             }
 4205:         }
 4206:     }
 4207:     return;
 4208: }
 4209: 
 4210: # ---------------------------------------------------------- DC e-mail
 4211: 
 4212: sub dcmailput {
 4213:     my ($domain,$msgid,$message,$server)=@_;
 4214:     my $status = &Apache::lonnet::critical(
 4215:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4216:        &escape($message),$server);
 4217:     return $status;
 4218: }
 4219: 
 4220: sub dcmaildump {
 4221:     my ($dom,$startdate,$enddate,$senders) = @_;
 4222:     my %returnhash=();
 4223: 
 4224:     if (defined(&domain($dom,'primary'))) {
 4225:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4226:                                                          &escape($enddate).':';
 4227: 	my @esc_senders=map { &escape($_)} @$senders;
 4228: 	$cmd.=&escape(join('&',@esc_senders));
 4229: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4230:             my ($key,$value) = split(/\=/,$line,2);
 4231:             if (($key) && ($value)) {
 4232:                 $returnhash{&unescape($key)} = &unescape($value);
 4233:             }
 4234:         }
 4235:     }
 4236:     return %returnhash;
 4237: }
 4238: # ---------------------------------------------------------- Domain roles
 4239: 
 4240: sub get_domain_roles {
 4241:     my ($dom,$roles,$startdate,$enddate)=@_;
 4242:     if ((!defined($startdate)) || ($startdate eq '')) {
 4243:         $startdate = '.';
 4244:     }
 4245:     if ((!defined($enddate)) || ($enddate eq '')) {
 4246:         $enddate = '.';
 4247:     }
 4248:     my $rolelist;
 4249:     if (ref($roles) eq 'ARRAY') {
 4250:         $rolelist = join(':',@{$roles});
 4251:     }
 4252:     my %personnel = ();
 4253: 
 4254:     my %servers = &get_servers($dom,'library');
 4255:     foreach my $tryserver (keys(%servers)) {
 4256: 	%{$personnel{$tryserver}}=();
 4257: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4258: 					    &escape($startdate).':'.
 4259: 					    &escape($enddate).':'.
 4260: 					    &escape($rolelist), $tryserver))) {
 4261: 	    my ($key,$value) = split(/\=/,$line,2);
 4262: 	    if (($key) && ($value)) {
 4263: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4264: 	    }
 4265: 	}
 4266:     }
 4267:     return %personnel;
 4268: }
 4269: 
 4270: # ----------------------------------------------------------- Interval timing 
 4271: 
 4272: {
 4273: # Caches needed for speedup of navmaps
 4274: # We don't want to cache this for very long at all (5 seconds at most)
 4275: # 
 4276: # The user for whom we cache
 4277: my $cachedkey='';
 4278: # The cached times for this user
 4279: my %cachedtimes=();
 4280: # When this was last done
 4281: my $cachedtime=();
 4282: 
 4283: sub load_all_first_access {
 4284:     my ($uname,$udom)=@_;
 4285:     if (($cachedkey eq $uname.':'.$udom) &&
 4286:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4287:         return;
 4288:     }
 4289:     $cachedtime=time;
 4290:     $cachedkey=$uname.':'.$udom;
 4291:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4292: }
 4293: 
 4294: sub get_first_access {
 4295:     my ($type,$argsymb,$argmap)=@_;
 4296:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4297:     if ($argsymb) { $symb=$argsymb; }
 4298:     my ($map,$id,$res)=&decode_symb($symb);
 4299:     if ($argmap) { $map = $argmap; }
 4300:     if ($type eq 'course') {
 4301: 	$res='course';
 4302:     } elsif ($type eq 'map') {
 4303: 	$res=&symbread($map);
 4304:     } else {
 4305: 	$res=$symb;
 4306:     }
 4307:     &load_all_first_access($uname,$udom);
 4308:     return $cachedtimes{"$courseid\0$res"};
 4309: }
 4310: 
 4311: sub set_first_access {
 4312:     my ($type,$interval)=@_;
 4313:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4314:     my ($map,$id,$res)=&decode_symb($symb);
 4315:     if ($type eq 'course') {
 4316: 	$res='course';
 4317:     } elsif ($type eq 'map') {
 4318: 	$res=&symbread($map);
 4319:     } else {
 4320: 	$res=$symb;
 4321:     }
 4322:     $cachedkey='';
 4323:     my $firstaccess=&get_first_access($type,$symb,$map);
 4324:     if (!$firstaccess) {
 4325:         my $start = time;
 4326: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4327:                           $udom,$uname);
 4328:         if ($putres eq 'ok') {
 4329:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4330:                  $udom,$uname); 
 4331:             &appenv(
 4332:                      {
 4333:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4334:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4335:                      }
 4336:                   );
 4337:         }
 4338:         return $putres;
 4339:     }
 4340:     return 'already_set';
 4341: }
 4342: }
 4343: # --------------------------------------------- Set Expire Date for Spreadsheet
 4344: 
 4345: sub expirespread {
 4346:     my ($uname,$udom,$stype,$usymb)=@_;
 4347:     my $cid=$env{'request.course.id'}; 
 4348:     if ($cid) {
 4349:        my $now=time;
 4350:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4351:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4352:                             $env{'course.'.$cid.'.num'}.
 4353: 	        	    ':nohist_expirationdates:'.
 4354:                             &escape($key).'='.$now,
 4355:                             $env{'course.'.$cid.'.home'})
 4356:     }
 4357:     return 'ok';
 4358: }
 4359: 
 4360: # ----------------------------------------------------- Devalidate Spreadsheets
 4361: 
 4362: sub devalidate {
 4363:     my ($symb,$uname,$udom)=@_;
 4364:     my $cid=$env{'request.course.id'}; 
 4365:     if ($cid) {
 4366:         # delete the stored spreadsheets for
 4367:         # - the student level sheet of this user in course's homespace
 4368:         # - the assessment level sheet for this resource 
 4369:         #   for this user in user's homespace
 4370: 	# - current conditional state info
 4371: 	my $key=$uname.':'.$udom.':';
 4372:         my $status=
 4373: 	    &del('nohist_calculatedsheets',
 4374: 		 [$key.'studentcalc:'],
 4375: 		 $env{'course.'.$cid.'.domain'},
 4376: 		 $env{'course.'.$cid.'.num'})
 4377: 		.' '.
 4378: 	    &del('nohist_calculatedsheets_'.$cid,
 4379: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4380:         unless ($status eq 'ok ok') {
 4381:            &logthis('Could not devalidate spreadsheet '.
 4382:                     $uname.' at '.$udom.' for '.
 4383: 		    $symb.': '.$status);
 4384:         }
 4385: 	&delenv('user.state.'.$cid);
 4386:     }
 4387: }
 4388: 
 4389: sub get_scalar {
 4390:     my ($string,$end) = @_;
 4391:     my $value;
 4392:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4393: 	$value = $1;
 4394:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4395: 	$value = $1;
 4396:     }
 4397:     return &unescape($value);
 4398: }
 4399: 
 4400: sub array2str {
 4401:   my (@array) = @_;
 4402:   my $result=&arrayref2str(\@array);
 4403:   $result=~s/^__ARRAY_REF__//;
 4404:   $result=~s/__END_ARRAY_REF__$//;
 4405:   return $result;
 4406: }
 4407: 
 4408: sub arrayref2str {
 4409:   my ($arrayref) = @_;
 4410:   my $result='__ARRAY_REF__';
 4411:   foreach my $elem (@$arrayref) {
 4412:     if(ref($elem) eq 'ARRAY') {
 4413:       $result.=&arrayref2str($elem).'&';
 4414:     } elsif(ref($elem) eq 'HASH') {
 4415:       $result.=&hashref2str($elem).'&';
 4416:     } elsif(ref($elem)) {
 4417:       #print("Got a ref of ".(ref($elem))." skipping.");
 4418:     } else {
 4419:       $result.=&escape($elem).'&';
 4420:     }
 4421:   }
 4422:   $result=~s/\&$//;
 4423:   $result .= '__END_ARRAY_REF__';
 4424:   return $result;
 4425: }
 4426: 
 4427: sub hash2str {
 4428:   my (%hash) = @_;
 4429:   my $result=&hashref2str(\%hash);
 4430:   $result=~s/^__HASH_REF__//;
 4431:   $result=~s/__END_HASH_REF__$//;
 4432:   return $result;
 4433: }
 4434: 
 4435: sub hashref2str {
 4436:   my ($hashref)=@_;
 4437:   my $result='__HASH_REF__';
 4438:   foreach my $key (sort(keys(%$hashref))) {
 4439:     if (ref($key) eq 'ARRAY') {
 4440:       $result.=&arrayref2str($key).'=';
 4441:     } elsif (ref($key) eq 'HASH') {
 4442:       $result.=&hashref2str($key).'=';
 4443:     } elsif (ref($key)) {
 4444:       $result.='=';
 4445:       #print("Got a ref of ".(ref($key))." skipping.");
 4446:     } else {
 4447: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4448:     }
 4449: 
 4450:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4451:       $result.=&arrayref2str($hashref->{$key}).'&';
 4452:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4453:       $result.=&hashref2str($hashref->{$key}).'&';
 4454:     } elsif(ref($hashref->{$key})) {
 4455:        $result.='&';
 4456:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4457:     } else {
 4458:       $result.=&escape($hashref->{$key}).'&';
 4459:     }
 4460:   }
 4461:   $result=~s/\&$//;
 4462:   $result .= '__END_HASH_REF__';
 4463:   return $result;
 4464: }
 4465: 
 4466: sub str2hash {
 4467:     my ($string)=@_;
 4468:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4469:     return %$hash;
 4470: }
 4471: 
 4472: sub str2hashref {
 4473:   my ($string) = @_;
 4474: 
 4475:   my %hash;
 4476: 
 4477:   if($string !~ /^__HASH_REF__/) {
 4478:       if (! ($string eq '' || !defined($string))) {
 4479: 	  $hash{'error'}='Not hash reference';
 4480:       }
 4481:       return (\%hash, $string);
 4482:   }
 4483: 
 4484:   $string =~ s/^__HASH_REF__//;
 4485: 
 4486:   while($string !~ /^__END_HASH_REF__/) {
 4487:       #key
 4488:       my $key='';
 4489:       if($string =~ /^__HASH_REF__/) {
 4490:           ($key, $string)=&str2hashref($string);
 4491:           if(defined($key->{'error'})) {
 4492:               $hash{'error'}='Bad data';
 4493:               return (\%hash, $string);
 4494:           }
 4495:       } elsif($string =~ /^__ARRAY_REF__/) {
 4496:           ($key, $string)=&str2arrayref($string);
 4497:           if($key->[0] eq 'Array reference error') {
 4498:               $hash{'error'}='Bad data';
 4499:               return (\%hash, $string);
 4500:           }
 4501:       } else {
 4502:           $string =~ s/^(.*?)=//;
 4503: 	  $key=&unescape($1);
 4504:       }
 4505:       $string =~ s/^=//;
 4506: 
 4507:       #value
 4508:       my $value='';
 4509:       if($string =~ /^__HASH_REF__/) {
 4510:           ($value, $string)=&str2hashref($string);
 4511:           if(defined($value->{'error'})) {
 4512:               $hash{'error'}='Bad data';
 4513:               return (\%hash, $string);
 4514:           }
 4515:       } elsif($string =~ /^__ARRAY_REF__/) {
 4516:           ($value, $string)=&str2arrayref($string);
 4517:           if($value->[0] eq 'Array reference error') {
 4518:               $hash{'error'}='Bad data';
 4519:               return (\%hash, $string);
 4520:           }
 4521:       } else {
 4522: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4523:       }
 4524:       $string =~ s/^&//;
 4525: 
 4526:       $hash{$key}=$value;
 4527:   }
 4528: 
 4529:   $string =~ s/^__END_HASH_REF__//;
 4530: 
 4531:   return (\%hash, $string);
 4532: }
 4533: 
 4534: sub str2array {
 4535:     my ($string)=@_;
 4536:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4537:     return @$array;
 4538: }
 4539: 
 4540: sub str2arrayref {
 4541:   my ($string) = @_;
 4542:   my @array;
 4543: 
 4544:   if($string !~ /^__ARRAY_REF__/) {
 4545:       if (! ($string eq '' || !defined($string))) {
 4546: 	  $array[0]='Array reference error';
 4547:       }
 4548:       return (\@array, $string);
 4549:   }
 4550: 
 4551:   $string =~ s/^__ARRAY_REF__//;
 4552: 
 4553:   while($string !~ /^__END_ARRAY_REF__/) {
 4554:       my $value='';
 4555:       if($string =~ /^__HASH_REF__/) {
 4556:           ($value, $string)=&str2hashref($string);
 4557:           if(defined($value->{'error'})) {
 4558:               $array[0] ='Array reference error';
 4559:               return (\@array, $string);
 4560:           }
 4561:       } elsif($string =~ /^__ARRAY_REF__/) {
 4562:           ($value, $string)=&str2arrayref($string);
 4563:           if($value->[0] eq 'Array reference error') {
 4564:               $array[0] ='Array reference error';
 4565:               return (\@array, $string);
 4566:           }
 4567:       } else {
 4568: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4569:       }
 4570:       $string =~ s/^&//;
 4571: 
 4572:       push(@array, $value);
 4573:   }
 4574: 
 4575:   $string =~ s/^__END_ARRAY_REF__//;
 4576: 
 4577:   return (\@array, $string);
 4578: }
 4579: 
 4580: # -------------------------------------------------------------------Temp Store
 4581: 
 4582: sub tmpreset {
 4583:   my ($symb,$namespace,$domain,$stuname) = @_;
 4584:   if (!$symb) {
 4585:     $symb=&symbread();
 4586:     if (!$symb) { $symb= $env{'request.url'}; }
 4587:   }
 4588:   $symb=escape($symb);
 4589: 
 4590:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4591:   $namespace=~s/\//\_/g;
 4592:   $namespace=~s/\W//g;
 4593: 
 4594:   if (!$domain) { $domain=$env{'user.domain'}; }
 4595:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4596:   if ($domain eq 'public' && $stuname eq 'public') {
 4597:       $stuname=$ENV{'REMOTE_ADDR'};
 4598:   }
 4599:   my $path=LONCAPA::tempdir();
 4600:   my %hash;
 4601:   if (tie(%hash,'GDBM_File',
 4602: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4603: 	  &GDBM_WRCREAT(),0640)) {
 4604:     foreach my $key (keys(%hash)) {
 4605:       if ($key=~ /:$symb/) {
 4606: 	delete($hash{$key});
 4607:       }
 4608:     }
 4609:   }
 4610: }
 4611: 
 4612: sub tmpstore {
 4613:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4614: 
 4615:   if (!$symb) {
 4616:     $symb=&symbread();
 4617:     if (!$symb) { $symb= $env{'request.url'}; }
 4618:   }
 4619:   $symb=escape($symb);
 4620: 
 4621:   if (!$namespace) {
 4622:     # I don't think we would ever want to store this for a course.
 4623:     # it seems this will only be used if we don't have a course.
 4624:     #$namespace=$env{'request.course.id'};
 4625:     #if (!$namespace) {
 4626:       $namespace=$env{'request.state'};
 4627:     #}
 4628:   }
 4629:   $namespace=~s/\//\_/g;
 4630:   $namespace=~s/\W//g;
 4631:   if (!$domain) { $domain=$env{'user.domain'}; }
 4632:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4633:   if ($domain eq 'public' && $stuname eq 'public') {
 4634:       $stuname=$ENV{'REMOTE_ADDR'};
 4635:   }
 4636:   my $now=time;
 4637:   my %hash;
 4638:   my $path=LONCAPA::tempdir();
 4639:   if (tie(%hash,'GDBM_File',
 4640: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4641: 	  &GDBM_WRCREAT(),0640)) {
 4642:     $hash{"version:$symb"}++;
 4643:     my $version=$hash{"version:$symb"};
 4644:     my $allkeys=''; 
 4645:     foreach my $key (keys(%$storehash)) {
 4646:       $allkeys.=$key.':';
 4647:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4648:     }
 4649:     $hash{"$version:$symb:timestamp"}=$now;
 4650:     $allkeys.='timestamp';
 4651:     $hash{"$version:keys:$symb"}=$allkeys;
 4652:     if (untie(%hash)) {
 4653:       return 'ok';
 4654:     } else {
 4655:       return "error:$!";
 4656:     }
 4657:   } else {
 4658:     return "error:$!";
 4659:   }
 4660: }
 4661: 
 4662: # -----------------------------------------------------------------Temp Restore
 4663: 
 4664: sub tmprestore {
 4665:   my ($symb,$namespace,$domain,$stuname) = @_;
 4666: 
 4667:   if (!$symb) {
 4668:     $symb=&symbread();
 4669:     if (!$symb) { $symb= $env{'request.url'}; }
 4670:   }
 4671:   $symb=escape($symb);
 4672: 
 4673:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4674: 
 4675:   if (!$domain) { $domain=$env{'user.domain'}; }
 4676:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4677:   if ($domain eq 'public' && $stuname eq 'public') {
 4678:       $stuname=$ENV{'REMOTE_ADDR'};
 4679:   }
 4680:   my %returnhash;
 4681:   $namespace=~s/\//\_/g;
 4682:   $namespace=~s/\W//g;
 4683:   my %hash;
 4684:   my $path=LONCAPA::tempdir();
 4685:   if (tie(%hash,'GDBM_File',
 4686: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4687: 	  &GDBM_READER(),0640)) {
 4688:     my $version=$hash{"version:$symb"};
 4689:     $returnhash{'version'}=$version;
 4690:     my $scope;
 4691:     for ($scope=1;$scope<=$version;$scope++) {
 4692:       my $vkeys=$hash{"$scope:keys:$symb"};
 4693:       my @keys=split(/:/,$vkeys);
 4694:       my $key;
 4695:       $returnhash{"$scope:keys"}=$vkeys;
 4696:       foreach $key (@keys) {
 4697: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4698: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4699:       }
 4700:     }
 4701:     if (!(untie(%hash))) {
 4702:       return "error:$!";
 4703:     }
 4704:   } else {
 4705:     return "error:$!";
 4706:   }
 4707:   return %returnhash;
 4708: }
 4709: 
 4710: # ----------------------------------------------------------------------- Store
 4711: 
 4712: sub store {
 4713:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4714:     my $home='';
 4715: 
 4716:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4717: 
 4718:     $symb=&symbclean($symb);
 4719:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4720: 
 4721:     if (!$domain) { $domain=$env{'user.domain'}; }
 4722:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4723: 
 4724:     &devalidate($symb,$stuname,$domain);
 4725: 
 4726:     $symb=escape($symb);
 4727:     if (!$namespace) { 
 4728:        unless ($namespace=$env{'request.course.id'}) { 
 4729:           return ''; 
 4730:        } 
 4731:     }
 4732:     if (!$home) { $home=$env{'user.home'}; }
 4733: 
 4734:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4735:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4736: 
 4737:     my $namevalue='';
 4738:     foreach my $key (keys(%$storehash)) {
 4739:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4740:     }
 4741:     $namevalue=~s/\&$//;
 4742:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4743:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4744: }
 4745: 
 4746: # -------------------------------------------------------------- Critical Store
 4747: 
 4748: sub cstore {
 4749:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4750:     my $home='';
 4751: 
 4752:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4753: 
 4754:     $symb=&symbclean($symb);
 4755:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4756: 
 4757:     if (!$domain) { $domain=$env{'user.domain'}; }
 4758:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4759: 
 4760:     &devalidate($symb,$stuname,$domain);
 4761: 
 4762:     $symb=escape($symb);
 4763:     if (!$namespace) { 
 4764:        unless ($namespace=$env{'request.course.id'}) { 
 4765:           return ''; 
 4766:        } 
 4767:     }
 4768:     if (!$home) { $home=$env{'user.home'}; }
 4769: 
 4770:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4771:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4772: 
 4773:     my $namevalue='';
 4774:     foreach my $key (keys(%$storehash)) {
 4775:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4776:     }
 4777:     $namevalue=~s/\&$//;
 4778:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4779:     return critical
 4780:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4781: }
 4782: 
 4783: # --------------------------------------------------------------------- Restore
 4784: 
 4785: sub restore {
 4786:     my ($symb,$namespace,$domain,$stuname) = @_;
 4787:     my $home='';
 4788: 
 4789:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4790: 
 4791:     if (!$symb) {
 4792:       unless ($symb=escape(&symbread())) { return ''; }
 4793:     } else {
 4794:       $symb=&escape(&symbclean($symb));
 4795:     }
 4796:     if (!$namespace) { 
 4797:        unless ($namespace=$env{'request.course.id'}) { 
 4798:           return ''; 
 4799:        } 
 4800:     }
 4801:     if (!$domain) { $domain=$env{'user.domain'}; }
 4802:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4803:     if (!$home) { $home=$env{'user.home'}; }
 4804:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4805: 
 4806:     my %returnhash=();
 4807:     foreach my $line (split(/\&/,$answer)) {
 4808: 	my ($name,$value)=split(/\=/,$line);
 4809:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4810:     }
 4811:     my $version;
 4812:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4813:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4814:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4815:        }
 4816:     }
 4817:     return %returnhash;
 4818: }
 4819: 
 4820: # ---------------------------------------------------------- Course Description
 4821: #
 4822: #  
 4823: 
 4824: sub coursedescription {
 4825:     my ($courseid,$args)=@_;
 4826:     $courseid=~s/^\///;
 4827:     $courseid=~s/\_/\//g;
 4828:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4829:     my $chome=&homeserver($cnum,$cdomain);
 4830:     my $normalid=$cdomain.'_'.$cnum;
 4831:     # need to always cache even if we get errors otherwise we keep 
 4832:     # trying and trying and trying to get the course description.
 4833:     my %envhash=();
 4834:     my %returnhash=();
 4835:     
 4836:     my $expiretime=600;
 4837:     if ($env{'request.course.id'} eq $normalid) {
 4838: 	$expiretime=120;
 4839:     }
 4840: 
 4841:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4842:     if (!$args->{'freshen_cache'}
 4843: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4844: 	foreach my $key (keys(%env)) {
 4845: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4846: 	    my ($setting) = $1;
 4847: 	    $returnhash{$setting} = $env{$key};
 4848: 	}
 4849: 	return %returnhash;
 4850:     }
 4851: 
 4852:     # get the data again
 4853: 
 4854:     if (!$args->{'one_time'}) {
 4855: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4856:     }
 4857: 
 4858:     if ($chome ne 'no_host') {
 4859:        %returnhash=&dump('environment',$cdomain,$cnum);
 4860:        if (!exists($returnhash{'con_lost'})) {
 4861: 	   my $username = $env{'user.name'}; # Defult username
 4862: 	   if(defined $args->{'user'}) {
 4863: 	       $username = $args->{'user'};
 4864: 	   }
 4865:            $returnhash{'home'}= $chome;
 4866: 	   $returnhash{'domain'} = $cdomain;
 4867: 	   $returnhash{'num'} = $cnum;
 4868:            if (!defined($returnhash{'type'})) {
 4869:                $returnhash{'type'} = 'Course';
 4870:            }
 4871:            while (my ($name,$value) = each %returnhash) {
 4872:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4873:            }
 4874:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4875:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4876: 	       $username.'_'.$cdomain.'_'.$cnum;
 4877:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4878:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4879:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4880:        }
 4881:     }
 4882:     if (!$args->{'one_time'}) {
 4883: 	&appenv(\%envhash);
 4884:     }
 4885:     return %returnhash;
 4886: }
 4887: 
 4888: sub update_released_required {
 4889:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4890:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4891:         $cid = $env{'request.course.id'};
 4892:         $cdom = $env{'course.'.$cid.'.domain'};
 4893:         $cnum = $env{'course.'.$cid.'.num'};
 4894:         $chome = $env{'course.'.$cid.'.home'};
 4895:     }
 4896:     if ($needsrelease) {
 4897:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4898:         my $needsupdate;
 4899:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4900:             $needsupdate = 1;
 4901:         } else {
 4902:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4903:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4904:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4905:                 $needsupdate = 1;
 4906:             }
 4907:         }
 4908:         if ($needsupdate) {
 4909:             my %needshash = (
 4910:                              'internal.releaserequired' => $needsrelease,
 4911:                             );
 4912:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4913:             if ($putresult eq 'ok') {
 4914:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4915:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4916:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4917:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4918:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4919:                 }
 4920:             }
 4921:         }
 4922:     }
 4923:     return;
 4924: }
 4925: 
 4926: # -------------------------------------------------See if a user is privileged
 4927: 
 4928: sub privileged {
 4929:     my ($username,$domain)=@_;
 4930: 
 4931:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4932:     my $now = time;
 4933: 
 4934:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4935:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4936:             if (($trole eq 'dc') || ($trole eq 'su')) {
 4937:                 return 1 unless ($tend && $tend < $now) 
 4938:                     or ($tstart && $tstart > $now);
 4939:             }
 4940: 	}
 4941: 
 4942:     return 0;
 4943: }
 4944: 
 4945: # -------------------------------------------------------- Get user privileges
 4946: 
 4947: sub rolesinit {
 4948:     my ($domain, $username) = @_;
 4949:     my %userroles = ('user.login.time' => time);
 4950:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 4951: 
 4952:     # firstaccess and timerinterval are related to timed maps/resources. 
 4953:     # also, blocking can be triggered by an activating timer
 4954:     # it's saved in the user's %env.
 4955:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 4956:     my %timerinterval = &dump('timerinterval', $domain, $username);
 4957:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 4958:         %timerintchk, %timerintenv);
 4959: 
 4960:     foreach my $key (keys(%firstaccess)) {
 4961:         my ($cid, $rest) = split(/\0/, $key);
 4962:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4963:     }
 4964: 
 4965:     foreach my $key (keys(%timerinterval)) {
 4966:         my ($cid,$rest) = split(/\0/,$key);
 4967:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4968:     }
 4969: 
 4970:     my %allroles=();
 4971:     my %allgroups=();
 4972: 
 4973:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 4974:         my $role = $rolesdump{$area};
 4975:         $area =~ s/\_\w\w$//;
 4976: 
 4977:         my ($trole, $tend, $tstart, $group_privs);
 4978: 
 4979:         if ($role =~ /^cr/) {
 4980:         # Custom role, defined by a user 
 4981:         # e.g., user.role.cr/msu/smith/mynewrole
 4982:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4983:                 $trole = $1;
 4984:                 ($tend, $tstart) = split('_', $2);
 4985:             } else {
 4986:                 $trole = $role;
 4987:             }
 4988:         } elsif ($role =~ m|^gr/|) {
 4989:         # Role of member in a group, defined within a course/community
 4990:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 4991:             ($trole, $tend, $tstart) = split(/_/, $role);
 4992:             next if $tstart eq '-1';
 4993:             ($trole, $group_privs) = split(/\//, $trole);
 4994:             $group_privs = &unescape($group_privs);
 4995:         } else {
 4996:         # Just a normal role, defined in roles.tab
 4997:             ($trole, $tend, $tstart) = split(/_/,$role);
 4998:         }
 4999: 
 5000:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5001:                  $username);
 5002:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5003: 
 5004:         # role expired or not available yet?
 5005:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5006:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5007: 
 5008:         next if $area eq '' or $trole eq '';
 5009: 
 5010:         my $spec = "$trole.$area";
 5011:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5012: 
 5013:         if ($trole =~ /^cr\//) {
 5014:         # Custom role, defined by a user
 5015:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5016:         } elsif ($trole eq 'gr') {
 5017:         # Role of a member in a group, defined within a course/community
 5018:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5019:             next;
 5020:         } else {
 5021:         # Normal role, defined in roles.tab
 5022:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5023:         }
 5024: 
 5025:         my $cid = $tdomain.'_'.$trest;
 5026:         unless ($firstaccchk{$cid}) {
 5027:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5028:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5029:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5030:                         $coursetimerstarts{$cid}{$item}; 
 5031:                 }
 5032:             }
 5033:             $firstaccchk{$cid} = 1;
 5034:         }
 5035:         unless ($timerintchk{$cid}) {
 5036:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5037:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5038:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5039:                        $coursetimerintervals{$cid}{$item};
 5040:                 }
 5041:             }
 5042:             $timerintchk{$cid} = 1;
 5043:         }
 5044:     }
 5045: 
 5046:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5047:         \%allroles, \%allgroups);
 5048:     $env{'user.adv'} = $userroles{'user.adv'};
 5049: 
 5050:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5051: }
 5052: 
 5053: sub set_arearole {
 5054:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 5055: # log the associated role with the area
 5056:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5057:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5058: }
 5059: 
 5060: sub custom_roleprivs {
 5061:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5062:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5063:     my $homsvr=homeserver($rauthor,$rdomain);
 5064:     if (&hostname($homsvr) ne '') {
 5065:         my ($rdummy,$roledef)=
 5066:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5067:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5068:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5069:             if (defined($syspriv)) {
 5070:                 if ($trest =~ /^$match_community$/) {
 5071:                     $syspriv =~ s/bre\&S//; 
 5072:                 }
 5073:                 $$allroles{'cm./'}.=':'.$syspriv;
 5074:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5075:             }
 5076:             if ($tdomain ne '') {
 5077:                 if (defined($dompriv)) {
 5078:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5079:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5080:                 }
 5081:                 if (($trest ne '') && (defined($coursepriv))) {
 5082:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5083:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5084:                 }
 5085:             }
 5086:         }
 5087:     }
 5088: }
 5089: 
 5090: sub group_roleprivs {
 5091:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5092:     my $access = 1;
 5093:     my $now = time;
 5094:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5095:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5096:     if ($access) {
 5097:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5098:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5099:     }
 5100: }
 5101: 
 5102: sub standard_roleprivs {
 5103:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5104:     if (defined($pr{$trole.':s'})) {
 5105:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5106:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5107:     }
 5108:     if ($tdomain ne '') {
 5109:         if (defined($pr{$trole.':d'})) {
 5110:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5111:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5112:         }
 5113:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5114:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5115:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5116:         }
 5117:     }
 5118: }
 5119: 
 5120: sub set_userprivs {
 5121:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5122:     my $author=0;
 5123:     my $adv=0;
 5124:     my %grouproles = ();
 5125:     if (keys(%{$allgroups}) > 0) {
 5126:         my @groupkeys; 
 5127:         foreach my $role (keys(%{$allroles})) {
 5128:             push(@groupkeys,$role);
 5129:         }
 5130:         if (ref($groups_roles) eq 'HASH') {
 5131:             foreach my $key (keys(%{$groups_roles})) {
 5132:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5133:                     push(@groupkeys,$key);
 5134:                 }
 5135:             }
 5136:         }
 5137:         if (@groupkeys > 0) {
 5138:             foreach my $role (@groupkeys) {
 5139:                 my ($trole,$area,$sec,$extendedarea);
 5140:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5141:                     $trole = $1;
 5142:                     $area = $2;
 5143:                     $sec = $3;
 5144:                     $extendedarea = $area.$sec;
 5145:                     if (exists($$allgroups{$area})) {
 5146:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5147:                             my $spec = $trole.'.'.$extendedarea;
 5148:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5149:                                                 $$allgroups{$area}{$group};
 5150:                         }
 5151:                     }
 5152:                 }
 5153:             }
 5154:         }
 5155:     }
 5156:     foreach my $group (keys(%grouproles)) {
 5157:         $$allroles{$group} = $grouproles{$group};
 5158:     }
 5159:     foreach my $role (keys(%{$allroles})) {
 5160:         my %thesepriv;
 5161:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5162:         foreach my $item (split(/:/,$$allroles{$role})) {
 5163:             if ($item ne '') {
 5164:                 my ($privilege,$restrictions)=split(/&/,$item);
 5165:                 if ($restrictions eq '') {
 5166:                     $thesepriv{$privilege}='F';
 5167:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5168:                     $thesepriv{$privilege}.=$restrictions;
 5169:                 }
 5170:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5171:             }
 5172:         }
 5173:         my $thesestr='';
 5174:         foreach my $priv (sort(keys(%thesepriv))) {
 5175: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5176: 	}
 5177:         $userroles->{'user.priv.'.$role} = $thesestr;
 5178:     }
 5179:     return ($author,$adv);
 5180: }
 5181: 
 5182: sub role_status {
 5183:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5184:     my @pwhere = ();
 5185:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5186:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5187:         unless (!defined($$role) || $$role eq '') {
 5188:             $$where=join('.',@pwhere);
 5189:             $$trolecode=$$role.'.'.$$where;
 5190:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5191:             $$tstatus='is';
 5192:             if ($$tstart && $$tstart>$update) {
 5193:                 $$tstatus='future';
 5194:                 if ($$tstart<$now) {
 5195:                     if ($$tstart && $$tstart>$refresh) {
 5196:                         if (($$where ne '') && ($$role ne '')) {
 5197:                             my (%allroles,%allgroups,$group_privs,
 5198:                                 %groups_roles,@rolecodes);
 5199:                             my %userroles = (
 5200:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5201:                             );
 5202:                             @rolecodes = ('cm'); 
 5203:                             my $spec=$$role.'.'.$$where;
 5204:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5205:                             if ($$role =~ /^cr\//) {
 5206:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5207:                                 push(@rolecodes,'cr');
 5208:                             } elsif ($$role eq 'gr') {
 5209:                                 push(@rolecodes,$$role);
 5210:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5211:                                                     $env{'user.name'});
 5212:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5213:                                 (undef,my $group_privs) = split(/\//,$trole);
 5214:                                 $group_privs = &unescape($group_privs);
 5215:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5216:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5217:                                 &get_groups_roles($tdomain,$trest,
 5218:                                                   \%course_roles,\@rolecodes,
 5219:                                                   \%groups_roles);
 5220:                             } else {
 5221:                                 push(@rolecodes,$$role);
 5222:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5223:                             }
 5224:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5225:                             &appenv(\%userroles,\@rolecodes);
 5226:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5227:                         }
 5228:                     }
 5229:                     $$tstatus = 'is';
 5230:                 }
 5231:             }
 5232:             if ($$tend) {
 5233:                 if ($$tend<$update) {
 5234:                     $$tstatus='expired';
 5235:                 } elsif ($$tend<$now) {
 5236:                     $$tstatus='will_not';
 5237:                 }
 5238:             }
 5239:         }
 5240:     }
 5241: }
 5242: 
 5243: sub get_groups_roles {
 5244:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5245:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5246:                   (ref($rolecodes) eq 'ARRAY') && 
 5247:                   (ref($groups_roles) eq 'HASH')); 
 5248:     if (keys(%{$cdom_courseroles}) > 0) {
 5249:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5250:         if ($cdom ne '' && $cnum ne '') {
 5251:             foreach my $key (keys(%{$cdom_courseroles})) {
 5252:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5253:                     my $crsrole = $1;
 5254:                     my $crssec = $2;
 5255:                     if ($crsrole =~ /^cr/) {
 5256:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5257:                             push(@{$rolecodes},'cr');
 5258:                         }
 5259:                     } else {
 5260:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5261:                             push(@{$rolecodes},$crsrole);
 5262:                         }
 5263:                     }
 5264:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5265:                     if ($crssec ne '') {
 5266:                         $rolekey .= "/$crssec";
 5267:                     }
 5268:                     $rolekey .= './';
 5269:                     $groups_roles->{$rolekey} = $rolecodes;
 5270:                 }
 5271:             }
 5272:         }
 5273:     }
 5274:     return;
 5275: }
 5276: 
 5277: sub delete_env_groupprivs {
 5278:     my ($where,$courseroles,$possroles) = @_;
 5279:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5280:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5281:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5282:         %{$courseroles->{$udom}} =
 5283:             &get_my_roles('','','userroles',['active'],
 5284:                           $possroles,[$udom],1);
 5285:     }
 5286:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5287:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5288:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5289:             my $area = '/'.$cdom.'/'.$cnum;
 5290:             my $privkey = "user.priv.$crsrole.$area";
 5291:             if ($crssec ne '') {
 5292:                 $privkey .= '/'.$crssec;
 5293:             }
 5294:             $privkey .= ".$area/$group";
 5295:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5296:         }
 5297:     }
 5298:     return;
 5299: }
 5300: 
 5301: sub check_adhoc_privs {
 5302:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5303:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5304:     my $setprivs;
 5305:     if ($env{$cckey}) {
 5306:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5307:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5308:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5309:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5310:             $setprivs = 1;
 5311:         }
 5312:     } else {
 5313:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5314:         $setprivs = 1;
 5315:     }
 5316:     return $setprivs;
 5317: }
 5318: 
 5319: sub set_adhoc_privileges {
 5320: # role can be cc or ca
 5321:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5322:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5323:     my $spec = $role.'.'.$area;
 5324:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5325:                                   $env{'user.name'});
 5326:     my %ccrole = ();
 5327:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5328:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5329:     &appenv(\%userroles,[$role,'cm']);
 5330:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5331:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5332:         &appenv( {'request.role'        => $spec,
 5333:                   'request.role.domain' => $dcdom,
 5334:                   'request.course.sec'  => ''
 5335:                  }
 5336:                );
 5337:         my $tadv=0;
 5338:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5339:         &appenv({'request.role.adv'    => $tadv});
 5340:     }
 5341: }
 5342: 
 5343: # --------------------------------------------------------------- get interface
 5344: 
 5345: sub get {
 5346:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5347:    my $items='';
 5348:    foreach my $item (@$storearr) {
 5349:        $items.=&escape($item).'&';
 5350:    }
 5351:    $items=~s/\&$//;
 5352:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5353:    if (!$uname) { $uname=$env{'user.name'}; }
 5354:    my $uhome=&homeserver($uname,$udomain);
 5355: 
 5356:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5357:    my @pairs=split(/\&/,$rep);
 5358:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5359:      return @pairs;
 5360:    }
 5361:    my %returnhash=();
 5362:    my $i=0;
 5363:    foreach my $item (@$storearr) {
 5364:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5365:       $i++;
 5366:    }
 5367:    return %returnhash;
 5368: }
 5369: 
 5370: # --------------------------------------------------------------- del interface
 5371: 
 5372: sub del {
 5373:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5374:    my $items='';
 5375:    foreach my $item (@$storearr) {
 5376:        $items.=&escape($item).'&';
 5377:    }
 5378: 
 5379:    $items=~s/\&$//;
 5380:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5381:    if (!$uname) { $uname=$env{'user.name'}; }
 5382:    my $uhome=&homeserver($uname,$udomain);
 5383:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5384: }
 5385: 
 5386: # -------------------------------------------------------------- dump interface
 5387: 
 5388: sub unserialize {
 5389:     my ($rep, $escapedkeys) = @_;
 5390: 
 5391:     return {} if $rep =~ /^error/;
 5392: 
 5393:     my %returnhash=();
 5394: 	foreach my $item (split /\&/, $rep) {
 5395: 	    my ($key, $value) = split(/=/, $item, 2);
 5396: 	    $key = unescape($key) unless $escapedkeys;
 5397: 	    next if $key =~ /^error: 2 /;
 5398: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5399: 	}
 5400:     #return %returnhash;
 5401:     return \%returnhash;
 5402: }        
 5403: 
 5404: # see Lond::dump_with_regexp
 5405: # if $escapedkeys hash keys won't get unescaped.
 5406: sub dump {
 5407:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5408:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5409:     if (!$uname) { $uname=$env{'user.name'}; }
 5410:     my $uhome=&homeserver($uname,$udomain);
 5411: 
 5412:     my $reply;
 5413:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5414:         # user is hosted on this machine
 5415:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5416:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
 5417:         return %{unserialize($reply, $escapedkeys)};
 5418:     }
 5419:     if ($regexp) {
 5420: 	$regexp=&escape($regexp);
 5421:     } else {
 5422: 	$regexp='.';
 5423:     }
 5424:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5425:     my @pairs=split(/\&/,$rep);
 5426:     my %returnhash=();
 5427:     if (!($rep =~ /^error/ )) {
 5428: 	foreach my $item (@pairs) {
 5429: 	    my ($key,$value)=split(/=/,$item,2);
 5430:         $key = unescape($key) unless $escapedkeys;
 5431:         #$key = &unescape($key);
 5432: 	    next if ($key =~ /^error: 2 /);
 5433: 	    $returnhash{$key}=&thaw_unescape($value);
 5434: 	}
 5435:     }
 5436:     return %returnhash;
 5437: }
 5438: 
 5439: 
 5440: # --------------------------------------------------------- dumpstore interface
 5441: 
 5442: sub dumpstore {
 5443:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5444:    # same as dump but keys must be escaped. They may contain colon separated
 5445:    # lists of values that may themself contain colons (e.g. symbs).
 5446:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5447: }
 5448: 
 5449: # -------------------------------------------------------------- keys interface
 5450: 
 5451: sub getkeys {
 5452:    my ($namespace,$udomain,$uname)=@_;
 5453:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5454:    if (!$uname) { $uname=$env{'user.name'}; }
 5455:    my $uhome=&homeserver($uname,$udomain);
 5456:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5457:    my @keyarray=();
 5458:    foreach my $key (split(/\&/,$rep)) {
 5459:       next if ($key =~ /^error: 2 /);
 5460:       push(@keyarray,&unescape($key));
 5461:    }
 5462:    return @keyarray;
 5463: }
 5464: 
 5465: # --------------------------------------------------------------- currentdump
 5466: sub currentdump {
 5467:    my ($courseid,$sdom,$sname)=@_;
 5468:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5469:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5470:    $sname    = $env{'user.name'}         if (! defined($sname));
 5471:    my $uhome = &homeserver($sname,$sdom);
 5472:    my $rep;
 5473: 
 5474:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5475:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5476:                    $courseid)));
 5477:    } else {
 5478:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5479:    }
 5480: 
 5481:    return if ($rep =~ /^(error:|no_such_host)/);
 5482:    #
 5483:    my %returnhash=();
 5484:    #
 5485:    if ($rep eq "unknown_cmd") { 
 5486:        # an old lond will not know currentdump
 5487:        # Do a dump and make it look like a currentdump
 5488:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5489:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5490:        my %hash = @tmp;
 5491:        @tmp=();
 5492:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5493:    } else {
 5494:        my @pairs=split(/\&/,$rep);
 5495:        foreach my $pair (@pairs) {
 5496:            my ($key,$value)=split(/=/,$pair,2);
 5497:            my ($symb,$param) = split(/:/,$key);
 5498:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5499:                                                         &thaw_unescape($value);
 5500:        }
 5501:    }
 5502:    return %returnhash;
 5503: }
 5504: 
 5505: sub convert_dump_to_currentdump{
 5506:     my %hash = %{shift()};
 5507:     my %returnhash;
 5508:     # Code ripped from lond, essentially.  The only difference
 5509:     # here is the unescaping done by lonnet::dump().  Conceivably
 5510:     # we might run in to problems with parameter names =~ /^v\./
 5511:     while (my ($key,$value) = each(%hash)) {
 5512:         my ($v,$symb,$param) = split(/:/,$key);
 5513: 	$symb  = &unescape($symb);
 5514: 	$param = &unescape($param);
 5515:         next if ($v eq 'version' || $symb eq 'keys');
 5516:         next if (exists($returnhash{$symb}) &&
 5517:                  exists($returnhash{$symb}->{$param}) &&
 5518:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5519:         $returnhash{$symb}->{$param}=$value;
 5520:         $returnhash{$symb}->{'v.'.$param}=$v;
 5521:     }
 5522:     #
 5523:     # Remove all of the keys in the hashes which keep track of
 5524:     # the version of the parameter.
 5525:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5526:         # use a foreach because we are going to delete from the hash.
 5527:         foreach my $key (keys(%$param_hash)) {
 5528:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5529:         }
 5530:     }
 5531:     return \%returnhash;
 5532: }
 5533: 
 5534: # ------------------------------------------------------ critical inc interface
 5535: 
 5536: sub cinc {
 5537:     return &inc(@_,'critical');
 5538: }
 5539: 
 5540: # --------------------------------------------------------------- inc interface
 5541: 
 5542: sub inc {
 5543:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5544:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5545:     if (!$uname) { $uname=$env{'user.name'}; }
 5546:     my $uhome=&homeserver($uname,$udomain);
 5547:     my $items='';
 5548:     if (! ref($store)) {
 5549:         # got a single value, so use that instead
 5550:         $items = &escape($store).'=&';
 5551:     } elsif (ref($store) eq 'SCALAR') {
 5552:         $items = &escape($$store).'=&';        
 5553:     } elsif (ref($store) eq 'ARRAY') {
 5554:         $items = join('=&',map {&escape($_);} @{$store});
 5555:     } elsif (ref($store) eq 'HASH') {
 5556:         while (my($key,$value) = each(%{$store})) {
 5557:             $items.= &escape($key).'='.&escape($value).'&';
 5558:         }
 5559:     }
 5560:     $items=~s/\&$//;
 5561:     if ($critical) {
 5562: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5563:     } else {
 5564: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5565:     }
 5566: }
 5567: 
 5568: # --------------------------------------------------------------- put interface
 5569: 
 5570: sub put {
 5571:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5572:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5573:    if (!$uname) { $uname=$env{'user.name'}; }
 5574:    my $uhome=&homeserver($uname,$udomain);
 5575:    my $items='';
 5576:    foreach my $item (keys(%$storehash)) {
 5577:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5578:    }
 5579:    $items=~s/\&$//;
 5580:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5581: }
 5582: 
 5583: # ------------------------------------------------------------ newput interface
 5584: 
 5585: sub newput {
 5586:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5587:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5588:    if (!$uname) { $uname=$env{'user.name'}; }
 5589:    my $uhome=&homeserver($uname,$udomain);
 5590:    my $items='';
 5591:    foreach my $key (keys(%$storehash)) {
 5592:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5593:    }
 5594:    $items=~s/\&$//;
 5595:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5596: }
 5597: 
 5598: # ---------------------------------------------------------  putstore interface
 5599: 
 5600: sub putstore {
 5601:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5602:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5603:    if (!$uname) { $uname=$env{'user.name'}; }
 5604:    my $uhome=&homeserver($uname,$udomain);
 5605:    my $items='';
 5606:    foreach my $key (keys(%$storehash)) {
 5607:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5608:    }
 5609:    $items=~s/\&$//;
 5610:    my $esc_symb=&escape($symb);
 5611:    my $esc_v=&escape($version);
 5612:    my $reply =
 5613:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5614: 	      $uhome);
 5615:    if ($reply eq 'unknown_cmd') {
 5616:        # gfall back to way things use to be done
 5617:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5618: 			    $uname);
 5619:    }
 5620:    return $reply;
 5621: }
 5622: 
 5623: sub old_putstore {
 5624:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5625:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5626:     if (!$uname) { $uname=$env{'user.name'}; }
 5627:     my $uhome=&homeserver($uname,$udomain);
 5628:     my %newstorehash;
 5629:     foreach my $item (keys(%$storehash)) {
 5630: 	my $key = $version.':'.&escape($symb).':'.$item;
 5631: 	$newstorehash{$key} = $storehash->{$item};
 5632:     }
 5633:     my $items='';
 5634:     my %allitems = ();
 5635:     foreach my $item (keys(%newstorehash)) {
 5636: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5637: 	    my $key = $1.':keys:'.$2;
 5638: 	    $allitems{$key} .= $3.':';
 5639: 	}
 5640: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5641:     }
 5642:     foreach my $item (keys(%allitems)) {
 5643: 	$allitems{$item} =~ s/\:$//;
 5644: 	$items.= $item.'='.$allitems{$item}.'&';
 5645:     }
 5646:     $items=~s/\&$//;
 5647:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5648: }
 5649: 
 5650: # ------------------------------------------------------ critical put interface
 5651: 
 5652: sub cput {
 5653:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5654:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5655:    if (!$uname) { $uname=$env{'user.name'}; }
 5656:    my $uhome=&homeserver($uname,$udomain);
 5657:    my $items='';
 5658:    foreach my $item (keys(%$storehash)) {
 5659:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5660:    }
 5661:    $items=~s/\&$//;
 5662:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5663: }
 5664: 
 5665: # -------------------------------------------------------------- eget interface
 5666: 
 5667: sub eget {
 5668:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5669:    my $items='';
 5670:    foreach my $item (@$storearr) {
 5671:        $items.=&escape($item).'&';
 5672:    }
 5673:    $items=~s/\&$//;
 5674:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5675:    if (!$uname) { $uname=$env{'user.name'}; }
 5676:    my $uhome=&homeserver($uname,$udomain);
 5677:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5678:    my @pairs=split(/\&/,$rep);
 5679:    my %returnhash=();
 5680:    my $i=0;
 5681:    foreach my $item (@$storearr) {
 5682:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5683:       $i++;
 5684:    }
 5685:    return %returnhash;
 5686: }
 5687: 
 5688: # ------------------------------------------------------------ tmpput interface
 5689: sub tmpput {
 5690:     my ($storehash,$server,$context)=@_;
 5691:     my $items='';
 5692:     foreach my $item (keys(%$storehash)) {
 5693: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5694:     }
 5695:     $items=~s/\&$//;
 5696:     if (defined($context)) {
 5697:         $items .= ':'.&escape($context);
 5698:     }
 5699:     return &reply("tmpput:$items",$server);
 5700: }
 5701: 
 5702: # ------------------------------------------------------------ tmpget interface
 5703: sub tmpget {
 5704:     my ($token,$server)=@_;
 5705:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5706:     my $rep=&reply("tmpget:$token",$server);
 5707:     my %returnhash;
 5708:     foreach my $item (split(/\&/,$rep)) {
 5709: 	my ($key,$value)=split(/=/,$item);
 5710:         next if ($key =~ /^error: 2 /);
 5711: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5712:     }
 5713:     return %returnhash;
 5714: }
 5715: 
 5716: # ------------------------------------------------------------ tmpdel interface
 5717: sub tmpdel {
 5718:     my ($token,$server)=@_;
 5719:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5720:     return &reply("tmpdel:$token",$server);
 5721: }
 5722: 
 5723: # ------------------------------------------------------------ get_timebased_id 
 5724: 
 5725: sub get_timebased_id {
 5726:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5727:         $maxtries) = @_;
 5728:     my ($newid,$error,$dellock);
 5729:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5730:         return ('','ok','invalid call to get suffix');
 5731:     }
 5732: 
 5733: # set defaults for any optional args for which values were not supplied
 5734:     if ($who eq '') {
 5735:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5736:     }
 5737:     if (!$locktries) {
 5738:         $locktries = 3;
 5739:     }
 5740:     if (!$maxtries) {
 5741:         $maxtries = 10;
 5742:     }
 5743:     
 5744:     if (($cdom eq '') || ($cnum eq '')) {
 5745:         if ($env{'request.course.id'}) {
 5746:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5747:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5748:         }
 5749:         if (($cdom eq '') || ($cnum eq '')) {
 5750:             return ('','ok','call to get suffix not in course context');
 5751:         }
 5752:     }
 5753: 
 5754: # construct locking item
 5755:     my $lockhash = {
 5756:                       $prefix."\0".'locked_'.$keyid => $who,
 5757:                    };
 5758:     my $tries = 0;
 5759: 
 5760: # attempt to get lock on nohist_$namespace file
 5761:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5762:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5763:         $tries ++;
 5764:         sleep 1;
 5765:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5766:     }
 5767: 
 5768: # attempt to get unique identifier, based on current timestamp
 5769:     if ($gotlock eq 'ok') {
 5770:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5771:         my $id = time;
 5772:         $newid = $id;
 5773:         my $idtries = 0;
 5774:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5775:             if ($idtype eq 'concat') {
 5776:                 $newid = $id.$idtries;
 5777:             } else {
 5778:                 $newid ++;
 5779:             }
 5780:             $idtries ++;
 5781:         }
 5782:         if (!exists($inuse{$prefix."\0".$newid})) {
 5783:             my %new_item =  (
 5784:                               $prefix."\0".$newid => $who,
 5785:                             );
 5786:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5787:                                                  $cdom,$cnum);
 5788:             if ($putresult ne 'ok') {
 5789:                 undef($newid);
 5790:                 $error = 'error saving new item: '.$putresult;
 5791:             }
 5792:         } else {
 5793:              $error = ('error: no unique suffix available for the new item ');
 5794:         }
 5795: #  remove lock
 5796:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5797:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5798:     } else {
 5799:         $error = "error: could not obtain lockfile\n";
 5800:         $dellock = 'ok';
 5801:     }
 5802:     return ($newid,$dellock,$error);
 5803: }
 5804: 
 5805: # -------------------------------------------------- portfolio access checking
 5806: 
 5807: sub portfolio_access {
 5808:     my ($requrl) = @_;
 5809:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5810:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5811:     if ($result) {
 5812:         my %setters;
 5813:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5814:             my ($startblock,$endblock) =
 5815:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5816:             if ($startblock && $endblock) {
 5817:                 return 'B';
 5818:             }
 5819:         } else {
 5820:             my ($startblock,$endblock) =
 5821:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5822:             if ($startblock && $endblock) {
 5823:                 return 'B';
 5824:             }
 5825:         }
 5826:     }
 5827:     if ($result eq 'ok') {
 5828:        return 'F';
 5829:     } elsif ($result =~ /^[^:]+:guest_/) {
 5830:        return 'A';
 5831:     }
 5832:     return '';
 5833: }
 5834: 
 5835: sub get_portfolio_access {
 5836:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5837: 
 5838:     if (!ref($access_hash)) {
 5839: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5840: 	my %access_controls = &get_access_controls($current_perms,$group,
 5841: 						   $file_name);
 5842: 	$access_hash = $access_controls{$file_name};
 5843:     }
 5844: 
 5845:     my ($public,$guest,@domains,@users,@courses,@groups);
 5846:     my $now = time;
 5847:     if (ref($access_hash) eq 'HASH') {
 5848:         foreach my $key (keys(%{$access_hash})) {
 5849:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5850:             if ($start > $now) {
 5851:                 next;
 5852:             }
 5853:             if ($end && $end<$now) {
 5854:                 next;
 5855:             }
 5856:             if ($scope eq 'public') {
 5857:                 $public = $key;
 5858:                 last;
 5859:             } elsif ($scope eq 'guest') {
 5860:                 $guest = $key;
 5861:             } elsif ($scope eq 'domains') {
 5862:                 push(@domains,$key);
 5863:             } elsif ($scope eq 'users') {
 5864:                 push(@users,$key);
 5865:             } elsif ($scope eq 'course') {
 5866:                 push(@courses,$key);
 5867:             } elsif ($scope eq 'group') {
 5868:                 push(@groups,$key);
 5869:             }
 5870:         }
 5871:         if ($public) {
 5872:             return 'ok';
 5873:         }
 5874:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5875:             if ($guest) {
 5876:                 return $guest;
 5877:             }
 5878:         } else {
 5879:             if (@domains > 0) {
 5880:                 foreach my $domkey (@domains) {
 5881:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5882:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5883:                             return 'ok';
 5884:                         }
 5885:                     }
 5886:                 }
 5887:             }
 5888:             if (@users > 0) {
 5889:                 foreach my $userkey (@users) {
 5890:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5891:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5892:                             if (ref($item) eq 'HASH') {
 5893:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5894:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5895:                                     return 'ok';
 5896:                                 }
 5897:                             }
 5898:                         }
 5899:                     } 
 5900:                 }
 5901:             }
 5902:             my %roleshash;
 5903:             my @courses_and_groups = @courses;
 5904:             push(@courses_and_groups,@groups); 
 5905:             if (@courses_and_groups > 0) {
 5906:                 my (%allgroups,%allroles); 
 5907:                 my ($start,$end,$role,$sec,$group);
 5908:                 foreach my $envkey (%env) {
 5909:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5910:                         my $cid = $2.'_'.$3; 
 5911:                         if ($1 eq 'gr') {
 5912:                             $group = $4;
 5913:                             $allgroups{$cid}{$group} = $env{$envkey};
 5914:                         } else {
 5915:                             if ($4 eq '') {
 5916:                                 $sec = 'none';
 5917:                             } else {
 5918:                                 $sec = $4;
 5919:                             }
 5920:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5921:                         }
 5922:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5923:                         my $cid = $2.'_'.$3;
 5924:                         if ($4 eq '') {
 5925:                             $sec = 'none';
 5926:                         } else {
 5927:                             $sec = $4;
 5928:                         }
 5929:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5930:                     }
 5931:                 }
 5932:                 if (keys(%allroles) == 0) {
 5933:                     return;
 5934:                 }
 5935:                 foreach my $key (@courses_and_groups) {
 5936:                     my %content = %{$$access_hash{$key}};
 5937:                     my $cnum = $content{'number'};
 5938:                     my $cdom = $content{'domain'};
 5939:                     my $cid = $cdom.'_'.$cnum;
 5940:                     if (!exists($allroles{$cid})) {
 5941:                         next;
 5942:                     }    
 5943:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5944:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5945:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5946:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5947:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5948:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5949:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5950:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5951:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5952:                                         if (grep/^all$/,@sections) {
 5953:                                             return 'ok';
 5954:                                         } else {
 5955:                                             if (grep/^$sec$/,@sections) {
 5956:                                                 return 'ok';
 5957:                                             }
 5958:                                         }
 5959:                                     }
 5960:                                 }
 5961:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5962:                                     if (grep/^none$/,@groups) {
 5963:                                         return 'ok';
 5964:                                     }
 5965:                                 } else {
 5966:                                     if (grep/^all$/,@groups) {
 5967:                                         return 'ok';
 5968:                                     } 
 5969:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5970:                                         if (grep/^$group$/,@groups) {
 5971:                                             return 'ok';
 5972:                                         }
 5973:                                     }
 5974:                                 } 
 5975:                             }
 5976:                         }
 5977:                     }
 5978:                 }
 5979:             }
 5980:             if ($guest) {
 5981:                 return $guest;
 5982:             }
 5983:         }
 5984:     }
 5985:     return;
 5986: }
 5987: 
 5988: sub course_group_datechecker {
 5989:     my ($dates,$now,$status) = @_;
 5990:     my ($start,$end) = split(/\./,$dates);
 5991:     if (!$start && !$end) {
 5992:         return 'ok';
 5993:     }
 5994:     if (grep/^active$/,@{$status}) {
 5995:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5996:             return 'ok';
 5997:         }
 5998:     }
 5999:     if (grep/^previous$/,@{$status}) {
 6000:         if ($end > $now ) {
 6001:             return 'ok';
 6002:         }
 6003:     }
 6004:     if (grep/^future$/,@{$status}) {
 6005:         if ($start > $now) {
 6006:             return 'ok';
 6007:         }
 6008:     }
 6009:     return; 
 6010: }
 6011: 
 6012: sub parse_portfolio_url {
 6013:     my ($url) = @_;
 6014: 
 6015:     my ($type,$udom,$unum,$group,$file_name);
 6016:     
 6017:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6018: 	$type = 1;
 6019:         $udom = $1;
 6020:         $unum = $2;
 6021:         $file_name = $3;
 6022:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6023: 	$type = 2;
 6024:         $udom = $1;
 6025:         $unum = $2;
 6026:         $group = $3;
 6027:         $file_name = $3.'/'.$4;
 6028:     }
 6029:     if (wantarray) {
 6030: 	return ($type,$udom,$unum,$file_name,$group);
 6031:     }
 6032:     return $type;
 6033: }
 6034: 
 6035: sub is_portfolio_url {
 6036:     my ($url) = @_;
 6037:     return scalar(&parse_portfolio_url($url));
 6038: }
 6039: 
 6040: sub is_portfolio_file {
 6041:     my ($file) = @_;
 6042:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6043:         return 1;
 6044:     }
 6045:     return;
 6046: }
 6047: 
 6048: sub usertools_access {
 6049:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6050:     my ($access,%tools);
 6051:     if ($context eq '') {
 6052:         $context = 'tools';
 6053:     }
 6054:     if ($context eq 'requestcourses') {
 6055:         %tools = (
 6056:                       official   => 1,
 6057:                       unofficial => 1,
 6058:                       community  => 1,
 6059:                  );
 6060:     } elsif ($context eq 'requestauthor') {
 6061:         %tools = (
 6062:                       requestauthor => 1,
 6063:                  );
 6064:     } else {
 6065:         %tools = (
 6066:                       aboutme   => 1,
 6067:                       blog      => 1,
 6068:                       webdav    => 1,
 6069:                       portfolio => 1,
 6070:                  );
 6071:     }
 6072:     return if (!defined($tools{$tool}));
 6073: 
 6074:     if ((!defined($udom)) || (!defined($uname))) {
 6075:         $udom = $env{'user.domain'};
 6076:         $uname = $env{'user.name'};
 6077:     }
 6078: 
 6079:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6080:         if ($action ne 'reload') {
 6081:             if ($context eq 'requestcourses') {
 6082:                 return $env{'environment.canrequest.'.$tool};
 6083:             } elsif ($context eq 'requestauthor') {
 6084:                 return $env{'environment.canrequest.author'};
 6085:             } else {
 6086:                 return $env{'environment.availabletools.'.$tool};
 6087:             }
 6088:         }
 6089:     }
 6090: 
 6091:     my ($toolstatus,$inststatus,$envkey);
 6092:     if ($context eq 'requestauthor') {
 6093:         $envkey = $context; 
 6094:     } else {
 6095:         $envkey = $context.'.'.$tool;
 6096:     }
 6097: 
 6098:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6099:          ($action ne 'reload')) {
 6100:         $toolstatus = $env{'environment.'.$envkey};
 6101:         $inststatus = $env{'environment.inststatus'};
 6102:     } else {
 6103:         if (ref($userenvref) eq 'HASH') {
 6104:             $toolstatus = $userenvref->{$envkey};
 6105:             $inststatus = $userenvref->{'inststatus'};
 6106:         } else {
 6107:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6108:             $toolstatus = $userenv{$envkey};
 6109:             $inststatus = $userenv{'inststatus'};
 6110:         }
 6111:     }
 6112: 
 6113:     if ($toolstatus ne '') {
 6114:         if ($toolstatus) {
 6115:             $access = 1;
 6116:         } else {
 6117:             $access = 0;
 6118:         }
 6119:         return $access;
 6120:     }
 6121: 
 6122:     my ($is_adv,%domdef);
 6123:     if (ref($is_advref) eq 'HASH') {
 6124:         $is_adv = $is_advref->{'is_adv'};
 6125:     } else {
 6126:         $is_adv = &is_advanced_user($udom,$uname);
 6127:     }
 6128:     if (ref($domdefref) eq 'HASH') {
 6129:         %domdef = %{$domdefref};
 6130:     } else {
 6131:         %domdef = &get_domain_defaults($udom);
 6132:     }
 6133:     if (ref($domdef{$tool}) eq 'HASH') {
 6134:         if ($is_adv) {
 6135:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6136:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6137:                     $access = 1;
 6138:                 } else {
 6139:                     $access = 0;
 6140:                 }
 6141:                 return $access;
 6142:             }
 6143:         }
 6144:         if ($inststatus ne '') {
 6145:             my ($hasaccess,$hasnoaccess);
 6146:             foreach my $affiliation (split(/:/,$inststatus)) {
 6147:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6148:                     if ($domdef{$tool}{$affiliation}) {
 6149:                         $hasaccess = 1;
 6150:                     } else {
 6151:                         $hasnoaccess = 1;
 6152:                     }
 6153:                 }
 6154:             }
 6155:             if ($hasaccess || $hasnoaccess) {
 6156:                 if ($hasaccess) {
 6157:                     $access = 1;
 6158:                 } elsif ($hasnoaccess) {
 6159:                     $access = 0; 
 6160:                 }
 6161:                 return $access;
 6162:             }
 6163:         } else {
 6164:             if ($domdef{$tool}{'default'} ne '') {
 6165:                 if ($domdef{$tool}{'default'}) {
 6166:                     $access = 1;
 6167:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6168:                     $access = 0;
 6169:                 }
 6170:                 return $access;
 6171:             }
 6172:         }
 6173:     } else {
 6174:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6175:             $access = 1;
 6176:         } else {
 6177:             $access = 0;
 6178:         }
 6179:         return $access;
 6180:     }
 6181: }
 6182: 
 6183: sub is_course_owner {
 6184:     my ($cdom,$cnum,$udom,$uname) = @_;
 6185:     if (($udom eq '') || ($uname eq '')) {
 6186:         $udom = $env{'user.domain'};
 6187:         $uname = $env{'user.name'};
 6188:     }
 6189:     unless (($udom eq '') || ($uname eq '')) {
 6190:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6191:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6192:                 return 1;
 6193:             } else {
 6194:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6195:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6196:                     return 1;
 6197:                 }
 6198:             }
 6199:         }
 6200:     }
 6201:     return;
 6202: }
 6203: 
 6204: sub is_advanced_user {
 6205:     my ($udom,$uname) = @_;
 6206:     if ($udom ne '' && $uname ne '') {
 6207:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6208:             if (wantarray) {
 6209:                 return ($env{'user.adv'},$env{'user.author'});
 6210:             } else {
 6211:                 return $env{'user.adv'};
 6212:             }
 6213:         }
 6214:     }
 6215:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6216:     my %allroles;
 6217:     my ($is_adv,$is_author);
 6218:     foreach my $role (keys(%roleshash)) {
 6219:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6220:         my $area = '/'.$tdomain.'/'.$trest;
 6221:         if ($sec ne '') {
 6222:             $area .= '/'.$sec;
 6223:         }
 6224:         if (($area ne '') && ($trole ne '')) {
 6225:             my $spec=$trole.'.'.$area;
 6226:             if ($trole =~ /^cr\//) {
 6227:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6228:             } elsif ($trole ne 'gr') {
 6229:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6230:             }
 6231:             if ($trole eq 'au') {
 6232:                 $is_author = 1;
 6233:             }
 6234:         }
 6235:     }
 6236:     foreach my $role (keys(%allroles)) {
 6237:         last if ($is_adv);
 6238:         foreach my $item (split(/:/,$allroles{$role})) {
 6239:             if ($item ne '') {
 6240:                 my ($privilege,$restrictions)=split(/&/,$item);
 6241:                 if ($privilege eq 'adv') {
 6242:                     $is_adv = 1;
 6243:                     last;
 6244:                 }
 6245:             }
 6246:         }
 6247:     }
 6248:     if (wantarray) {
 6249:         return ($is_adv,$is_author);
 6250:     }
 6251:     return $is_adv;
 6252: }
 6253: 
 6254: sub check_can_request {
 6255:     my ($dom,$can_request,$request_domains) = @_;
 6256:     my $canreq = 0;
 6257:     my ($types,$typename) = &Apache::loncommon::course_types();
 6258:     my @options = ('approval','validate','autolimit');
 6259:     my $optregex = join('|',@options);
 6260:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6261:         foreach my $type (@{$types}) {
 6262:             if (&usertools_access($env{'user.name'},
 6263:                                   $env{'user.domain'},
 6264:                                   $type,undef,'requestcourses')) {
 6265:                 $canreq ++;
 6266:                 if (ref($request_domains) eq 'HASH') {
 6267:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6268:                 }
 6269:                 if ($dom eq $env{'user.domain'}) {
 6270:                     $can_request->{$type} = 1;
 6271:                 }
 6272:             }
 6273:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6274:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6275:                 if (@curr > 0) {
 6276:                     foreach my $item (@curr) {
 6277:                         if (ref($request_domains) eq 'HASH') {
 6278:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6279:                             if ($otherdom ne '') {
 6280:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6281:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6282:                                         push(@{$request_domains->{$type}},$otherdom);
 6283:                                     }
 6284:                                 } else {
 6285:                                     push(@{$request_domains->{$type}},$otherdom);
 6286:                                 }
 6287:                             }
 6288:                         }
 6289:                     }
 6290:                     unless($dom eq $env{'user.domain'}) {
 6291:                         $canreq ++;
 6292:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6293:                             $can_request->{$type} = 1;
 6294:                         }
 6295:                     }
 6296:                 }
 6297:             }
 6298:         }
 6299:     }
 6300:     return $canreq;
 6301: }
 6302: 
 6303: # ---------------------------------------------- Custom access rule evaluation
 6304: 
 6305: sub customaccess {
 6306:     my ($priv,$uri)=@_;
 6307:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6308:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6309:     $udom = &LONCAPA::clean_domain($udom);
 6310:     $ucrs = &LONCAPA::clean_username($ucrs);
 6311:     my $access=0;
 6312:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6313: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6314: 	if ($type eq 'user') {
 6315: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6316: 		my ($tdom,$tuname)=split(m{/},$scope);
 6317: 		if ($tdom) {
 6318: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6319: 		}
 6320: 		if ($tuname) {
 6321: 		    if ($tuname ne $env{'user.name'}) { next; }
 6322: 		}
 6323: 		$access=($effect eq 'allow');
 6324: 		last;
 6325: 	    }
 6326: 	} else {
 6327: 	    if ($role) {
 6328: 		if ($role ne $urole) { next; }
 6329: 	    }
 6330: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6331: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6332: 		if ($tdom) {
 6333: 		    if ($tdom ne $udom) { next; }
 6334: 		}
 6335: 		if ($tcrs) {
 6336: 		    if ($tcrs ne $ucrs) { next; }
 6337: 		}
 6338: 		if ($tsec) {
 6339: 		    if ($tsec ne $usec) { next; }
 6340: 		}
 6341: 		$access=($effect eq 'allow');
 6342: 		last;
 6343: 	    }
 6344: 	    if ($realm eq '' && $role eq '') {
 6345: 		$access=($effect eq 'allow');
 6346: 	    }
 6347: 	}
 6348:     }
 6349:     return $access;
 6350: }
 6351: 
 6352: # ------------------------------------------------- Check for a user privilege
 6353: 
 6354: sub allowed {
 6355:     my ($priv,$uri,$symb,$role)=@_;
 6356:     my $ver_orguri=$uri;
 6357:     $uri=&deversion($uri);
 6358:     my $orguri=$uri;
 6359:     $uri=&declutter($uri);
 6360: 
 6361:     if ($priv eq 'evb') {
 6362: # Evade communication block restrictions for specified role in a course
 6363:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6364:             return $1;
 6365:         } else {
 6366:             return;
 6367:         }
 6368:     }
 6369: 
 6370:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6371: # Free bre access to adm and meta resources
 6372:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6373: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6374: 	&& ($priv eq 'bre')) {
 6375: 	return 'F';
 6376:     }
 6377: 
 6378: # Free bre access to user's own portfolio contents
 6379:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6380:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6381: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6382:         my %setters;
 6383:         my ($startblock,$endblock) = 
 6384:             &Apache::loncommon::blockcheck(\%setters,'port');
 6385:         if ($startblock && $endblock) {
 6386:             return 'B';
 6387:         } else {
 6388:             return 'F';
 6389:         }
 6390:     }
 6391: 
 6392: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6393:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6394:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6395:         if (exists($env{'request.course.id'})) {
 6396:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6397:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6398:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6399:                 my $courseprivid=$env{'request.course.id'};
 6400:                 $courseprivid=~s/\_/\//;
 6401:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6402:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6403:                     return $1; 
 6404:                 } else {
 6405:                     if ($env{'request.course.sec'}) {
 6406:                         $courseprivid.='/'.$env{'request.course.sec'};
 6407:                     }
 6408:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6409:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6410:                         return $2;
 6411:                     }
 6412:                 }
 6413:             }
 6414:         }
 6415:     }
 6416: 
 6417: # Free bre to public access
 6418: 
 6419:     if ($priv eq 'bre') {
 6420:         my $copyright=&metadata($uri,'copyright');
 6421: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6422:            return 'F'; 
 6423:         }
 6424:         if ($copyright eq 'priv') {
 6425:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6426: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6427: 		return '';
 6428:             }
 6429:         }
 6430:         if ($copyright eq 'domain') {
 6431:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6432: 	    unless (($env{'user.domain'} eq $1) ||
 6433:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6434: 		return '';
 6435:             }
 6436:         }
 6437:         if ($env{'request.role'}=~ /li\.\//) {
 6438:             # Library role, so allow browsing of resources in this domain.
 6439:             return 'F';
 6440:         }
 6441:         if ($copyright eq 'custom') {
 6442: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6443:         }
 6444:     }
 6445:     # Domain coordinator is trying to create a course
 6446:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6447:         # uri is the requested domain in this case.
 6448:         # comparison to 'request.role.domain' shows if the user has selected
 6449:         # a role of dc for the domain in question.
 6450:         return 'F' if ($uri eq $env{'request.role.domain'});
 6451:     }
 6452: 
 6453:     my $thisallowed='';
 6454:     my $statecond=0;
 6455:     my $courseprivid='';
 6456: 
 6457:     my $ownaccess;
 6458:     # Community Coordinator or Assistant Co-author browsing resource space.
 6459:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6460:         if ($uri eq '') {
 6461:             $ownaccess = 1;
 6462:         } else {
 6463:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6464:                 my $udom = $env{'user.domain'};
 6465:                 my $uname = $env{'user.name'};
 6466:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6467:                     $ownaccess = 1;
 6468:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6469:                     unless ($uri =~ m{\.\./}) {
 6470:                         $ownaccess = 1;
 6471:                     }
 6472:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6473:                     my $now = time;
 6474:                     if ($uri =~ m{^([^/]+)/?$}) {
 6475:                         my $adom = $1;
 6476:                         foreach my $key (keys(%env)) {
 6477:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6478:                                 my ($start,$end) = split('.',$env{$key});
 6479:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6480:                                     $ownaccess = 1;
 6481:                                     last;
 6482:                                 }
 6483:                             }
 6484:                         }
 6485:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6486:                         my $adom = $1;
 6487:                         my $aname = $2;
 6488:                         foreach my $role ('ca','aa') { 
 6489:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6490:                                 my ($start,$end) =
 6491:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6492:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6493:                                     $ownaccess = 1;
 6494:                                     last;
 6495:                                 }
 6496:                             }
 6497:                         }
 6498:                     }
 6499:                 }
 6500:             }
 6501:         }
 6502:     }
 6503: 
 6504: # Course
 6505: 
 6506:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6507:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6508:             $thisallowed.=$1;
 6509:         }
 6510:     }
 6511: 
 6512: # Domain
 6513: 
 6514:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6515:        =~/\Q$priv\E\&([^\:]*)/) {
 6516:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6517:             $thisallowed.=$1;
 6518:         }
 6519:     }
 6520: 
 6521: # User who is not author or co-author might still be able to edit
 6522: # resource of an author in the domain (e.g., if Domain Coordinator).
 6523:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6524:         (&allowed('mdc',$env{'request.course.id'}))) {
 6525:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6526:             $thisallowed.=$1;
 6527:         }
 6528:     }
 6529: 
 6530: # Course: uri itself is a course
 6531:     my $courseuri=$uri;
 6532:     $courseuri=~s/\_(\d)/\/$1/;
 6533:     $courseuri=~s/^([^\/])/\/$1/;
 6534: 
 6535:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6536:        =~/\Q$priv\E\&([^\:]*)/) {
 6537:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6538:             $thisallowed.=$1;
 6539:         }
 6540:     }
 6541: 
 6542: # URI is an uploaded document for this course, default permissions don't matter
 6543: # not allowing 'edit' access (editupload) to uploaded course docs
 6544:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6545: 	$thisallowed='';
 6546:         my ($match)=&is_on_map($uri);
 6547:         if ($match) {
 6548:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6549:                   =~/\Q$priv\E\&([^\:]*)/) {
 6550:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6551:                 if (@blockers > 0) {
 6552:                     $thisallowed = 'B';
 6553:                 } else {
 6554:                     $thisallowed.=$1;
 6555:                 }
 6556:             }
 6557:         } else {
 6558:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6559:             if ($refuri) {
 6560:                 if ($refuri =~ m|^/adm/|) {
 6561:                     $thisallowed='F';
 6562:                 } else {
 6563:                     $refuri=&declutter($refuri);
 6564:                     my ($match) = &is_on_map($refuri);
 6565:                     if ($match) {
 6566:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6567:                         if (@blockers > 0) {
 6568:                             $thisallowed = 'B';
 6569:                         } else {
 6570:                             $thisallowed='F';
 6571:                         }
 6572:                     }
 6573:                 }
 6574:             }
 6575:         }
 6576:     }
 6577: 
 6578:     if ($priv eq 'bre'
 6579: 	&& $thisallowed ne 'F' 
 6580: 	&& $thisallowed ne '2'
 6581: 	&& &is_portfolio_url($uri)) {
 6582: 	$thisallowed = &portfolio_access($uri);
 6583:     }
 6584:     
 6585: # Full access at system, domain or course-wide level? Exit.
 6586:     if ($thisallowed=~/F/) {
 6587: 	return 'F';
 6588:     }
 6589: 
 6590: # If this is generating or modifying users, exit with special codes
 6591: 
 6592:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6593: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6594: 	    my ($audom,$auname)=split('/',$uri);
 6595: # no author name given, so this just checks on the general right to make a co-author in this domain
 6596: 	    unless ($auname) { return $thisallowed; }
 6597: # an author name is given, so we are about to actually make a co-author for a certain account
 6598: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6599: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6600: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6601: 	}
 6602: 	return $thisallowed;
 6603:     }
 6604: #
 6605: # Gathered so far: system, domain and course wide privileges
 6606: #
 6607: # Course: See if uri or referer is an individual resource that is part of 
 6608: # the course
 6609: 
 6610:     if ($env{'request.course.id'}) {
 6611: 
 6612:        $courseprivid=$env{'request.course.id'};
 6613:        if ($env{'request.course.sec'}) {
 6614:           $courseprivid.='/'.$env{'request.course.sec'};
 6615:        }
 6616:        $courseprivid=~s/\_/\//;
 6617:        my $checkreferer=1;
 6618:        my ($match,$cond)=&is_on_map($uri);
 6619:        if ($match) {
 6620:            $statecond=$cond;
 6621:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6622:                =~/\Q$priv\E\&([^\:]*)/) {
 6623:                my $value = $1;
 6624:                if ($priv eq 'bre') {
 6625:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6626:                    if (@blockers > 0) {
 6627:                        $thisallowed = 'B';
 6628:                    } else {
 6629:                        $thisallowed.=$value;
 6630:                    }
 6631:                } else {
 6632:                    $thisallowed.=$value;
 6633:                }
 6634:                $checkreferer=0;
 6635:            }
 6636:        }
 6637:        
 6638:        if ($checkreferer) {
 6639: 	  my $refuri=$env{'httpref.'.$orguri};
 6640:             unless ($refuri) {
 6641:                 foreach my $key (keys(%env)) {
 6642: 		    if ($key=~/^httpref\..*\*/) {
 6643: 			my $pattern=$key;
 6644:                         $pattern=~s/^httpref\.\/res\///;
 6645:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6646:                         $pattern=~s/\//\\\//g;
 6647:                         if ($orguri=~/$pattern/) {
 6648: 			    $refuri=$env{$key};
 6649:                         }
 6650:                     }
 6651:                 }
 6652:             }
 6653: 
 6654:          if ($refuri) { 
 6655: 	  $refuri=&declutter($refuri);
 6656:           my ($match,$cond)=&is_on_map($refuri);
 6657:             if ($match) {
 6658:               my $refstatecond=$cond;
 6659:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6660:                   =~/\Q$priv\E\&([^\:]*)/) {
 6661:                   my $value = $1;
 6662:                   if ($priv eq 'bre') {
 6663:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6664:                       if (@blockers > 0) {
 6665:                           $thisallowed = 'B';
 6666:                       } else {
 6667:                           $thisallowed.=$value;
 6668:                       }
 6669:                   } else {
 6670:                       $thisallowed.=$value;
 6671:                   }
 6672:                   $uri=$refuri;
 6673:                   $statecond=$refstatecond;
 6674:               }
 6675:           }
 6676:         }
 6677:        }
 6678:    }
 6679: 
 6680: #
 6681: # Gathered now: all privileges that could apply, and condition number
 6682: # 
 6683: #
 6684: # Full or no access?
 6685: #
 6686: 
 6687:     if ($thisallowed=~/F/) {
 6688: 	return 'F';
 6689:     }
 6690: 
 6691:     unless ($thisallowed) {
 6692:         return '';
 6693:     }
 6694: 
 6695: # Restrictions exist, deal with them
 6696: #
 6697: #   C:according to course preferences
 6698: #   R:according to resource settings
 6699: #   L:unless locked
 6700: #   X:according to user session state
 6701: #
 6702: 
 6703: # Possibly locked functionality, check all courses
 6704: # Locks might take effect only after 10 minutes cache expiration for other
 6705: # courses, and 2 minutes for current course
 6706: 
 6707:     my $envkey;
 6708:     if ($thisallowed=~/L/) {
 6709:         foreach $envkey (keys(%env)) {
 6710:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6711:                my $courseid=$2;
 6712:                my $roleid=$1.'.'.$2;
 6713:                $courseid=~s/^\///;
 6714:                my $expiretime=600;
 6715:                if ($env{'request.role'} eq $roleid) {
 6716: 		  $expiretime=120;
 6717:                }
 6718: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6719:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6720:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6721: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6722:                }
 6723:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6724:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6725: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6726:                        &log($env{'user.domain'},$env{'user.name'},
 6727:                             $env{'user.home'},
 6728:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6729:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6730:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6731: 		       return '';
 6732:                    }
 6733:                }
 6734:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6735:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6736: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6737:                        &log($env{'user.domain'},$env{'user.name'},
 6738:                             $env{'user.home'},
 6739:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6740:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6741:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6742: 		       return '';
 6743:                    }
 6744:                }
 6745: 	   }
 6746:        }
 6747:     }
 6748:    
 6749: #
 6750: # Rest of the restrictions depend on selected course
 6751: #
 6752: 
 6753:     unless ($env{'request.course.id'}) {
 6754: 	if ($thisallowed eq 'A') {
 6755: 	    return 'A';
 6756:         } elsif ($thisallowed eq 'B') {
 6757:             return 'B';
 6758: 	} else {
 6759: 	    return '1';
 6760: 	}
 6761:     }
 6762: 
 6763: #
 6764: # Now user is definitely in a course
 6765: #
 6766: 
 6767: 
 6768: # Course preferences
 6769: 
 6770:    if ($thisallowed=~/C/) {
 6771:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6772:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6773:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6774: 	   =~/\Q$rolecode\E/) {
 6775: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6776: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6777: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6778: 			$env{'request.course.id'});
 6779: 	   }
 6780:            return '';
 6781:        }
 6782: 
 6783:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6784: 	   =~/\Q$unamedom\E/) {
 6785: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6786: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6787: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6788: 			$env{'request.course.id'});
 6789: 	   }
 6790:            return '';
 6791:        }
 6792:    }
 6793: 
 6794: # Resource preferences
 6795: 
 6796:    if ($thisallowed=~/R/) {
 6797:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6798:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6799: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6800: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6801: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6802: 	   }
 6803: 	   return '';
 6804:        }
 6805:    }
 6806: 
 6807: # Restricted by state or randomout?
 6808: 
 6809:    if ($thisallowed=~/X/) {
 6810:       if ($env{'acc.randomout'}) {
 6811: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6812:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6813:             return ''; 
 6814:          }
 6815:       }
 6816:       if (&condval($statecond)) {
 6817: 	 return '2';
 6818:       } else {
 6819:          return '';
 6820:       }
 6821:    }
 6822: 
 6823:     if ($thisallowed eq 'A') {
 6824: 	return 'A';
 6825:     } elsif ($thisallowed eq 'B') {
 6826:         return 'B';
 6827:     }
 6828:    return 'F';
 6829: }
 6830: 
 6831: # ------------------------------------------- Check construction space access
 6832: 
 6833: sub constructaccess {
 6834:     my ($url,$setpriv)=@_;
 6835: 
 6836: # We do not allow editing of previous versions of files
 6837:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6838: 
 6839: # Get username and domain from URL
 6840:     my ($ownername,$ownerdomain,$ownerhome);
 6841: 
 6842:     ($ownerdomain,$ownername) =
 6843:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6844: 
 6845: # The URL does not really point to any authorspace, forget it
 6846:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6847: 
 6848: # Now we need to see if the user has access to the authorspace of
 6849: # $ownername at $ownerdomain
 6850: 
 6851:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6852: # Real author for this?
 6853:        $ownerhome = $env{'user.home'};
 6854:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6855:           return ($ownername,$ownerdomain,$ownerhome);
 6856:        }
 6857:     } else {
 6858: # Co-author for this?
 6859:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6860:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6861:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6862:             return ($ownername,$ownerdomain,$ownerhome);
 6863:         }
 6864:     }
 6865: 
 6866: # We don't have any access right now. If we are not possibly going to do anything about this,
 6867: # we might as well leave
 6868:    unless ($setpriv) { return ''; }
 6869: 
 6870: # Backdoor access?
 6871:     my $allowed=&allowed('eco',$ownerdomain);
 6872: # Nope
 6873:     unless ($allowed) { return ''; }
 6874: # Looks like we may have access, but could be locked by the owner of the construction space
 6875:     if ($allowed eq 'U') {
 6876:         my %blocked=&get('environment',['domcoord.author'],
 6877:                          $ownerdomain,$ownername);
 6878: # Is blocked by owner
 6879:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 6880:     }
 6881:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 6882: # Grant temporary access
 6883:         my $then=$env{'user.login.time'};
 6884:         my $update==$env{'user.update.time'};
 6885:         if (!$update) { $update = $then; }
 6886:         my $refresh=$env{'user.refresh.time'};
 6887:         if (!$refresh) { $refresh = $update; }
 6888:         my $now = time;
 6889:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 6890:                            $now,'ca','constructaccess');
 6891:         $ownerhome = &homeserver($ownername,$ownerdomain);
 6892:         return($ownername,$ownerdomain,$ownerhome);
 6893:     }
 6894: # No business here
 6895:     return '';
 6896: }
 6897: 
 6898: sub get_comm_blocks {
 6899:     my ($cdom,$cnum) = @_;
 6900:     if ($cdom eq '' || $cnum eq '') {
 6901:         return unless ($env{'request.course.id'});
 6902:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6903:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6904:     }
 6905:     my %commblocks;
 6906:     my $hashid=$cdom.'_'.$cnum;
 6907:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6908:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6909:         %commblocks = %{$blocksref};
 6910:     } else {
 6911:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6912:         my $cachetime = 600;
 6913:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6914:     }
 6915:     return %commblocks;
 6916: }
 6917: 
 6918: sub has_comm_blocking {
 6919:     my ($priv,$symb,$uri,$blocks) = @_;
 6920:     return unless ($env{'request.course.id'});
 6921:     return unless ($priv eq 'bre');
 6922:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6923:     my %commblocks;
 6924:     if (ref($blocks) eq 'HASH') {
 6925:         %commblocks = %{$blocks};
 6926:     } else {
 6927:         %commblocks = &get_comm_blocks();
 6928:     }
 6929:     return unless (keys(%commblocks) > 0);
 6930:     if (!$symb) { $symb=&symbread($uri,1); }
 6931:     my ($map,$resid,undef)=&decode_symb($symb);
 6932:     my %tocheck = (
 6933:                     maps      => $map,
 6934:                     resources => $symb,
 6935:                   );
 6936:     my @blockers;
 6937:     my $now = time;
 6938:     my $navmap = Apache::lonnavmaps::navmap->new();
 6939:     foreach my $block (keys(%commblocks)) {
 6940:         if ($block =~ /^(\d+)____(\d+)$/) {
 6941:             my ($start,$end) = ($1,$2);
 6942:             if ($start <= $now && $end >= $now) {
 6943:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6944:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6945:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6946:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6947:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6948:                                     push(@blockers,$block);
 6949:                                 }
 6950:                             }
 6951:                         }
 6952:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6953:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6954:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6955:                                     push(@blockers,$block);
 6956:                                 }
 6957:                             }
 6958:                         }
 6959:                     }
 6960:                 }
 6961:             }
 6962:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6963:             my $item = $1;
 6964:             my @to_test;
 6965:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6966:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6967:                     my $check_interval;
 6968:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6969:                         my @interval;
 6970:                         my $type = 'map';
 6971:                         if ($item eq 'course') {
 6972:                             $type = 'course';
 6973:                             @interval=&EXT("resource.0.interval");
 6974:                         } else {
 6975:                             if ($item =~ /___\d+___/) {
 6976:                                 $type = 'resource';
 6977:                                 @interval=&EXT("resource.0.interval",$item);
 6978:                                 if (ref($navmap)) {                        
 6979:                                     my $res = $navmap->getBySymb($item); 
 6980:                                     push(@to_test,$res);
 6981:                                 }
 6982:                             } else {
 6983:                                 my $mapsymb = &symbread($item,1);
 6984:                                 if ($mapsymb) {
 6985:                                     if (ref($navmap)) {
 6986:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6987:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6988:                                         foreach my $res (@to_test) {
 6989:                                             my $symb = $res->symb();
 6990:                                             next if ($symb eq $mapsymb);
 6991:                                             if ($symb ne '') {
 6992:                                                 @interval=&EXT("resource.0.interval",$symb);
 6993:                                                 last;
 6994:                                             }
 6995:                                         }
 6996:                                     }
 6997:                                 }
 6998:                             }
 6999:                         }
 7000:                         if ($interval[0] =~ /\d+/) {
 7001:                             my $first_access;
 7002:                             if ($type eq 'resource') {
 7003:                                 $first_access=&get_first_access($interval[1],$item);
 7004:                             } elsif ($type eq 'map') {
 7005:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7006:                             } else {
 7007:                                 $first_access=&get_first_access($interval[1]);
 7008:                             }
 7009:                             if ($first_access) {
 7010:                                 my $timesup = $first_access+$interval[0];
 7011:                                 if ($timesup > $now) {
 7012:                                     foreach my $res (@to_test) {
 7013:                                         if ($res->is_problem()) {
 7014:                                             if ($res->completable()) {
 7015:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7016:                                                     push(@blockers,$block);
 7017:                                                 }
 7018:                                                 last;
 7019:                                             }
 7020:                                         }
 7021:                                     }
 7022:                                 }
 7023:                             }
 7024:                         }
 7025:                     }
 7026:                 }
 7027:             }
 7028:         }
 7029:     }
 7030:     return @blockers;
 7031: }
 7032: 
 7033: sub check_docs_block {
 7034:     my ($docsblock,$tocheck) =@_;
 7035:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7036:         return;
 7037:     }
 7038:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7039:         if ($tocheck->{'maps'}) {
 7040:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7041:                 return 1;
 7042:             }
 7043:         }
 7044:     }
 7045:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7046:         if ($tocheck->{'resources'}) {
 7047:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7048:                 return 1;
 7049:             }
 7050:         }
 7051:     }
 7052:     return;
 7053: }
 7054: 
 7055: #
 7056: #   Removes the versino from a URI and
 7057: #   splits it in to its filename and path to the filename.
 7058: #   Seems like File::Basename could have done this more clearly.
 7059: #   Parameters:
 7060: #      $uri   - input URI
 7061: #   Returns:
 7062: #     Two element list consisting of 
 7063: #     $pathname  - the URI up to and excluding the trailing /
 7064: #     $filename  - The part of the URI following the last /
 7065: #  NOTE:
 7066: #    Another realization of this is simply:
 7067: #    use File::Basename;
 7068: #    ...
 7069: #    $uri = shift;
 7070: #    $filename = basename($uri);
 7071: #    $path     = dirname($uri);
 7072: #    return ($filename, $path);
 7073: #
 7074: #     The implementation below is probably faster however.
 7075: #
 7076: sub split_uri_for_cond {
 7077:     my $uri=&deversion(&declutter(shift));
 7078:     my @uriparts=split(/\//,$uri);
 7079:     my $filename=pop(@uriparts);
 7080:     my $pathname=join('/',@uriparts);
 7081:     return ($pathname,$filename);
 7082: }
 7083: # --------------------------------------------------- Is a resource on the map?
 7084: 
 7085: sub is_on_map {
 7086:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7087:     #Trying to find the conditional for the file
 7088:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7089: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7090:     if ($match) {
 7091: 	return (1,$1);
 7092:     } else {
 7093: 	return (0,0);
 7094:     }
 7095: }
 7096: 
 7097: # --------------------------------------------------------- Get symb from alias
 7098: 
 7099: sub get_symb_from_alias {
 7100:     my $symb=shift;
 7101:     my ($map,$resid,$url)=&decode_symb($symb);
 7102: # Already is a symb
 7103:     if ($url) { return $symb; }
 7104: # Must be an alias
 7105:     my $aliassymb='';
 7106:     my %bighash;
 7107:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7108:                             &GDBM_READER(),0640)) {
 7109:         my $rid=$bighash{'mapalias_'.$symb};
 7110: 	if ($rid) {
 7111: 	    my ($mapid,$resid)=split(/\./,$rid);
 7112: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7113: 				    $resid,$bighash{'src_'.$rid});
 7114: 	}
 7115:         untie %bighash;
 7116:     }
 7117:     return $aliassymb;
 7118: }
 7119: 
 7120: # ----------------------------------------------------------------- Define Role
 7121: 
 7122: sub definerole {
 7123:   if (allowed('mcr','/')) {
 7124:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7125:     foreach my $role (split(':',$sysrole)) {
 7126: 	my ($crole,$cqual)=split(/\&/,$role);
 7127:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7128:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7129: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7130:                return "refused:s:$crole&$cqual"; 
 7131:             }
 7132:         }
 7133:     }
 7134:     foreach my $role (split(':',$domrole)) {
 7135: 	my ($crole,$cqual)=split(/\&/,$role);
 7136:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7137:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7138: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7139:                return "refused:d:$crole&$cqual"; 
 7140:             }
 7141:         }
 7142:     }
 7143:     foreach my $role (split(':',$courole)) {
 7144: 	my ($crole,$cqual)=split(/\&/,$role);
 7145:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7146:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7147: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7148:                return "refused:c:$crole&$cqual"; 
 7149:             }
 7150:         }
 7151:     }
 7152:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7153:                 "$env{'user.domain'}:$env{'user.name'}:".
 7154: 	        "rolesdef_$rolename=".
 7155:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7156:     return reply($command,$env{'user.home'});
 7157:   } else {
 7158:     return 'refused';
 7159:   }
 7160: }
 7161: 
 7162: # ---------------- Make a metadata query against the network of library servers
 7163: 
 7164: sub metadata_query {
 7165:     my ($query,$custom,$customshow,$server_array)=@_;
 7166:     my %rhash;
 7167:     my %libserv = &all_library();
 7168:     my @server_list = (defined($server_array) ? @$server_array
 7169:                                               : keys(%libserv) );
 7170:     for my $server (@server_list) {
 7171: 	unless ($custom or $customshow) {
 7172: 	    my $reply=&reply("querysend:".&escape($query),$server);
 7173: 	    $rhash{$server}=$reply;
 7174: 	}
 7175: 	else {
 7176: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7177: 			     &escape($custom).':'.&escape($customshow),
 7178: 			     $server);
 7179: 	    $rhash{$server}=$reply;
 7180: 	}
 7181:     }
 7182:     return \%rhash;
 7183: }
 7184: 
 7185: # ----------------------------------------- Send log queries and wait for reply
 7186: 
 7187: sub log_query {
 7188:     my ($uname,$udom,$query,%filters)=@_;
 7189:     my $uhome=&homeserver($uname,$udom);
 7190:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7191:     my $uhost=&hostname($uhome);
 7192:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7193:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7194:                        $uhome);
 7195:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7196:     return get_query_reply($queryid);
 7197: }
 7198: 
 7199: # -------------------------- Update MySQL table for portfolio file
 7200: 
 7201: sub update_portfolio_table {
 7202:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7203:     if ($group ne '') {
 7204:         $file_name =~s /^\Q$group\E//;
 7205:     }
 7206:     my $homeserver = &homeserver($uname,$udom);
 7207:     my $queryid=
 7208:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7209:                ':'.&escape($file_name).':'.$action,$homeserver);
 7210:     my $reply = &get_query_reply($queryid);
 7211:     return $reply;
 7212: }
 7213: 
 7214: # -------------------------- Update MySQL allusers table
 7215: 
 7216: sub update_allusers_table {
 7217:     my ($uname,$udom,$names) = @_;
 7218:     my $homeserver = &homeserver($uname,$udom);
 7219:     my $queryid=
 7220:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7221:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7222:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7223:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7224:                'generation='.&escape($names->{'generation'}).'%%'.
 7225:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7226:                'id='.&escape($names->{'id'}),$homeserver);
 7227:     return;
 7228: }
 7229: 
 7230: # ------- Request retrieval of institutional classlists for course(s)
 7231: 
 7232: sub fetch_enrollment_query {
 7233:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7234:     my $homeserver;
 7235:     my $maxtries = 1;
 7236:     if ($context eq 'automated') {
 7237:         $homeserver = $perlvar{'lonHostID'};
 7238:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7239:     } else {
 7240:         $homeserver = &homeserver($cnum,$dom);
 7241:     }
 7242:     my $host=&hostname($homeserver);
 7243:     my $cmd = '';
 7244:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7245:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7246:     }
 7247:     $cmd =~ s/%%$//;
 7248:     $cmd = &escape($cmd);
 7249:     my $query = 'fetchenrollment';
 7250:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7251:     unless ($queryid=~/^\Q$host\E\_/) { 
 7252:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7253:         return 'error: '.$queryid;
 7254:     }
 7255:     my $reply = &get_query_reply($queryid);
 7256:     my $tries = 1;
 7257:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7258:         $reply = &get_query_reply($queryid);
 7259:         $tries ++;
 7260:     }
 7261:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7262:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7263:     } else {
 7264:         my @responses = split(/:/,$reply);
 7265:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7266:             foreach my $line (@responses) {
 7267:                 my ($key,$value) = split(/=/,$line,2);
 7268:                 $$replyref{$key} = $value;
 7269:             }
 7270:         } else {
 7271:             my $pathname = LONCAPA::tempdir();
 7272:             foreach my $line (@responses) {
 7273:                 my ($key,$value) = split(/=/,$line);
 7274:                 $$replyref{$key} = $value;
 7275:                 if ($value > 0) {
 7276:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7277:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7278:                         my $destname = $pathname.'/'.$filename;
 7279:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7280:                         if ($xml_classlist =~ /^error/) {
 7281:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7282:                         } else {
 7283:                             if ( open(FILE,">$destname") ) {
 7284:                                 print FILE &unescape($xml_classlist);
 7285:                                 close(FILE);
 7286:                             } else {
 7287:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7288:                             }
 7289:                         }
 7290:                     }
 7291:                 }
 7292:             }
 7293:         }
 7294:         return 'ok';
 7295:     }
 7296:     return 'error';
 7297: }
 7298: 
 7299: sub get_query_reply {
 7300:     my $queryid=shift;
 7301:     my $replyfile=LONCAPA::tempdir().$queryid;
 7302:     my $reply='';
 7303:     for (1..100) {
 7304: 	sleep 2;
 7305:         if (-e $replyfile.'.end') {
 7306: 	    if (open(my $fh,$replyfile)) {
 7307: 		$reply = join('',<$fh>);
 7308: 		close($fh);
 7309: 	   } else { return 'error: reply_file_error'; }
 7310:            return &unescape($reply);
 7311: 	}
 7312:     }
 7313:     return 'timeout:'.$queryid;
 7314: }
 7315: 
 7316: sub courselog_query {
 7317: #
 7318: # possible filters:
 7319: # url: url or symb
 7320: # username
 7321: # domain
 7322: # action: view, submit, grade
 7323: # start: timestamp
 7324: # end: timestamp
 7325: #
 7326:     my (%filters)=@_;
 7327:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7328:     if ($filters{'url'}) {
 7329: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7330:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7331:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7332:     }
 7333:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7334:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7335:     return &log_query($cname,$cdom,'courselog',%filters);
 7336: }
 7337: 
 7338: sub userlog_query {
 7339: #
 7340: # possible filters:
 7341: # action: log check role
 7342: # start: timestamp
 7343: # end: timestamp
 7344: #
 7345:     my ($uname,$udom,%filters)=@_;
 7346:     return &log_query($uname,$udom,'userlog',%filters);
 7347: }
 7348: 
 7349: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7350: 
 7351: sub auto_run {
 7352:     my ($cnum,$cdom) = @_;
 7353:     my $response = 0;
 7354:     my $settings;
 7355:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7356:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7357:         $settings = $domconfig{'autoenroll'};
 7358:         if ($settings->{'run'} eq '1') {
 7359:             $response = 1;
 7360:         }
 7361:     } else {
 7362:         my $homeserver;
 7363:         if (&is_course($cdom,$cnum)) {
 7364:             $homeserver = &homeserver($cnum,$cdom);
 7365:         } else {
 7366:             $homeserver = &domain($cdom,'primary');
 7367:         }
 7368:         if ($homeserver ne 'no_host') {
 7369:             $response = &reply('autorun:'.$cdom,$homeserver);
 7370:         }
 7371:     }
 7372:     return $response;
 7373: }
 7374: 
 7375: sub auto_get_sections {
 7376:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7377:     my $homeserver;
 7378:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7379:         $homeserver = &homeserver($cnum,$cdom);
 7380:     }
 7381:     if (!defined($homeserver)) { 
 7382:         if ($cdom =~ /^$match_domain$/) {
 7383:             $homeserver = &domain($cdom,'primary');
 7384:         }
 7385:     }
 7386:     my @secs;
 7387:     if (defined($homeserver)) {
 7388:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7389:         unless ($response eq 'refused') {
 7390:             @secs = split(/:/,$response);
 7391:         }
 7392:     }
 7393:     return @secs;
 7394: }
 7395: 
 7396: sub auto_new_course {
 7397:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7398:     my $homeserver = &homeserver($cnum,$cdom);
 7399:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7400:     return $response;
 7401: }
 7402: 
 7403: sub auto_validate_courseID {
 7404:     my ($cnum,$cdom,$inst_course_id) = @_;
 7405:     my $homeserver = &homeserver($cnum,$cdom);
 7406:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7407:     return $response;
 7408: }
 7409: 
 7410: sub auto_validate_instcode {
 7411:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7412:     my ($homeserver,$response);
 7413:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7414:         $homeserver = &homeserver($cnum,$cdom);
 7415:     }
 7416:     if (!defined($homeserver)) {
 7417:         if ($cdom =~ /^$match_domain$/) {
 7418:             $homeserver = &domain($cdom,'primary');
 7419:         }
 7420:     }
 7421:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7422:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7423:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 7424:     return ($outcome,$description);
 7425: }
 7426: 
 7427: sub auto_create_password {
 7428:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7429:     my ($homeserver,$response);
 7430:     my $create_passwd = 0;
 7431:     my $authchk = '';
 7432:     if ($udom =~ /^$match_domain$/) {
 7433:         $homeserver = &domain($udom,'primary');
 7434:     }
 7435:     if ($homeserver eq '') {
 7436:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7437:             $homeserver = &homeserver($cnum,$cdom);
 7438:         }
 7439:     }
 7440:     if ($homeserver eq '') {
 7441:         $authchk = 'nodomain';
 7442:     } else {
 7443:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7444:         if ($response eq 'refused') {
 7445:             $authchk = 'refused';
 7446:         } else {
 7447:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7448:         }
 7449:     }
 7450:     return ($authparam,$create_passwd,$authchk);
 7451: }
 7452: 
 7453: sub auto_photo_permission {
 7454:     my ($cnum,$cdom,$students) = @_;
 7455:     my $homeserver = &homeserver($cnum,$cdom);
 7456:     my ($outcome,$perm_reqd,$conditions) = 
 7457: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7458:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7459: 	return (undef,undef);
 7460:     }
 7461:     return ($outcome,$perm_reqd,$conditions);
 7462: }
 7463: 
 7464: sub auto_checkphotos {
 7465:     my ($uname,$udom,$pid) = @_;
 7466:     my $homeserver = &homeserver($uname,$udom);
 7467:     my ($result,$resulttype);
 7468:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7469: 				   &escape($uname).':'.&escape($pid),
 7470: 				   $homeserver));
 7471:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7472: 	return (undef,undef);
 7473:     }
 7474:     if ($outcome) {
 7475:         ($result,$resulttype) = split(/:/,$outcome);
 7476:     } 
 7477:     return ($result,$resulttype);
 7478: }
 7479: 
 7480: sub auto_photochoice {
 7481:     my ($cnum,$cdom) = @_;
 7482:     my $homeserver = &homeserver($cnum,$cdom);
 7483:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7484: 						       &escape($cdom),
 7485: 						       $homeserver)));
 7486:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7487: 	return (undef,undef);
 7488:     }
 7489:     return ($update,$comment);
 7490: }
 7491: 
 7492: sub auto_photoupdate {
 7493:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7494:     my $homeserver = &homeserver($cnum,$dom);
 7495:     my $host=&hostname($homeserver);
 7496:     my $cmd = '';
 7497:     my $maxtries = 1;
 7498:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7499:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7500:     }
 7501:     $cmd =~ s/%%$//;
 7502:     $cmd = &escape($cmd);
 7503:     my $query = 'institutionalphotos';
 7504:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7505:     unless ($queryid=~/^\Q$host\E\_/) {
 7506:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7507:         return 'error: '.$queryid;
 7508:     }
 7509:     my $reply = &get_query_reply($queryid);
 7510:     my $tries = 1;
 7511:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7512:         $reply = &get_query_reply($queryid);
 7513:         $tries ++;
 7514:     }
 7515:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7516:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7517:     } else {
 7518:         my @responses = split(/:/,$reply);
 7519:         my $outcome = shift(@responses); 
 7520:         foreach my $item (@responses) {
 7521:             my ($key,$value) = split(/=/,$item);
 7522:             $$photo{$key} = $value;
 7523:         }
 7524:         return $outcome;
 7525:     }
 7526:     return 'error';
 7527: }
 7528: 
 7529: sub auto_instcode_format {
 7530:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7531: 	$cat_order) = @_;
 7532:     my $courses = '';
 7533:     my @homeservers;
 7534:     if ($caller eq 'global') {
 7535: 	my %servers = &get_servers($codedom,'library');
 7536: 	foreach my $tryserver (keys(%servers)) {
 7537: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7538: 		push(@homeservers,$tryserver);
 7539: 	    }
 7540:         }
 7541:     } elsif ($caller eq 'requests') {
 7542:         if ($codedom =~ /^$match_domain$/) {
 7543:             my $chome = &domain($codedom,'primary');
 7544:             unless ($chome eq 'no_host') {
 7545:                 push(@homeservers,$chome);
 7546:             }
 7547:         }
 7548:     } else {
 7549:         push(@homeservers,&homeserver($caller,$codedom));
 7550:     }
 7551:     foreach my $code (keys(%{$instcodes})) {
 7552:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7553:     }
 7554:     chop($courses);
 7555:     my $ok_response = 0;
 7556:     my $response;
 7557:     while (@homeservers > 0 && $ok_response == 0) {
 7558:         my $server = shift(@homeservers); 
 7559:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7560:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7561:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7562: 		split(/:/,$response);
 7563:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7564:             push(@{$codetitles},&str2array($codetitles_str));
 7565:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7566:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7567:             $ok_response = 1;
 7568:         }
 7569:     }
 7570:     if ($ok_response) {
 7571:         return 'ok';
 7572:     } else {
 7573:         return $response;
 7574:     }
 7575: }
 7576: 
 7577: sub auto_instcode_defaults {
 7578:     my ($domain,$returnhash,$code_order) = @_;
 7579:     my @homeservers;
 7580: 
 7581:     my %servers = &get_servers($domain,'library');
 7582:     foreach my $tryserver (keys(%servers)) {
 7583: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7584: 	    push(@homeservers,$tryserver);
 7585: 	}
 7586:     }
 7587: 
 7588:     my $response;
 7589:     foreach my $server (@homeservers) {
 7590:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7591:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7592: 	
 7593: 	foreach my $pair (split(/\&/,$response)) {
 7594: 	    my ($name,$value)=split(/\=/,$pair);
 7595: 	    if ($name eq 'code_order') {
 7596: 		@{$code_order} = split(/\&/,&unescape($value));
 7597: 	    } else {
 7598: 		$returnhash->{&unescape($name)}=&unescape($value);
 7599: 	    }
 7600: 	}
 7601: 	return 'ok';
 7602:     }
 7603: 
 7604:     return $response;
 7605: }
 7606: 
 7607: sub auto_possible_instcodes {
 7608:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7609:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7610:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7611:         return;
 7612:     }
 7613:     my (@homeservers,$uhome);
 7614:     if (defined(&domain($domain,'primary'))) {
 7615:         $uhome=&domain($domain,'primary');
 7616:         push(@homeservers,&domain($domain,'primary'));
 7617:     } else {
 7618:         my %servers = &get_servers($domain,'library');
 7619:         foreach my $tryserver (keys(%servers)) {
 7620:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7621:                 push(@homeservers,$tryserver);
 7622:             }
 7623:         }
 7624:     }
 7625:     my $response;
 7626:     foreach my $server (@homeservers) {
 7627:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7628:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7629:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7630:             split(':',$response);
 7631:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7632:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7633:         foreach my $item (split('&',$cat_title)) {   
 7634:             my ($name,$value)=split('=',$item);
 7635:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7636:         }
 7637:         foreach my $item (split('&',$cat_order)) {
 7638:             my ($name,$value)=split('=',$item);
 7639:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7640:         }
 7641:         return 'ok';
 7642:     }
 7643:     return $response;
 7644: }
 7645: 
 7646: sub auto_courserequest_checks {
 7647:     my ($dom) = @_;
 7648:     my ($homeserver,%validations);
 7649:     if ($dom =~ /^$match_domain$/) {
 7650:         $homeserver = &domain($dom,'primary');
 7651:     }
 7652:     unless ($homeserver eq 'no_host') {
 7653:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7654:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7655:             my @items = split(/&/,$response);
 7656:             foreach my $item (@items) {
 7657:                 my ($key,$value) = split('=',$item);
 7658:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7659:             }
 7660:         }
 7661:     }
 7662:     return %validations; 
 7663: }
 7664: 
 7665: sub auto_courserequest_validation {
 7666:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7667:     my ($homeserver,$response);
 7668:     if ($dom =~ /^$match_domain$/) {
 7669:         $homeserver = &domain($dom,'primary');
 7670:     }
 7671:     unless ($homeserver eq 'no_host') {  
 7672:           
 7673:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7674:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7675:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7676:                                     $homeserver));
 7677:     }
 7678:     return $response;
 7679: }
 7680: 
 7681: sub auto_validate_class_sec {
 7682:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7683:     my $homeserver = &homeserver($cnum,$cdom);
 7684:     my $ownerlist;
 7685:     if (ref($owners) eq 'ARRAY') {
 7686:         $ownerlist = join(',',@{$owners});
 7687:     } else {
 7688:         $ownerlist = $owners;
 7689:     }
 7690:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7691:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7692:     return $response;
 7693: }
 7694: 
 7695: # ------------------------------------------------------- Course Group routines
 7696: 
 7697: sub get_coursegroups {
 7698:     my ($cdom,$cnum,$group,$namespace) = @_;
 7699:     return(&dump($namespace,$cdom,$cnum,$group));
 7700: }
 7701: 
 7702: sub modify_coursegroup {
 7703:     my ($cdom,$cnum,$groupsettings) = @_;
 7704:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7705: }
 7706: 
 7707: sub toggle_coursegroup_status {
 7708:     my ($cdom,$cnum,$group,$action) = @_;
 7709:     my ($from_namespace,$to_namespace);
 7710:     if ($action eq 'delete') {
 7711:         $from_namespace = 'coursegroups';
 7712:         $to_namespace = 'deleted_groups';
 7713:     } else {
 7714:         $from_namespace = 'deleted_groups';
 7715:         $to_namespace = 'coursegroups';
 7716:     }
 7717:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7718:     if (my $tmp = &error(%curr_group)) {
 7719:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7720:         return ('read error',$tmp);
 7721:     } else {
 7722:         my %savedsettings = %curr_group; 
 7723:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7724:         my $deloutcome;
 7725:         if ($result eq 'ok') {
 7726:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7727:         } else {
 7728:             return ('write error',$result);
 7729:         }
 7730:         if ($deloutcome eq 'ok') {
 7731:             return 'ok';
 7732:         } else {
 7733:             return ('delete error',$deloutcome);
 7734:         }
 7735:     }
 7736: }
 7737: 
 7738: sub modify_group_roles {
 7739:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7740:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7741:     my $role = 'gr/'.&escape($userprivs);
 7742:     my ($uname,$udom) = split(/:/,$user);
 7743:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7744:     if ($result eq 'ok') {
 7745:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7746:     }
 7747:     return $result;
 7748: }
 7749: 
 7750: sub modify_coursegroup_membership {
 7751:     my ($cdom,$cnum,$membership) = @_;
 7752:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7753:     return $result;
 7754: }
 7755: 
 7756: sub get_active_groups {
 7757:     my ($udom,$uname,$cdom,$cnum) = @_;
 7758:     my $now = time;
 7759:     my %groups = ();
 7760:     foreach my $key (keys(%env)) {
 7761:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7762:             my ($start,$end) = split(/\./,$env{$key});
 7763:             if (($end!=0) && ($end<$now)) { next; }
 7764:             if (($start!=0) && ($start>$now)) { next; }
 7765:             if ($1 eq $cdom && $2 eq $cnum) {
 7766:                 $groups{$3} = $env{$key} ;
 7767:             }
 7768:         }
 7769:     }
 7770:     return %groups;
 7771: }
 7772: 
 7773: sub get_group_membership {
 7774:     my ($cdom,$cnum,$group) = @_;
 7775:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7776: }
 7777: 
 7778: sub get_users_groups {
 7779:     my ($udom,$uname,$courseid) = @_;
 7780:     my @usersgroups;
 7781:     my $cachetime=1800;
 7782: 
 7783:     my $hashid="$udom:$uname:$courseid";
 7784:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7785:     if (defined($cached)) {
 7786:         @usersgroups = split(/:/,$grouplist);
 7787:     } else {  
 7788:         $grouplist = '';
 7789:         my $courseurl = &courseid_to_courseurl($courseid);
 7790:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7791:         my $access_end = $env{'course.'.$courseid.
 7792:                               '.default_enrollment_end_date'};
 7793:         my $now = time;
 7794:         foreach my $key (keys(%roleshash)) {
 7795:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7796:                 my $group = $1;
 7797:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7798:                     my $start = $2;
 7799:                     my $end = $1;
 7800:                     if ($start == -1) { next; } # deleted from group
 7801:                     if (($start!=0) && ($start>$now)) { next; }
 7802:                     if (($end!=0) && ($end<$now)) {
 7803:                         if ($access_end && $access_end < $now) {
 7804:                             if ($access_end - $end < 86400) {
 7805:                                 push(@usersgroups,$group);
 7806:                             }
 7807:                         }
 7808:                         next;
 7809:                     }
 7810:                     push(@usersgroups,$group);
 7811:                 }
 7812:             }
 7813:         }
 7814:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7815:         $grouplist = join(':',@usersgroups);
 7816:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7817:     }
 7818:     return @usersgroups;
 7819: }
 7820: 
 7821: sub devalidate_getgroups_cache {
 7822:     my ($udom,$uname,$cdom,$cnum)=@_;
 7823:     my $courseid = $cdom.'_'.$cnum;
 7824: 
 7825:     my $hashid="$udom:$uname:$courseid";
 7826:     &devalidate_cache_new('getgroups',$hashid);
 7827: }
 7828: 
 7829: # ------------------------------------------------------------------ Plain Text
 7830: 
 7831: sub plaintext {
 7832:     my ($short,$type,$cid,$forcedefault) = @_;
 7833:     if ($short =~ m{^cr/}) {
 7834: 	return (split('/',$short))[-1];
 7835:     }
 7836:     if (!defined($cid)) {
 7837:         $cid = $env{'request.course.id'};
 7838:     }
 7839:     my %rolenames = (
 7840:                       Course    => 'std',
 7841:                       Community => 'alt1',
 7842:                     );
 7843:     if ($cid ne '') {
 7844:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7845:             unless ($forcedefault) {
 7846:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7847:                 &Apache::lonlocal::mt_escape(\$roletext);
 7848:                 return &Apache::lonlocal::mt($roletext);
 7849:             }
 7850:         }
 7851:     }
 7852:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7853:         (defined($rolenames{$type})) && 
 7854:         (defined($prp{$short}{$rolenames{$type}}))) {
 7855:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7856:     } elsif ($cid ne '') {
 7857:         my $crstype = $env{'course.'.$cid.'.type'};
 7858:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7859:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7860:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7861:         }
 7862:     }
 7863:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7864: }
 7865: 
 7866: # ----------------------------------------------------------------- Assign Role
 7867: 
 7868: sub assignrole {
 7869:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7870:         $context)=@_;
 7871:     my $mrole;
 7872:     if ($role =~ /^cr\//) {
 7873:         my $cwosec=$url;
 7874:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7875: 	unless (&allowed('ccr',$cwosec)) {
 7876:            my $refused = 1;
 7877:            if ($context eq 'requestcourses') {
 7878:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7879:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7880:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7881:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7882:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7883:                            if ($crsenv{'internal.courseowner'} eq
 7884:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7885:                                $refused = '';
 7886:                            }
 7887:                        }
 7888:                    }
 7889:                }
 7890:            }
 7891:            if ($refused) {
 7892:                &logthis('Refused custom assignrole: '.
 7893:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7894:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7895:                return 'refused';
 7896:            }
 7897:         }
 7898:         $mrole='cr';
 7899:     } elsif ($role =~ /^gr\//) {
 7900:         my $cwogrp=$url;
 7901:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7902:         unless (&allowed('mdg',$cwogrp)) {
 7903:             &logthis('Refused group assignrole: '.
 7904:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7905:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7906:             return 'refused';
 7907:         }
 7908:         $mrole='gr';
 7909:     } else {
 7910:         my $cwosec=$url;
 7911:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7912:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7913:             my $refused;
 7914:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7915:                 if (!(&allowed('c'.$role,$url))) {
 7916:                     $refused = 1;
 7917:                 }
 7918:             } else {
 7919:                 $refused = 1;
 7920:             }
 7921:             if ($refused) {
 7922:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7923:                 if (!$selfenroll && $context eq 'course') {
 7924:                     my %crsenv;
 7925:                     if ($role eq 'cc' || $role eq 'co') {
 7926:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7927:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7928:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7929:                                 if ($crsenv{'internal.courseowner'} eq 
 7930:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7931:                                     $refused = '';
 7932:                                 }
 7933:                             }
 7934:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7935:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7936:                                 if ($crsenv{'internal.courseowner'} eq 
 7937:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7938:                                     $refused = '';
 7939:                                 }
 7940:                             }
 7941:                         }
 7942:                     }
 7943:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7944:                     $refused = '';
 7945:                 } elsif ($context eq 'requestcourses') {
 7946:                     my @possroles = ('st','ta','ep','in','cc','co');
 7947:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7948:                         my $wrongcc;
 7949:                         if ($cnum =~ /^$match_community$/) {
 7950:                             $wrongcc = 1 if ($role eq 'cc');
 7951:                         } else {
 7952:                             $wrongcc = 1 if ($role eq 'co');
 7953:                         }
 7954:                         unless ($wrongcc) {
 7955:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7956:                             if ($crsenv{'internal.courseowner'} eq 
 7957:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7958:                                 $refused = '';
 7959:                             }
 7960:                         }
 7961:                     }
 7962:                 } elsif ($context eq 'requestauthor') {
 7963:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 7964:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 7965:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 7966:                             $refused = '';
 7967:                         } else {
 7968:                             my %domdefaults = &get_domain_defaults($udom);
 7969:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 7970:                                 my $checkbystatus;
 7971:                                 if ($env{'user.adv'}) { 
 7972:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 7973:                                     if ($disposition eq 'automatic') {
 7974:                                         $refused = '';
 7975:                                     } elsif ($disposition eq '') {
 7976:                                         $checkbystatus = 1;
 7977:                                     } 
 7978:                                 } else {
 7979:                                     $checkbystatus = 1;
 7980:                                 }
 7981:                                 if ($checkbystatus) {
 7982:                                     if ($env{'environment.inststatus'}) {
 7983:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 7984:                                         foreach my $type (@inststatuses) {
 7985:                                             if (($type ne '') &&
 7986:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 7987:                                                 $refused = '';
 7988:                                             }
 7989:                                         }
 7990:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 7991:                                         $refused = '';
 7992:                                     }
 7993:                                 }
 7994:                             }
 7995:                         }
 7996:                     }
 7997:                 }
 7998:                 if ($refused) {
 7999:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8000:                              ' '.$role.' '.$end.' '.$start.' by '.
 8001: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8002:                     return 'refused';
 8003:                 }
 8004:             }
 8005:         } elsif ($role eq 'au') {
 8006:             if ($url ne '/'.$udom.'/') {
 8007:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8008:                          ' to assign author role for '.$uname.':'.$udom.
 8009:                          ' in domain: '.$url.' refused (wrong domain).');
 8010:                 return 'refused';
 8011:             }
 8012:         }
 8013:         $mrole=$role;
 8014:     }
 8015:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8016:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8017:     if ($end) { $command.='_'.$end; }
 8018:     if ($start) {
 8019: 	if ($end) { 
 8020:            $command.='_'.$start; 
 8021:         } else {
 8022:            $command.='_0_'.$start;
 8023:         }
 8024:     }
 8025:     my $origstart = $start;
 8026:     my $origend = $end;
 8027:     my $delflag;
 8028: # actually delete
 8029:     if ($deleteflag) {
 8030: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8031: # modify command to delete the role
 8032:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8033:                 "$udom:$uname:$url".'_'."$mrole";
 8034: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8035: # set start and finish to negative values for userrolelog
 8036:            $start=-1;
 8037:            $end=-1;
 8038:            $delflag = 1;
 8039:         }
 8040:     }
 8041: # send command
 8042:     my $answer=&reply($command,&homeserver($uname,$udom));
 8043: # log new user role if status is ok
 8044:     if ($answer eq 'ok') {
 8045: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8046:         if (($role eq 'cc') || ($role eq 'in') ||
 8047:             ($role eq 'ep') || ($role eq 'ad') ||
 8048:             ($role eq 'ta') || ($role eq 'st') ||
 8049:             ($role=~/^cr/) || ($role eq 'gr') ||
 8050:             ($role eq 'co')) {
 8051: # for course roles, perform group memberships changes triggered by role change.
 8052:             unless ($role =~ /^gr/) {
 8053:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8054:                                                  $origstart,$selfenroll,$context);
 8055:             }
 8056:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8057:                            $selfenroll,$context);
 8058:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8059:                  ($role eq 'au') || ($role eq 'dc')) {
 8060:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8061:                            $context);
 8062:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8063:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8064:                              $context); 
 8065:         }
 8066:         if ($role eq 'cc') {
 8067:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8068:         }
 8069:     }
 8070:     return $answer;
 8071: }
 8072: 
 8073: sub autoupdate_coowners {
 8074:     my ($url,$end,$start,$uname,$udom) = @_;
 8075:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8076:     if (($cdom ne '') && ($cnum ne '')) {
 8077:         my $now = time;
 8078:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8079:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8080:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8081:             my $instcode = $coursehash{'internal.coursecode'};
 8082:             if ($instcode ne '') {
 8083:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8084:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8085:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8086:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8087:                         if ($result eq 'valid') {
 8088:                             if ($coursehash{'internal.co-owners'}) {
 8089:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8090:                                     push(@newcoowners,$coowner);
 8091:                                 }
 8092:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8093:                                     push(@newcoowners,$uname.':'.$udom);
 8094:                                 }
 8095:                                 @newcoowners = sort(@newcoowners);
 8096:                             } else {
 8097:                                 push(@newcoowners,$uname.':'.$udom);
 8098:                             }
 8099:                         } else {
 8100:                             if ($coursehash{'internal.co-owners'}) {
 8101:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8102:                                     unless ($coowner eq $uname.':'.$udom) {
 8103:                                         push(@newcoowners,$coowner);
 8104:                                     }
 8105:                                 }
 8106:                                 unless (@newcoowners > 0) {
 8107:                                     $delcoowners = 1;
 8108:                                     $coowners = '';
 8109:                                 }
 8110:                             }
 8111:                         }
 8112:                         if (@newcoowners || $delcoowners) {
 8113:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8114:                                             $delcoowners,@newcoowners);
 8115:                         }
 8116:                     }
 8117:                 }
 8118:             }
 8119:         }
 8120:     }
 8121: }
 8122: 
 8123: sub store_coowners {
 8124:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8125:     my $cid = $cdom.'_'.$cnum;
 8126:     my ($coowners,$delresult,$putresult);
 8127:     if (@newcoowners) {
 8128:         $coowners = join(',',@newcoowners);
 8129:         my %coownershash = (
 8130:                             'internal.co-owners' => $coowners,
 8131:                            );
 8132:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8133:         if ($putresult eq 'ok') {
 8134:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8135:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8136:             }
 8137:         }
 8138:     }
 8139:     if ($delcoowners) {
 8140:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8141:         if ($delresult eq 'ok') {
 8142:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8143:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8144:             }
 8145:         }
 8146:     }
 8147:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8148:         my %crsinfo =
 8149:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8150:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8151:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8152:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8153:         }
 8154:     }
 8155: }
 8156: 
 8157: # -------------------------------------------------- Modify user authentication
 8158: # Overrides without validation
 8159: 
 8160: sub modifyuserauth {
 8161:     my ($udom,$uname,$umode,$upass)=@_;
 8162:     my $uhome=&homeserver($uname,$udom);
 8163:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8164:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8165:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8166:              ' in domain '.$env{'request.role.domain'});  
 8167:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8168: 		     &escape($upass),$uhome);
 8169:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8170:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8171:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8172:     &log($udom,,$uname,$uhome,
 8173:         'Authentication changed by '.$env{'user.domain'}.', '.
 8174:                                      $env{'user.name'}.', '.$umode.
 8175:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8176:     unless ($reply eq 'ok') {
 8177:         &logthis('Authentication mode error: '.$reply);
 8178: 	return 'error: '.$reply;
 8179:     }   
 8180:     return 'ok';
 8181: }
 8182: 
 8183: # --------------------------------------------------------------- Modify a user
 8184: 
 8185: sub modifyuser {
 8186:     my ($udom,    $uname, $uid,
 8187:         $umode,   $upass, $first,
 8188:         $middle,  $last,  $gene,
 8189:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8190:     $udom= &LONCAPA::clean_domain($udom);
 8191:     $uname=&LONCAPA::clean_username($uname);
 8192:     my $showcandelete = 'none';
 8193:     if (ref($candelete) eq 'ARRAY') {
 8194:         if (@{$candelete} > 0) {
 8195:             $showcandelete = join(', ',@{$candelete});
 8196:         }
 8197:     }
 8198:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8199:              $umode.', '.$first.', '.$middle.', '.
 8200: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8201:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8202:                                      ' desiredhome not specified'). 
 8203:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8204:              ' in domain '.$env{'request.role.domain'});
 8205:     my $uhome=&homeserver($uname,$udom,'true');
 8206:     my $newuser;
 8207:     if ($uhome eq 'no_host') {
 8208:         $newuser = 1;
 8209:     }
 8210: # ----------------------------------------------------------------- Create User
 8211:     if (($uhome eq 'no_host') && 
 8212: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8213:         my $unhome='';
 8214:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8215:             $unhome = $desiredhome;
 8216: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8217: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8218:         } else { # load balancing routine for determining $unhome
 8219:             my $loadm=10000000;
 8220: 	    my %servers = &get_servers($udom,'library');
 8221: 	    foreach my $tryserver (keys(%servers)) {
 8222: 		my $answer=reply('load',$tryserver);
 8223: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8224: 		    $loadm=$answer;
 8225: 		    $unhome=$tryserver;
 8226: 		}
 8227: 	    }
 8228:         }
 8229:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8230: 	    return 'error: unable to find a home server for '.$uname.
 8231:                    ' in domain '.$udom;
 8232:         }
 8233:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8234:                          &escape($upass),$unhome);
 8235: 	unless ($reply eq 'ok') {
 8236:             return 'error: '.$reply;
 8237:         }   
 8238:         $uhome=&homeserver($uname,$udom,'true');
 8239:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8240: 	    return 'error: unable verify users home machine.';
 8241:         }
 8242:     }   # End of creation of new user
 8243: # ---------------------------------------------------------------------- Add ID
 8244:     if ($uid) {
 8245:        $uid=~tr/A-Z/a-z/;
 8246:        my %uidhash=&idrget($udom,$uname);
 8247:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8248:          && (!$forceid)) {
 8249: 	  unless ($uid eq $uidhash{$uname}) {
 8250: 	      return 'error: user id "'.$uid.'" does not match '.
 8251:                   'current user id "'.$uidhash{$uname}.'".';
 8252:           }
 8253:        } else {
 8254: 	  &idput($udom,($uname => $uid));
 8255:        }
 8256:     }
 8257: # -------------------------------------------------------------- Add names, etc
 8258:     my @tmp=&get('environment',
 8259: 		   ['firstname','middlename','lastname','generation','id',
 8260:                     'permanentemail','inststatus'],
 8261: 		   $udom,$uname);
 8262:     my (%names,%oldnames);
 8263:     if ($tmp[0] =~ m/^error:.*/) { 
 8264:         %names=(); 
 8265:     } else {
 8266:         %names = @tmp;
 8267:         %oldnames = %names;
 8268:     }
 8269: #
 8270: # If name, email and/or uid are blank (e.g., because an uploaded file
 8271: # of users did not contain them), do not overwrite existing values
 8272: # unless field is in $candelete array ref.  
 8273: #
 8274: 
 8275:     my @fields = ('firstname','middlename','lastname','generation',
 8276:                   'permanentemail','id');
 8277:     my %newvalues;
 8278:     if (ref($candelete) eq 'ARRAY') {
 8279:         foreach my $field (@fields) {
 8280:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8281:                 if ($field eq 'firstname') {
 8282:                     $names{$field} = $first;
 8283:                 } elsif ($field eq 'middlename') {
 8284:                     $names{$field} = $middle;
 8285:                 } elsif ($field eq 'lastname') {
 8286:                     $names{$field} = $last;
 8287:                 } elsif ($field eq 'generation') { 
 8288:                     $names{$field} = $gene;
 8289:                 } elsif ($field eq 'permanentemail') {
 8290:                     $names{$field} = $email;
 8291:                 } elsif ($field eq 'id') {
 8292:                     $names{$field}  = $uid;
 8293:                 }
 8294:             }
 8295:         }
 8296:     }
 8297:     if ($first)  { $names{'firstname'}  = $first; }
 8298:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8299:     if ($last)   { $names{'lastname'}   = $last; }
 8300:     if (defined($gene))   { $names{'generation'} = $gene; }
 8301:     if ($email) {
 8302:        $email=~s/[^\w\@\.\-\,]//gs;
 8303:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8304:     }
 8305:     if ($uid) { $names{'id'}  = $uid; }
 8306:     if (defined($inststatus)) {
 8307:         $names{'inststatus'} = '';
 8308:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8309:         if (ref($usertypes) eq 'HASH') {
 8310:             my @okstatuses; 
 8311:             foreach my $item (split(/:/,$inststatus)) {
 8312:                 if (defined($usertypes->{$item})) {
 8313:                     push(@okstatuses,$item);  
 8314:                 }
 8315:             }
 8316:             if (@okstatuses) {
 8317:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8318:             }
 8319:         }
 8320:     }
 8321:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8322:                  $umode.', '.$first.', '.$middle.', '.
 8323:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8324:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8325:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8326:     } else {
 8327:         $logmsg .= ' during self creation';
 8328:     }
 8329:     my $changed;
 8330:     if ($newuser) {
 8331:         $changed = 1;
 8332:     } else {
 8333:         foreach my $field (@fields) {
 8334:             if ($names{$field} ne $oldnames{$field}) {
 8335:                 $changed = 1;
 8336:                 last;
 8337:             }
 8338:         }
 8339:     }
 8340:     unless ($changed) {
 8341:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8342:         &logthis($logmsg);
 8343:         return 'ok';
 8344:     }
 8345:     my $reply = &put('environment', \%names, $udom,$uname);
 8346:     if ($reply ne 'ok') { 
 8347:         return 'error: '.$reply;
 8348:     }
 8349:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8350:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8351:     }
 8352:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8353:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8354:     $logmsg = 'Success modifying user '.$logmsg;
 8355:     &logthis($logmsg);
 8356:     return 'ok';
 8357: }
 8358: 
 8359: # -------------------------------------------------------------- Modify student
 8360: 
 8361: sub modifystudent {
 8362:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8363:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8364:         $selfenroll,$context,$inststatus)=@_;
 8365:     if (!$cid) {
 8366: 	unless ($cid=$env{'request.course.id'}) {
 8367: 	    return 'not_in_class';
 8368: 	}
 8369:     }
 8370: # --------------------------------------------------------------- Make the user
 8371:     my $reply=&modifyuser
 8372: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8373:          $desiredhome,$email,$inststatus);
 8374:     unless ($reply eq 'ok') { return $reply; }
 8375:     # This will cause &modify_student_enrollment to get the uid from the
 8376:     # students environment
 8377:     $uid = undef if (!$forceid);
 8378:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8379: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 8380:     return $reply;
 8381: }
 8382: 
 8383: sub modify_student_enrollment {
 8384:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 8385:     my ($cdom,$cnum,$chome);
 8386:     if (!$cid) {
 8387: 	unless ($cid=$env{'request.course.id'}) {
 8388: 	    return 'not_in_class';
 8389: 	}
 8390: 	$cdom=$env{'course.'.$cid.'.domain'};
 8391: 	$cnum=$env{'course.'.$cid.'.num'};
 8392:     } else {
 8393: 	($cdom,$cnum)=split(/_/,$cid);
 8394:     }
 8395:     $chome=$env{'course.'.$cid.'.home'};
 8396:     if (!$chome) {
 8397: 	$chome=&homeserver($cnum,$cdom);
 8398:     }
 8399:     if (!$chome) { return 'unknown_course'; }
 8400:     # Make sure the user exists
 8401:     my $uhome=&homeserver($uname,$udom);
 8402:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8403: 	return 'error: no such user';
 8404:     }
 8405:     # Get student data if we were not given enough information
 8406:     if (!defined($first)  || $first  eq '' || 
 8407:         !defined($last)   || $last   eq '' || 
 8408:         !defined($uid)    || $uid    eq '' || 
 8409:         !defined($middle) || $middle eq '' || 
 8410:         !defined($gene)   || $gene   eq '') {
 8411:         # They did not supply us with enough data to enroll the student, so
 8412:         # we need to pick up more information.
 8413:         my %tmp = &get('environment',
 8414:                        ['firstname','middlename','lastname', 'generation','id']
 8415:                        ,$udom,$uname);
 8416: 
 8417:         #foreach my $key (keys(%tmp)) {
 8418:         #    &logthis("key $key = ".$tmp{$key});
 8419:         #}
 8420:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8421:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8422:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8423:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8424:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8425:     }
 8426:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8427:     my $user = "$uname:$udom";
 8428:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8429:     my $reply=cput('classlist',
 8430: 		   {$user => 
 8431: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 8432: 		   $cdom,$cnum);
 8433:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8434:         &devalidate_getsection_cache($udom,$uname,$cid);
 8435:     } else { 
 8436: 	return 'error: '.$reply;
 8437:     }
 8438:     # Add student role to user
 8439:     my $uurl='/'.$cid;
 8440:     $uurl=~s/\_/\//g;
 8441:     if ($usec) {
 8442: 	$uurl.='/'.$usec;
 8443:     }
 8444:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8445:                              $selfenroll,$context);
 8446:     if ($result ne 'ok') {
 8447:         if ($old_entry{$user} ne '') {
 8448:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8449:         } else {
 8450:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8451:         }
 8452:     }
 8453:     return $result; 
 8454: }
 8455: 
 8456: sub format_name {
 8457:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8458:     my $name;
 8459:     if ($first ne 'lastname') {
 8460: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8461:     } else {
 8462: 	if ($lastname=~/\S/) {
 8463: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8464: 	    $name=~s/\s+,/,/;
 8465: 	} else {
 8466: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8467: 	}
 8468:     }
 8469:     $name=~s/^\s+//;
 8470:     $name=~s/\s+$//;
 8471:     $name=~s/\s+/ /g;
 8472:     return $name;
 8473: }
 8474: 
 8475: # ------------------------------------------------- Write to course preferences
 8476: 
 8477: sub writecoursepref {
 8478:     my ($courseid,%prefs)=@_;
 8479:     $courseid=~s/^\///;
 8480:     $courseid=~s/\_/\//g;
 8481:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8482:     my $chome=homeserver($cnum,$cdomain);
 8483:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8484: 	return 'error: no such course';
 8485:     }
 8486:     my $cstring='';
 8487:     foreach my $pref (keys(%prefs)) {
 8488: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8489:     }
 8490:     $cstring=~s/\&$//;
 8491:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8492: }
 8493: 
 8494: # ---------------------------------------------------------- Make/modify course
 8495: 
 8496: sub createcourse {
 8497:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8498:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8499:     $url=&declutter($url);
 8500:     my $cid='';
 8501:     if ($context eq 'requestcourses') {
 8502:         my $can_create = 0;
 8503:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8504:         if ($udom eq $ownerdom) {
 8505:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8506:                                   $context)) {
 8507:                 $can_create = 1;
 8508:             }
 8509:         } else {
 8510:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8511:                                            $category);
 8512:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8513:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8514:                 if (@curr > 0) {
 8515:                     my @options = qw(approval validate autolimit);
 8516:                     my $optregex = join('|',@options);
 8517:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8518:                         $can_create = 1;
 8519:                     }
 8520:                 }
 8521:             }
 8522:         }
 8523:         if ($can_create) {
 8524:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8525:                 unless (&allowed('ccc',$udom)) {
 8526:                     return 'refused'; 
 8527:                 }
 8528:             }
 8529:         } else {
 8530:             return 'refused';
 8531:         }
 8532:     } elsif (!&allowed('ccc',$udom)) {
 8533:         return 'refused';
 8534:     }
 8535: # --------------------------------------------------------------- Get Unique ID
 8536:     my $uname;
 8537:     if ($cnum =~ /^$match_courseid$/) {
 8538:         my $chome=&homeserver($cnum,$udom,'true');
 8539:         if (($chome eq '') || ($chome eq 'no_host')) {
 8540:             $uname = $cnum;
 8541:         } else {
 8542:             $uname = &generate_coursenum($udom,$crstype);
 8543:         }
 8544:     } else {
 8545:         $uname = &generate_coursenum($udom,$crstype);
 8546:     }
 8547:     return $uname if ($uname =~ /^error/);
 8548: # -------------------------------------------------- Check supplied server name
 8549:     if (!defined($course_server)) {
 8550:         if (defined(&domain($udom,'primary'))) {
 8551:             $course_server = &domain($udom,'primary');
 8552:         } else {
 8553:             $course_server = $env{'user.home'}; 
 8554:         }
 8555:     }
 8556:     my %host_servers =
 8557:         &Apache::lonnet::get_servers($udom,'library');
 8558:     unless ($host_servers{$course_server}) {
 8559:         return 'error: invalid home server for course: '.$course_server;
 8560:     }
 8561: # ------------------------------------------------------------- Make the course
 8562:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8563:                       $course_server);
 8564:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8565:     my $uhome=&homeserver($uname,$udom,'true');
 8566:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8567: 	return 'error: no such course';
 8568:     }
 8569: # ----------------------------------------------------------------- Course made
 8570: # log existence
 8571:     my $now = time;
 8572:     my $newcourse = {
 8573:                     $udom.'_'.$uname => {
 8574:                                      description => $description,
 8575:                                      inst_code   => $inst_code,
 8576:                                      owner       => $course_owner,
 8577:                                      type        => $crstype,
 8578:                                      creator     => $env{'user.name'}.':'.
 8579:                                                     $env{'user.domain'},
 8580:                                      created     => $now,
 8581:                                      context     => $context,
 8582:                                                 },
 8583:                     };
 8584:     &courseidput($udom,$newcourse,$uhome,'notime');
 8585: # set toplevel url
 8586:     my $topurl=$url;
 8587:     unless ($nonstandard) {
 8588: # ------------------------------------------ For standard courses, make top url
 8589:         my $mapurl=&clutter($url);
 8590:         if ($mapurl eq '/res/') { $mapurl=''; }
 8591:         $env{'form.initmap'}=(<<ENDINITMAP);
 8592: <map>
 8593: <resource id="1" type="start"></resource>
 8594: <resource id="2" src="$mapurl"></resource>
 8595: <resource id="3" type="finish"></resource>
 8596: <link index="1" from="1" to="2"></link>
 8597: <link index="2" from="2" to="3"></link>
 8598: </map>
 8599: ENDINITMAP
 8600:         $topurl=&declutter(
 8601:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8602:                           );
 8603:     }
 8604: # ----------------------------------------------------------- Write preferences
 8605:     &writecoursepref($udom.'_'.$uname,
 8606:                      ('description'              => $description,
 8607:                       'url'                      => $topurl,
 8608:                       'internal.creator'         => $env{'user.name'}.':'.
 8609:                                                     $env{'user.domain'},
 8610:                       'internal.created'         => $now,
 8611:                       'internal.creationcontext' => $context)
 8612:                     );
 8613:     return '/'.$udom.'/'.$uname;
 8614: }
 8615: 
 8616: # ------------------------------------------------------------------- Create ID
 8617: sub generate_coursenum {
 8618:     my ($udom,$crstype) = @_;
 8619:     my $domdesc = &domain($udom);
 8620:     return 'error: invalid domain' if ($domdesc eq '');
 8621:     my $first;
 8622:     if ($crstype eq 'Community') {
 8623:         $first = '0';
 8624:     } else {
 8625:         $first = int(1+rand(9)); 
 8626:     } 
 8627:     my $uname=$first.
 8628:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8629:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8630:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8631: # ----------------------------------------------- Make sure that does not exist
 8632:     my $uhome=&homeserver($uname,$udom,'true');
 8633:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8634:         if ($crstype eq 'Community') {
 8635:             $first = '0';
 8636:         } else {
 8637:             $first = int(1+rand(9));
 8638:         }
 8639:         $uname=$first.
 8640:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8641:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8642:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8643:         $uhome=&homeserver($uname,$udom,'true');
 8644:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8645:             return 'error: unable to generate unique course-ID';
 8646:         }
 8647:     }
 8648:     return $uname;
 8649: }
 8650: 
 8651: sub is_course {
 8652:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8653:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8654: 
 8655:     return unless $cdom and $cnum;
 8656: 
 8657:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8658:         '.');
 8659: 
 8660:     return unless exists($courses{$cdom.'_'.$cnum});
 8661:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8662: }
 8663: 
 8664: sub store_userdata {
 8665:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8666:     my $result;
 8667:     if ($datakey ne '') {
 8668:         if (ref($storehash) eq 'HASH') {
 8669:             if ($udom eq '' || $uname eq '') {
 8670:                 $udom = $env{'user.domain'};
 8671:                 $uname = $env{'user.name'};
 8672:             }
 8673:             my $uhome=&homeserver($uname,$udom);
 8674:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8675:                 $result = 'error: no_host';
 8676:             } else {
 8677:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8678:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8679: 
 8680:                 my $namevalue='';
 8681:                 foreach my $key (keys(%{$storehash})) {
 8682:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8683:                 }
 8684:                 $namevalue=~s/\&$//;
 8685:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8686:                                   $namevalue,$uhome);
 8687:             }
 8688:         } else {
 8689:             $result = 'error: data to store was not a hash reference'; 
 8690:         }
 8691:     } else {
 8692:         $result= 'error: invalid requestkey'; 
 8693:     }
 8694:     return $result;
 8695: }
 8696: 
 8697: # ---------------------------------------------------------- Assign Custom Role
 8698: 
 8699: sub assigncustomrole {
 8700:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8701:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8702:                        $end,$start,$deleteflag,$selfenroll,$context);
 8703: }
 8704: 
 8705: # ----------------------------------------------------------------- Revoke Role
 8706: 
 8707: sub revokerole {
 8708:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8709:     my $now=time;
 8710:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8711: }
 8712: 
 8713: # ---------------------------------------------------------- Revoke Custom Role
 8714: 
 8715: sub revokecustomrole {
 8716:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8717:     my $now=time;
 8718:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8719:            $deleteflag,$selfenroll,$context);
 8720: }
 8721: 
 8722: # ------------------------------------------------------------ Disk usage
 8723: sub diskusage {
 8724:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8725:     $directorypath =~ s/\/$//;
 8726:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8727:                        .&escape($getpropath).':'.&escape($uname).':'
 8728:                        .&escape($udom),homeserver($uname,$udom));
 8729:     if ($listing eq 'unknown_cmd') {
 8730:         if ($getpropath) {
 8731:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8732:         }
 8733:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8734:     }
 8735:     return $listing;
 8736: }
 8737: 
 8738: sub is_locked {
 8739:     my ($file_name, $domain, $user, $which) = @_;
 8740:     my @check;
 8741:     my $is_locked;
 8742:     push (@check,$file_name);
 8743:     my %locked = &get('file_permissions',\@check,
 8744: 		      $env{'user.domain'},$env{'user.name'});
 8745:     my ($tmp)=keys(%locked);
 8746:     if ($tmp=~/^error:/) { undef(%locked); }
 8747:     
 8748:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8749:         $is_locked = 'false';
 8750:         foreach my $entry (@{$locked{$file_name}}) {
 8751:            if (ref($entry) eq 'ARRAY') {
 8752:                $is_locked = 'true';
 8753:                if (ref($which) eq 'ARRAY') {
 8754:                    push(@{$which},$entry);
 8755:                } else {
 8756:                    last;
 8757:                }
 8758:            }
 8759:        }
 8760:     } else {
 8761:         $is_locked = 'false';
 8762:     }
 8763:     return $is_locked;
 8764: }
 8765: 
 8766: sub declutter_portfile {
 8767:     my ($file) = @_;
 8768:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8769:     return $file;
 8770: }
 8771: 
 8772: # ------------------------------------------------------------- Mark as Read Only
 8773: 
 8774: sub mark_as_readonly {
 8775:     my ($domain,$user,$files,$what) = @_;
 8776:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8777:     my ($tmp)=keys(%current_permissions);
 8778:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8779:     foreach my $file (@{$files}) {
 8780: 	$file = &declutter_portfile($file);
 8781:         push(@{$current_permissions{$file}},$what);
 8782:     }
 8783:     &put('file_permissions',\%current_permissions,$domain,$user);
 8784:     return;
 8785: }
 8786: 
 8787: # ------------------------------------------------------------Save Selected Files
 8788: 
 8789: sub save_selected_files {
 8790:     my ($user, $path, @files) = @_;
 8791:     my $filename = $user."savedfiles";
 8792:     my @other_files = &files_not_in_path($user, $path);
 8793:     open (OUT, '>'.$tmpdir.$filename);
 8794:     foreach my $file (@files) {
 8795:         print (OUT $env{'form.currentpath'}.$file."\n");
 8796:     }
 8797:     foreach my $file (@other_files) {
 8798:         print (OUT $file."\n");
 8799:     }
 8800:     close (OUT);
 8801:     return 'ok';
 8802: }
 8803: 
 8804: sub clear_selected_files {
 8805:     my ($user) = @_;
 8806:     my $filename = $user."savedfiles";
 8807:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8808:     print (OUT undef);
 8809:     close (OUT);
 8810:     return ("ok");    
 8811: }
 8812: 
 8813: sub files_in_path {
 8814:     my ($user, $path) = @_;
 8815:     my $filename = $user."savedfiles";
 8816:     my %return_files;
 8817:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8818:     while (my $line_in = <IN>) {
 8819:         chomp ($line_in);
 8820:         my @paths_and_file = split (m!/!, $line_in);
 8821:         my $file_part = pop (@paths_and_file);
 8822:         my $path_part = join ('/', @paths_and_file);
 8823:         $path_part.='/';
 8824:         my $path_and_file = $path_part.$file_part;
 8825:         if ($path_part eq $path) {
 8826:             $return_files{$file_part}= 'selected';
 8827:         }
 8828:     }
 8829:     close (IN);
 8830:     return (\%return_files);
 8831: }
 8832: 
 8833: # called in portfolio select mode, to show files selected NOT in current directory
 8834: sub files_not_in_path {
 8835:     my ($user, $path) = @_;
 8836:     my $filename = $user."savedfiles";
 8837:     my @return_files;
 8838:     my $path_part;
 8839:     open(IN, '<'.LONCAPA::.$filename);
 8840:     while (my $line = <IN>) {
 8841:         #ok, I know it's clunky, but I want it to work
 8842:         my @paths_and_file = split(m|/|, $line);
 8843:         my $file_part = pop(@paths_and_file);
 8844:         chomp($file_part);
 8845:         my $path_part = join('/', @paths_and_file);
 8846:         $path_part .= '/';
 8847:         my $path_and_file = $path_part.$file_part;
 8848:         if ($path_part ne $path) {
 8849:             push(@return_files, ($path_and_file));
 8850:         }
 8851:     }
 8852:     close(OUT);
 8853:     return (@return_files);
 8854: }
 8855: 
 8856: #----------------------------------------------Get portfolio file permissions
 8857: 
 8858: sub get_portfile_permissions {
 8859:     my ($domain,$user) = @_;
 8860:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8861:     my ($tmp)=keys(%current_permissions);
 8862:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8863:     return \%current_permissions;
 8864: }
 8865: 
 8866: #---------------------------------------------Get portfolio file access controls
 8867: 
 8868: sub get_access_controls {
 8869:     my ($current_permissions,$group,$file) = @_;
 8870:     my %access;
 8871:     my $real_file = $file;
 8872:     $file =~ s/\.meta$//;
 8873:     if (defined($file)) {
 8874:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8875:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8876:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8877:             }
 8878:         }
 8879:     } else {
 8880:         foreach my $key (keys(%{$current_permissions})) {
 8881:             if ($key =~ /\0accesscontrol$/) {
 8882:                 if (defined($group)) {
 8883:                     if ($key !~ m-^\Q$group\E/-) {
 8884:                         next;
 8885:                     }
 8886:                 }
 8887:                 my ($fullpath) = split(/\0/,$key);
 8888:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8889:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8890:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8891:                     }
 8892:                 }
 8893:             }
 8894:         }
 8895:     }
 8896:     return %access;
 8897: }
 8898: 
 8899: sub modify_access_controls {
 8900:     my ($file_name,$changes,$domain,$user)=@_;
 8901:     my ($outcome,$deloutcome);
 8902:     my %store_permissions;
 8903:     my %new_values;
 8904:     my %new_control;
 8905:     my %translation;
 8906:     my @deletions = ();
 8907:     my $now = time;
 8908:     if (exists($$changes{'activate'})) {
 8909:         if (ref($$changes{'activate'}) eq 'HASH') {
 8910:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8911:             my $numnew = scalar(@newitems);
 8912:             for (my $i=0; $i<$numnew; $i++) {
 8913:                 my $newkey = $newitems[$i];
 8914:                 my $newid = &Apache::loncommon::get_cgi_id();
 8915:                 if ($newkey =~ /^\d+:/) { 
 8916:                     $newkey =~ s/^(\d+)/$newid/;
 8917:                     $translation{$1} = $newid;
 8918:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8919:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8920:                     $translation{$1} = $newid;
 8921:                 }
 8922:                 $new_values{$file_name."\0".$newkey} = 
 8923:                                           $$changes{'activate'}{$newitems[$i]};
 8924:                 $new_control{$newkey} = $now;
 8925:             }
 8926:         }
 8927:     }
 8928:     my %todelete;
 8929:     my %changed_items;
 8930:     foreach my $action ('delete','update') {
 8931:         if (exists($$changes{$action})) {
 8932:             if (ref($$changes{$action}) eq 'HASH') {
 8933:                 foreach my $key (keys(%{$$changes{$action}})) {
 8934:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8935:                     if ($action eq 'delete') { 
 8936:                         $todelete{$itemnum} = 1;
 8937:                     } else {
 8938:                         $changed_items{$itemnum} = $key;
 8939:                     }
 8940:                 }
 8941:             }
 8942:         }
 8943:     }
 8944:     # get lock on access controls for file.
 8945:     my $lockhash = {
 8946:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8947:                                                        ':'.$env{'user.domain'},
 8948:                    }; 
 8949:     my $tries = 0;
 8950:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8951:    
 8952:     while (($gotlock ne 'ok') && $tries <3) {
 8953:         $tries ++;
 8954:         sleep 1;
 8955:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8956:     }
 8957:     if ($gotlock eq 'ok') {
 8958:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8959:         my ($tmp)=keys(%curr_permissions);
 8960:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8961:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8962:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8963:             if (ref($curr_controls) eq 'HASH') {
 8964:                 foreach my $control_item (keys(%{$curr_controls})) {
 8965:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8966:                     if (defined($todelete{$itemnum})) {
 8967:                         push(@deletions,$file_name."\0".$control_item);
 8968:                     } else {
 8969:                         if (defined($changed_items{$itemnum})) {
 8970:                             $new_control{$changed_items{$itemnum}} = $now;
 8971:                             push(@deletions,$file_name."\0".$control_item);
 8972:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8973:                         } else {
 8974:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8975:                         }
 8976:                     }
 8977:                 }
 8978:             }
 8979:         }
 8980:         my ($group);
 8981:         if (&is_course($domain,$user)) {
 8982:             ($group,my $file) = split(/\//,$file_name,2);
 8983:         }
 8984:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8985:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8986:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8987:         #  remove lock
 8988:         my @del_lock = ($file_name."\0".'locked_access_records');
 8989:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8990:         my $sqlresult =
 8991:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8992:                                     $group);
 8993:     } else {
 8994:         $outcome = "error: could not obtain lockfile\n";  
 8995:     }
 8996:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8997: }
 8998: 
 8999: sub make_public_indefinitely {
 9000:     my ($requrl) = @_;
 9001:     my $now = time;
 9002:     my $action = 'activate';
 9003:     my $aclnum = 0;
 9004:     if (&is_portfolio_url($requrl)) {
 9005:         my (undef,$udom,$unum,$file_name,$group) =
 9006:             &parse_portfolio_url($requrl);
 9007:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9008:         my %access_controls = &get_access_controls($current_perms,
 9009:                                                    $group,$file_name);
 9010:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9011:             my ($num,$scope,$end,$start) = 
 9012:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9013:             if ($scope eq 'public') {
 9014:                 if ($start <= $now && $end == 0) {
 9015:                     $action = 'none';
 9016:                 } else {
 9017:                     $action = 'update';
 9018:                     $aclnum = $num;
 9019:                 }
 9020:                 last;
 9021:             }
 9022:         }
 9023:         if ($action eq 'none') {
 9024:              return 'ok';
 9025:         } else {
 9026:             my %changes;
 9027:             my $newend = 0;
 9028:             my $newstart = $now;
 9029:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9030:             $changes{$action}{$newkey} = {
 9031:                 type => 'public',
 9032:                 time => {
 9033:                     start => $newstart,
 9034:                     end   => $newend,
 9035:                 },
 9036:             };
 9037:             my ($outcome,$deloutcome,$new_values,$translation) =
 9038:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9039:             return $outcome;
 9040:         }
 9041:     } else {
 9042:         return 'invalid';
 9043:     }
 9044: }
 9045: 
 9046: #------------------------------------------------------Get Marked as Read Only
 9047: 
 9048: sub get_marked_as_readonly {
 9049:     my ($domain,$user,$what,$group) = @_;
 9050:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9051:     my @readonly_files;
 9052:     my $cmp1=$what;
 9053:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9054:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9055:         if (defined($group)) {
 9056:             if ($file_name !~ m-^\Q$group\E/-) {
 9057:                 next;
 9058:             }
 9059:         }
 9060:         if (ref($value) eq "ARRAY"){
 9061:             foreach my $stored_what (@{$value}) {
 9062:                 my $cmp2=$stored_what;
 9063:                 if (ref($stored_what) eq 'ARRAY') {
 9064:                     $cmp2=join('',@{$stored_what});
 9065:                 }
 9066:                 if ($cmp1 eq $cmp2) {
 9067:                     push(@readonly_files, $file_name);
 9068:                     last;
 9069:                 } elsif (!defined($what)) {
 9070:                     push(@readonly_files, $file_name);
 9071:                     last;
 9072:                 }
 9073:             }
 9074:         }
 9075:     }
 9076:     return @readonly_files;
 9077: }
 9078: #-----------------------------------------------------------Get Marked as Read Only Hash
 9079: 
 9080: sub get_marked_as_readonly_hash {
 9081:     my ($current_permissions,$group,$what) = @_;
 9082:     my %readonly_files;
 9083:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9084:         if (defined($group)) {
 9085:             if ($file_name !~ m-^\Q$group\E/-) {
 9086:                 next;
 9087:             }
 9088:         }
 9089:         if (ref($value) eq "ARRAY"){
 9090:             foreach my $stored_what (@{$value}) {
 9091:                 if (ref($stored_what) eq 'ARRAY') {
 9092:                     foreach my $lock_descriptor(@{$stored_what}) {
 9093:                         if ($lock_descriptor eq 'graded') {
 9094:                             $readonly_files{$file_name} = 'graded';
 9095:                         } elsif ($lock_descriptor eq 'handback') {
 9096:                             $readonly_files{$file_name} = 'handback';
 9097:                         } else {
 9098:                             if (!exists($readonly_files{$file_name})) {
 9099:                                 $readonly_files{$file_name} = 'locked';
 9100:                             }
 9101:                         }
 9102:                     }
 9103:                 } 
 9104:             }
 9105:         } 
 9106:     }
 9107:     return %readonly_files;
 9108: }
 9109: # ------------------------------------------------------------ Unmark as Read Only
 9110: 
 9111: sub unmark_as_readonly {
 9112:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9113:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9114:     my ($domain,$user,$what,$file_name,$group) = @_;
 9115:     $file_name = &declutter_portfile($file_name);
 9116:     my $symb_crs = $what;
 9117:     if (ref($what)) { $symb_crs=join('',@$what); }
 9118:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9119:     my ($tmp)=keys(%current_permissions);
 9120:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9121:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9122:     foreach my $file (@readonly_files) {
 9123: 	my $clean_file = &declutter_portfile($file);
 9124: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9125: 	my $current_locks = $current_permissions{$file};
 9126:         my @new_locks;
 9127:         my @del_keys;
 9128:         if (ref($current_locks) eq "ARRAY"){
 9129:             foreach my $locker (@{$current_locks}) {
 9130:                 my $compare=$locker;
 9131:                 if (ref($locker) eq 'ARRAY') {
 9132:                     $compare=join('',@{$locker});
 9133:                     if ($compare ne $symb_crs) {
 9134:                         push(@new_locks, $locker);
 9135:                     }
 9136:                 }
 9137:             }
 9138:             if (scalar(@new_locks) > 0) {
 9139:                 $current_permissions{$file} = \@new_locks;
 9140:             } else {
 9141:                 push(@del_keys, $file);
 9142:                 &del('file_permissions',\@del_keys, $domain, $user);
 9143:                 delete($current_permissions{$file});
 9144:             }
 9145:         }
 9146:     }
 9147:     &put('file_permissions',\%current_permissions,$domain,$user);
 9148:     return;
 9149: }
 9150: 
 9151: # ------------------------------------------------------------ Directory lister
 9152: 
 9153: sub dirlist {
 9154:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9155:     $uri=~s/^\///;
 9156:     $uri=~s/\/$//;
 9157:     my ($udom, $uname);
 9158:     if ($getuserdir) {
 9159:         $udom = $userdomain;
 9160:         $uname = $username;
 9161:     } else {
 9162:         (undef,$udom,$uname)=split(/\//,$uri);
 9163:         if(defined($userdomain)) {
 9164:             $udom = $userdomain;
 9165:         }
 9166:         if(defined($username)) {
 9167:             $uname = $username;
 9168:         }
 9169:     }
 9170:     my ($dirRoot,$listing,@listing_results);
 9171: 
 9172:     $dirRoot = $perlvar{'lonDocRoot'};
 9173:     if (defined($getpropath)) {
 9174:         $dirRoot = &propath($udom,$uname);
 9175:         $dirRoot =~ s/\/$//;
 9176:     } elsif (defined($getuserdir)) {
 9177:         my $subdir=$uname.'__';
 9178:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9179:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9180:                    ."/$udom/$subdir/$uname";
 9181:     } elsif (defined($alternateRoot)) {
 9182:         $dirRoot = $alternateRoot;
 9183:     }
 9184: 
 9185:     if($udom) {
 9186:         if($uname) {
 9187:             my $uhome = &homeserver($uname,$udom);
 9188:             if ($uhome eq 'no_host') {
 9189:                 return ([],'no_host');
 9190:             }
 9191:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9192:                               .$getuserdir.':'.&escape($dirRoot)
 9193:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9194:             if ($listing eq 'unknown_cmd') {
 9195:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9196:             } else {
 9197:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9198:             }
 9199:             if ($listing eq 'unknown_cmd') {
 9200:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9201:                 @listing_results = split(/:/,$listing);
 9202:             } else {
 9203:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9204:             }
 9205:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9206:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9207:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9208:                 return ([],$listing);
 9209:             } else {
 9210:                 return (\@listing_results);
 9211:             }
 9212:         } elsif(!$alternateRoot) {
 9213:             my (%allusers,%listerror);
 9214: 	    my %servers = &get_servers($udom,'library');
 9215:  	    foreach my $tryserver (keys(%servers)) {
 9216:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9217:                                   &escape($udom),$tryserver);
 9218:                 if ($listing eq 'unknown_cmd') {
 9219: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9220: 				      $udom, $tryserver);
 9221:                 } else {
 9222:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9223:                 }
 9224: 		if ($listing eq 'unknown_cmd') {
 9225: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9226: 				      $udom, $tryserver);
 9227: 		    @listing_results = split(/:/,$listing);
 9228: 		} else {
 9229: 		    @listing_results =
 9230: 			map { &unescape($_); } split(/:/,$listing);
 9231: 		}
 9232:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9233:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9234:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9235:                     $listerror{$tryserver} = $listing;
 9236:                 } else {
 9237: 		    foreach my $line (@listing_results) {
 9238: 			my ($entry) = split(/&/,$line,2);
 9239: 			$allusers{$entry} = 1;
 9240: 		    }
 9241: 		}
 9242:             }
 9243:             my @alluserslist=();
 9244:             foreach my $user (sort(keys(%allusers))) {
 9245:                 push(@alluserslist,$user.'&user');
 9246:             }
 9247:             return (\@alluserslist);
 9248:         } else {
 9249:             return ([],'missing username');
 9250:         }
 9251:     } elsif(!defined($getpropath)) {
 9252:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9253:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9254:         return (\@all_domains);
 9255:     } else {
 9256:         return ([],'missing domain');
 9257:     }
 9258: }
 9259: 
 9260: # --------------------------------------------- GetFileTimestamp
 9261: # This function utilizes dirlist and returns the date stamp for
 9262: # when it was last modified.  It will also return an error of -1
 9263: # if an error occurs
 9264: 
 9265: sub GetFileTimestamp {
 9266:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9267:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9268:     $studentName   = &LONCAPA::clean_username($studentName);
 9269:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9270:                                     undef,$getuserdir);
 9271:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9272:         return -1;
 9273:     }
 9274:     if (ref($fileref) eq 'ARRAY') {
 9275:         my @stats = split('&',$fileref->[0]);
 9276:         # @stats contains first the filename, then the stat output
 9277:         return $stats[10]; # so this is 10 instead of 9.
 9278:     } else {
 9279:         return -1;
 9280:     }
 9281: }
 9282: 
 9283: sub stat_file {
 9284:     my ($uri) = @_;
 9285:     $uri = &clutter_with_no_wrapper($uri);
 9286: 
 9287:     my ($udom,$uname,$file);
 9288:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9289: 	($udom,$uname,$file) =
 9290: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9291: 	$file = 'userfiles/'.$file;
 9292:     }
 9293:     if ($uri =~ m-^/res/-) {
 9294: 	($udom,$uname) = 
 9295: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9296: 	$file = $uri;
 9297:     }
 9298: 
 9299:     if (!$udom || !$uname || !$file) {
 9300: 	# unable to handle the uri
 9301: 	return ();
 9302:     }
 9303:     my $getpropath;
 9304:     if ($file =~ /^userfiles\//) {
 9305:         $getpropath = 1;
 9306:     }
 9307:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9308:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9309:         return ();
 9310:     } else {
 9311:         if (ref($listref) eq 'ARRAY') {
 9312:             my @stats = split('&',$listref->[0]);
 9313: 	    shift(@stats); #filename is first
 9314: 	    return @stats;
 9315:         }
 9316:     }
 9317:     return ();
 9318: }
 9319: 
 9320: # -------------------------------------------------------- Value of a Condition
 9321: 
 9322: # gets the value of a specific preevaluated condition
 9323: #    stored in the string  $env{user.state.<cid>}
 9324: # or looks up a condition reference in the bighash and if if hasn't
 9325: # already been evaluated recurses into docondval to get the value of
 9326: # the condition, then memoizing it to 
 9327: #   $env{user.state.<cid>.<condition>}
 9328: sub directcondval {
 9329:     my $number=shift;
 9330:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9331: 	&Apache::lonuserstate::evalstate();
 9332:     }
 9333:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9334: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9335:     } elsif ($number =~ /^_/) {
 9336: 	my $sub_condition;
 9337: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9338: 		&GDBM_READER(),0640)) {
 9339: 	    $sub_condition=$bighash{'conditions'.$number};
 9340: 	    untie(%bighash);
 9341: 	}
 9342: 	my $value = &docondval($sub_condition);
 9343: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9344: 	return $value;
 9345:     }
 9346:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9347:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9348:     } else {
 9349:        return 2;
 9350:     }
 9351: }
 9352: 
 9353: # get the collection of conditions for this resource
 9354: sub condval {
 9355:     my $condidx=shift;
 9356:     my $allpathcond='';
 9357:     foreach my $cond (split(/\|/,$condidx)) {
 9358: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9359: 	    $allpathcond.=
 9360: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9361: 	}
 9362:     }
 9363:     $allpathcond=~s/\|$//;
 9364:     return &docondval($allpathcond);
 9365: }
 9366: 
 9367: #evaluates an expression of conditions
 9368: sub docondval {
 9369:     my ($allpathcond) = @_;
 9370:     my $result=0;
 9371:     if ($env{'request.course.id'}
 9372: 	&& defined($allpathcond)) {
 9373: 	my $operand='|';
 9374: 	my @stack;
 9375: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9376: 	    if ($chunk eq '(') {
 9377: 		push @stack,($operand,$result);
 9378: 	    } elsif ($chunk eq ')') {
 9379: 		my $before=pop @stack;
 9380: 		if (pop @stack eq '&') {
 9381: 		    $result=$result>$before?$before:$result;
 9382: 		} else {
 9383: 		    $result=$result>$before?$result:$before;
 9384: 		}
 9385: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9386: 		$operand=$chunk;
 9387: 	    } else {
 9388: 		my $new=directcondval($chunk);
 9389: 		if ($operand eq '&') {
 9390: 		    $result=$result>$new?$new:$result;
 9391: 		} else {
 9392: 		    $result=$result>$new?$result:$new;
 9393: 		}
 9394: 	    }
 9395: 	}
 9396:     }
 9397:     return $result;
 9398: }
 9399: 
 9400: # ---------------------------------------------------- Devalidate courseresdata
 9401: 
 9402: sub devalidatecourseresdata {
 9403:     my ($coursenum,$coursedomain)=@_;
 9404:     my $hashid=$coursenum.':'.$coursedomain;
 9405:     &devalidate_cache_new('courseres',$hashid);
 9406: }
 9407: 
 9408: 
 9409: # --------------------------------------------------- Course Resourcedata Query
 9410: #
 9411: #  Parameters:
 9412: #      $coursenum    - Number of the course.
 9413: #      $coursedomain - Domain at which the course was created.
 9414: #  Returns:
 9415: #     A hash of the course parameters along (I think) with timestamps
 9416: #     and version info.
 9417: 
 9418: sub get_courseresdata {
 9419:     my ($coursenum,$coursedomain)=@_;
 9420:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9421:     my $hashid=$coursenum.':'.$coursedomain;
 9422:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9423:     my %dumpreply;
 9424:     unless (defined($cached)) {
 9425: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9426: 	$result=\%dumpreply;
 9427: 	my ($tmp) = keys(%dumpreply);
 9428: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9429: 	    &do_cache_new('courseres',$hashid,$result,600);
 9430: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9431: 	    return $tmp;
 9432: 	} elsif ($tmp =~ /^(error)/) {
 9433: 	    $result=undef;
 9434: 	    &do_cache_new('courseres',$hashid,$result,600);
 9435: 	}
 9436:     }
 9437:     return $result;
 9438: }
 9439: 
 9440: sub devalidateuserresdata {
 9441:     my ($uname,$udom)=@_;
 9442:     my $hashid="$udom:$uname";
 9443:     &devalidate_cache_new('userres',$hashid);
 9444: }
 9445: 
 9446: sub get_userresdata {
 9447:     my ($uname,$udom)=@_;
 9448:     #most student don\'t have any data set, check if there is some data
 9449:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9450: 
 9451:     my $hashid="$udom:$uname";
 9452:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9453:     if (!defined($cached)) {
 9454: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9455: 	$result=\%resourcedata;
 9456: 	&do_cache_new('userres',$hashid,$result,600);
 9457:     }
 9458:     my ($tmp)=keys(%$result);
 9459:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9460: 	return $result;
 9461:     }
 9462:     #error 2 occurs when the .db doesn't exist
 9463:     if ($tmp!~/error: 2 /) {
 9464: 	&logthis("<font color=\"blue\">WARNING:".
 9465: 		 " Trying to get resource data for ".
 9466: 		 $uname." at ".$udom.": ".
 9467: 		 $tmp."</font>");
 9468:     } elsif ($tmp=~/error: 2 /) {
 9469: 	#&EXT_cache_set($udom,$uname);
 9470: 	&do_cache_new('userres',$hashid,undef,600);
 9471: 	undef($tmp); # not really an error so don't send it back
 9472:     }
 9473:     return $tmp;
 9474: }
 9475: #----------------------------------------------- resdata - return resource data
 9476: #  Purpose:
 9477: #    Return resource data for either users or for a course.
 9478: #  Parameters:
 9479: #     $name      - Course/user name.
 9480: #     $domain    - Name of the domain the user/course is registered on.
 9481: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9482: #     @which     - Array of names of resources desired.
 9483: #  Returns:
 9484: #     The value of the first reasource in @which that is found in the
 9485: #     resource hash.
 9486: #  Exceptional Conditions:
 9487: #     If the $type passed in is not valid (not the string 'course' or 
 9488: #     'user', an undefined  reference is returned.
 9489: #     If none of the resources are found, an undef is returned
 9490: sub resdata {
 9491:     my ($name,$domain,$type,@which)=@_;
 9492:     my $result;
 9493:     if ($type eq 'course') {
 9494: 	$result=&get_courseresdata($name,$domain);
 9495:     } elsif ($type eq 'user') {
 9496: 	$result=&get_userresdata($name,$domain);
 9497:     }
 9498:     if (!ref($result)) { return $result; }    
 9499:     foreach my $item (@which) {
 9500: 	if (defined($result->{$item->[0]})) {
 9501: 	    return [$result->{$item->[0]},$item->[1]];
 9502: 	}
 9503:     }
 9504:     return undef;
 9505: }
 9506: 
 9507: #
 9508: # EXT resource caching routines
 9509: #
 9510: 
 9511: sub clear_EXT_cache_status {
 9512:     &delenv('cache.EXT.');
 9513: }
 9514: 
 9515: sub EXT_cache_status {
 9516:     my ($target_domain,$target_user) = @_;
 9517:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9518:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9519:         # We know already the user has no data
 9520:         return 1;
 9521:     } else {
 9522:         return 0;
 9523:     }
 9524: }
 9525: 
 9526: sub EXT_cache_set {
 9527:     my ($target_domain,$target_user) = @_;
 9528:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9529:     #&appenv({$cachename => time});
 9530: }
 9531: 
 9532: # --------------------------------------------------------- Value of a Variable
 9533: sub EXT {
 9534: 
 9535:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 9536:     unless ($varname) { return ''; }
 9537:     #get real user name/domain, courseid and symb
 9538:     my $courseid;
 9539:     my $publicuser;
 9540:     if ($symbparm) {
 9541: 	$symbparm=&get_symb_from_alias($symbparm);
 9542:     }
 9543:     if (!($uname && $udom)) {
 9544:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9545:       if (!$symbparm) {	$symbparm=$cursymb; }
 9546:     } else {
 9547: 	$courseid=$env{'request.course.id'};
 9548:     }
 9549:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9550:     my $rest;
 9551:     if (defined($therest[0])) {
 9552:        $rest=join('.',@therest);
 9553:     } else {
 9554:        $rest='';
 9555:     }
 9556: 
 9557:     my $qualifierrest=$qualifier;
 9558:     if ($rest) { $qualifierrest.='.'.$rest; }
 9559:     my $spacequalifierrest=$space;
 9560:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9561:     if ($realm eq 'user') {
 9562: # --------------------------------------------------------------- user.resource
 9563: 	if ($space eq 'resource') {
 9564: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9565: 		  || defined($Apache::lonhomework::parsing_a_task))
 9566: 		 &&
 9567: 		 ($symbparm eq &symbread()) ) {	
 9568: 		# if we are in the middle of processing the resource the
 9569: 		# get the value we are planning on committing
 9570:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9571:                     return $Apache::lonhomework::results{$qualifierrest};
 9572:                 } else {
 9573:                     return $Apache::lonhomework::history{$qualifierrest};
 9574:                 }
 9575: 	    } else {
 9576: 		my %restored;
 9577: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9578: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9579: 		} else {
 9580: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9581: 		}
 9582: 		return $restored{$qualifierrest};
 9583: 	    }
 9584: # ----------------------------------------------------------------- user.access
 9585:         } elsif ($space eq 'access') {
 9586: 	    # FIXME - not supporting calls for a specific user
 9587:             return &allowed($qualifier,$rest);
 9588: # ------------------------------------------ user.preferences, user.environment
 9589:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9590: 	    if (($uname eq $env{'user.name'}) &&
 9591: 		($udom eq $env{'user.domain'})) {
 9592: 		return $env{join('.',('environment',$qualifierrest))};
 9593: 	    } else {
 9594: 		my %returnhash;
 9595: 		if (!$publicuser) {
 9596: 		    %returnhash=&userenvironment($udom,$uname,
 9597: 						 $qualifierrest);
 9598: 		}
 9599: 		return $returnhash{$qualifierrest};
 9600: 	    }
 9601: # ----------------------------------------------------------------- user.course
 9602:         } elsif ($space eq 'course') {
 9603: 	    # FIXME - not supporting calls for a specific user
 9604:             return $env{join('.',('request.course',$qualifier))};
 9605: # ------------------------------------------------------------------- user.role
 9606:         } elsif ($space eq 'role') {
 9607: 	    # FIXME - not supporting calls for a specific user
 9608:             my ($role,$where)=split(/\./,$env{'request.role'});
 9609:             if ($qualifier eq 'value') {
 9610: 		return $role;
 9611:             } elsif ($qualifier eq 'extent') {
 9612:                 return $where;
 9613:             }
 9614: # ----------------------------------------------------------------- user.domain
 9615:         } elsif ($space eq 'domain') {
 9616:             return $udom;
 9617: # ------------------------------------------------------------------- user.name
 9618:         } elsif ($space eq 'name') {
 9619:             return $uname;
 9620: # ---------------------------------------------------- Any other user namespace
 9621:         } else {
 9622: 	    my %reply;
 9623: 	    if (!$publicuser) {
 9624: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9625: 	    }
 9626: 	    return $reply{$qualifierrest};
 9627:         }
 9628:     } elsif ($realm eq 'query') {
 9629: # ---------------------------------------------- pull stuff out of query string
 9630:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9631: 						[$spacequalifierrest]);
 9632: 	return $env{'form.'.$spacequalifierrest}; 
 9633:    } elsif ($realm eq 'request') {
 9634: # ------------------------------------------------------------- request.browser
 9635:         if ($space eq 'browser') {
 9636:             return $env{'browser.'.$qualifier};
 9637: # ------------------------------------------------------------ request.filename
 9638:         } else {
 9639:             return $env{'request.'.$spacequalifierrest};
 9640:         }
 9641:     } elsif ($realm eq 'course') {
 9642: # ---------------------------------------------------------- course.description
 9643:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9644:     } elsif ($realm eq 'resource') {
 9645: 
 9646: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9647: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9648: 	}
 9649: 
 9650: 	if ($space eq 'title') {
 9651: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9652: 	    return &gettitle($symbparm);
 9653: 	}
 9654: 	
 9655: 	if ($space eq 'map') {
 9656: 	    my ($map) = &decode_symb($symbparm);
 9657: 	    return &symbread($map);
 9658: 	}
 9659: 	if ($space eq 'filename') {
 9660: 	    if ($symbparm) {
 9661: 		return &clutter((&decode_symb($symbparm))[2]);
 9662: 	    }
 9663: 	    return &hreflocation('',$env{'request.filename'});
 9664: 	}
 9665: 
 9666: 	my ($section, $group, @groups);
 9667: 	my ($courselevelm,$courselevel);
 9668: 	if ($symbparm && defined($courseid) && 
 9669: 	    $courseid eq $env{'request.course.id'}) {
 9670: 
 9671: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9672: 
 9673: # ----------------------------------------------------- Cascading lookup scheme
 9674: 	    my $symbp=$symbparm;
 9675: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9676: 
 9677: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9678: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9679: 
 9680: 	    if (($env{'user.name'} eq $uname) &&
 9681: 		($env{'user.domain'} eq $udom)) {
 9682: 		$section=$env{'request.course.sec'};
 9683:                 @groups = split(/:/,$env{'request.course.groups'});  
 9684:                 @groups=&sort_course_groups($courseid,@groups); 
 9685: 	    } else {
 9686: 		if (! defined($usection)) {
 9687: 		    $section=&getsection($udom,$uname,$courseid);
 9688: 		} else {
 9689: 		    $section = $usection;
 9690: 		}
 9691:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9692: 	    }
 9693: 
 9694: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9695: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9696: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9697: 
 9698: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9699: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9700: 	    $courselevelm=$courseid.'.'.$mapparm;
 9701: 
 9702: # ----------------------------------------------------------- first, check user
 9703: 
 9704: 	    my $userreply=&resdata($uname,$udom,'user',
 9705: 				       ([$courselevelr,'resource'],
 9706: 					[$courselevelm,'map'     ],
 9707: 					[$courselevel, 'course'  ]));
 9708: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9709: 
 9710: # ------------------------------------------------ second, check some of course
 9711:             my $coursereply;
 9712:             if (@groups > 0) {
 9713:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9714:                                        $mapparm,$spacequalifierrest);
 9715:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9716:             }
 9717: 
 9718: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9719: 				  $env{'course.'.$courseid.'.domain'},
 9720: 				  'course',
 9721: 				  ([$seclevelr,   'resource'],
 9722: 				   [$seclevelm,   'map'     ],
 9723: 				   [$seclevel,    'course'  ],
 9724: 				   [$courselevelr,'resource']));
 9725: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9726: 
 9727: # ------------------------------------------------------ third, check map parms
 9728: 	    my %parmhash=();
 9729: 	    my $thisparm='';
 9730: 	    if (tie(%parmhash,'GDBM_File',
 9731: 		    $env{'request.course.fn'}.'_parms.db',
 9732: 		    &GDBM_READER(),0640)) {
 9733: 		$thisparm=$parmhash{$symbparm};
 9734: 		untie(%parmhash);
 9735: 	    }
 9736: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9737: 	}
 9738: # ------------------------------------------ fourth, look in resource metadata
 9739: 
 9740: 	$spacequalifierrest=~s/\./\_/;
 9741: 	my $filename;
 9742: 	if (!$symbparm) { $symbparm=&symbread(); }
 9743: 	if ($symbparm) {
 9744: 	    $filename=(&decode_symb($symbparm))[2];
 9745: 	} else {
 9746: 	    $filename=$env{'request.filename'};
 9747: 	}
 9748: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9749: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9750: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9751: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9752: 
 9753: # ---------------------------------------------- fourth, look in rest of course
 9754: 	if ($symbparm && defined($courseid) && 
 9755: 	    $courseid eq $env{'request.course.id'}) {
 9756: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9757: 				     $env{'course.'.$courseid.'.domain'},
 9758: 				     'course',
 9759: 				     ([$courselevelm,'map'   ],
 9760: 				      [$courselevel, 'course']));
 9761: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9762: 	}
 9763: # ------------------------------------------------------------------ Cascade up
 9764: 	unless ($space eq '0') {
 9765: 	    my @parts=split(/_/,$space);
 9766: 	    my $id=pop(@parts);
 9767: 	    my $part=join('_',@parts);
 9768: 	    if ($part eq '') { $part='0'; }
 9769: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9770: 				 $symbparm,$udom,$uname,$section,1);
 9771: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9772: 	}
 9773: 	if ($recurse) { return undef; }
 9774: 	my $pack_def=&packages_tab_default($filename,$varname);
 9775: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9776: # ---------------------------------------------------- Any other user namespace
 9777:     } elsif ($realm eq 'environment') {
 9778: # ----------------------------------------------------------------- environment
 9779: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9780: 	    return $env{'environment.'.$spacequalifierrest};
 9781: 	} else {
 9782: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9783: 		return '';
 9784: 	    }
 9785: 	    my %returnhash=&userenvironment($udom,$uname,
 9786: 					    $spacequalifierrest);
 9787: 	    return $returnhash{$spacequalifierrest};
 9788: 	}
 9789:     } elsif ($realm eq 'system') {
 9790: # ----------------------------------------------------------------- system.time
 9791: 	if ($space eq 'time') {
 9792: 	    return time;
 9793:         }
 9794:     } elsif ($realm eq 'server') {
 9795: # ----------------------------------------------------------------- system.time
 9796: 	if ($space eq 'name') {
 9797: 	    return $ENV{'SERVER_NAME'};
 9798:         }
 9799:     }
 9800:     return '';
 9801: }
 9802: 
 9803: sub get_reply {
 9804:     my ($reply_value) = @_;
 9805:     if (ref($reply_value) eq 'ARRAY') {
 9806:         if (wantarray) {
 9807: 	    return @$reply_value;
 9808:         }
 9809:         return $reply_value->[0];
 9810:     } else {
 9811:         return $reply_value;
 9812:     }
 9813: }
 9814: 
 9815: sub check_group_parms {
 9816:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9817:     my @groupitems = ();
 9818:     my $resultitem;
 9819:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9820:     foreach my $group (@{$groups}) {
 9821:         foreach my $level (@levels) {
 9822:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9823:              push(@groupitems,[$item,$level->[1]]);
 9824:         }
 9825:     }
 9826:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9827:                             $env{'course.'.$courseid.'.domain'},
 9828:                                      'course',@groupitems);
 9829:     return $coursereply;
 9830: }
 9831: 
 9832: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9833:     my ($courseid,@groups) = @_;
 9834:     @groups = sort(@groups);
 9835:     return @groups;
 9836: }
 9837: 
 9838: sub packages_tab_default {
 9839:     my ($uri,$varname)=@_;
 9840:     my (undef,$part,$name)=split(/\./,$varname);
 9841: 
 9842:     my (@extension,@specifics,$do_default);
 9843:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9844: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9845: 	if ($pack_type eq 'default') {
 9846: 	    $do_default=1;
 9847: 	} elsif ($pack_type eq 'extension') {
 9848: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9849: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9850: 	    # only look at packages defaults for packages that this id is
 9851: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9852: 	}
 9853:     }
 9854:     # first look for a package that matches the requested part id
 9855:     foreach my $package (@specifics) {
 9856: 	my (undef,$pack_type,$pack_part)=@{$package};
 9857: 	next if ($pack_part ne $part);
 9858: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9859: 	    return $packagetab{"$pack_type&$name&default"};
 9860: 	}
 9861:     }
 9862:     # look for any possible matching non extension_ package
 9863:     foreach my $package (@specifics) {
 9864: 	my (undef,$pack_type,$pack_part)=@{$package};
 9865: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9866: 	    return $packagetab{"$pack_type&$name&default"};
 9867: 	}
 9868: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9869: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9870: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9871: 	}
 9872:     }
 9873:     # look for any posible extension_ match
 9874:     foreach my $package (@extension) {
 9875: 	my ($package,$pack_type)=@{$package};
 9876: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9877: 	    return $packagetab{"$pack_type&$name&default"};
 9878: 	}
 9879: 	if (defined($packagetab{$package."&$name&default"})) {
 9880: 	    return $packagetab{$package."&$name&default"};
 9881: 	}
 9882:     }
 9883:     # look for a global default setting
 9884:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9885: 	return $packagetab{"default&$name&default"};
 9886:     }
 9887:     return undef;
 9888: }
 9889: 
 9890: sub add_prefix_and_part {
 9891:     my ($prefix,$part)=@_;
 9892:     my $keyroot;
 9893:     if (defined($prefix) && $prefix !~ /^__/) {
 9894: 	# prefix that has a part already
 9895: 	$keyroot=$prefix;
 9896:     } elsif (defined($prefix)) {
 9897: 	# prefix that is missing a part
 9898: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9899:     } else {
 9900: 	# no prefix at all
 9901: 	if (defined($part)) { $keyroot='_'.$part; }
 9902:     }
 9903:     return $keyroot;
 9904: }
 9905: 
 9906: # ---------------------------------------------------------------- Get metadata
 9907: 
 9908: my %metaentry;
 9909: my %importedpartids;
 9910: sub metadata {
 9911:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9912:     $uri=&declutter($uri);
 9913:     # if it is a non metadata possible uri return quickly
 9914:     if (($uri eq '') || 
 9915: 	(($uri =~ m|^/*adm/|) && 
 9916: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9917:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9918: 	return undef;
 9919:     }
 9920:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9921: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9922: 	return undef;
 9923:     }
 9924:     my $filename=$uri;
 9925:     $uri=~s/\.meta$//;
 9926: #
 9927: # Is the metadata already cached?
 9928: # Look at timestamp of caching
 9929: # Everything is cached by the main uri, libraries are never directly cached
 9930: #
 9931:     if (!defined($liburi)) {
 9932: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9933: 	if (defined($cached)) { return $result->{':'.$what}; }
 9934:     }
 9935:     {
 9936: # Imported parts would go here
 9937:         my %importedids=();
 9938:         my @origfileimportpartids=();
 9939:         my $importedparts=0;
 9940: #
 9941: # Is this a recursive call for a library?
 9942: #
 9943: #	if (! exists($metacache{$uri})) {
 9944: #	    $metacache{$uri}={};
 9945: #	}
 9946: 	my $cachetime = 60*60;
 9947:         if ($liburi) {
 9948: 	    $liburi=&declutter($liburi);
 9949:             $filename=$liburi;
 9950:         } else {
 9951: 	    &devalidate_cache_new('meta',$uri);
 9952: 	    undef(%metaentry);
 9953: 	}
 9954:         my %metathesekeys=();
 9955:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9956: 	my $metastring;
 9957: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9958: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9959: 	    $metastring = 
 9960: 		&Apache::lonnet::ssi_body($which,
 9961: 					  ('grade_target' => 'meta'));
 9962: 	    $cachetime = 1; # only want this cached in the child not long term
 9963: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9964:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9965: 	    my $file=&filelocation('',&clutter($filename));
 9966: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9967: 	    $metastring=&getfile($file);
 9968: 	}
 9969:         my $parser=HTML::LCParser->new(\$metastring);
 9970:         my $token;
 9971:         undef %metathesekeys;
 9972:         while ($token=$parser->get_token) {
 9973: 	    if ($token->[0] eq 'S') {
 9974: 		if (defined($token->[2]->{'package'})) {
 9975: #
 9976: # This is a package - get package info
 9977: #
 9978: 		    my $package=$token->[2]->{'package'};
 9979: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9980: 		    if (defined($token->[2]->{'id'})) { 
 9981: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9982: 		    }
 9983: 		    if ($metaentry{':packages'}) {
 9984: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9985: 		    } else {
 9986: 			$metaentry{':packages'}=$package.$keyroot;
 9987: 		    }
 9988: 		    foreach my $pack_entry (keys(%packagetab)) {
 9989: 			my $part=$keyroot;
 9990: 			$part=~s/^\_//;
 9991: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9992: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9993: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9994: 			    # ignore package.tab specified default values
 9995:                             # here &package_tab_default() will fetch those
 9996: 			    if ($subp eq 'default') { next; }
 9997: 			    my $value=$packagetab{$pack_entry};
 9998: 			    my $unikey;
 9999: 			    if ($pack =~ /_0$/) {
10000: 				$unikey='parameter_0_'.$name;
10001: 				$part=0;
10002: 			    } else {
10003: 				$unikey='parameter'.$keyroot.'_'.$name;
10004: 			    }
10005: 			    if ($subp eq 'display') {
10006: 				$value.=' [Part: '.$part.']';
10007: 			    }
10008: 			    $metaentry{':'.$unikey.'.part'}=$part;
10009: 			    $metathesekeys{$unikey}=1;
10010: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10011: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10012: 			    }
10013: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10014: 				$metaentry{':'.$unikey}=
10015: 				    $metaentry{':'.$unikey.'.default'};
10016: 			    }
10017: 			}
10018: 		    }
10019: 		} else {
10020: #
10021: # This is not a package - some other kind of start tag
10022: #
10023: 		    my $entry=$token->[1];
10024: 		    my $unikey='';
10025: 
10026: 		    if ($entry eq 'import') {
10027: #
10028: # Importing a library here
10029: #
10030:                         my $location=$parser->get_text('/import');
10031:                         my $dir=$filename;
10032:                         $dir=~s|[^/]*$||;
10033:                         $location=&filelocation($dir,$location);
10034:                        
10035:                         my $importmode=$token->[2]->{'importmode'};
10036:                         if ($importmode eq 'problem') {
10037: # Import as problem/response
10038:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10039:                         } elsif ($importmode eq 'part') {
10040: # Import as part(s)
10041:                            $importedparts=1;
10042: # We need to get the original file and the imported file to get the part order correct
10043: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10044: # Load and inspect original file
10045:                            if ($#origfileimportpartids<0) {
10046:                               undef(%importedpartids);
10047:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10048:                               my $origfile=&getfile($origfilelocation);
10049:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10050:                            }
10051: 
10052: # Load and inspect imported file
10053:                            my $impfile=&getfile($location);
10054:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10055:                            if ($#impfilepartids>=0) {
10056: # This problem had parts
10057:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10058:                            } else {
10059: # Importing by turning a single problem into a problem part
10060: # It gets the import-tags ID as part-ID
10061:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10062:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10063:                            }
10064:                         } else {
10065: # Normal import
10066:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10067:                            if (defined($token->[2]->{'id'})) {
10068:                               $unikey.='_'.$token->[2]->{'id'};
10069:                            }
10070:                         }
10071: 
10072: 			if ($depthcount<20) {
10073: 			    my $metadata = 
10074: 				&metadata($uri,'keys', $location,$unikey,
10075: 					  $depthcount+1);
10076: 			    foreach my $meta (split(',',$metadata)) {
10077: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10078: 				$metathesekeys{$meta}=1;
10079: 			    }
10080: 			
10081:                         }
10082: 		    } else {
10083: #
10084: # Not importing, some other kind of non-package, non-library start tag
10085: # 
10086:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10087:                         if (defined($token->[2]->{'id'})) {
10088:                             $unikey.='_'.$token->[2]->{'id'};
10089:                         }
10090: 			if (defined($token->[2]->{'name'})) { 
10091: 			    $unikey.='_'.$token->[2]->{'name'}; 
10092: 			}
10093: 			$metathesekeys{$unikey}=1;
10094: 			foreach my $param (@{$token->[3]}) {
10095: 			    $metaentry{':'.$unikey.'.'.$param} =
10096: 				$token->[2]->{$param};
10097: 			}
10098: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10099: 			my $default=$metaentry{':'.$unikey.'.default'};
10100: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10101: 		 # only ws inside the tag, and not in default, so use default
10102: 		 # as value
10103: 			    $metaentry{':'.$unikey}=$default;
10104: 			} elsif ( $internaltext =~ /\S/ ) {
10105: 		  # something interesting inside the tag
10106: 			    $metaentry{':'.$unikey}=$internaltext;
10107: 			} else {
10108: 		  # no interesting values, don't set a default
10109: 			}
10110: # end of not-a-package not-a-library import
10111: 		    }
10112: # end of not-a-package start tag
10113: 		}
10114: # the next is the end of "start tag"
10115: 	    }
10116: 	}
10117: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10118: 	$extension = lc($extension);
10119: 	if ($extension eq 'htm') { $extension='html'; }
10120: 
10121: 	foreach my $key (keys(%packagetab)) {
10122: 	    #no specific packages #how's our extension
10123: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10124: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10125: 					 \%metathesekeys);
10126: 	}
10127: 
10128: 	if (!exists($metaentry{':packages'})
10129: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10130: 	    foreach my $key (keys(%packagetab)) {
10131: 		#no specific packages well let's get default then
10132: 		if ($key!~/^default&/) { next; }
10133: 		&metadata_create_package_def($uri,$key,'default',
10134: 					     \%metathesekeys);
10135: 	    }
10136: 	}
10137: # are there custom rights to evaluate
10138: 	if ($metaentry{':copyright'} eq 'custom') {
10139: 
10140:     #
10141:     # Importing a rights file here
10142:     #
10143: 	    unless ($depthcount) {
10144: 		my $location=$metaentry{':customdistributionfile'};
10145: 		my $dir=$filename;
10146: 		$dir=~s|[^/]*$||;
10147: 		$location=&filelocation($dir,$location);
10148: 		my $rights_metadata =
10149: 		    &metadata($uri,'keys',$location,'_rights',
10150: 			      $depthcount+1);
10151: 		foreach my $rights (split(',',$rights_metadata)) {
10152: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10153: 		    $metathesekeys{$rights}=1;
10154: 		}
10155: 	    }
10156: 	}
10157: 	# uniqifiy package listing
10158: 	my %seen;
10159: 	my @uniq_packages =
10160: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10161: 	$metaentry{':packages'} = join(',',@uniq_packages);
10162: 
10163:         if ($importedparts) {
10164: # We had imported parts and need to rebuild partorder
10165:            $metaentry{':partorder'}='';
10166:            $metathesekeys{'partorder'}=1;
10167:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10168:                if ($origfileimportpartids[$index] eq 'part') {
10169: # original part, part of the problem
10170:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10171:                } else {
10172: # we have imported parts at this position
10173:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10174:                }
10175:            }
10176:            $metaentry{':partorder'}=~s/^\,//;
10177:         }
10178: 
10179: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10180: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10181: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10182: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10183: # this is the end of "was not already recently cached
10184:     }
10185:     return $metaentry{':'.$what};
10186: }
10187: 
10188: sub metadata_create_package_def {
10189:     my ($uri,$key,$package,$metathesekeys)=@_;
10190:     my ($pack,$name,$subp)=split(/\&/,$key);
10191:     if ($subp eq 'default') { next; }
10192:     
10193:     if (defined($metaentry{':packages'})) {
10194: 	$metaentry{':packages'}.=','.$package;
10195:     } else {
10196: 	$metaentry{':packages'}=$package;
10197:     }
10198:     my $value=$packagetab{$key};
10199:     my $unikey;
10200:     $unikey='parameter_0_'.$name;
10201:     $metaentry{':'.$unikey.'.part'}=0;
10202:     $$metathesekeys{$unikey}=1;
10203:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10204: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10205:     }
10206:     if (defined($metaentry{':'.$unikey.'.default'})) {
10207: 	$metaentry{':'.$unikey}=
10208: 	    $metaentry{':'.$unikey.'.default'};
10209:     }
10210: }
10211: 
10212: sub metadata_generate_part0 {
10213:     my ($metadata,$metacache,$uri) = @_;
10214:     my %allnames;
10215:     foreach my $metakey (keys(%$metadata)) {
10216: 	if ($metakey=~/^parameter\_(.*)/) {
10217: 	  my $part=$$metacache{':'.$metakey.'.part'};
10218: 	  my $name=$$metacache{':'.$metakey.'.name'};
10219: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10220: 	    $allnames{$name}=$part;
10221: 	  }
10222: 	}
10223:     }
10224:     foreach my $name (keys(%allnames)) {
10225:       $$metadata{"parameter_0_$name"}=1;
10226:       my $key=":parameter_0_$name";
10227:       $$metacache{"$key.part"}='0';
10228:       $$metacache{"$key.name"}=$name;
10229:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10230: 					   $allnames{$name}.'_'.$name.
10231: 					   '.type'};
10232:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10233: 			     '.display'};
10234:       my $expr='[Part: '.$allnames{$name}.']';
10235:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10236:       $$metacache{"$key.display"}=$olddis;
10237:     }
10238: }
10239: 
10240: # ------------------------------------------------------ Devalidate title cache
10241: 
10242: sub devalidate_title_cache {
10243:     my ($url)=@_;
10244:     if (!$env{'request.course.id'}) { return; }
10245:     my $symb=&symbread($url);
10246:     if (!$symb) { return; }
10247:     my $key=$env{'request.course.id'}."\0".$symb;
10248:     &devalidate_cache_new('title',$key);
10249: }
10250: 
10251: # ------------------------------------------------- Get the title of a course
10252: 
10253: sub current_course_title {
10254:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10255: }
10256: # ------------------------------------------------- Get the title of a resource
10257: 
10258: sub gettitle {
10259:     my $urlsymb=shift;
10260:     my $symb=&symbread($urlsymb);
10261:     if ($symb) {
10262: 	my $key=$env{'request.course.id'}."\0".$symb;
10263: 	my ($result,$cached)=&is_cached_new('title',$key);
10264: 	if (defined($cached)) { 
10265: 	    return $result;
10266: 	}
10267: 	my ($map,$resid,$url)=&decode_symb($symb);
10268: 	my $title='';
10269: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10270: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10271: 	} else {
10272: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10273: 		    &GDBM_READER(),0640)) {
10274: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10275: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10276: 		untie(%bighash);
10277: 	    }
10278: 	}
10279: 	$title=~s/\&colon\;/\:/gs;
10280: 	if ($title) {
10281: # Remember both $symb and $title for dynamic metadata
10282:             $accesshash{$symb.'___crstitle'}=$title;
10283:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10284: # Cache this title and then return it
10285: 	    return &do_cache_new('title',$key,$title,600);
10286: 	}
10287: 	$urlsymb=$url;
10288:     }
10289:     my $title=&metadata($urlsymb,'title');
10290:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10291:     return $title;
10292: }
10293: 
10294: sub getdocspath {
10295:     my ($symb) = @_;
10296:     my $path;
10297:     if ($symb) {
10298:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
10299:         if ($resurl=~/\.(sequence|page)$/) {
10300:             $mapurl=$resurl;
10301:         } elsif ($resurl eq 'adm/navmaps') {
10302:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
10303:         }
10304:         my $mapresobj;
10305:         my $navmap = Apache::lonnavmaps::navmap->new();
10306:         if (ref($navmap)) {
10307:             $mapresobj = $navmap->getResourceByUrl($mapurl);
10308:         }
10309:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
10310:         my $type=$2;
10311:         if (ref($mapresobj)) {
10312:             my $pcslist = $mapresobj->map_hierarchy();
10313:             if ($pcslist ne '') {
10314:                 foreach my $pc (split(/,/,$pcslist)) {
10315:                     next if ($pc <= 1);
10316:                     my $res = $navmap->getByMapPc($pc);
10317:                     if (ref($res)) {
10318:                         my $thisurl = $res->src();
10319:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
10320:                         my $thistitle = $res->title();
10321:                         $path .= '&'.
10322:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
10323:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
10324:                                  ':'.$res->randompick().
10325:                                  ':'.$res->randomout().
10326:                                  ':'.$res->encrypted().
10327:                                  ':'.$res->randomorder().
10328:                                  ':'.$res->is_page();
10329:                     }
10330:                 }
10331:             }
10332:             $path =~ s/^\&//;
10333:             my $maptitle = $mapresobj->title();
10334:             if ($mapurl eq 'default') {
10335:                 $maptitle = 'Main Course Documents';
10336:             }
10337:             $path .= ($path ne '')? '&' : ''.
10338:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10339:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
10340:                     ':'.$mapresobj->randompick().
10341:                     ':'.$mapresobj->randomout().
10342:                     ':'.$mapresobj->encrypted().
10343:                     ':'.$mapresobj->randomorder().
10344:                     ':'.$mapresobj->is_page();
10345:         } else {
10346:             my $maptitle = &gettitle($mapurl);
10347:             my $ispage;
10348:             if ($mapurl =~ /\.page$/) {
10349:                 $ispage = 1;
10350:             }
10351:             if ($mapurl eq 'default') {
10352:                 $maptitle = 'Main Course Documents';
10353:             }
10354:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10355:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
10356:         }
10357:         unless ($mapurl eq 'default') {
10358:             $path = 'default&'.
10359:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
10360:                     ':::::&'.$path;
10361:         }
10362:     }
10363:     return $path;
10364: }
10365: 
10366: sub get_slot {
10367:     my ($which,$cnum,$cdom)=@_;
10368:     if (!$cnum || !$cdom) {
10369: 	(undef,my $courseid)=&whichuser();
10370: 	$cdom=$env{'course.'.$courseid.'.domain'};
10371: 	$cnum=$env{'course.'.$courseid.'.num'};
10372:     }
10373:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10374:     my %slotinfo;
10375:     if (exists($remembered{$key})) {
10376: 	$slotinfo{$which} = $remembered{$key};
10377:     } else {
10378: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10379: 	&Apache::lonhomework::showhash(%slotinfo);
10380: 	my ($tmp)=keys(%slotinfo);
10381: 	if ($tmp=~/^error:/) { return (); }
10382: 	$remembered{$key} = $slotinfo{$which};
10383:     }
10384:     if (ref($slotinfo{$which}) eq 'HASH') {
10385: 	return %{$slotinfo{$which}};
10386:     }
10387:     return $slotinfo{$which};
10388: }
10389: 
10390: sub get_reservable_slots {
10391:     my ($cnum,$cdom,$uname,$udom) = @_;
10392:     my $now = time;
10393:     my $reservable_info;
10394:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10395:     if (exists($remembered{$key})) {
10396:         $reservable_info = $remembered{$key};
10397:     } else {
10398:         my %resv;
10399:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10400:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10401:         $reservable_info = \%resv;
10402:         $remembered{$key} = $reservable_info;
10403:     }
10404:     return $reservable_info;
10405: }
10406: 
10407: sub get_course_slots {
10408:     my ($cnum,$cdom) = @_;
10409:     my $hashid=$cnum.':'.$cdom;
10410:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10411:     if (defined($cached)) {
10412:         if (ref($result) eq 'HASH') {
10413:             return %{$result};
10414:         }
10415:     } else {
10416:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10417:         my ($tmp) = keys(%slots);
10418:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10419:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
10420:             return %slots;
10421:         }
10422:     }
10423:     return;
10424: }
10425: 
10426: sub devalidate_slots_cache {
10427:     my ($cnum,$cdom)=@_;
10428:     my $hashid=$cnum.':'.$cdom;
10429:     &devalidate_cache_new('allslots',$hashid);
10430: }
10431: 
10432: sub get_coursechange {
10433:     my ($cdom,$cnum) = @_;
10434:     if ($cdom eq '' || $cnum eq '') {
10435:         return unless ($env{'request.course.id'});
10436:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10437:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10438:     }
10439:     my $hashid=$cdom.'_'.$cnum;
10440:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10441:     if ((defined($cached)) && ($change ne '')) {
10442:         return $change;
10443:     } else {
10444:         my %crshash;
10445:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10446:         if ($crshash{'internal.contentchange'} eq '') {
10447:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10448:             if ($change eq '') {
10449:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10450:                 $change = $crshash{'internal.created'};
10451:             }
10452:         } else {
10453:             $change = $crshash{'internal.contentchange'};
10454:         }
10455:         my $cachetime = 600;
10456:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10457:     }
10458:     return $change;
10459: }
10460: 
10461: sub devalidate_coursechange_cache {
10462:     my ($cnum,$cdom)=@_;
10463:     my $hashid=$cnum.':'.$cdom;
10464:     &devalidate_cache_new('crschange',$hashid);
10465: }
10466: 
10467: # ------------------------------------------------- Update symbolic store links
10468: 
10469: sub symblist {
10470:     my ($mapname,%newhash)=@_;
10471:     $mapname=&deversion(&declutter($mapname));
10472:     my %hash;
10473:     if (($env{'request.course.fn'}) && (%newhash)) {
10474:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10475:                       &GDBM_WRCREAT(),0640)) {
10476: 	    foreach my $url (keys(%newhash)) {
10477: 		next if ($url eq 'last_known'
10478: 			 && $env{'form.no_update_last_known'});
10479: 		$hash{declutter($url)}=&encode_symb($mapname,
10480: 						    $newhash{$url}->[1],
10481: 						    $newhash{$url}->[0]);
10482:             }
10483:             if (untie(%hash)) {
10484: 		return 'ok';
10485:             }
10486:         }
10487:     }
10488:     return 'error';
10489: }
10490: 
10491: # --------------------------------------------------------------- Verify a symb
10492: 
10493: sub symbverify {
10494:     my ($symb,$thisurl,$encstate)=@_;
10495:     my $thisfn=$thisurl;
10496:     $thisfn=&declutter($thisfn);
10497: # direct jump to resource in page or to a sequence - will construct own symbs
10498:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10499: # check URL part
10500:     my ($map,$resid,$url)=&decode_symb($symb);
10501: 
10502:     unless ($url eq $thisfn) { return 0; }
10503: 
10504:     $symb=&symbclean($symb);
10505:     $thisurl=&deversion($thisurl);
10506:     $thisfn=&deversion($thisfn);
10507: 
10508:     my %bighash;
10509:     my $okay=0;
10510: 
10511:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10512:                             &GDBM_READER(),0640)) {
10513:         my $noclutter;
10514:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10515:             $thisurl =~ s/\?.+$//;
10516:             if ($map =~ m{^uploaded/.+\.page$}) {
10517:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10518:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10519:                 $noclutter = 1;
10520:             }
10521:         }
10522:         my $ids;
10523:         if ($noclutter) {
10524:             $ids=$bighash{'ids_'.$thisurl};
10525:         } else {
10526:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10527:         }
10528:         unless ($ids) {
10529:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10530:             $ids=$bighash{$idkey};
10531:         }
10532:         if ($ids) {
10533: # ------------------------------------------------------------------- Has ID(s)
10534:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10535:                 $symb =~ s/\?.+$//;
10536:             }
10537: 	    foreach my $id (split(/\,/,$ids)) {
10538: 	       my ($mapid,$resid)=split(/\./,$id);
10539:                if (
10540:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10541:    eq $symb) {
10542:                    if (ref($encstate)) {
10543:                        $$encstate = $bighash{'encrypted_'.$id};
10544:                    }
10545: 		   if (($env{'request.role.adv'}) ||
10546: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10547:                        ($thisurl eq '/adm/navmaps')) {
10548: 		       $okay=1;
10549:                        last;
10550: 		   }
10551: 	       }
10552: 	   }
10553:         }
10554: 	untie(%bighash);
10555:     }
10556:     return $okay;
10557: }
10558: 
10559: # --------------------------------------------------------------- Clean-up symb
10560: 
10561: sub symbclean {
10562:     my $symb=shift;
10563:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10564: # remove version from map
10565:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10566: 
10567: # remove version from URL
10568:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10569: 
10570: # remove wrapper
10571: 
10572:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10573:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10574:     return $symb;
10575: }
10576: 
10577: # ---------------------------------------------- Split symb to find map and url
10578: 
10579: sub encode_symb {
10580:     my ($map,$resid,$url)=@_;
10581:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10582: }
10583: 
10584: sub decode_symb {
10585:     my $symb=shift;
10586:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10587:     my ($map,$resid,$url)=split(/___/,$symb);
10588:     return (&fixversion($map),$resid,&fixversion($url));
10589: }
10590: 
10591: sub fixversion {
10592:     my $fn=shift;
10593:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10594:     my %bighash;
10595:     my $uri=&clutter($fn);
10596:     my $key=$env{'request.course.id'}.'_'.$uri;
10597: # is this cached?
10598:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10599:     if (defined($cached)) { return $result; }
10600: # unfortunately not cached, or expired
10601:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10602: 	    &GDBM_READER(),0640)) {
10603:  	if ($bighash{'version_'.$uri}) {
10604:  	    my $version=$bighash{'version_'.$uri};
10605:  	    unless (($version eq 'mostrecent') || 
10606: 		    ($version==&getversion($uri))) {
10607:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10608:  	    }
10609:  	}
10610:  	untie %bighash;
10611:     }
10612:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10613: }
10614: 
10615: sub deversion {
10616:     my $url=shift;
10617:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10618:     return $url;
10619: }
10620: 
10621: # ------------------------------------------------------ Return symb list entry
10622: 
10623: sub symbread {
10624:     my ($thisfn,$donotrecurse)=@_;
10625:     my $cache_str='request.symbread.cached.'.$thisfn;
10626:     if (defined($env{$cache_str})) {
10627:         if (($thisfn) || ($env{$cache_str} ne '')) {
10628:             return $env{$cache_str};
10629:         }
10630:     }
10631: # no filename provided? try from environment
10632:     unless ($thisfn) {
10633:         if ($env{'request.symb'}) {
10634: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10635: 	}
10636: 	$thisfn=$env{'request.filename'};
10637:     }
10638:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10639: # is that filename actually a symb? Verify, clean, and return
10640:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10641: 	if (&symbverify($thisfn,$1)) {
10642: 	    return $env{$cache_str}=&symbclean($thisfn);
10643: 	}
10644:     }
10645:     $thisfn=declutter($thisfn);
10646:     my %hash;
10647:     my %bighash;
10648:     my $syval='';
10649:     if (($env{'request.course.fn'}) && ($thisfn)) {
10650:         my $targetfn = $thisfn;
10651:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10652:             $targetfn = 'adm/wrapper/'.$thisfn;
10653:         }
10654: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10655: 	    $targetfn=$1;
10656: 	}
10657:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10658:                       &GDBM_READER(),0640)) {
10659: 	    $syval=$hash{$targetfn};
10660:             untie(%hash);
10661:         }
10662: # ---------------------------------------------------------- There was an entry
10663:         if ($syval) {
10664: 	    #unless ($syval=~/\_\d+$/) {
10665: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10666: 		    #&appenv({'request.ambiguous' => $thisfn});
10667: 		    #return $env{$cache_str}='';
10668: 		#}    
10669: 		#$syval.=$1;
10670: 	    #}
10671:         } else {
10672: # ------------------------------------------------------- Was not in symb table
10673:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10674:                             &GDBM_READER(),0640)) {
10675: # ---------------------------------------------- Get ID(s) for current resource
10676:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10677:               unless ($ids) { 
10678:                  $ids=$bighash{'ids_/'.$thisfn};
10679:               }
10680:               unless ($ids) {
10681: # alias?
10682: 		  $ids=$bighash{'mapalias_'.$thisfn};
10683:               }
10684:               if ($ids) {
10685: # ------------------------------------------------------------------- Has ID(s)
10686:                  my @possibilities=split(/\,/,$ids);
10687:                  if ($#possibilities==0) {
10688: # ----------------------------------------------- There is only one possibility
10689: 		     my ($mapid,$resid)=split(/\./,$ids);
10690: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10691: 						    $resid,$thisfn);
10692:                  } elsif (!$donotrecurse) {
10693: # ------------------------------------------ There is more than one possibility
10694:                      my $realpossible=0;
10695:                      foreach my $id (@possibilities) {
10696: 			 my $file=$bighash{'src_'.$id};
10697:                          if (&allowed('bre',$file)) {
10698:          		    my ($mapid,$resid)=split(/\./,$id);
10699:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10700: 				$realpossible++;
10701:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10702: 						    $resid,$thisfn);
10703:                             }
10704: 			 }
10705:                      }
10706: 		     if ($realpossible!=1) { $syval=''; }
10707:                  } else {
10708:                      $syval='';
10709:                  }
10710: 	      }
10711:               untie(%bighash)
10712:            }
10713:         }
10714:         if ($syval) {
10715: 	    return $env{$cache_str}=$syval;
10716:         }
10717:     }
10718:     &appenv({'request.ambiguous' => $thisfn});
10719:     return $env{$cache_str}='';
10720: }
10721: 
10722: # ---------------------------------------------------------- Return random seed
10723: 
10724: sub numval {
10725:     my $txt=shift;
10726:     $txt=~tr/A-J/0-9/;
10727:     $txt=~tr/a-j/0-9/;
10728:     $txt=~tr/K-T/0-9/;
10729:     $txt=~tr/k-t/0-9/;
10730:     $txt=~tr/U-Z/0-5/;
10731:     $txt=~tr/u-z/0-5/;
10732:     $txt=~s/\D//g;
10733:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10734:     return int($txt);
10735: }
10736: 
10737: sub numval2 {
10738:     my $txt=shift;
10739:     $txt=~tr/A-J/0-9/;
10740:     $txt=~tr/a-j/0-9/;
10741:     $txt=~tr/K-T/0-9/;
10742:     $txt=~tr/k-t/0-9/;
10743:     $txt=~tr/U-Z/0-5/;
10744:     $txt=~tr/u-z/0-5/;
10745:     $txt=~s/\D//g;
10746:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10747:     my $total;
10748:     foreach my $val (@txts) { $total+=$val; }
10749:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10750:     return int($total);
10751: }
10752: 
10753: sub numval3 {
10754:     use integer;
10755:     my $txt=shift;
10756:     $txt=~tr/A-J/0-9/;
10757:     $txt=~tr/a-j/0-9/;
10758:     $txt=~tr/K-T/0-9/;
10759:     $txt=~tr/k-t/0-9/;
10760:     $txt=~tr/U-Z/0-5/;
10761:     $txt=~tr/u-z/0-5/;
10762:     $txt=~s/\D//g;
10763:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10764:     my $total;
10765:     foreach my $val (@txts) { $total+=$val; }
10766:     if ($_64bit) { $total=(($total<<32)>>32); }
10767:     return $total;
10768: }
10769: 
10770: sub digest {
10771:     my ($data)=@_;
10772:     my $digest=&Digest::MD5::md5($data);
10773:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10774:     my ($e,$f);
10775:     {
10776:         use integer;
10777:         $e=($a+$b);
10778:         $f=($c+$d);
10779:         if ($_64bit) {
10780:             $e=(($e<<32)>>32);
10781:             $f=(($f<<32)>>32);
10782:         }
10783:     }
10784:     if (wantarray) {
10785: 	return ($e,$f);
10786:     } else {
10787: 	my $g;
10788: 	{
10789: 	    use integer;
10790: 	    $g=($e+$f);
10791: 	    if ($_64bit) {
10792: 		$g=(($g<<32)>>32);
10793: 	    }
10794: 	}
10795: 	return $g;
10796:     }
10797: }
10798: 
10799: sub latest_rnd_algorithm_id {
10800:     return '64bit5';
10801: }
10802: 
10803: sub get_rand_alg {
10804:     my ($courseid)=@_;
10805:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10806:     if ($courseid) {
10807: 	return $env{"course.$courseid.rndseed"};
10808:     }
10809:     return &latest_rnd_algorithm_id();
10810: }
10811: 
10812: sub validCODE {
10813:     my ($CODE)=@_;
10814:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10815:     return 0;
10816: }
10817: 
10818: sub getCODE {
10819:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10820:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10821: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10822: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10823: 	return $Apache::lonhomework::history{'resource.CODE'};
10824:     }
10825:     return undef;
10826: }
10827: #
10828: #  Determines the random seed for a specific context:
10829: #
10830: # parameters:
10831: #   symb      - in course context the symb for the seed.
10832: #   course_id - The course id of the form domain_coursenum.
10833: #   domain    - Domain for the user.
10834: #   course    - Course for the user.
10835: #   cenv      - environment of the course.
10836: #
10837: # NOTE:
10838: #   All parameters are picked out of the environment if missing
10839: #   or not defined.
10840: #   If a symb cannot be determined the current time is used instead.
10841: #
10842: #  For a given well defined symb, courside, domain, username,
10843: #  and course environment, the seed is reproducible.
10844: #
10845: sub rndseed {
10846:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10847:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10848:     if (!defined($symb)) {
10849: 	unless ($symb=$wsymb) { return time; }
10850:     }
10851:     if (!defined $courseid) { 
10852: 	$courseid=$wcourseid; 
10853:     }
10854:     if (!defined $domain) { $domain=$wdomain; }
10855:     if (!defined $username) { $username=$wusername }
10856: 
10857:     my $which;
10858:     if (defined($cenv->{'rndseed'})) {
10859: 	$which = $cenv->{'rndseed'};
10860:     } else {
10861: 	$which =&get_rand_alg($courseid);
10862:     }
10863:     if (defined(&getCODE())) {
10864: 
10865: 	if ($which eq '64bit5') {
10866: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10867: 	} elsif ($which eq '64bit4') {
10868: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10869: 	} else {
10870: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10871: 	}
10872:     } elsif ($which eq '64bit5') {
10873: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10874:     } elsif ($which eq '64bit4') {
10875: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10876:     } elsif ($which eq '64bit3') {
10877: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10878:     } elsif ($which eq '64bit2') {
10879: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10880:     } elsif ($which eq '64bit') {
10881: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10882:     }
10883:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10884: }
10885: 
10886: sub rndseed_32bit {
10887:     my ($symb,$courseid,$domain,$username)=@_;
10888:     {
10889: 	use integer;
10890: 	my $symbchck=unpack("%32C*",$symb) << 27;
10891: 	my $symbseed=numval($symb) << 22;
10892: 	my $namechck=unpack("%32C*",$username) << 17;
10893: 	my $nameseed=numval($username) << 12;
10894: 	my $domainseed=unpack("%32C*",$domain) << 7;
10895: 	my $courseseed=unpack("%32C*",$courseid);
10896: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10897: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10898: 	#&logthis("rndseed :$num:$symb");
10899: 	if ($_64bit) { $num=(($num<<32)>>32); }
10900: 	return $num;
10901:     }
10902: }
10903: 
10904: sub rndseed_64bit {
10905:     my ($symb,$courseid,$domain,$username)=@_;
10906:     {
10907: 	use integer;
10908: 	my $symbchck=unpack("%32S*",$symb) << 21;
10909: 	my $symbseed=numval($symb) << 10;
10910: 	my $namechck=unpack("%32S*",$username);
10911: 	
10912: 	my $nameseed=numval($username) << 21;
10913: 	my $domainseed=unpack("%32S*",$domain) << 10;
10914: 	my $courseseed=unpack("%32S*",$courseid);
10915: 	
10916: 	my $num1=$symbchck+$symbseed+$namechck;
10917: 	my $num2=$nameseed+$domainseed+$courseseed;
10918: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10919: 	#&logthis("rndseed :$num:$symb");
10920: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10921: 	return "$num1,$num2";
10922:     }
10923: }
10924: 
10925: sub rndseed_64bit2 {
10926:     my ($symb,$courseid,$domain,$username)=@_;
10927:     {
10928: 	use integer;
10929: 	# strings need to be an even # of cahracters long, it it is odd the
10930:         # last characters gets thrown away
10931: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10932: 	my $symbseed=numval($symb) << 10;
10933: 	my $namechck=unpack("%32S*",$username.' ');
10934: 	
10935: 	my $nameseed=numval($username) << 21;
10936: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10937: 	my $courseseed=unpack("%32S*",$courseid.' ');
10938: 	
10939: 	my $num1=$symbchck+$symbseed+$namechck;
10940: 	my $num2=$nameseed+$domainseed+$courseseed;
10941: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10942: 	#&logthis("rndseed :$num:$symb");
10943: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10944: 	return "$num1,$num2";
10945:     }
10946: }
10947: 
10948: sub rndseed_64bit3 {
10949:     my ($symb,$courseid,$domain,$username)=@_;
10950:     {
10951: 	use integer;
10952: 	# strings need to be an even # of cahracters long, it it is odd the
10953:         # last characters gets thrown away
10954: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10955: 	my $symbseed=numval2($symb) << 10;
10956: 	my $namechck=unpack("%32S*",$username.' ');
10957: 	
10958: 	my $nameseed=numval2($username) << 21;
10959: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10960: 	my $courseseed=unpack("%32S*",$courseid.' ');
10961: 	
10962: 	my $num1=$symbchck+$symbseed+$namechck;
10963: 	my $num2=$nameseed+$domainseed+$courseseed;
10964: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10965: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10966: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10967: 	
10968: 	return "$num1:$num2";
10969:     }
10970: }
10971: 
10972: sub rndseed_64bit4 {
10973:     my ($symb,$courseid,$domain,$username)=@_;
10974:     {
10975: 	use integer;
10976: 	# strings need to be an even # of cahracters long, it it is odd the
10977:         # last characters gets thrown away
10978: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10979: 	my $symbseed=numval3($symb) << 10;
10980: 	my $namechck=unpack("%32S*",$username.' ');
10981: 	
10982: 	my $nameseed=numval3($username) << 21;
10983: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10984: 	my $courseseed=unpack("%32S*",$courseid.' ');
10985: 	
10986: 	my $num1=$symbchck+$symbseed+$namechck;
10987: 	my $num2=$nameseed+$domainseed+$courseseed;
10988: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10989: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10990: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10991: 	
10992: 	return "$num1:$num2";
10993:     }
10994: }
10995: 
10996: sub rndseed_64bit5 {
10997:     my ($symb,$courseid,$domain,$username)=@_;
10998:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10999:     return "$num1:$num2";
11000: }
11001: 
11002: sub rndseed_CODE_64bit {
11003:     my ($symb,$courseid,$domain,$username)=@_;
11004:     {
11005: 	use integer;
11006: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11007: 	my $symbseed=numval2($symb);
11008: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11009: 	my $CODEseed=numval(&getCODE());
11010: 	my $courseseed=unpack("%32S*",$courseid.' ');
11011: 	my $num1=$symbseed+$CODEchck;
11012: 	my $num2=$CODEseed+$courseseed+$symbchck;
11013: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11014: 	#&logthis("rndseed :$num1:$num2:$symb");
11015: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11016: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11017: 	return "$num1:$num2";
11018:     }
11019: }
11020: 
11021: sub rndseed_CODE_64bit4 {
11022:     my ($symb,$courseid,$domain,$username)=@_;
11023:     {
11024: 	use integer;
11025: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11026: 	my $symbseed=numval3($symb);
11027: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11028: 	my $CODEseed=numval3(&getCODE());
11029: 	my $courseseed=unpack("%32S*",$courseid.' ');
11030: 	my $num1=$symbseed+$CODEchck;
11031: 	my $num2=$CODEseed+$courseseed+$symbchck;
11032: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11033: 	#&logthis("rndseed :$num1:$num2:$symb");
11034: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11035: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11036: 	return "$num1:$num2";
11037:     }
11038: }
11039: 
11040: sub rndseed_CODE_64bit5 {
11041:     my ($symb,$courseid,$domain,$username)=@_;
11042:     my $code = &getCODE();
11043:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11044:     return "$num1:$num2";
11045: }
11046: 
11047: sub setup_random_from_rndseed {
11048:     my ($rndseed)=@_;
11049:     if ($rndseed =~/([,:])/) {
11050: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11051: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11052:     } else {
11053: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11054:     }
11055: }
11056: 
11057: sub latest_receipt_algorithm_id {
11058:     return 'receipt3';
11059: }
11060: 
11061: sub recunique {
11062:     my $fucourseid=shift;
11063:     my $unique;
11064:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11065: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11066: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11067:     } else {
11068: 	$unique=$perlvar{'lonReceipt'};
11069:     }
11070:     return unpack("%32C*",$unique);
11071: }
11072: 
11073: sub recprefix {
11074:     my $fucourseid=shift;
11075:     my $prefix;
11076:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11077: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11078: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11079:     } else {
11080: 	$prefix=$perlvar{'lonHostID'};
11081:     }
11082:     return unpack("%32C*",$prefix);
11083: }
11084: 
11085: sub ireceipt {
11086:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11087: 
11088:     my $return =&recprefix($fucourseid).'-';
11089: 
11090:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11091: 	$env{'request.state'} eq 'construct') {
11092: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11093: 	return $return;
11094:     }
11095: 
11096:     my $cuname=unpack("%32C*",$funame);
11097:     my $cudom=unpack("%32C*",$fudom);
11098:     my $cucourseid=unpack("%32C*",$fucourseid);
11099:     my $cusymb=unpack("%32C*",$fusymb);
11100:     my $cunique=&recunique($fucourseid);
11101:     my $cpart=unpack("%32S*",$part);
11102:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11103: 
11104: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11105: 			       
11106: 	$return.= ($cunique%$cuname+
11107: 		   $cunique%$cudom+
11108: 		   $cusymb%$cuname+
11109: 		   $cusymb%$cudom+
11110: 		   $cucourseid%$cuname+
11111: 		   $cucourseid%$cudom+
11112: 		   $cpart%$cuname+
11113: 		   $cpart%$cudom);
11114:     } else {
11115: 	$return.= ($cunique%$cuname+
11116: 		   $cunique%$cudom+
11117: 		   $cusymb%$cuname+
11118: 		   $cusymb%$cudom+
11119: 		   $cucourseid%$cuname+
11120: 		   $cucourseid%$cudom);
11121:     }
11122:     return $return;
11123: }
11124: 
11125: sub receipt {
11126:     my ($part)=@_;
11127:     my ($symb,$courseid,$domain,$name) = &whichuser();
11128:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11129: }
11130: 
11131: sub whichuser {
11132:     my ($passedsymb)=@_;
11133:     my ($symb,$courseid,$domain,$name,$publicuser);
11134:     if (defined($env{'form.grade_symb'})) {
11135: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11136: 	my $allowed=&allowed('vgr',$tmp_courseid);
11137: 	if (!$allowed &&
11138: 	    exists($env{'request.course.sec'}) &&
11139: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11140: 	    $allowed=&allowed('vgr',$tmp_courseid.
11141: 			      '/'.$env{'request.course.sec'});
11142: 	}
11143: 	if ($allowed) {
11144: 	    ($symb)=&get_env_multiple('form.grade_symb');
11145: 	    $courseid=$tmp_courseid;
11146: 	    ($domain)=&get_env_multiple('form.grade_domain');
11147: 	    ($name)=&get_env_multiple('form.grade_username');
11148: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11149: 	}
11150:     }
11151:     if (!$passedsymb) {
11152: 	$symb=&symbread();
11153:     } else {
11154: 	$symb=$passedsymb;
11155:     }
11156:     $courseid=$env{'request.course.id'};
11157:     $domain=$env{'user.domain'};
11158:     $name=$env{'user.name'};
11159:     if ($name eq 'public' && $domain eq 'public') {
11160: 	if (!defined($env{'form.username'})) {
11161: 	    $env{'form.username'}.=time.rand(10000000);
11162: 	}
11163: 	$name.=$env{'form.username'};
11164:     }
11165:     return ($symb,$courseid,$domain,$name,$publicuser);
11166: 
11167: }
11168: 
11169: # ------------------------------------------------------------ Serves up a file
11170: # returns either the contents of the file or 
11171: # -1 if the file doesn't exist
11172: #
11173: # if the target is a file that was uploaded via DOCS, 
11174: # a check will be made to see if a current copy exists on the local server,
11175: # if it does this will be served, otherwise a copy will be retrieved from
11176: # the home server for the course and stored in /home/httpd/html/userfiles on
11177: # the local server.   
11178: 
11179: sub getfile {
11180:     my ($file) = @_;
11181:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11182:     &repcopy($file);
11183:     return &readfile($file);
11184: }
11185: 
11186: sub repcopy_userfile {
11187:     my ($file)=@_;
11188:     my $londocroot = $perlvar{'lonDocRoot'};
11189:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11190:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11191:     my ($cdom,$cnum,$filename) = 
11192: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11193:     my $uri="/uploaded/$cdom/$cnum/$filename";
11194:     if (-e "$file") {
11195: # we already have a local copy, check it out
11196: 	my @fileinfo = stat($file);
11197: 	my $rtncode;
11198: 	my $info;
11199: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11200: 	if ($lwpresp ne 'ok') {
11201: # there is no such file anymore, even though we had a local copy
11202: 	    if ($rtncode eq '404') {
11203: 		unlink($file);
11204: 	    }
11205: 	    return -1;
11206: 	}
11207: 	if ($info < $fileinfo[9]) {
11208: # nice, the file we have is up-to-date, just say okay
11209: 	    return 'ok';
11210: 	} else {
11211: # the file is outdated, get rid of it
11212: 	    unlink($file);
11213: 	}
11214:     }
11215: # one way or the other, at this point, we don't have the file
11216: # construct the correct path for the file
11217:     my @parts = ($cdom,$cnum); 
11218:     if ($filename =~ m|^(.+)/[^/]+$|) {
11219: 	push @parts, split(/\//,$1);
11220:     }
11221:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11222:     foreach my $part (@parts) {
11223: 	$path .= '/'.$part;
11224: 	if (!-e $path) {
11225: 	    mkdir($path,0770);
11226: 	}
11227:     }
11228: # now the path exists for sure
11229: # get a user agent
11230:     my $ua=new LWP::UserAgent;
11231:     my $transferfile=$file.'.in.transfer';
11232: # FIXME: this should flock
11233:     if (-e $transferfile) { return 'ok'; }
11234:     my $request;
11235:     $uri=~s/^\///;
11236:     my $homeserver = &homeserver($cnum,$cdom);
11237:     my $protocol = $protocol{$homeserver};
11238:     $protocol = 'http' if ($protocol ne 'https');
11239:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11240:     my $response=$ua->request($request,$transferfile);
11241: # did it work?
11242:     if ($response->is_error()) {
11243: 	unlink($transferfile);
11244: 	&logthis("Userfile repcopy failed for $uri");
11245: 	return -1;
11246:     }
11247: # worked, rename the transfer file
11248:     rename($transferfile,$file);
11249:     return 'ok';
11250: }
11251: 
11252: sub tokenwrapper {
11253:     my $uri=shift;
11254:     $uri=~s|^https?\://([^/]+)||;
11255:     $uri=~s|^/||;
11256:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11257:     my $token=$1;
11258:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11259:     if ($udom && $uname && $file) {
11260: 	$file=~s|(\?\.*)*$||;
11261:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11262:         my $homeserver = &homeserver($uname,$udom);
11263:         my $protocol = $protocol{$homeserver};
11264:         $protocol = 'http' if ($protocol ne 'https');
11265:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11266:                (($uri=~/\?/)?'&':'?').'token='.$token.
11267:                                '&tokenissued='.$perlvar{'lonHostID'};
11268:     } else {
11269:         return '/adm/notfound.html';
11270:     }
11271: }
11272: 
11273: # call with reqtype HEAD: get last modification time
11274: # call with reqtype GET: get the file contents
11275: # Do not call this with reqtype GET for large files! It loads everything into memory
11276: #
11277: sub getuploaded {
11278:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11279:     $uri=~s/^\///;
11280:     my $homeserver = &homeserver($cnum,$cdom);
11281:     my $protocol = $protocol{$homeserver};
11282:     $protocol = 'http' if ($protocol ne 'https');
11283:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11284:     my $ua=new LWP::UserAgent;
11285:     my $request=new HTTP::Request($reqtype,$uri);
11286:     my $response=$ua->request($request);
11287:     $$rtncode = $response->code;
11288:     if (! $response->is_success()) {
11289: 	return 'failed';
11290:     }      
11291:     if ($reqtype eq 'HEAD') {
11292: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11293:     } elsif ($reqtype eq 'GET') {
11294: 	$$info = $response->content;
11295:     }
11296:     return 'ok';
11297: }
11298: 
11299: sub readfile {
11300:     my $file = shift;
11301:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11302:     my $fh;
11303:     open($fh,"<$file");
11304:     my $a='';
11305:     while (my $line = <$fh>) { $a .= $line; }
11306:     return $a;
11307: }
11308: 
11309: sub filelocation {
11310:     my ($dir,$file) = @_;
11311:     my $location;
11312:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11313: 
11314:     if ($file =~ m-^/adm/-) {
11315: 	$file=~s-^/adm/wrapper/-/-;
11316: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11317:     }
11318: 
11319:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11320:         $location = $file;
11321:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11322:         my ($udom,$uname,$filename)=
11323:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11324:         my $home=&homeserver($uname,$udom);
11325:         my $is_me=0;
11326:         my @ids=&current_machine_ids();
11327:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11328:         if ($is_me) {
11329:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11330:         } else {
11331:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11332:   	      $udom.'/'.$uname.'/'.$filename;
11333:         }
11334:     } elsif ($file =~ m-^/adm/-) {
11335: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11336:     } else {
11337:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11338:         $file=~s:^/(res|priv)/:/:;
11339:         my $space=$1;
11340:         if ( !( $file =~ m:^/:) ) {
11341:             $location = $dir. '/'.$file;
11342:         } else {
11343:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11344:         }
11345:     }
11346:     $location=~s://+:/:g; # remove duplicate /
11347:     while ($location=~m{/\.\./}) {
11348: 	if ($location =~ m{/[^/]+/\.\./}) {
11349: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11350: 	} else {
11351: 	    $location=~ s{/\.\./}{/}g;
11352: 	}
11353:     } #remove dir/..
11354:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11355:     return $location;
11356: }
11357: 
11358: sub hreflocation {
11359:     my ($dir,$file)=@_;
11360:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11361: 	$file=filelocation($dir,$file);
11362:     } elsif ($file=~m-^/adm/-) {
11363: 	$file=~s-^/adm/wrapper/-/-;
11364: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11365:     }
11366:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11367: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11368:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11369: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11370: 	        {/uploaded/$1/$2/}x;
11371:     }
11372:     if ($file=~ m{^/userfiles/}) {
11373: 	$file =~ s{^/userfiles/}{/uploaded/};
11374:     }
11375:     return $file;
11376: }
11377: 
11378: 
11379: 
11380: 
11381: 
11382: sub current_machine_domains {
11383:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11384: }
11385: 
11386: sub machine_domains {
11387:     my ($hostname) = @_;
11388:     my @domains;
11389:     my %hostname = &all_hostnames();
11390:     while( my($id, $name) = each(%hostname)) {
11391: #	&logthis("-$id-$name-$hostname-");
11392: 	if ($hostname eq $name) {
11393: 	    push(@domains,&host_domain($id));
11394: 	}
11395:     }
11396:     return @domains;
11397: }
11398: 
11399: sub current_machine_ids {
11400:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11401: }
11402: 
11403: sub machine_ids {
11404:     my ($hostname) = @_;
11405:     $hostname ||= &hostname($perlvar{'lonHostID'});
11406:     my @ids;
11407:     my %name_to_host = &all_names();
11408:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11409: 	return @{ $name_to_host{$hostname} };
11410:     }
11411:     return;
11412: }
11413: 
11414: sub additional_machine_domains {
11415:     my @domains;
11416:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11417:     while( my $line = <$fh>) {
11418:         $line =~ s/\s//g;
11419:         push(@domains,$line);
11420:     }
11421:     return @domains;
11422: }
11423: 
11424: sub default_login_domain {
11425:     my $domain = $perlvar{'lonDefDomain'};
11426:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11427:     foreach my $posdom (&current_machine_domains(),
11428:                         &additional_machine_domains()) {
11429:         if (lc($posdom) eq lc($testdomain)) {
11430:             $domain=$posdom;
11431:             last;
11432:         }
11433:     }
11434:     return $domain;
11435: }
11436: 
11437: # ------------------------------------------------------------- Declutters URLs
11438: 
11439: sub declutter {
11440:     my $thisfn=shift;
11441:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11442:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11443:     $thisfn=~s/^\///;
11444:     $thisfn=~s|^adm/wrapper/||;
11445:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11446:     $thisfn=~s/^res\///;
11447:     $thisfn=~s/^priv\///;
11448:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11449:         $thisfn=~s/\?.+$//;
11450:     }
11451:     return $thisfn;
11452: }
11453: 
11454: # ------------------------------------------------------------- Clutter up URLs
11455: 
11456: sub clutter {
11457:     my $thisfn='/'.&declutter(shift);
11458:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11459: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11460:        $thisfn='/res'.$thisfn; 
11461:     }
11462:     if ($thisfn !~m|^/adm|) {
11463: 	if ($thisfn =~ m|^/ext/|) {
11464: 	    $thisfn='/adm/wrapper'.$thisfn;
11465: 	} else {
11466: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11467: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11468: 	    if ($embstyle eq 'ssi'
11469: 		|| ($embstyle eq 'hdn')
11470: 		|| ($embstyle eq 'rat')
11471: 		|| ($embstyle eq 'prv')
11472: 		|| ($embstyle eq 'ign')) {
11473: 		#do nothing with these
11474: 	    } elsif (($embstyle eq 'img') 
11475: 		|| ($embstyle eq 'emb')
11476: 		|| ($embstyle eq 'wrp')) {
11477: 		$thisfn='/adm/wrapper'.$thisfn;
11478: 	    } elsif ($embstyle eq 'unk'
11479: 		     && $thisfn!~/\.(sequence|page)$/) {
11480: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11481: 	    } else {
11482: #		&logthis("Got a blank emb style");
11483: 	    }
11484: 	}
11485:     }
11486:     return $thisfn;
11487: }
11488: 
11489: sub clutter_with_no_wrapper {
11490:     my $uri = &clutter(shift);
11491:     if ($uri =~ m-^/adm/-) {
11492: 	$uri =~ s-^/adm/wrapper/-/-;
11493: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11494:     }
11495:     return $uri;
11496: }
11497: 
11498: sub freeze_escape {
11499:     my ($value)=@_;
11500:     if (ref($value)) {
11501: 	$value=&nfreeze($value);
11502: 	return '__FROZEN__'.&escape($value);
11503:     }
11504:     return &escape($value);
11505: }
11506: 
11507: 
11508: sub thaw_unescape {
11509:     my ($value)=@_;
11510:     if ($value =~ /^__FROZEN__/) {
11511: 	substr($value,0,10,undef);
11512: 	$value=&unescape($value);
11513: 	return &thaw($value);
11514:     }
11515:     return &unescape($value);
11516: }
11517: 
11518: sub correct_line_ends {
11519:     my ($result)=@_;
11520:     $$result =~s/\r\n/\n/mg;
11521:     $$result =~s/\r/\n/mg;
11522: }
11523: # ================================================================ Main Program
11524: 
11525: sub goodbye {
11526:    &logthis("Starting Shut down");
11527: #not converted to using infrastruture and probably shouldn't be
11528:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11529: #converted
11530: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11531:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11532: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11533: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11534: #1.1 only
11535: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11536: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11537: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11538: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11539:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11540:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11541:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11542:    &flushcourselogs();
11543:    &logthis("Shutting down");
11544: }
11545: 
11546: sub get_dns {
11547:     my ($url,$func,$ignore_cache) = @_;
11548:     if (!$ignore_cache) {
11549: 	my ($content,$cached)=
11550: 	    &Apache::lonnet::is_cached_new('dns',$url);
11551: 	if ($cached) {
11552: 	    &$func($content);
11553: 	    return;
11554: 	}
11555:     }
11556: 
11557:     my %alldns;
11558:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11559:     foreach my $dns (<$config>) {
11560: 	next if ($dns !~ /^\^(\S*)/x);
11561:         my $line = $1;
11562:         my ($host,$protocol) = split(/:/,$line);
11563:         if ($protocol ne 'https') {
11564:             $protocol = 'http';
11565:         }
11566: 	$alldns{$host} = $protocol;
11567:     }
11568:     while (%alldns) {
11569: 	my ($dns) = keys(%alldns);
11570: 	my $ua=new LWP::UserAgent;
11571:         $ua->timeout(30);
11572: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11573: 	my $response=$ua->request($request);
11574:         delete($alldns{$dns});
11575: 	next if ($response->is_error());
11576: 	my @content = split("\n",$response->content);
11577: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
11578: 	&$func(\@content);
11579: 	return;
11580:     }
11581:     close($config);
11582:     my $which = (split('/',$url))[3];
11583:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11584:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11585:     my @content = <$config>;
11586:     &$func(\@content);
11587:     return;
11588: }
11589: # ------------------------------------------------------------ Read domain file
11590: {
11591:     my $loaded;
11592:     my %domain;
11593: 
11594:     sub parse_domain_tab {
11595: 	my ($lines) = @_;
11596: 	foreach my $line (@$lines) {
11597: 	    next if ($line =~ /^(\#|\s*$ )/x);
11598: 
11599: 	    chomp($line);
11600: 	    my ($name,@elements) = split(/:/,$line,9);
11601: 	    my %this_domain;
11602: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11603: 			       'lang_def', 'city', 'longi', 'lati',
11604: 			       'primary') {
11605: 		$this_domain{$field} = shift(@elements);
11606: 	    }
11607: 	    $domain{$name} = \%this_domain;
11608: 	}
11609:     }
11610: 
11611:     sub reset_domain_info {
11612: 	undef($loaded);
11613: 	undef(%domain);
11614:     }
11615: 
11616:     sub load_domain_tab {
11617: 	my ($ignore_cache) = @_;
11618: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11619: 	my $fh;
11620: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11621: 	    my @lines = <$fh>;
11622: 	    &parse_domain_tab(\@lines);
11623: 	}
11624: 	close($fh);
11625: 	$loaded = 1;
11626:     }
11627: 
11628:     sub domain {
11629: 	&load_domain_tab() if (!$loaded);
11630: 
11631: 	my ($name,$what) = @_;
11632: 	return if ( !exists($domain{$name}) );
11633: 
11634: 	if (!$what) {
11635: 	    return $domain{$name}{'description'};
11636: 	}
11637: 	return $domain{$name}{$what};
11638:     }
11639: 
11640:     sub domain_info {
11641:         &load_domain_tab() if (!$loaded);
11642:         return %domain;
11643:     }
11644: 
11645: }
11646: 
11647: 
11648: # ------------------------------------------------------------- Read hosts file
11649: {
11650:     my %hostname;
11651:     my %hostdom;
11652:     my %libserv;
11653:     my $loaded;
11654:     my %name_to_host;
11655:     my %internetdom;
11656:     my %LC_dns_serv;
11657: 
11658:     sub parse_hosts_tab {
11659: 	my ($file) = @_;
11660: 	foreach my $configline (@$file) {
11661: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11662:             chomp($configline);
11663: 	    if ($configline =~ /^\^/) {
11664:                 if ($configline =~ /^\^([\w.\-]+)/) {
11665:                     $LC_dns_serv{$1} = 1;
11666:                 }
11667:                 next;
11668:             }
11669: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11670: 	    $name=~s/\s//g;
11671: 	    if ($id && $domain && $role && $name) {
11672: 		$hostname{$id}=$name;
11673: 		push(@{$name_to_host{$name}}, $id);
11674: 		$hostdom{$id}=$domain;
11675: 		if ($role eq 'library') { $libserv{$id}=$name; }
11676:                 if (defined($protocol)) {
11677:                     if ($protocol eq 'https') {
11678:                         $protocol{$id} = $protocol;
11679:                     } else {
11680:                         $protocol{$id} = 'http'; 
11681:                     }
11682:                 } else {
11683:                     $protocol{$id} = 'http';
11684:                 }
11685:                 if (defined($intdom)) {
11686:                     $internetdom{$id} = $intdom;
11687:                 }
11688: 	    }
11689: 	}
11690:     }
11691:     
11692:     sub reset_hosts_info {
11693: 	&purge_remembered();
11694: 	&reset_domain_info();
11695: 	&reset_hosts_ip_info();
11696: 	undef(%name_to_host);
11697: 	undef(%hostname);
11698: 	undef(%hostdom);
11699: 	undef(%libserv);
11700: 	undef($loaded);
11701:     }
11702: 
11703:     sub load_hosts_tab {
11704: 	my ($ignore_cache) = @_;
11705: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11706: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11707: 	my @config = <$config>;
11708: 	&parse_hosts_tab(\@config);
11709: 	close($config);
11710: 	$loaded=1;
11711:     }
11712: 
11713:     sub hostname {
11714: 	&load_hosts_tab() if (!$loaded);
11715: 
11716: 	my ($lonid) = @_;
11717: 	return $hostname{$lonid};
11718:     }
11719: 
11720:     sub all_hostnames {
11721: 	&load_hosts_tab() if (!$loaded);
11722: 
11723: 	return %hostname;
11724:     }
11725: 
11726:     sub all_names {
11727: 	&load_hosts_tab() if (!$loaded);
11728: 
11729: 	return %name_to_host;
11730:     }
11731: 
11732:     sub all_host_domain {
11733:         &load_hosts_tab() if (!$loaded);
11734:         return %hostdom;
11735:     }
11736: 
11737:     sub is_library {
11738: 	&load_hosts_tab() if (!$loaded);
11739: 
11740: 	return exists($libserv{$_[0]});
11741:     }
11742: 
11743:     sub all_library {
11744: 	&load_hosts_tab() if (!$loaded);
11745: 
11746: 	return %libserv;
11747:     }
11748: 
11749:     sub unique_library {
11750: 	#2x reverse removes all hostnames that appear more than once
11751:         my %unique = reverse &all_library();
11752:         return reverse %unique;
11753:     }
11754: 
11755:     sub get_servers {
11756: 	&load_hosts_tab() if (!$loaded);
11757: 
11758: 	my ($domain,$type) = @_;
11759: 	my %possible_hosts = ($type eq 'library') ? %libserv
11760: 	                                          : %hostname;
11761: 	my %result;
11762: 	if (ref($domain) eq 'ARRAY') {
11763: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11764: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11765: 		    $result{$host} = $hostname;
11766: 		}
11767: 	    }
11768: 	} else {
11769: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11770: 		if ($hostdom{$host} eq $domain) {
11771: 		    $result{$host} = $hostname;
11772: 		}
11773: 	    }
11774: 	}
11775: 	return %result;
11776:     }
11777: 
11778:     sub get_unique_servers {
11779:         my %unique = reverse &get_servers(@_);
11780: 	return reverse %unique;
11781:     }
11782: 
11783:     sub host_domain {
11784: 	&load_hosts_tab() if (!$loaded);
11785: 
11786: 	my ($lonid) = @_;
11787: 	return $hostdom{$lonid};
11788:     }
11789: 
11790:     sub all_domains {
11791: 	&load_hosts_tab() if (!$loaded);
11792: 
11793: 	my %seen;
11794: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11795: 	return @uniq;
11796:     }
11797: 
11798:     sub internet_dom {
11799:         &load_hosts_tab() if (!$loaded);
11800: 
11801:         my ($lonid) = @_;
11802:         return $internetdom{$lonid};
11803:     }
11804: 
11805:     sub is_LC_dns {
11806:         &load_hosts_tab() if (!$loaded);
11807: 
11808:         my ($hostname) = @_;
11809:         return exists($LC_dns_serv{$hostname});
11810:     }
11811: 
11812: }
11813: 
11814: { 
11815:     my %iphost;
11816:     my %name_to_ip;
11817:     my %lonid_to_ip;
11818: 
11819:     sub get_hosts_from_ip {
11820: 	my ($ip) = @_;
11821: 	my %iphosts = &get_iphost();
11822: 	if (ref($iphosts{$ip})) {
11823: 	    return @{$iphosts{$ip}};
11824: 	}
11825: 	return;
11826:     }
11827:     
11828:     sub reset_hosts_ip_info {
11829: 	undef(%iphost);
11830: 	undef(%name_to_ip);
11831: 	undef(%lonid_to_ip);
11832:     }
11833: 
11834:     sub get_host_ip {
11835: 	my ($lonid) = @_;
11836: 	if (exists($lonid_to_ip{$lonid})) {
11837: 	    return $lonid_to_ip{$lonid};
11838: 	}
11839: 	my $name=&hostname($lonid);
11840:    	my $ip = gethostbyname($name);
11841: 	return if (!$ip || length($ip) ne 4);
11842: 	$ip=inet_ntoa($ip);
11843: 	$name_to_ip{$name}   = $ip;
11844: 	$lonid_to_ip{$lonid} = $ip;
11845: 	return $ip;
11846:     }
11847:     
11848:     sub get_iphost {
11849: 	my ($ignore_cache) = @_;
11850: 
11851: 	if (!$ignore_cache) {
11852: 	    if (%iphost) {
11853: 		return %iphost;
11854: 	    }
11855: 	    my ($ip_info,$cached)=
11856: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11857: 	    if ($cached) {
11858: 		%iphost      = %{$ip_info->[0]};
11859: 		%name_to_ip  = %{$ip_info->[1]};
11860: 		%lonid_to_ip = %{$ip_info->[2]};
11861: 		return %iphost;
11862: 	    }
11863: 	}
11864: 
11865: 	# get yesterday's info for fallback
11866: 	my %old_name_to_ip;
11867: 	my ($ip_info,$cached)=
11868: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11869: 	if ($cached) {
11870: 	    %old_name_to_ip = %{$ip_info->[1]};
11871: 	}
11872: 
11873: 	my %name_to_host = &all_names();
11874: 	foreach my $name (keys(%name_to_host)) {
11875: 	    my $ip;
11876: 	    if (!exists($name_to_ip{$name})) {
11877: 		$ip = gethostbyname($name);
11878: 		if (!$ip || length($ip) ne 4) {
11879: 		    if (defined($old_name_to_ip{$name})) {
11880: 			$ip = $old_name_to_ip{$name};
11881: 			&logthis("Can't find $name defaulting to old $ip");
11882: 		    } else {
11883: 			&logthis("Name $name no IP found");
11884: 			next;
11885: 		    }
11886: 		} else {
11887: 		    $ip=inet_ntoa($ip);
11888: 		}
11889: 		$name_to_ip{$name} = $ip;
11890: 	    } else {
11891: 		$ip = $name_to_ip{$name};
11892: 	    }
11893: 	    foreach my $id (@{ $name_to_host{$name} }) {
11894: 		$lonid_to_ip{$id} = $ip;
11895: 	    }
11896: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11897: 	}
11898: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11899: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11900: 				      48*60*60);
11901: 
11902: 	return %iphost;
11903:     }
11904: 
11905:     #
11906:     #  Given a DNS returns the loncapa host name for that DNS 
11907:     # 
11908:     sub host_from_dns {
11909:         my ($dns) = @_;
11910:         my @hosts;
11911:         my $ip;
11912: 
11913:         if (exists($name_to_ip{$dns})) {
11914:             $ip = $name_to_ip{$dns};
11915:         }
11916:         if (!$ip) {
11917:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11918:             if (length($ip) == 4) { 
11919: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11920:             }
11921:         }
11922:         if ($ip) {
11923: 	    @hosts = get_hosts_from_ip($ip);
11924: 	    return $hosts[0];
11925:         }
11926:         return undef;
11927:     }
11928: 
11929:     sub get_internet_names {
11930:         my ($lonid) = @_;
11931:         return if ($lonid eq '');
11932:         my ($idnref,$cached)=
11933:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11934:         if ($cached) {
11935:             return $idnref;
11936:         }
11937:         my $ip = &get_host_ip($lonid);
11938:         my @hosts = &get_hosts_from_ip($ip);
11939:         my %iphost = &get_iphost();
11940:         my (@idns,%seen);
11941:         foreach my $id (@hosts) {
11942:             my $dom = &host_domain($id);
11943:             my $prim_id = &domain($dom,'primary');
11944:             my $prim_ip = &get_host_ip($prim_id);
11945:             next if ($seen{$prim_ip});
11946:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11947:                 foreach my $id (@{$iphost{$prim_ip}}) {
11948:                     my $intdom = &internet_dom($id);
11949:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11950:                         push(@idns,$intdom);
11951:                     }
11952:                 }
11953:             }
11954:             $seen{$prim_ip} = 1;
11955:         }
11956:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11957:     }
11958: 
11959: }
11960: 
11961: sub all_loncaparevs {
11962:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
11963: }
11964: 
11965: BEGIN {
11966: 
11967: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11968:     unless ($readit) {
11969: {
11970:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11971:     %perlvar = (%perlvar,%{$configvars});
11972: }
11973: 
11974: 
11975: # ------------------------------------------------------ Read spare server file
11976: {
11977:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11978: 
11979:     while (my $configline=<$config>) {
11980:        chomp($configline);
11981:        if ($configline) {
11982: 	   my ($host,$type) = split(':',$configline,2);
11983: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11984: 	   push(@{ $spareid{$type} }, $host);
11985:        }
11986:     }
11987:     close($config);
11988: }
11989: # ------------------------------------------------------------ Read permissions
11990: {
11991:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11992: 
11993:     while (my $configline=<$config>) {
11994: 	chomp($configline);
11995: 	if ($configline) {
11996: 	    my ($role,$perm)=split(/ /,$configline);
11997: 	    if ($perm ne '') { $pr{$role}=$perm; }
11998: 	}
11999:     }
12000:     close($config);
12001: }
12002: 
12003: # -------------------------------------------- Read plain texts for permissions
12004: {
12005:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12006: 
12007:     while (my $configline=<$config>) {
12008: 	chomp($configline);
12009: 	if ($configline) {
12010: 	    my ($short,@plain)=split(/:/,$configline);
12011:             %{$prp{$short}} = ();
12012: 	    if (@plain > 0) {
12013:                 $prp{$short}{'std'} = $plain[0];
12014:                 for (my $i=1; $i<@plain; $i++) {
12015:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12016:                 }
12017:             }
12018: 	}
12019:     }
12020:     close($config);
12021: }
12022: 
12023: # ---------------------------------------------------------- Read package table
12024: {
12025:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12026: 
12027:     while (my $configline=<$config>) {
12028: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12029: 	chomp($configline);
12030: 	my ($short,$plain)=split(/:/,$configline);
12031: 	my ($pack,$name)=split(/\&/,$short);
12032: 	if ($plain ne '') {
12033: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12034: 	    $packagetab{$short}=$plain; 
12035: 	}
12036:     }
12037:     close($config);
12038: }
12039: 
12040: # ---------------------------------------------------------- Read loncaparev table
12041: {
12042:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12043:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12044:             while (my $configline=<$config>) {
12045:                 chomp($configline);
12046:                 my ($hostid,$loncaparev)=split(/:/,$configline);
12047:                 $loncaparevs{$hostid}=$loncaparev;
12048:             }
12049:             close($config);
12050:         }
12051:     }
12052: }
12053: 
12054: # ---------------------------------------------------------- Read serverhostID table
12055: {
12056:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12057:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12058:             while (my $configline=<$config>) {
12059:                 chomp($configline);
12060:                 my ($name,$id)=split(/:/,$configline);
12061:                 $serverhomeIDs{$name}=$id;
12062:             }
12063:             close($config);
12064:         }
12065:     }
12066: }
12067: 
12068: {
12069:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12070:     if (-e $file) {
12071:         my $parser = HTML::LCParser->new($file);
12072:         while (my $token = $parser->get_token()) {
12073:             if ($token->[0] eq 'S') {
12074:                 my $item = $token->[1];
12075:                 my $name = $token->[2]{'name'};
12076:                 my $value = $token->[2]{'value'};
12077:                 if ($item ne '' && $name ne '' && $value ne '') {
12078:                     my $release = $parser->get_text();
12079:                     $release =~ s/(^\s*|\s*$ )//gx;
12080:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12081:                 }
12082:             }
12083:         }
12084:     }
12085: }
12086: 
12087: # ---------------------------------------------------------- Read managers table
12088: {
12089:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12090:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12091:             while (my $configline=<$config>) {
12092:                 chomp($configline);
12093:                 next if ($configline =~ /^\#/);
12094:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12095:                     $managerstab{$configline} = 1;
12096:                 }
12097:             }
12098:             close($config);
12099:         }
12100:     }
12101: }
12102: 
12103: # ------------- set up temporary directory
12104: {
12105:     $tmpdir = LONCAPA::tempdir();
12106: 
12107: }
12108: 
12109: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12110: 				'compress_threshold'=> 20_000,
12111:  			        });
12112: 
12113: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12114: $dumpcount=0;
12115: $locknum=0;
12116: 
12117: &logtouch();
12118: &logthis('<font color="yellow">INFO: Read configuration</font>');
12119: $readit=1;
12120:     {
12121: 	use integer;
12122: 	my $test=(2**32)+1;
12123: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12124: 	&logthis(" Detected 64bit platform ($_64bit)");
12125:     }
12126: }
12127: }
12128: 
12129: 1;
12130: __END__
12131: 
12132: =pod
12133: 
12134: =head1 NAME
12135: 
12136: Apache::lonnet - Subroutines to ask questions about things in the network.
12137: 
12138: =head1 SYNOPSIS
12139: 
12140: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12141: 
12142:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12143: 
12144: Common parameters:
12145: 
12146: =over 4
12147: 
12148: =item *
12149: 
12150: $uname : an internal username (if $cname expecting a course Id specifically)
12151: 
12152: =item *
12153: 
12154: $udom : a domain (if $cdom expecting a course's domain specifically)
12155: 
12156: =item *
12157: 
12158: $symb : a resource instance identifier
12159: 
12160: =item *
12161: 
12162: $namespace : the name of a .db file that contains the data needed or
12163: being set.
12164: 
12165: =back
12166: 
12167: =head1 OVERVIEW
12168: 
12169: lonnet provides subroutines which interact with the
12170: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12171: about classes, users, and resources.
12172: 
12173: For many of these objects you can also use this to store data about
12174: them or modify them in various ways.
12175: 
12176: =head2 Symbs
12177: 
12178: To identify a specific instance of a resource, LON-CAPA uses symbols
12179: or "symbs"X<symb>. These identifiers are built from the URL of the
12180: map, the resource number of the resource in the map, and the URL of
12181: the resource itself. The latter is somewhat redundant, but might help
12182: if maps change.
12183: 
12184: An example is
12185: 
12186:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12187: 
12188: The respective map entry is
12189: 
12190:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12191:   title="Problem 2">
12192:  </resource>
12193: 
12194: Symbs are used by the random number generator, as well as to store and
12195: restore data specific to a certain instance of for example a problem.
12196: 
12197: =head2 Storing And Retrieving Data
12198: 
12199: X<store()>X<cstore()>X<restore()>Three of the most important functions
12200: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12201: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12202: is is the non-critical message twin of cstore. These functions are for
12203: handlers to store a perl hash to a user's permanent data space in an
12204: easy manner, and to retrieve it again on another call. It is expected
12205: that a handler would use this once at the beginning to retrieve data,
12206: and then again once at the end to send only the new data back.
12207: 
12208: The data is stored in the user's data directory on the user's
12209: homeserver under the ID of the course.
12210: 
12211: The hash that is returned by restore will have all of the previous
12212: value for all of the elements of the hash.
12213: 
12214: Example:
12215: 
12216:  #creating a hash
12217:  my %hash;
12218:  $hash{'foo'}='bar';
12219: 
12220:  #storing it
12221:  &Apache::lonnet::cstore(\%hash);
12222: 
12223:  #changing a value
12224:  $hash{'foo'}='notbar';
12225: 
12226:  #adding a new value
12227:  $hash{'bar'}='foo';
12228:  &Apache::lonnet::cstore(\%hash);
12229: 
12230:  #retrieving the hash
12231:  my %history=&Apache::lonnet::restore();
12232: 
12233:  #print the hash
12234:  foreach my $key (sort(keys(%history))) {
12235:    print("\%history{$key} = $history{$key}");
12236:  }
12237: 
12238: Will print out:
12239: 
12240:  %history{1:foo} = bar
12241:  %history{1:keys} = foo:timestamp
12242:  %history{1:timestamp} = 990455579
12243:  %history{2:bar} = foo
12244:  %history{2:foo} = notbar
12245:  %history{2:keys} = foo:bar:timestamp
12246:  %history{2:timestamp} = 990455580
12247:  %history{bar} = foo
12248:  %history{foo} = notbar
12249:  %history{timestamp} = 990455580
12250:  %history{version} = 2
12251: 
12252: Note that the special hash entries C<keys>, C<version> and
12253: C<timestamp> were added to the hash. C<version> will be equal to the
12254: total number of versions of the data that have been stored. The
12255: C<timestamp> attribute will be the UNIX time the hash was
12256: stored. C<keys> is available in every historical section to list which
12257: keys were added or changed at a specific historical revision of a
12258: hash.
12259: 
12260: B<Warning>: do not store the hash that restore returns directly. This
12261: will cause a mess since it will restore the historical keys as if the
12262: were new keys. I.E. 1:foo will become 1:1:foo etc.
12263: 
12264: Calling convention:
12265: 
12266:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
12267:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
12268: 
12269: For more detailed information, see lonnet specific documentation.
12270: 
12271: =head1 RETURN MESSAGES
12272: 
12273: =over 4
12274: 
12275: =item * B<con_lost>: unable to contact remote host
12276: 
12277: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12278: when the connection is brought back up
12279: 
12280: =item * B<con_failed>: unable to contact remote host and unable to save message
12281: for later delivery
12282: 
12283: =item * B<error:>: an error a occurred, a description of the error follows the :
12284: 
12285: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12286: that was requested
12287: 
12288: =back
12289: 
12290: =head1 PUBLIC SUBROUTINES
12291: 
12292: =head2 Session Environment Functions
12293: 
12294: =over 4
12295: 
12296: =item * 
12297: X<appenv()>
12298: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12299: the user envirnoment file, and will be restored for each access this
12300: user makes during this session, also modifies the %env for the current
12301: process. Optional rolesarrayref - if defined contains a reference to an array
12302: of roles which are exempt from the restriction on modifying user.role entries 
12303: in the user's environment.db and in %env.    
12304: 
12305: =item *
12306: X<delenv()>
12307: B<delenv($delthis,$regexp)>: removes all items from the session
12308: environment file that begin with $delthis. If the 
12309: optional second arg - $regexp - is true, $delthis is treated as a 
12310: regular expression, otherwise \Q$delthis\E is used. 
12311: The values are also deleted from the current processes %env.
12312: 
12313: =item * get_env_multiple($name) 
12314: 
12315: gets $name from the %env hash, it seemlessly handles the cases where multiple
12316: values may be defined and end up as an array ref.
12317: 
12318: returns an array of values
12319: 
12320: =back
12321: 
12322: =head2 User Information
12323: 
12324: =over 4
12325: 
12326: =item *
12327: X<queryauthenticate()>
12328: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12329: authentication scheme
12330: 
12331: =item *
12332: X<authenticate()>
12333: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12334: authenticate user from domain's lib servers (first use the current
12335: one). C<$upass> should be the users password.
12336: $checkdefauth is optional (value is 1 if a check should be made to
12337:    authenticate user using default authentication method, and allow
12338:    account creation if username does not have account in the domain).
12339: $clientcancheckhost is optional (value is 1 if checking whether the
12340:    server can host will occur on the client side in lonauth.pm).   
12341: 
12342: =item *
12343: X<homeserver()>
12344: B<homeserver($uname,$udom)>: find the server which has
12345: the user's directory and files (there must be only one), this caches
12346: the answer, and also caches if there is a borken connection.
12347: 
12348: =item *
12349: X<idget()>
12350: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12351: (IDs are a unique resource in a domain, there must be only 1 ID per
12352: username, and only 1 username per ID in a specific domain) (returns
12353: hash: id=>name,id=>name)
12354: 
12355: =item *
12356: X<idrget()>
12357: B<idrget($udom,@unames)>: find the IDs behind a list of
12358: usernames (returns hash: name=>id,name=>id)
12359: 
12360: =item *
12361: X<idput()>
12362: B<idput($udom,%ids)>: store away a list of names and associated IDs
12363: 
12364: =item *
12365: X<rolesinit()>
12366: B<rolesinit($udom,$username)>: get user privileges.
12367: returns user role, first access and timer interval hashes
12368: 
12369: =item *
12370: X<privileged()>
12371: B<privileged($username,$domain)>: returns a true if user has a
12372: privileged and active role (i.e. su or dc), false otherwise.
12373: 
12374: =item *
12375: X<getsection()>
12376: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12377: course $cname, return section name/number or '' for "not in course"
12378: and '-1' for "no section"
12379: 
12380: =item *
12381: X<userenvironment()>
12382: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12383: passed in @what from the requested user's environment, returns a hash
12384: 
12385: =item * 
12386: X<userlog_query()>
12387: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12388: activity.log file. %filters defines filters applied when parsing the
12389: log file. These can be start or end timestamps, or the type of action
12390: - log to look for Login or Logout events, check for Checkin or
12391: Checkout, role for role selection. The response is in the form
12392: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12393: escaped strings of the action recorded in the activity.log file.
12394: 
12395: =back
12396: 
12397: =head2 User Roles
12398: 
12399: =over 4
12400: 
12401: =item *
12402: 
12403: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12404:  F: full access
12405:  U,I,K: authentication modes (cxx only)
12406:  '': forbidden
12407:  1: user needs to choose course
12408:  2: browse allowed
12409:  A: passphrase authentication needed
12410: 
12411: =item *
12412: 
12413: constructaccess($url,$setpriv) : check for access to construction space URL
12414: 
12415: See if the owner domain and name in the URL match those in the
12416: expected environment.  If so, return three element list
12417: ($ownername,$ownerdomain,$ownerhome).
12418: 
12419: Otherwise return the null string.
12420: 
12421: If second argument 'setpriv' is true, it assigns the privileges,
12422: and returns the same three element list, unless the owner has
12423: blocked "ad hoc" Domain Coordinator access to the Author Space,
12424: in which case the null string is returned.
12425: 
12426: =item *
12427: 
12428: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12429: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12430: and course level
12431: 
12432: =item *
12433: 
12434: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12435: (rolesplain.tab); plain text explanation of a user role term.
12436: $type is Course (default) or Community.
12437: If $forcedefault evaluates to true, text returned will be default 
12438: text for $type. Otherwise, if this is a course, the text returned 
12439: will be a custom name for the role (if defined in the course's 
12440: environment).  If no custom name is defined the default is returned.
12441:    
12442: =item *
12443: 
12444: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
12445: All arguments are optional. Returns a hash of a roles, either for
12446: co-author/assistant author roles for a user's Construction Space
12447: (default), or if $context is 'userroles', roles for the user himself,
12448: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12449: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12450: For each key, value is set to colon-separated start and end times for
12451: the role.  If no username and domain are specified, will default to
12452: current user/domain. Types, roles, and roledoms are references to arrays
12453: of role statuses (active, future or previous), roles 
12454: (e.g., cc,in, st etc.) and domains of the roles which can be used
12455: to restrict the list of roles reported. If no array ref is 
12456: provided for types, will default to return only active roles.
12457: 
12458: =item *
12459: 
12460: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12461: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12462: 
12463: Additional optional arguments are: $type (if role checking is to be restricted 
12464: to certain user status types -- previous (expired roles), active (currently
12465: available roles) or future (roles available in the future), and
12466: $hideprivileged -- if true will not report course roles for users who
12467: have active Domain Coordinator or Super User roles.
12468: 
12469: =back
12470: 
12471: =head2 User Modification
12472: 
12473: =over 4
12474: 
12475: =item *
12476: 
12477: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12478: user for the level given by URL.  Optional start and end dates (leave empty
12479: string or zero for "no date")
12480: 
12481: =item *
12482: 
12483: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12484: change a users, password, possible return values are: ok,
12485: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12486: refused
12487: 
12488: =item *
12489: 
12490: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12491: 
12492: =item *
12493: 
12494: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12495:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12496: 
12497: will update user information (firstname,middlename,lastname,generation,
12498: permanentemail), and if forceid is true, student/employee ID also.
12499: A user's institutional affiliation(s) can also be updated.
12500: User information fields will not be overwritten with empty entries 
12501: unless the field is included in the $candelete array reference.
12502: This array is included when a single user is modified via "Manage Users",
12503: or when Autoupdate.pl is run by cron in a domain.
12504: 
12505: =item *
12506: 
12507: modifystudent
12508: 
12509: modify a student's enrollment and identification information.
12510: The course id is resolved based on the current users environment.  
12511: This means the envoking user must be a course coordinator or otherwise
12512: associated with a course.
12513: 
12514: This call is essentially a wrapper for lonnet::modifyuser and
12515: lonnet::modify_student_enrollment
12516: 
12517: Inputs: 
12518: 
12519: =over 4
12520: 
12521: =item B<$udom> Student's loncapa domain
12522: 
12523: =item B<$uname> Student's loncapa login name
12524: 
12525: =item B<$uid> Student/Employee ID
12526: 
12527: =item B<$umode> Student's authentication mode
12528: 
12529: =item B<$upass> Student's password
12530: 
12531: =item B<$first> Student's first name
12532: 
12533: =item B<$middle> Student's middle name
12534: 
12535: =item B<$last> Student's last name
12536: 
12537: =item B<$gene> Student's generation
12538: 
12539: =item B<$usec> Student's section in course
12540: 
12541: =item B<$end> Unix time of the roles expiration
12542: 
12543: =item B<$start> Unix time of the roles start date
12544: 
12545: =item B<$forceid> If defined, allow $uid to be changed
12546: 
12547: =item B<$desiredhome> server to use as home server for student
12548: 
12549: =item B<$email> Student's permanent e-mail address
12550: 
12551: =item B<$type> Type of enrollment (auto or manual)
12552: 
12553: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12554: 
12555: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12556: 
12557: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12558: 
12559: =item B<$context> role change context (shown in User Management Logs display in a course)
12560: 
12561: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
12562: 
12563: =back
12564: 
12565: =item *
12566: 
12567: modify_student_enrollment
12568: 
12569: Change a students enrollment status in a class.  The environment variable
12570: 'role.request.course' must be defined for this function to proceed.
12571: 
12572: Inputs:
12573: 
12574: =over 4
12575: 
12576: =item $udom, students domain
12577: 
12578: =item $uname, students name
12579: 
12580: =item $uid, students user id
12581: 
12582: =item $first, students first name
12583: 
12584: =item $middle
12585: 
12586: =item $last
12587: 
12588: =item $gene
12589: 
12590: =item $usec
12591: 
12592: =item $end
12593: 
12594: =item $start
12595: 
12596: =item $type
12597: 
12598: =item $locktype
12599: 
12600: =item $cid
12601: 
12602: =item $selfenroll
12603: 
12604: =item $context
12605: 
12606: =back
12607: 
12608: 
12609: =item *
12610: 
12611: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12612: custom role; give a custom role to a user for the level given by URL.  Specify
12613: name and domain of role author, and role name
12614: 
12615: =item *
12616: 
12617: revokerole($udom,$uname,$url,$role) : revoke a role for url
12618: 
12619: =item *
12620: 
12621: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12622: 
12623: =back
12624: 
12625: =head2 Course Infomation
12626: 
12627: =over 4
12628: 
12629: =item *
12630: 
12631: coursedescription($courseid,$options) : returns a hash of information about the
12632: specified course id, including all environment settings for the
12633: course, the description of the course will be in the hash under the
12634: key 'description'
12635: 
12636: $options is an optional parameter that if supplied is a hash reference that controls
12637: what how this function works.  It has the following key/values:
12638: 
12639: =over 4
12640: 
12641: =item freshen_cache
12642: 
12643: If defined, and the environment cache for the course is valid, it is 
12644: returned in the returned hash.
12645: 
12646: =item one_time
12647: 
12648: If defined, the last cache time is set to _now_
12649: 
12650: =item user
12651: 
12652: If defined, the supplied username is used instead of the current user.
12653: 
12654: 
12655: =back
12656: 
12657: =item *
12658: 
12659: resdata($name,$domain,$type,@which) : request for current parameter
12660: setting for a specific $type, where $type is either 'course' or 'user',
12661: @what should be a list of parameters to ask about. This routine caches
12662: answers for 5 minutes.
12663: 
12664: =item *
12665: 
12666: get_courseresdata($courseid, $domain) : dump the entire course resource
12667: data base, returning a hash that is keyed by the resource name and has
12668: values that are the resource value.  I believe that the timestamps and
12669: versions are also returned.
12670: 
12671: =back
12672: 
12673: =head2 Course Modification
12674: 
12675: =over 4
12676: 
12677: =item *
12678: 
12679: writecoursepref($courseid,%prefs) : write preferences (environment
12680: database) for a course
12681: 
12682: =item *
12683: 
12684: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12685: 
12686: =item *
12687: 
12688: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12689: 
12690: =item *
12691: 
12692: is_course($courseid), is_course($cdom, $cnum)
12693: 
12694: Accepts either a combined $courseid (in the form of domain_courseid) or the
12695: two component version $cdom, $cnum. It checks if the specified course exists.
12696: 
12697: Returns:
12698:     undef if the course doesn't exist, otherwise
12699:     in scalar context the combined courseid.
12700:     in list context the two components of the course identifier, domain and 
12701:     courseid.    
12702: 
12703: =back
12704: 
12705: =head2 Resource Subroutines
12706: 
12707: =over 4
12708: 
12709: =item *
12710: 
12711: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12712: 
12713: =item *
12714: 
12715: repcopy($filename) : subscribes to the requested file, and attempts to
12716: replicate from the owning library server, Might return
12717: 'unavailable', 'not_found', 'forbidden', 'ok', or
12718: 'bad_request', also attempts to grab the metadata for the
12719: resource. Expects the local filesystem pathname
12720: (/home/httpd/html/res/....)
12721: 
12722: =back
12723: 
12724: =head2 Resource Information
12725: 
12726: =over 4
12727: 
12728: =item *
12729: 
12730: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12731: a vairety of different possible values, $varname should be a request
12732: string, and the other parameters can be used to specify who and what
12733: one is asking about.
12734: 
12735: Possible values for $varname are environment.lastname (or other item
12736: from the envirnment hash), user.name (or someother aspect about the
12737: user), resource.0.maxtries (or some other part and parameter of a
12738: resource)
12739: 
12740: =item *
12741: 
12742: directcondval($number) : get current value of a condition; reads from a state
12743: string
12744: 
12745: =item *
12746: 
12747: condval($condidx) : value of condition index based on state
12748: 
12749: =item *
12750: 
12751: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12752: resource's metadata, $what should be either a specific key, or either
12753: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12754: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12755: 
12756: this function automatically caches all requests
12757: 
12758: =item *
12759: 
12760: metadata_query($query,$custom,$customshow) : make a metadata query against the
12761: network of library servers; returns file handle of where SQL and regex results
12762: will be stored for query
12763: 
12764: =item *
12765: 
12766: symbread($filename) : return symbolic list entry (filename argument optional);
12767: returns the data handle
12768: 
12769: =item *
12770: 
12771: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12772: and is a possible symb for the URL in $thisfn, and if is an encrypted
12773: resource that the user accessed using /enc/ returns a 1 on success, 0
12774: on failure, user must be in a course, as it assumes the existence of
12775: the course initial hash, and uses $env('request.course.id'}.  The third
12776: arg is an optional reference to a scalar.  If this arg is passed in the 
12777: call to symbverify, it will be set to 1 if the symb has been set to be 
12778: encrypted; otherwise it will be null.  
12779: 
12780: =item *
12781: 
12782: symbclean($symb) : removes versions numbers from a symb, returns the
12783: cleaned symb
12784: 
12785: =item *
12786: 
12787: is_on_map($uri) : checks if the $uri is somewhere on the current
12788: course map, user must be in a course for it to work.
12789: 
12790: =item *
12791: 
12792: numval($salt) : return random seed value (addend for rndseed)
12793: 
12794: =item *
12795: 
12796: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12797: a random seed, all arguments are optional, if they aren't sent it uses the
12798: environment to derive them. Note: if symb isn't sent and it can't get one
12799: from &symbread it will use the current time as its return value
12800: 
12801: =item *
12802: 
12803: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12804: unfakeable, receipt
12805: 
12806: =item *
12807: 
12808: receipt() : API to ireceipt working off of env values; given out to users
12809: 
12810: =item *
12811: 
12812: countacc($url) : count the number of accesses to a given URL
12813: 
12814: =item *
12815: 
12816: 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
12817: 
12818: =item *
12819: 
12820: 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)
12821: 
12822: =item *
12823: 
12824: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12825: 
12826: =item *
12827: 
12828: devalidate($symb) : devalidate temporary spreadsheet calculations,
12829: forcing spreadsheet to reevaluate the resource scores next time.
12830: 
12831: =item * 
12832: 
12833: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
12834: when viewing in course context.
12835: 
12836:  input: six args -- filename (decluttered), course number, course domain,
12837:                     url, symb (if registered) and group (if this is a 
12838:                     group item -- e.g., bulletin board, group page etc.).
12839: 
12840:  output: array of five scalars --
12841:          $cfile -- url for file editing if editable on current server
12842:          $home -- homeserver of resource (i.e., for author if published,
12843:                                           or course if uploaded.).
12844:          $switchserver --  1 if server switch will be needed.
12845:          $forceedit -- 1 if icon/link should be to go to edit mode 
12846:          $forceview -- 1 if icon/link should be to go to view mode
12847: 
12848: =item *
12849: 
12850: is_course_upload($file,$cnum,$cdom)
12851: 
12852: Used in course context to determine if current file was uploaded to 
12853: the course (i.e., would be found in /userfiles/docs on the course's 
12854: homeserver.
12855: 
12856:   input: 3 args -- filename (decluttered), course number and course domain.
12857:   output: boolean -- 1 if file was uploaded.
12858: 
12859: =back
12860: 
12861: =head2 Storing/Retreiving Data
12862: 
12863: =over 4
12864: 
12865: =item *
12866: 
12867: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12868: for this url; hashref needs to be given and should be a \%hashname; the
12869: remaining args aren't required and if they aren't passed or are '' they will
12870: be derived from the env
12871: 
12872: =item *
12873: 
12874: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12875: uses critical subroutine
12876: 
12877: =item *
12878: 
12879: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12880: all args are optional
12881: 
12882: =item *
12883: 
12884: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12885: dumps the complete (or key matching regexp) namespace into a hash
12886: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12887: normally &store()ed into
12888: 
12889: $range should be either an integer '100' (give me the first 100
12890:                                            matching records)
12891:               or be  two integers sperated by a - with no spaces
12892:                  '30-50' (give me the 30th through the 50th matching
12893:                           records)
12894: 
12895: 
12896: =item *
12897: 
12898: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12899: replaces a &store() version of data with a replacement set of data
12900: for a particular resource in a namespace passed in the $storehash hash 
12901: reference
12902: 
12903: =item *
12904: 
12905: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12906: works very similar to store/cstore, but all data is stored in a
12907: temporary location and can be reset using tmpreset, $storehash should
12908: be a hash reference, returns nothing on success
12909: 
12910: =item *
12911: 
12912: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12913: similar to restore, but all data is stored in a temporary location and
12914: can be reset using tmpreset. Returns a hash of values on success,
12915: error string otherwise.
12916: 
12917: =item *
12918: 
12919: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12920: deltes all keys for $symb form the temporary storage hash.
12921: 
12922: =item *
12923: 
12924: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12925: reference filled in from namesp ($udom and $uname are optional)
12926: 
12927: =item *
12928: 
12929: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12930: namesp ($udom and $uname are optional)
12931: 
12932: =item *
12933: 
12934: dump($namespace,$udom,$uname,$regexp,$range) : 
12935: dumps the complete (or key matching regexp) namespace into a hash
12936: ($udom, $uname, $regexp, $range are optional)
12937: 
12938: $range should be either an integer '100' (give me the first 100
12939:                                            matching records)
12940:               or be  two integers sperated by a - with no spaces
12941:                  '30-50' (give me the 30th through the 50th matching
12942:                           records)
12943: =item *
12944: 
12945: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12946: $store can be a scalar, an array reference, or if the amount to be 
12947: incremented is > 1, a hash reference.
12948: 
12949: ($udom and $uname are optional)
12950: 
12951: =item *
12952: 
12953: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12954: ($udom and $uname are optional)
12955: 
12956: =item *
12957: 
12958: cput($namespace,$storehash,$udom,$uname) : critical put
12959: ($udom and $uname are optional)
12960: 
12961: =item *
12962: 
12963: newput($namespace,$storehash,$udom,$uname) :
12964: 
12965: Attempts to store the items in the $storehash, but only if they don't
12966: currently exist, if this succeeds you can be certain that you have 
12967: successfully created a new key value pair in the $namespace db.
12968: 
12969: 
12970: Args:
12971:  $namespace: name of database to store values to
12972:  $storehash: hashref to store to the db
12973:  $udom: (optional) domain of user containing the db
12974:  $uname: (optional) name of user caontaining the db
12975: 
12976: Returns:
12977:  'ok' -> succeeded in storing all keys of $storehash
12978:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12979:                         least <key> already existed in the db (other
12980:                         requested keys may also already exist)
12981:  'error: <msg>' -> unable to tie the DB or other error occurred
12982:  'con_lost' -> unable to contact request server
12983:  'refused' -> action was not allowed by remote machine
12984: 
12985: 
12986: =item *
12987: 
12988: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12989: reference filled in from namesp (encrypts the return communication)
12990: ($udom and $uname are optional)
12991: 
12992: =item *
12993: 
12994: log($udom,$name,$home,$message) : write to permanent log for user; use
12995: critical subroutine
12996: 
12997: =item *
12998: 
12999: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13000: array reference filled in from namespace found in domain level on either
13001: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13002: 
13003: =item *
13004: 
13005: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13006: domain level either on specified domain server ($uhome) or primary domain 
13007: server ($udom and $uhome are optional)
13008: 
13009: =item * 
13010: 
13011: get_domain_defaults($target_domain) : returns hash with defaults for
13012: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
13013: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
13014: or localauth), initial password or a kerberos realm, language (e.g., en-us).
13015: Values are retrieved from cache (if current), or from domain's configuration.db
13016: (if available), or lastly from values in lonTabs/dns_domain,tab, 
13017: or lonTabs/domain.tab. 
13018: 
13019: %domdefaults = &get_auth_defaults($target_domain);
13020: 
13021: =back
13022: 
13023: =head2 Network Status Functions
13024: 
13025: =over 4
13026: 
13027: =item *
13028: 
13029: dirlist() : return directory list based on URI (first arg).
13030: 
13031: Inputs: 1 required, 5 optional.
13032: 
13033: =over
13034: 
13035: =item 
13036: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13037: 
13038: =item
13039: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13040: 
13041: =item
13042: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13043: 
13044: =item
13045: $getpropath - boolean: 1 if prepend path using &propath(). 
13046: 
13047: =item
13048: $getuserdir - boolean: 1 if prepend path for "userfiles".
13049: 
13050: =item 
13051: $alternateRoot - path to prepend in place of path from $uri.
13052: 
13053: =back
13054: 
13055: Returns: Array of up to two items.
13056: 
13057: =over
13058: 
13059: a reference to an array of files/subdirectories
13060: 
13061: =over
13062: 
13063: Each element in the array of files/subdirectories is a & separated list of
13064: item name and the result of running stat on the item.  If dirlist was requested
13065: for a file instead of a directory, the item name will be ''. For a directory 
13066: listing, if the item is a metadata file, the element will end &N&M 
13067: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13068: default copyright set (1).  
13069: 
13070: =back
13071: 
13072: a scalar containing error condition (if encountered).
13073: 
13074: =over
13075: 
13076: =item 
13077: no_host (no homeserver identified for $username:$domain).
13078: 
13079: =item 
13080: no_such_host (server contacted for listing not identified as valid host).
13081: 
13082: =item 
13083: con_lost (connection to remote server failed).
13084: 
13085: =item 
13086: refused (invalid $username:$domain received on lond side).
13087: 
13088: =item 
13089: no_such_dir (directory at specified path on lond side does not exist). 
13090: 
13091: =item 
13092: empty (directory at specified path on lond side is empty).
13093: 
13094: =over
13095: 
13096: This is currently not encountered because the &ls3, &ls2, 
13097: &ls (_handler) routines on the lond side do not filter out
13098: . and .. from a directory listing. 
13099: 
13100: =back
13101: 
13102: =back
13103: 
13104: =back
13105: 
13106: =item *
13107: 
13108: spareserver() : find server with least workload from spare.tab
13109: 
13110: 
13111: =item *
13112: 
13113: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13114: if there is no corresponding loncapa host.
13115: 
13116: =back
13117: 
13118: 
13119: =head2 Apache Request
13120: 
13121: =over 4
13122: 
13123: =item *
13124: 
13125: ssi($url,%hash) : server side include, does a complete request cycle on url to
13126: localhost, posts hash
13127: 
13128: =back
13129: 
13130: =head2 Data to String to Data
13131: 
13132: =over 4
13133: 
13134: =item *
13135: 
13136: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13137: and '&' separators, supports elements that are arrayrefs and hashrefs
13138: 
13139: =item *
13140: 
13141: hashref2str($hashref) : convert a hashref into a string complete with
13142: escaping and '=' and '&' separators, supports elements that are
13143: arrayrefs and hashrefs
13144: 
13145: =item *
13146: 
13147: arrayref2str($arrayref) : convert an arrayref into a string complete
13148: with escaping and '&' separators, supports elements that are arrayrefs
13149: and hashrefs
13150: 
13151: =item *
13152: 
13153: str2hash($string) : convert string to hash using unescaping and
13154: splitting on '=' and '&', supports elements that are arrayrefs and
13155: hashrefs
13156: 
13157: =item *
13158: 
13159: str2array($string) : convert string to hash using unescaping and
13160: splitting on '&', supports elements that are arrayrefs and hashrefs
13161: 
13162: =back
13163: 
13164: =head2 Logging Routines
13165: 
13166: 
13167: These routines allow one to make log messages in the lonnet.log and
13168: lonnet.perm logfiles.
13169: 
13170: =over 4
13171: 
13172: =item *
13173: 
13174: logtouch() : make sure the logfile, lonnet.log, exists
13175: 
13176: =item *
13177: 
13178: logthis() : append message to the normal lonnet.log file, it gets
13179: preiodically rolled over and deleted.
13180: 
13181: =item *
13182: 
13183: logperm() : append a permanent message to lonnet.perm.log, this log
13184: file never gets deleted by any automated portion of the system, only
13185: messages of critical importance should go in here.
13186: 
13187: 
13188: =back
13189: 
13190: =head2 General File Helper Routines
13191: 
13192: =over 4
13193: 
13194: =item *
13195: 
13196: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13197: (a) files in /uploaded
13198:   (i) If a local copy of the file exists - 
13199:       compares modification date of local copy with last-modified date for 
13200:       definitive version stored on home server for course. If local copy is 
13201:       stale, requests a new version from the home server and stores it. 
13202:       If the original has been removed from the home server, then local copy 
13203:       is unlinked.
13204:   (ii) If local copy does not exist -
13205:       requests the file from the home server and stores it. 
13206:   
13207:   If $caller is 'uploadrep':  
13208:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13209:     for request for files originally uploaded via DOCS. 
13210:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13211:   
13212:   Otherwise:
13213:      This indicates a call from the content generation phase of the request.
13214:      -  returns the entire contents of the file or -1.
13215:      
13216: (b) files in /res
13217:    - returns the entire contents of a file or -1; 
13218:    it properly subscribes to and replicates the file if neccessary.
13219: 
13220: 
13221: =item *
13222: 
13223: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13224:                   reference
13225: 
13226: returns either a stat() list of data about the file or an empty list
13227: if the file doesn't exist or couldn't find out about it (connection
13228: problems or user unknown)
13229: 
13230: =item *
13231: 
13232: filelocation($dir,$file) : returns file system location of a file
13233: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13234: directory that relative $file lookups are to looked in ($dir of /a/dir
13235: and a file of ../bob will become /a/bob)
13236: 
13237: =item *
13238: 
13239: hreflocation($dir,$file) : returns file system location or a URL; same as
13240: filelocation except for hrefs
13241: 
13242: =item *
13243: 
13244: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13245: 
13246: =back
13247: 
13248: =head2 Usererfile file routines (/uploaded*)
13249: 
13250: =over 4
13251: 
13252: =item *
13253: 
13254: userfileupload(): main rotine for putting a file in a user or course's
13255:                   filespace, arguments are,
13256: 
13257:  formname - required - this is the name of the element in $env where the
13258:            filename, and the contents of the file to create/modifed exist
13259:            the filename is in $env{'form.'.$formname.'.filename'} and the
13260:            contents of the file is located in $env{'form.'.$formname}
13261:  context - if coursedoc, store the file in the course of the active role
13262:              of the current user; 
13263:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13264:            if 'canceloverwrite': delete file in tmp/overwrites directory
13265:  subdir - required - subdirectory to put the file in under ../userfiles/
13266:          if undefined, it will be placed in "unknown"
13267: 
13268:  (This routine calls clean_filename() to remove any dangerous
13269:  characters from the filename, and then calls finuserfileupload() to
13270:  complete the transaction)
13271: 
13272:  returns either the url of the uploaded file (/uploaded/....) if successful
13273:  and /adm/notfound.html if unsuccessful
13274: 
13275: =item *
13276: 
13277: clean_filename(): routine for cleaing a filename up for storage in
13278:                  userfile space, argument is:
13279: 
13280:  filename - proposed filename
13281: 
13282: returns: the new clean filename
13283: 
13284: =item *
13285: 
13286: finishuserfileupload(): routine that creates and sends the file to
13287: userspace, probably shouldn't be called directly
13288: 
13289:   docuname: username or courseid of destination for the file
13290:   docudom: domain of user/course of destination for the file
13291:   formname: same as for userfileupload()
13292:   fname: filename (including subdirectories) for the file
13293:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13294:   allfiles: reference to hash used to store objects found by parser
13295:   codebase: reference to hash used for codebases of java objects found by parser
13296:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13297:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13298:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13299:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13300:   context: if 'overwrite', will move the uploaded file from its temporary location to
13301:             userfiles to facilitate overwriting a previously uploaded file with same name.
13302:   mimetype: reference to scalar to accommodate mime type determined
13303:             from File::MMagic if $parser = parse.
13304: 
13305:  returns either the url of the uploaded file (/uploaded/....) if successful
13306:  and /adm/notfound.html if unsuccessful (or an error message if context 
13307:  was 'overwrite').
13308:  
13309: 
13310: =item *
13311: 
13312: renameuserfile(): renames an existing userfile to a new name
13313: 
13314:   Args:
13315:    docuname: username or courseid of destination for the file
13316:    docudom: domain of user/course of destination for the file
13317:    old: current file name (including any subdirs under userfiles)
13318:    new: desired file name (including any subdirs under userfiles)
13319: 
13320: =item *
13321: 
13322: mkdiruserfile(): creates a directory is a userfiles dir
13323: 
13324:   Args:
13325:    docuname: username or courseid of destination for the file
13326:    docudom: domain of user/course of destination for the file
13327:    dir: dir to create (including any subdirs under userfiles)
13328: 
13329: =item *
13330: 
13331: removeuserfile(): removes a file that exists in userfiles
13332: 
13333:   Args:
13334:    docuname: username or courseid of destination for the file
13335:    docudom: domain of user/course of destination for the file
13336:    fname: filname to delete (including any subdirs under userfiles)
13337: 
13338: =item *
13339: 
13340: removeuploadedurl(): convience function for removeuserfile()
13341: 
13342:   Args:
13343:    url:  a full /uploaded/... url to delete
13344: 
13345: =item * 
13346: 
13347: get_portfile_permissions():
13348:   Args:
13349:     domain: domain of user or course contain the portfolio files
13350:     user: name of user or num of course contain the portfolio files
13351:   Returns:
13352:     hashref of a dump of the proper file_permissions.db
13353:    
13354: 
13355: =item * 
13356: 
13357: get_access_controls():
13358: 
13359: Args:
13360:   current_permissions: the hash ref returned from get_portfile_permissions()
13361:   group: (optional) the group you want the files associated with
13362:   file: (optional) the file you want access info on
13363: 
13364: Returns:
13365:     a hash (keys are file names) of hashes containing
13366:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13367:         values are XML containing access control settings (see below) 
13368: 
13369: Internal notes:
13370: 
13371:  access controls are stored in file_permissions.db as key=value pairs.
13372:     key -> path to file/file_name\0uniqueID:scope_end_start
13373:         where scope -> public,guest,course,group,domains or users.
13374:               end -> UNIX time for end of access (0 -> no end date)
13375:               start -> UNIX time for start of access
13376: 
13377:     value -> XML description of access control
13378:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13379:             <start></start>
13380:             <end></end>
13381: 
13382:             <password></password>  for scope type = guest
13383: 
13384:             <domain></domain>     for scope type = course or group
13385:             <number></number>
13386:             <roles id="">
13387:              <role></role>
13388:              <access></access>
13389:              <section></section>
13390:              <group></group>
13391:             </roles>
13392: 
13393:             <dom></dom>         for scope type = domains
13394: 
13395:             <users>             for scope type = users
13396:              <user>
13397:               <uname></uname>
13398:               <udom></udom>
13399:              </user>
13400:             </users>
13401:            </scope> 
13402:               
13403:  Access data is also aggregated for each file in an additional key=value pair:
13404:  key -> path to file/file_name\0accesscontrol 
13405:  value -> reference to hash
13406:           hash contains key = value pairs
13407:           where key = uniqueID:scope_end_start
13408:                 value = UNIX time record was last updated
13409: 
13410:           Used to improve speed of look-ups of access controls for each file.  
13411:  
13412:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13413: 
13414: =item *
13415: 
13416: modify_access_controls():
13417: 
13418: Modifies access controls for a portfolio file
13419: Args
13420: 1. file name
13421: 2. reference to hash of required changes,
13422: 3. domain
13423: 4. username
13424:   where domain,username are the domain of the portfolio owner 
13425:   (either a user or a course) 
13426: 
13427: Returns:
13428: 1. result of additions or updates ('ok' or 'error', with error message). 
13429: 2. result of deletions ('ok' or 'error', with error message).
13430: 3. reference to hash of any new or updated access controls.
13431: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13432:    key = integer (inbound ID)
13433:    value = uniqueID
13434: 
13435: =item *
13436: 
13437: get_timebased_id():
13438: 
13439: Attempts to get a unique timestamp-based suffix for use with items added to a 
13440: course via the Course Editor (e.g., folders, composite pages, 
13441: group bulletin boards).
13442: 
13443: Args: (first three required; six others optional)
13444: 
13445: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13446:    docssequence, or name of group
13447: 
13448: 2. keyid (alphanumeric): name of temporary locking key in hash,
13449:    e.g., num, boardids
13450: 
13451: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13452:    file will be named nohist_namespace.db
13453: 
13454: 4. cdom: domain of course; default is current course domain from %env
13455: 
13456: 5. cnum: course number; default is current course number from %env
13457: 
13458: 6. idtype: set to concat if an additional digit is to be appended to the 
13459:    unix timestamp to form the suffix, if the plain timestamp is already
13460:    in use.  Default is to not do this, but simply increment the unix 
13461:    timestamp by 1 until a unique key is obtained.
13462: 
13463: 7. who: holder of locking key; defaults to user:domain for user.
13464: 
13465: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13466:    retrying); default is 3.
13467: 
13468: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13469: 
13470: Returns:
13471: 
13472: 1. suffix obtained (numeric)
13473: 
13474: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13475: 
13476: 3. error: contains (localized) error message if an error occurred.
13477: 
13478: 
13479: =back
13480: 
13481: =head2 HTTP Helper Routines
13482: 
13483: =over 4
13484: 
13485: =item *
13486: 
13487: escape() : unpack non-word characters into CGI-compatible hex codes
13488: 
13489: =item *
13490: 
13491: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13492: 
13493: =back
13494: 
13495: =head1 PRIVATE SUBROUTINES
13496: 
13497: =head2 Underlying communication routines (Shouldn't call)
13498: 
13499: =over 4
13500: 
13501: =item *
13502: 
13503: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13504: 
13505: =item *
13506: 
13507: reply() : uses subreply to send a message to remote machine, logs all failures
13508: 
13509: =item *
13510: 
13511: critical() : passes a critical message to another server; if cannot
13512: get through then place message in connection buffer directory and
13513: returns con_delayed, if incapable of saving message, returns
13514: con_failed
13515: 
13516: =item *
13517: 
13518: reconlonc() : tries to reconnect lonc client processes.
13519: 
13520: =back
13521: 
13522: =head2 Resource Access Logging
13523: 
13524: =over 4
13525: 
13526: =item *
13527: 
13528: flushcourselogs() : flush (save) buffer logs and access logs
13529: 
13530: =item *
13531: 
13532: courselog($what) : save message for course in hash
13533: 
13534: =item *
13535: 
13536: courseacclog($what) : save message for course using &courselog().  Perform
13537: special processing for specific resource types (problems, exams, quizzes, etc).
13538: 
13539: =item *
13540: 
13541: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13542: as a PerlChildExitHandler
13543: 
13544: =back
13545: 
13546: =head2 Other
13547: 
13548: =over 4
13549: 
13550: =item *
13551: 
13552: symblist($mapname,%newhash) : update symbolic storage links
13553: 
13554: =back
13555: 
13556: =cut
13557: 

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