File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1210: download - view: text, annotated - select for diffs
Sat Feb 2 00:22:47 2013 UTC (11 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Utilities to checksum LON-CAPA modules to verify integrity of
  LON-CAPA installation, and also to check the availibility of new
  LON-CAPA releases.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1210 2013/02/02 00:22:47 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:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2720:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2721:                     return;
 2722:                 }
 2723:             } elsif (!$crsedit) {
 2724: #
 2725: # No edit allowed where CC has switched to student role.
 2726: #
 2727:                 return;
 2728:             }
 2729:         }
 2730:     }
 2731: 
 2732:     if ($file ne '') {
 2733:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2734:             if (&is_course_upload($file,$cnum,$cdom)) {
 2735:                 $uploaded = 1;
 2736:                 $incourse = 1;
 2737:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2738:                     $cfile = &hreflocation('',$file);
 2739:                     if ($env{'form.forceedit'}) {
 2740:                         $forceview = 1;
 2741:                     } else {
 2742:                         $forceedit = 1;
 2743:                     }
 2744:                 }
 2745:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2746:                 $incourse = 1;
 2747:                 if ($env{'form.forceedit'}) {
 2748:                     $forceview = 1;
 2749:                 } else {
 2750:                     $forceedit = 1;
 2751:                 }
 2752:                 $cfile = $resurl;
 2753:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2754:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2755:                     $incourse = 1;
 2756:                     if ($env{'form.forceedit'}) {
 2757:                         $forceview = 1;
 2758:                     } else {
 2759:                         $forceedit = 1;
 2760:                     }
 2761:                     $cfile = $resurl;
 2762:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2763:                     $incourse = 1;
 2764:                     $cfile = $resurl.'/smpedit';
 2765:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2766:                     $incourse = 1;
 2767:                     if ($env{'form.forceedit'}) {
 2768:                         $forceview = 1;
 2769:                     } else {
 2770:                         $forceedit = 1;
 2771:                     }
 2772:                     $cfile = $resurl;
 2773:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2774:                     $incourse = 1;
 2775:                     if ($env{'form.forceedit'}) {
 2776:                         $forceview = 1;
 2777:                     } else {
 2778:                         $forceedit = 1;
 2779:                     }
 2780:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2781:                 }
 2782:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2783:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2784:                 if (&is_on_map($template)) { 
 2785:                     $incourse = 1;
 2786:                     $forceview = 1;
 2787:                     $cfile = $template;
 2788:                 }
 2789:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2790:                     $incourse = 1;
 2791:                     if ($env{'form.forceedit'}) {
 2792:                         $forceview = 1;
 2793:                     } else {
 2794:                         $forceedit = 1;
 2795:                     }
 2796:                     $cfile = $resurl;
 2797:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2798:                 $incourse = 1;
 2799:                 $forceview = 1;
 2800:                 if ($symb) {
 2801:                     my ($map,$id,$res)=&decode_symb($symb);
 2802:                     $env{'request.symb'} = $symb;
 2803:                     $cfile = &clutter($res);
 2804:                 } else {
 2805:                     $cfile = $env{'form.suppurl'};
 2806:                     $cfile =~ s{^http://}{};
 2807:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2808:                 }
 2809:             }
 2810:         }
 2811:         if ($uploaded || $incourse) {
 2812:             $home=&homeserver($cnum,$cdom);
 2813:         } elsif ($file !~ m{/$}) {
 2814:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2815:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2816:             # Check that the user has permission to edit this resource
 2817:             my $setpriv = 1;
 2818:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2819:             if (defined($cfudom)) {
 2820:                 $home=&homeserver($cfuname,$cfudom);
 2821:                 $cfile=$file;
 2822:             }
 2823:         }
 2824:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2825:             (($home ne '') && ($home ne 'no_host'))) {
 2826:             my @ids=&current_machine_ids();
 2827:             unless (grep(/^\Q$home\E$/,@ids)) {
 2828:                 $switchserver=1;
 2829:             }
 2830:         }
 2831:     }
 2832:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2833: }
 2834: 
 2835: sub is_course_upload {
 2836:     my ($file,$cnum,$cdom) = @_;
 2837:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2838:     $uploadpath =~ s{^\/}{};
 2839:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2840:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2841:         return 1;
 2842:     }
 2843:     return;
 2844: }
 2845: 
 2846: sub in_course {
 2847:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2848:     if ($hideprivileged) {
 2849:         my $skipuser;
 2850:         if (&privileged($uname,$udom)) {
 2851:             $skipuser = 1;
 2852:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2853:             if ($coursehash{'nothideprivileged'}) {
 2854:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2855:                     my $user;
 2856:                     if ($item =~ /:/) {
 2857:                         $user = $item;
 2858:                     } else {
 2859:                         $user = join(':',split(/[\@]/,$item));
 2860:                     }
 2861:                     if ($user eq $uname.':'.$udom) {
 2862:                         undef($skipuser);
 2863:                         last;
 2864:                     }
 2865:                 }
 2866:             }
 2867:             if ($skipuser) {
 2868:                 return 0;
 2869:             }
 2870:         }
 2871:     }
 2872:     $type ||= 'any';
 2873:     if (!defined($cdom) || !defined($cnum)) {
 2874:         my $cid  = $env{'request.course.id'};
 2875:         $cdom = $env{'course.'.$cid.'.domain'};
 2876:         $cnum = $env{'course.'.$cid.'.num'};
 2877:     }
 2878:     my $typesref;
 2879:     if (($type eq 'any') || ($type eq 'all')) {
 2880:         $typesref = ['active','previous','future'];
 2881:     } elsif ($type eq 'previous' || $type eq 'future') {
 2882:         $typesref = [$type];
 2883:     }
 2884:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2885:                               $typesref,undef,[$cdom]);
 2886:     my ($tmp) = keys(%roles);
 2887:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2888:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2889:     if (@course_roles > 0) {
 2890:         return 1;
 2891:     }
 2892:     return 0;
 2893: }
 2894: 
 2895: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2896: # input: action, courseID, current domain, intended
 2897: #        path to file, source of file, instruction to parse file for objects,
 2898: #        ref to hash for embedded objects,
 2899: #        ref to hash for codebase of java objects.
 2900: #        reference to scalar to accommodate mime type determined
 2901: #          from File::MMagic if $parser = parse.
 2902: #
 2903: # output: url to file (if action was uploaddoc), 
 2904: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2905: #
 2906: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2907: # course.
 2908: #
 2909: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2910: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2911: #          course's home server.
 2912: #
 2913: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2914: #          be copied from $source (current location) to 
 2915: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2916: #         and will then be copied to
 2917: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2918: #         course's home server.
 2919: #
 2920: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2921: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2922: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2923: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2924: #         in course's home server.
 2925: #
 2926: 
 2927: sub process_coursefile {
 2928:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2929:         $mimetype)=@_;
 2930:     my $fetchresult;
 2931:     my $home=&homeserver($docuname,$docudom);
 2932:     if ($action eq 'propagate') {
 2933:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2934: 			     $home);
 2935:     } else {
 2936:         my $fpath = '';
 2937:         my $fname = $file;
 2938:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2939:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2940:         my $filepath = &build_filepath($fpath);
 2941:         if ($action eq 'copy') {
 2942:             if ($source eq '') {
 2943:                 $fetchresult = 'no source file';
 2944:                 return $fetchresult;
 2945:             } else {
 2946:                 my $destination = $filepath.'/'.$fname;
 2947:                 rename($source,$destination);
 2948:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2949:                                  $home);
 2950:             }
 2951:         } elsif ($action eq 'uploaddoc') {
 2952:             open(my $fh,'>'.$filepath.'/'.$fname);
 2953:             print $fh $env{'form.'.$source};
 2954:             close($fh);
 2955:             if ($parser eq 'parse') {
 2956:                 my $mm = new File::MMagic;
 2957:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2958:                 if ($type eq 'text/html') {
 2959:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2960:                     unless ($parse_result eq 'ok') {
 2961:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2962:                     }
 2963:                 }
 2964:                 if (ref($mimetype)) {
 2965:                     $$mimetype = $type;
 2966:                 } 
 2967:             }
 2968:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2969:                                  $home);
 2970:             if ($fetchresult eq 'ok') {
 2971:                 return '/uploaded/'.$fpath.'/'.$fname;
 2972:             } else {
 2973:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2974:                         ' to host '.$home.': '.$fetchresult);
 2975:                 return '/adm/notfound.html';
 2976:             }
 2977:         }
 2978:     }
 2979:     unless ( $fetchresult eq 'ok') {
 2980:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2981:              ' to host '.$home.': '.$fetchresult);
 2982:     }
 2983:     return $fetchresult;
 2984: }
 2985: 
 2986: sub build_filepath {
 2987:     my ($fpath) = @_;
 2988:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2989:     unless ($fpath eq '') {
 2990:         my @parts=split('/',$fpath);
 2991:         foreach my $part (@parts) {
 2992:             $filepath.= '/'.$part;
 2993:             if ((-e $filepath)!=1) {
 2994:                 mkdir($filepath,0777);
 2995:             }
 2996:         }
 2997:     }
 2998:     return $filepath;
 2999: }
 3000: 
 3001: sub store_edited_file {
 3002:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3003:     my $file = $primary_url;
 3004:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3005:     my $fpath = '';
 3006:     my $fname = $file;
 3007:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3008:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3009:     my $filepath = &build_filepath($fpath);
 3010:     open(my $fh,'>'.$filepath.'/'.$fname);
 3011:     print $fh $content;
 3012:     close($fh);
 3013:     my $home=&homeserver($docuname,$docudom);
 3014:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3015: 			  $home);
 3016:     if ($$fetchresult eq 'ok') {
 3017:         return '/uploaded/'.$fpath.'/'.$fname;
 3018:     } else {
 3019:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3020: 		 ' to host '.$home.': '.$$fetchresult);
 3021:         return '/adm/notfound.html';
 3022:     }
 3023: }
 3024: 
 3025: sub clean_filename {
 3026:     my ($fname,$args)=@_;
 3027: # Replace Windows backslashes by forward slashes
 3028:     $fname=~s/\\/\//g;
 3029:     if (!$args->{'keep_path'}) {
 3030:         # Get rid of everything but the actual filename
 3031: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3032:     }
 3033: # Replace spaces by underscores
 3034:     $fname=~s/\s+/\_/g;
 3035: # Replace all other weird characters by nothing
 3036:     $fname=~s{[^/\w\.\-]}{}g;
 3037: # Replace all .\d. sequences with _\d. so they no longer look like version
 3038: # numbers
 3039:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3040:     return $fname;
 3041: }
 3042: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3043: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3044: # image with the same aspect ratio as the original, but with dimensions which do 
 3045: # not exceed $resizewidth and $resizeheight.
 3046:  
 3047: sub resizeImage {
 3048:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3049:     my $ima = Image::Magick->new;
 3050:     my $resized;
 3051:     if (-e $img_path) {
 3052:         $ima->Read($img_path);
 3053:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3054:             my $width = $ima->Get('width');
 3055:             my $height = $ima->Get('height');
 3056:             if ($width > $resizewidth) {
 3057: 	        my $factor = $width/$resizewidth;
 3058:                 my $newheight = $height/$factor;
 3059:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3060:                 $resized = 1;
 3061:             }
 3062:         }
 3063:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3064:             my $width = $ima->Get('width');
 3065:             my $height = $ima->Get('height');
 3066:             if ($height > $resizeheight) {
 3067:                 my $factor = $height/$resizeheight;
 3068:                 my $newwidth = $width/$factor;
 3069:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3070:                 $resized = 1;
 3071:             }
 3072:         }
 3073:         if ($resized) {
 3074:             $ima->Write($img_path);
 3075:         }
 3076:     }
 3077:     return;
 3078: }
 3079: 
 3080: # --------------- Take an uploaded file and put it into the userfiles directory
 3081: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3082: #                    the desired filename is in $env{"form.$formname.filename"}
 3083: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3084: #                                    canceloverwrite, or ''. 
 3085: #                   if 'coursedoc': upload to the current course
 3086: #                   if 'existingfile': write file to tmp/overwrites directory 
 3087: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3088: #                   $context is passed as argument to &finishuserfileupload
 3089: #        $subdir - directory in userfile to store the file into
 3090: #        $parser - instruction to parse file for objects ($parser = parse)    
 3091: #        $allfiles - reference to hash for embedded objects
 3092: #        $codebase - reference to hash for codebase of java objects
 3093: #        $desuname - username for permanent storage of uploaded file
 3094: #        $dsetudom - domain for permanaent storage of uploaded file
 3095: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3096: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3097: #        $resizewidth - width (pixels) to which to resize uploaded image
 3098: #        $resizeheight - height (pixels) to which to resize uploaded image
 3099: #        $mimetype - reference to scalar to accommodate mime type determined
 3100: #                    from File::MMagic.
 3101: # 
 3102: # output: url of file in userspace, or error: <message> 
 3103: #             or /adm/notfound.html if failure to upload occurse
 3104: 
 3105: sub userfileupload {
 3106:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3107:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3108:     if (!defined($subdir)) { $subdir='unknown'; }
 3109:     my $fname=$env{'form.'.$formname.'.filename'};
 3110:     $fname=&clean_filename($fname);
 3111:     # See if there is anything left
 3112:     unless ($fname) { return 'error: no uploaded file'; }
 3113:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3114:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3115:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3116:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3117:         my $now = time;
 3118:         my $filepath;
 3119:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3120:              $filepath = 'tmp/helprequests/'.$now;
 3121:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3122:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3123:                          '_'.$env{'user.domain'}.'/pending';
 3124:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3125:             my ($docuname,$docudom);
 3126:             if ($destudom) {
 3127:                 $docudom = $destudom;
 3128:             } else {
 3129:                 $docudom = $env{'user.domain'};
 3130:             }
 3131:             if ($destuname) {
 3132:                 $docuname = $destuname;
 3133:             } else {
 3134:                 $docuname = $env{'user.name'};
 3135:             }
 3136:             if (exists($env{'form.group'})) {
 3137:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3138:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3139:             }
 3140:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3141:             if ($context eq 'canceloverwrite') {
 3142:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3143:                 if (-e  $tempfile) {
 3144:                     my @info = stat($tempfile);
 3145:                     if ($info[9] eq $env{'form.timestamp'}) {
 3146:                         unlink($tempfile);
 3147:                     }
 3148:                 }
 3149:                 return;
 3150:             }
 3151:         }
 3152:         # Create the directory if not present
 3153:         my @parts=split(/\//,$filepath);
 3154:         my $fullpath = $perlvar{'lonDaemons'};
 3155:         for (my $i=0;$i<@parts;$i++) {
 3156:             $fullpath .= '/'.$parts[$i];
 3157:             if ((-e $fullpath)!=1) {
 3158:                 mkdir($fullpath,0777);
 3159:             }
 3160:         }
 3161:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3162:         print $fh $env{'form.'.$formname};
 3163:         close($fh);
 3164:         if ($context eq 'existingfile') {
 3165:             my @info = stat($fullpath.'/'.$fname);
 3166:             return ($fullpath.'/'.$fname,$info[9]);
 3167:         } else {
 3168:             return $fullpath.'/'.$fname;
 3169:         }
 3170:     }
 3171:     if ($subdir eq 'scantron') {
 3172:         $fname = 'scantron_orig_'.$fname;
 3173:     } else {
 3174:         $fname="$subdir/$fname";
 3175:     }
 3176:     if ($context eq 'coursedoc') {
 3177: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3178: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3179:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3180:             return &finishuserfileupload($docuname,$docudom,
 3181: 					 $formname,$fname,$parser,$allfiles,
 3182: 					 $codebase,$thumbwidth,$thumbheight,
 3183:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3184:         } else {
 3185:             $fname=$env{'form.folder'}.'/'.$fname;
 3186:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3187: 				       $fname,$formname,$parser,
 3188: 				       $allfiles,$codebase,$mimetype);
 3189:         }
 3190:     } elsif (defined($destuname)) {
 3191:         my $docuname=$destuname;
 3192:         my $docudom=$destudom;
 3193: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3194: 				     $parser,$allfiles,$codebase,
 3195:                                      $thumbwidth,$thumbheight,
 3196:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3197:     } else {
 3198:         my $docuname=$env{'user.name'};
 3199:         my $docudom=$env{'user.domain'};
 3200:         if (exists($env{'form.group'})) {
 3201:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3202:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3203:         }
 3204: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3205: 				     $parser,$allfiles,$codebase,
 3206:                                      $thumbwidth,$thumbheight,
 3207:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3208:     }
 3209: }
 3210: 
 3211: sub finishuserfileupload {
 3212:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3213:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3214:     my $path=$docudom.'/'.$docuname.'/';
 3215:     my $filepath=$perlvar{'lonDocRoot'};
 3216:   
 3217:     my ($fnamepath,$file,$fetchthumb);
 3218:     $file=$fname;
 3219:     if ($fname=~m|/|) {
 3220:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3221: 	$path.=$fnamepath.'/';
 3222:     }
 3223:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3224:     my $count;
 3225:     for ($count=4;$count<=$#parts;$count++) {
 3226:         $filepath.="/$parts[$count]";
 3227:         if ((-e $filepath)!=1) {
 3228: 	    mkdir($filepath,0777);
 3229:         }
 3230:     }
 3231: 
 3232: # Save the file
 3233:     {
 3234: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3235: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3236: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3237: 	    return '/adm/notfound.html';
 3238: 	}
 3239:         if ($context eq 'overwrite') {
 3240:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3241:             my $target = $filepath.'/'.$file;
 3242:             if (-e $source) {
 3243:                 my @info = stat($source);
 3244:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3245:                     unless (&File::Copy::move($source,$target)) {
 3246:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3247:                         return "Moving from $source failed";
 3248:                     }
 3249:                 } else {
 3250:                     return "Temporary file: $source had unexpected date/time for last modification";
 3251:                 }
 3252:             } else {
 3253:                 return "Temporary file: $source missing";
 3254:             }
 3255:         } elsif (!print FH ($env{'form.'.$formname})) {
 3256: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3257: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3258: 	    return '/adm/notfound.html';
 3259: 	}
 3260: 	close(FH);
 3261:         if ($resizewidth && $resizeheight) {
 3262:             my $mm = new File::MMagic;
 3263:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3264:             if ($mime_type =~ m{^image/}) {
 3265: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3266:             }  
 3267: 	}
 3268:     }
 3269:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3270:         if (ref($mimetype)) {
 3271:             if ($$mimetype eq '') {
 3272:                 my $mm = new File::MMagic;
 3273:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3274:                 $$mimetype = $type;
 3275:             }
 3276:         }
 3277:     }
 3278:     if ($parser eq 'parse') {
 3279:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3280:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3281:                                                        $allfiles,$codebase);
 3282:             unless ($parse_result eq 'ok') {
 3283:                 &logthis('Failed to parse '.$filepath.$file.
 3284: 	   	         ' for embedded media: '.$parse_result); 
 3285:             }
 3286:         }
 3287:     }
 3288:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3289:         my $input = $filepath.'/'.$file;
 3290:         my $output = $filepath.'/'.'tn-'.$file;
 3291:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3292:         system("convert -sample $thumbsize $input $output");
 3293:         if (-e $filepath.'/'.'tn-'.$file) {
 3294:             $fetchthumb  = 1; 
 3295:         }
 3296:     }
 3297:  
 3298: # Notify homeserver to grep it
 3299: #
 3300:     my $docuhome=&homeserver($docuname,$docudom);	
 3301:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3302:     if ($fetchresult eq 'ok') {
 3303:         if ($fetchthumb) {
 3304:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3305:             if ($thumbresult ne 'ok') {
 3306:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3307:                          $docuhome.': '.$thumbresult);
 3308:             }
 3309:         }
 3310: #
 3311: # Return the URL to it
 3312:         return '/uploaded/'.$path.$file;
 3313:     } else {
 3314:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3315: 		 ': '.$fetchresult);
 3316:         return '/adm/notfound.html';
 3317:     }
 3318: }
 3319: 
 3320: sub extract_embedded_items {
 3321:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3322:     my @state = ();
 3323:     my (%lastids,%related,%shockwave,%flashvars);
 3324:     my %javafiles = (
 3325:                       codebase => '',
 3326:                       code => '',
 3327:                       archive => ''
 3328:                     );
 3329:     my %mediafiles = (
 3330:                       src => '',
 3331:                       movie => '',
 3332:                      );
 3333:     my $p;
 3334:     if ($content) {
 3335:         $p = HTML::LCParser->new($content);
 3336:     } else {
 3337:         $p = HTML::LCParser->new($fullpath);
 3338:     }
 3339:     while (my $t=$p->get_token()) {
 3340: 	if ($t->[0] eq 'S') {
 3341: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3342: 	    push(@state, $tagname);
 3343:             if (lc($tagname) eq 'allow') {
 3344:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3345:             }
 3346: 	    if (lc($tagname) eq 'img') {
 3347: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3348: 	    }
 3349: 	    if (lc($tagname) eq 'a') {
 3350: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3351: 	    }
 3352:             if (lc($tagname) eq 'script') {
 3353:                 my $src;
 3354:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3355:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3356:                 } else {
 3357:                     if ($attr->{'src'} ne '') {
 3358:                         $src = $attr->{'src'};
 3359:                         &add_filetype($allfiles,$src,'src');
 3360:                     }
 3361:                 }
 3362:                 my $text = $p->get_trimmed_text();
 3363:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3364:                     my @swfargs = split(/,/,$1);
 3365:                     foreach my $item (@swfargs) {
 3366:                         $item =~ s/["']//g;
 3367:                         $item =~ s/^\s+//;
 3368:                         $item =~ s/\s+$//;
 3369:                     }
 3370:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3371:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3372:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3373:                         } else {
 3374:                             $related{$swfargs[0]} = [$swfargs[2]];
 3375:                         }
 3376:                     }
 3377:                 }
 3378:             }
 3379:             if (lc($tagname) eq 'link') {
 3380:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3381:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3382:                 }
 3383:             }
 3384: 	    if (lc($tagname) eq 'object' ||
 3385: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3386: 		foreach my $item (keys(%javafiles)) {
 3387: 		    $javafiles{$item} = '';
 3388: 		}
 3389:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3390:                     $lastids{lc($tagname)} = $attr->{'id'};
 3391:                 }
 3392: 	    }
 3393: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3394: 		my $name = lc($attr->{'name'});
 3395: 		foreach my $item (keys(%javafiles)) {
 3396: 		    if ($name eq $item) {
 3397: 			$javafiles{$item} = $attr->{'value'};
 3398: 			last;
 3399: 		    }
 3400: 		}
 3401:                 my $pathfrom;
 3402: 		foreach my $item (keys(%mediafiles)) {
 3403: 		    if ($name eq $item) {
 3404:                         $pathfrom = $attr->{'value'};
 3405:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3406: 			&add_filetype($allfiles,$pathfrom,$name);
 3407: 			last;
 3408: 		    }
 3409: 		}
 3410:                 if ($name eq 'flashvars') {
 3411:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3412:                 }
 3413:                 if ($pathfrom ne '') {
 3414:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3415:                                          $pathfrom);
 3416:                 }
 3417: 	    }
 3418: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3419: 		foreach my $item (keys(%javafiles)) {
 3420: 		    if ($attr->{$item}) {
 3421: 			$javafiles{$item} = $attr->{$item};
 3422: 			last;
 3423: 		    }
 3424: 		}
 3425: 		foreach my $item (keys(%mediafiles)) {
 3426: 		    if ($attr->{$item}) {
 3427: 			&add_filetype($allfiles,$attr->{$item},$item);
 3428: 			last;
 3429: 		    }
 3430: 		}
 3431:                 if (lc($tagname) eq 'embed') {
 3432:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3433:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3434:                                              $attr->{'src'});
 3435:                     }
 3436:                 }
 3437: 	    }
 3438:             if ($t->[4] =~ m{/>$}) {
 3439:                 pop(@state);  
 3440:             }
 3441: 	} elsif ($t->[0] eq 'E') {
 3442: 	    my ($tagname) = ($t->[1]);
 3443: 	    if ($javafiles{'codebase'} ne '') {
 3444: 		$javafiles{'codebase'} .= '/';
 3445: 	    }  
 3446: 	    if (lc($tagname) eq 'applet' ||
 3447: 		lc($tagname) eq 'object' ||
 3448: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3449: 		) {
 3450: 		foreach my $item (keys(%javafiles)) {
 3451: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3452: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3453: 			&add_filetype($allfiles,$file,$item);
 3454: 		    }
 3455: 		}
 3456: 	    } 
 3457: 	    pop @state;
 3458: 	}
 3459:     }
 3460:     foreach my $id (sort(keys(%flashvars))) {
 3461:         if ($shockwave{$id} ne '') {
 3462:             my @pairs = split(/\&/,$flashvars{$id});
 3463:             foreach my $pair (@pairs) {
 3464:                 my ($key,$value) = split(/\=/,$pair);
 3465:                 if ($key eq 'thumb') {
 3466:                     &add_filetype($allfiles,$value,$key);
 3467:                 } elsif ($key eq 'content') {
 3468:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3469:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3470:                     if ($ext ne '') {
 3471:                         &add_filetype($allfiles,$path.$value,$ext);
 3472:                     }
 3473:                 }
 3474:             }
 3475:         }
 3476:     }
 3477:     return 'ok';
 3478: }
 3479: 
 3480: sub add_filetype {
 3481:     my ($allfiles,$file,$type)=@_;
 3482:     if (exists($allfiles->{$file})) {
 3483: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3484: 	    push(@{$allfiles->{$file}}, &escape($type));
 3485: 	}
 3486:     } else {
 3487: 	@{$allfiles->{$file}} = (&escape($type));
 3488:     }
 3489: }
 3490: 
 3491: sub embedded_dependency {
 3492:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3493:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3494:         if (($identifier ne '') &&
 3495:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3496:             ($pathfrom ne '')) {
 3497:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3498:             foreach my $dep (@{$related->{$identifier}}) {
 3499:                 &add_filetype($allfiles,$path.$dep,'object');
 3500:             }
 3501:         }
 3502:     }
 3503:     return;
 3504: }
 3505: 
 3506: sub removeuploadedurl {
 3507:     my ($url)=@_;	
 3508:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3509:     return &removeuserfile($uname,$udom,$fname);
 3510: }
 3511: 
 3512: sub removeuserfile {
 3513:     my ($docuname,$docudom,$fname)=@_;
 3514:     my $home=&homeserver($docuname,$docudom);    
 3515:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3516:     if ($result eq 'ok') {	
 3517:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3518:             my $metafile = $fname.'.meta';
 3519:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3520: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3521:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3522:             my $sqlresult = 
 3523:                 &update_portfolio_table($docuname,$docudom,$file,
 3524:                                         'portfolio_metadata',$group,
 3525:                                         'delete');
 3526:         }
 3527:     }
 3528:     return $result;
 3529: }
 3530: 
 3531: sub mkdiruserfile {
 3532:     my ($docuname,$docudom,$dir)=@_;
 3533:     my $home=&homeserver($docuname,$docudom);
 3534:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3535: }
 3536: 
 3537: sub renameuserfile {
 3538:     my ($docuname,$docudom,$old,$new)=@_;
 3539:     my $home=&homeserver($docuname,$docudom);
 3540:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3541:                         &escape("$old").':'.&escape("$new"),$home);
 3542:     if ($result eq 'ok') {
 3543:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3544:             my $oldmeta = $old.'.meta';
 3545:             my $newmeta = $new.'.meta';
 3546:             my $metaresult = 
 3547:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3548: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3549:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3550:             my $sqlresult = 
 3551:                 &update_portfolio_table($docuname,$docudom,$file,
 3552:                                         'portfolio_metadata',$group,
 3553:                                         'delete');
 3554:         }
 3555:     }
 3556:     return $result;
 3557: }
 3558: 
 3559: # ------------------------------------------------------------------------- Log
 3560: 
 3561: sub log {
 3562:     my ($dom,$nam,$hom,$what)=@_;
 3563:     return critical("log:$dom:$nam:$what",$hom);
 3564: }
 3565: 
 3566: # ------------------------------------------------------------------ Course Log
 3567: #
 3568: # This routine flushes several buffers of non-mission-critical nature
 3569: #
 3570: 
 3571: sub flushcourselogs {
 3572:     &logthis('Flushing log buffers');
 3573: #
 3574: # course logs
 3575: # This is a log of all transactions in a course, which can be used
 3576: # for data mining purposes
 3577: #
 3578: # It also collects the courseid database, which lists last transaction
 3579: # times and course titles for all courseids
 3580: #
 3581:     my %courseidbuffer=();
 3582:     foreach my $crsid (keys(%courselogs)) {
 3583:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3584: 		          &escape($courselogs{$crsid}),
 3585: 		          $coursehombuf{$crsid}) eq 'ok') {
 3586: 	    delete $courselogs{$crsid};
 3587:         } else {
 3588:             &logthis('Failed to flush log buffer for '.$crsid);
 3589:             if (length($courselogs{$crsid})>40000) {
 3590:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3591:                         " exceeded maximum size, deleting.</font>");
 3592:                delete $courselogs{$crsid};
 3593:             }
 3594:         }
 3595:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3596:             'description' => $coursedescrbuf{$crsid},
 3597:             'inst_code'    => $courseinstcodebuf{$crsid},
 3598:             'type'        => $coursetypebuf{$crsid},
 3599:             'owner'       => $courseownerbuf{$crsid},
 3600:         };
 3601:     }
 3602: #
 3603: # Write course id database (reverse lookup) to homeserver of courses 
 3604: # Is used in pickcourse
 3605: #
 3606:     foreach my $crs_home (keys(%courseidbuffer)) {
 3607:         my $response = &courseidput(&host_domain($crs_home),
 3608:                                     $courseidbuffer{$crs_home},
 3609:                                     $crs_home,'timeonly');
 3610:     }
 3611: #
 3612: # File accesses
 3613: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3614: #
 3615:     foreach my $entry (keys(%accesshash)) {
 3616:         if ($entry =~ /___count$/) {
 3617:             my ($dom,$name);
 3618:             ($dom,$name,undef)=
 3619: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3620:             if (! defined($dom) || $dom eq '' || 
 3621:                 ! defined($name) || $name eq '') {
 3622:                 my $cid = $env{'request.course.id'};
 3623:                 $dom  = $env{'request.'.$cid.'.domain'};
 3624:                 $name = $env{'request.'.$cid.'.num'};
 3625:             }
 3626:             my $value = $accesshash{$entry};
 3627:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3628:             my %temphash=($url => $value);
 3629:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3630:             if ($result eq 'ok') {
 3631:                 delete $accesshash{$entry};
 3632:             }
 3633:         } else {
 3634:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3635:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3636:             my %temphash=($entry => $accesshash{$entry});
 3637:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3638:                 delete $accesshash{$entry};
 3639:             }
 3640:         }
 3641:     }
 3642: #
 3643: # Roles
 3644: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3645: #
 3646:     foreach my $entry (keys(%userrolehash)) {
 3647:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3648: 	    split(/\:/,$entry);
 3649:         if (&Apache::lonnet::put('nohist_userroles',
 3650:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3651:                 $rudom,$runame) eq 'ok') {
 3652: 	    delete $userrolehash{$entry};
 3653:         }
 3654:     }
 3655: #
 3656: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3657: #
 3658:     my %domrolebuffer = ();
 3659:     foreach my $entry (keys(%domainrolehash)) {
 3660:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3661:         if ($domrolebuffer{$rudom}) {
 3662:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3663:                       '='.&escape($domainrolehash{$entry});
 3664:         } else {
 3665:             $domrolebuffer{$rudom}.=&escape($entry).
 3666:                       '='.&escape($domainrolehash{$entry});
 3667:         }
 3668:         delete $domainrolehash{$entry};
 3669:     }
 3670:     foreach my $dom (keys(%domrolebuffer)) {
 3671: 	my %servers = &get_servers($dom,'library');
 3672: 	foreach my $tryserver (keys(%servers)) {
 3673: 	    unless (&reply('domroleput:'.$dom.':'.
 3674: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3675: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3676: 	    }
 3677:         }
 3678:     }
 3679:     $dumpcount++;
 3680: }
 3681: 
 3682: sub courselog {
 3683:     my $what=shift;
 3684:     $what=time.':'.$what;
 3685:     unless ($env{'request.course.id'}) { return ''; }
 3686:     $coursedombuf{$env{'request.course.id'}}=
 3687:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3688:     $coursenumbuf{$env{'request.course.id'}}=
 3689:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3690:     $coursehombuf{$env{'request.course.id'}}=
 3691:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3692:     $coursedescrbuf{$env{'request.course.id'}}=
 3693:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3694:     $courseinstcodebuf{$env{'request.course.id'}}=
 3695:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3696:     $courseownerbuf{$env{'request.course.id'}}=
 3697:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3698:     $coursetypebuf{$env{'request.course.id'}}=
 3699:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3700:     if (defined $courselogs{$env{'request.course.id'}}) {
 3701: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3702:     } else {
 3703: 	$courselogs{$env{'request.course.id'}}.=$what;
 3704:     }
 3705:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3706: 	&flushcourselogs();
 3707:     }
 3708: }
 3709: 
 3710: sub courseacclog {
 3711:     my $fnsymb=shift;
 3712:     unless ($env{'request.course.id'}) { return ''; }
 3713:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3714:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3715:         $what.=':POST';
 3716:         # FIXME: Probably ought to escape things....
 3717: 	foreach my $key (keys(%env)) {
 3718:             if ($key=~/^form\.(.*)/) {
 3719:                 my $formitem = $1;
 3720:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3721:                     $what.=':'.$formitem.'='.$env{$key};
 3722:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3723:                     $what.=':'.$formitem.'='.$env{$key};
 3724:                 }
 3725:             }
 3726:         }
 3727:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3728:         # FIXME: We should not be depending on a form parameter that someone
 3729:         # editing lonsearchcat.pm might change in the future.
 3730:         if ($env{'form.phase'} eq 'course_search') {
 3731:             $what.= ':POST';
 3732:             # FIXME: Probably ought to escape things....
 3733:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3734:                                  'crsdiscuss') {
 3735:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3736:             }
 3737:         }
 3738:     }
 3739:     &courselog($what);
 3740: }
 3741: 
 3742: sub countacc {
 3743:     my $url=&declutter(shift);
 3744:     return if (! defined($url) || $url eq '');
 3745:     unless ($env{'request.course.id'}) { return ''; }
 3746: #
 3747: # Mark that this url was used in this course
 3748: #
 3749:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3750: #
 3751: # Increase the access count for this resource in this child process
 3752: #
 3753:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3754:     $accesshash{$key}++;
 3755: }
 3756: 
 3757: sub linklog {
 3758:     my ($from,$to)=@_;
 3759:     $from=&declutter($from);
 3760:     $to=&declutter($to);
 3761:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3762:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3763: }
 3764: 
 3765: sub statslog {
 3766:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3767:     if ($users<2) { return; }
 3768:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3769:             'course'       => $env{'request.course.id'},
 3770:             'sections'     => '"all"',
 3771:             'num_students' => $users,
 3772:             'part'         => $part,
 3773:             'symb'         => $symb,
 3774:             'mean_tries'   => $av_attempts,
 3775:             'deg_of_diff'  => $degdiff});
 3776:     foreach my $key (keys(%dynstore)) {
 3777:         $accesshash{$key}=$dynstore{$key};
 3778:     }
 3779: }
 3780:   
 3781: sub userrolelog {
 3782:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3783:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3784:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3785:        $userrolehash
 3786:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3787:                     =$tend.':'.$tstart;
 3788:     }
 3789:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3790:        $userrolehash
 3791:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3792:                     =$tend.':'.$tstart;
 3793:     }
 3794:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3795:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3796:        $domainrolehash
 3797:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3798:                     = $tend.':'.$tstart;
 3799:     }
 3800: }
 3801: 
 3802: sub courserolelog {
 3803:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3804:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3805:         my $cdom = $1;
 3806:         my $cnum = $2;
 3807:         my $sec = $3;
 3808:         my $namespace = 'rolelog';
 3809:         my %storehash = (
 3810:                            role    => $trole,
 3811:                            start   => $tstart,
 3812:                            end     => $tend,
 3813:                            selfenroll => $selfenroll,
 3814:                            context    => $context,
 3815:                         );
 3816:         if ($trole eq 'gr') {
 3817:             $namespace = 'groupslog';
 3818:             $storehash{'group'} = $sec;
 3819:         } else {
 3820:             $storehash{'section'} = $sec;
 3821:         }
 3822:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3823:                    $domain,$cnum,$cdom);
 3824:         if (($trole ne 'st') || ($sec ne '')) {
 3825:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3826:         }
 3827:     }
 3828:     return;
 3829: }
 3830: 
 3831: sub domainrolelog {
 3832:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3833:     if ($area =~ m{^/($match_domain)/$}) {
 3834:         my $cdom = $1;
 3835:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3836:         my $namespace = 'rolelog';
 3837:         my %storehash = (
 3838:                            role    => $trole,
 3839:                            start   => $tstart,
 3840:                            end     => $tend,
 3841:                            context => $context,
 3842:                         );
 3843:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3844:                    $domain,$domconfiguser,$cdom);
 3845:     }
 3846:     return;
 3847: 
 3848: }
 3849: 
 3850: sub coauthorrolelog {
 3851:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3852:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3853:         my $audom = $1;
 3854:         my $auname = $2;
 3855:         my $namespace = 'rolelog';
 3856:         my %storehash = (
 3857:                            role    => $trole,
 3858:                            start   => $tstart,
 3859:                            end     => $tend,
 3860:                            context => $context,
 3861:                         );
 3862:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3863:                    $domain,$auname,$audom);
 3864:     }
 3865:     return;
 3866: }
 3867: 
 3868: sub get_course_adv_roles {
 3869:     my ($cid,$codes) = @_;
 3870:     $cid=$env{'request.course.id'} unless (defined($cid));
 3871:     my %coursehash=&coursedescription($cid);
 3872:     my $crstype = &Apache::loncommon::course_type($cid);
 3873:     my %nothide=();
 3874:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3875:         if ($user !~ /:/) {
 3876: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3877:         } else {
 3878:             $nothide{$user}=1;
 3879:         }
 3880:     }
 3881:     my %returnhash=();
 3882:     my %dumphash=
 3883:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3884:     my $now=time;
 3885:     my %privileged;
 3886:     foreach my $entry (keys(%dumphash)) {
 3887: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3888:         if (($tstart) && ($tstart<0)) { next; }
 3889:         if (($tend) && ($tend<$now)) { next; }
 3890:         if (($tstart) && ($now<$tstart)) { next; }
 3891:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3892: 	if ($username eq '' || $domain eq '') { next; }
 3893:         unless (ref($privileged{$domain}) eq 'HASH') {
 3894:             my %dompersonnel =
 3895:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3896:             $privileged{$domain} = {};
 3897:             foreach my $server (keys(%dompersonnel)) {
 3898:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3899:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3900:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3901:                         $privileged{$udom}{$uname} = 1;
 3902:                     }
 3903:                 }
 3904:             }
 3905:         }
 3906:         if ((exists($privileged{$domain}{$username})) && 
 3907:             (!$nothide{$username.':'.$domain})) { next; }
 3908: 	if ($role eq 'cr') { next; }
 3909:         if ($codes) {
 3910:             if ($section) { $role .= ':'.$section; }
 3911:             if ($returnhash{$role}) {
 3912:                 $returnhash{$role}.=','.$username.':'.$domain;
 3913:             } else {
 3914:                 $returnhash{$role}=$username.':'.$domain;
 3915:             }
 3916:         } else {
 3917:             my $key=&plaintext($role,$crstype);
 3918:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3919:             if ($returnhash{$key}) {
 3920: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3921:             } else {
 3922:                 $returnhash{$key}=$username.':'.$domain;
 3923:             }
 3924:         }
 3925:     }
 3926:     return %returnhash;
 3927: }
 3928: 
 3929: sub get_my_roles {
 3930:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3931:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3932:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3933:     my (%dumphash,%nothide);
 3934:     if ($context eq 'userroles') {
 3935:         %dumphash = &dump('roles',$udom,$uname);
 3936:     } else {
 3937:         %dumphash=
 3938:             &dump('nohist_userroles',$udom,$uname);
 3939:         if ($hidepriv) {
 3940:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3941:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3942:                 if ($user !~ /:/) {
 3943:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3944:                 } else {
 3945:                     $nothide{$user} = 1;
 3946:                 }
 3947:             }
 3948:         }
 3949:     }
 3950:     my %returnhash=();
 3951:     my $now=time;
 3952:     my %privileged;
 3953:     foreach my $entry (keys(%dumphash)) {
 3954:         my ($role,$tend,$tstart);
 3955:         if ($context eq 'userroles') {
 3956:             next if ($entry =~ /^rolesdef/);
 3957: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3958:         } else {
 3959:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3960:         }
 3961:         if (($tstart) && ($tstart<0)) { next; }
 3962:         my $status = 'active';
 3963:         if (($tend) && ($tend<=$now)) {
 3964:             $status = 'previous';
 3965:         } 
 3966:         if (($tstart) && ($now<$tstart)) {
 3967:             $status = 'future';
 3968:         }
 3969:         if (ref($types) eq 'ARRAY') {
 3970:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3971:                 next;
 3972:             } 
 3973:         } else {
 3974:             if ($status ne 'active') {
 3975:                 next;
 3976:             }
 3977:         }
 3978:         my ($rolecode,$username,$domain,$section,$area);
 3979:         if ($context eq 'userroles') {
 3980:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 3981:             (undef,$domain,$username,$section) = split(/\//,$area);
 3982:         } else {
 3983:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3984:         }
 3985:         if (ref($roledoms) eq 'ARRAY') {
 3986:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3987:                 next;
 3988:             }
 3989:         }
 3990:         if (ref($roles) eq 'ARRAY') {
 3991:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3992:                 if ($role =~ /^cr\//) {
 3993:                     if (!grep(/^cr$/,@{$roles})) {
 3994:                         next;
 3995:                     }
 3996:                 } elsif ($role =~ /^gr\//) {
 3997:                     if (!grep(/^gr$/,@{$roles})) {
 3998:                         next;
 3999:                     }
 4000:                 } else {
 4001:                     next;
 4002:                 }
 4003:             }
 4004:         }
 4005:         if ($hidepriv) {
 4006:             if ($context eq 'userroles') {
 4007:                 if ((&privileged($username,$domain)) &&
 4008:                     (!$nothide{$username.':'.$domain})) {
 4009:                     next;
 4010:                 }
 4011:             } else {
 4012:                 unless (ref($privileged{$domain}) eq 'HASH') {
 4013:                     my %dompersonnel =
 4014:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 4015:                     $privileged{$domain} = {};
 4016:                     if (keys(%dompersonnel)) {
 4017:                         foreach my $server (keys(%dompersonnel)) {
 4018:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 4019:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 4020:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 4021:                                     $privileged{$udom}{$uname} = $trole;
 4022:                                 }
 4023:                             }
 4024:                         }
 4025:                     }
 4026:                 }
 4027:                 if (exists($privileged{$domain}{$username})) {
 4028:                     if (!$nothide{$username.':'.$domain}) {
 4029:                         next;
 4030:                     }
 4031:                 }
 4032:             }
 4033:         }
 4034:         if ($withsec) {
 4035:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4036:                 $tstart.':'.$tend;
 4037:         } else {
 4038:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4039:         }
 4040:     }
 4041:     return %returnhash;
 4042: }
 4043: 
 4044: # ----------------------------------------------------- Frontpage Announcements
 4045: #
 4046: #
 4047: 
 4048: sub postannounce {
 4049:     my ($server,$text)=@_;
 4050:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4051:     unless ($text=~/\w/) { $text=''; }
 4052:     return &reply('setannounce:'.&escape($text),$server);
 4053: }
 4054: 
 4055: sub getannounce {
 4056: 
 4057:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4058: 	my $announcement='';
 4059: 	while (my $line = <$fh>) { $announcement .= $line; }
 4060: 	close($fh);
 4061: 	if ($announcement=~/\w/) { 
 4062: 	    return 
 4063:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4064:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4065: 	} else {
 4066: 	    return '';
 4067: 	}
 4068:     } else {
 4069: 	return '';
 4070:     }
 4071: }
 4072: 
 4073: # ---------------------------------------------------------- Course ID routines
 4074: # Deal with domain's nohist_courseid.db files
 4075: #
 4076: 
 4077: sub courseidput {
 4078:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4079:     return unless (ref($storehash) eq 'HASH');
 4080:     my $outcome;
 4081:     if ($caller eq 'timeonly') {
 4082:         my $cids = '';
 4083:         foreach my $item (keys(%$storehash)) {
 4084:             $cids.=&escape($item).'&';
 4085:         }
 4086:         $cids=~s/\&$//;
 4087:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4088:                           $coursehome);       
 4089:     } else {
 4090:         my $items = '';
 4091:         foreach my $item (keys(%$storehash)) {
 4092:             $items.= &escape($item).'='.
 4093:                      &freeze_escape($$storehash{$item}).'&';
 4094:         }
 4095:         $items=~s/\&$//;
 4096:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4097:                           $coursehome);
 4098:     }
 4099:     if ($outcome eq 'unknown_cmd') {
 4100:         my $what;
 4101:         foreach my $cid (keys(%$storehash)) {
 4102:             $what .= &escape($cid).'=';
 4103:             foreach my $item ('description','inst_code','owner','type') {
 4104:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4105:             }
 4106:             $what =~ s/\:$/&/;
 4107:         }
 4108:         $what =~ s/\&$//;  
 4109:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4110:     } else {
 4111:         return $outcome;
 4112:     }
 4113: }
 4114: 
 4115: sub courseiddump {
 4116:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4117:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4118:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4119:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4120:     my $as_hash = 1;
 4121:     my %returnhash;
 4122:     if (!$domfilter) { $domfilter=''; }
 4123:     my %libserv = &all_library();
 4124:     foreach my $tryserver (keys(%libserv)) {
 4125:         if ( (  $hostidflag == 1 
 4126: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4127: 	     || (!defined($hostidflag)) ) {
 4128: 
 4129: 	    if (($domfilter eq '') ||
 4130: 		(&host_domain($tryserver) eq $domfilter)) {
 4131:                 my $rep;
 4132:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4133:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4134:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4135:                                 &escape($descfilter), &escape($instcodefilter), 
 4136:                                 &escape($ownerfilter), &escape($coursefilter),
 4137:                                 &escape($typefilter), &escape($regexp_ok), 
 4138:                                 $as_hash, &escape($selfenrollonly), 
 4139:                                 &escape($catfilter), $showhidden, $caller, 
 4140:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4141:                                 &escape($createdbefore), &escape($createdafter), 
 4142:                                 &escape($creationcontext), $domcloner)));
 4143:                 } else {
 4144:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4145:                              $sincefilter.':'.&escape($descfilter).':'.
 4146:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4147:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4148:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4149:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4150:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4151:                              &escape($cc_clone).':'.$cloneonly.':'.
 4152:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4153:                              &escape($creationcontext).':'.$domcloner,
 4154:                              $tryserver);
 4155:                 }
 4156:                      
 4157:                 my @pairs=split(/\&/,$rep);
 4158:                 foreach my $item (@pairs) {
 4159:                     my ($key,$value)=split(/\=/,$item,2);
 4160:                     $key = &unescape($key);
 4161:                     next if ($key =~ /^error: 2 /);
 4162:                     my $result = &thaw_unescape($value);
 4163:                     if (ref($result) eq 'HASH') {
 4164:                         $returnhash{$key}=$result;
 4165:                     } else {
 4166:                         my @responses = split(/:/,$value);
 4167:                         my @items = ('description','inst_code','owner','type');
 4168:                         for (my $i=0; $i<@responses; $i++) {
 4169:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4170:                         }
 4171:                     }
 4172:                 }
 4173:             }
 4174:         }
 4175:     }
 4176:     return %returnhash;
 4177: }
 4178: 
 4179: sub courselastaccess {
 4180:     my ($cdom,$cnum,$hostidref) = @_;
 4181:     my %returnhash;
 4182:     if ($cdom && $cnum) {
 4183:         my $chome = &homeserver($cnum,$cdom);
 4184:         if ($chome ne 'no_host') {
 4185:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4186:             &extract_lastaccess(\%returnhash,$rep);
 4187:         }
 4188:     } else {
 4189:         if (!$cdom) { $cdom=''; }
 4190:         my %libserv = &all_library();
 4191:         foreach my $tryserver (keys(%libserv)) {
 4192:             if (ref($hostidref) eq 'ARRAY') {
 4193:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4194:             } 
 4195:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4196:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4197:                 &extract_lastaccess(\%returnhash,$rep);
 4198:             }
 4199:         }
 4200:     }
 4201:     return %returnhash;
 4202: }
 4203: 
 4204: sub extract_lastaccess {
 4205:     my ($returnhash,$rep) = @_;
 4206:     if (ref($returnhash) eq 'HASH') {
 4207:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4208:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4209:                  $rep eq '') {
 4210:             my @pairs=split(/\&/,$rep);
 4211:             foreach my $item (@pairs) {
 4212:                 my ($key,$value)=split(/\=/,$item,2);
 4213:                 $key = &unescape($key);
 4214:                 next if ($key =~ /^error: 2 /);
 4215:                 $returnhash->{$key} = &thaw_unescape($value);
 4216:             }
 4217:         }
 4218:     }
 4219:     return;
 4220: }
 4221: 
 4222: # ---------------------------------------------------------- DC e-mail
 4223: 
 4224: sub dcmailput {
 4225:     my ($domain,$msgid,$message,$server)=@_;
 4226:     my $status = &Apache::lonnet::critical(
 4227:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4228:        &escape($message),$server);
 4229:     return $status;
 4230: }
 4231: 
 4232: sub dcmaildump {
 4233:     my ($dom,$startdate,$enddate,$senders) = @_;
 4234:     my %returnhash=();
 4235: 
 4236:     if (defined(&domain($dom,'primary'))) {
 4237:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4238:                                                          &escape($enddate).':';
 4239: 	my @esc_senders=map { &escape($_)} @$senders;
 4240: 	$cmd.=&escape(join('&',@esc_senders));
 4241: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4242:             my ($key,$value) = split(/\=/,$line,2);
 4243:             if (($key) && ($value)) {
 4244:                 $returnhash{&unescape($key)} = &unescape($value);
 4245:             }
 4246:         }
 4247:     }
 4248:     return %returnhash;
 4249: }
 4250: # ---------------------------------------------------------- Domain roles
 4251: 
 4252: sub get_domain_roles {
 4253:     my ($dom,$roles,$startdate,$enddate)=@_;
 4254:     if ((!defined($startdate)) || ($startdate eq '')) {
 4255:         $startdate = '.';
 4256:     }
 4257:     if ((!defined($enddate)) || ($enddate eq '')) {
 4258:         $enddate = '.';
 4259:     }
 4260:     my $rolelist;
 4261:     if (ref($roles) eq 'ARRAY') {
 4262:         $rolelist = join(':',@{$roles});
 4263:     }
 4264:     my %personnel = ();
 4265: 
 4266:     my %servers = &get_servers($dom,'library');
 4267:     foreach my $tryserver (keys(%servers)) {
 4268: 	%{$personnel{$tryserver}}=();
 4269: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4270: 					    &escape($startdate).':'.
 4271: 					    &escape($enddate).':'.
 4272: 					    &escape($rolelist), $tryserver))) {
 4273: 	    my ($key,$value) = split(/\=/,$line,2);
 4274: 	    if (($key) && ($value)) {
 4275: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4276: 	    }
 4277: 	}
 4278:     }
 4279:     return %personnel;
 4280: }
 4281: 
 4282: # ----------------------------------------------------------- Interval timing 
 4283: 
 4284: {
 4285: # Caches needed for speedup of navmaps
 4286: # We don't want to cache this for very long at all (5 seconds at most)
 4287: # 
 4288: # The user for whom we cache
 4289: my $cachedkey='';
 4290: # The cached times for this user
 4291: my %cachedtimes=();
 4292: # When this was last done
 4293: my $cachedtime=();
 4294: 
 4295: sub load_all_first_access {
 4296:     my ($uname,$udom)=@_;
 4297:     if (($cachedkey eq $uname.':'.$udom) &&
 4298:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4299:         return;
 4300:     }
 4301:     $cachedtime=time;
 4302:     $cachedkey=$uname.':'.$udom;
 4303:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4304: }
 4305: 
 4306: sub get_first_access {
 4307:     my ($type,$argsymb,$argmap)=@_;
 4308:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4309:     if ($argsymb) { $symb=$argsymb; }
 4310:     my ($map,$id,$res)=&decode_symb($symb);
 4311:     if ($argmap) { $map = $argmap; }
 4312:     if ($type eq 'course') {
 4313: 	$res='course';
 4314:     } elsif ($type eq 'map') {
 4315: 	$res=&symbread($map);
 4316:     } else {
 4317: 	$res=$symb;
 4318:     }
 4319:     &load_all_first_access($uname,$udom);
 4320:     return $cachedtimes{"$courseid\0$res"};
 4321: }
 4322: 
 4323: sub set_first_access {
 4324:     my ($type,$interval)=@_;
 4325:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4326:     my ($map,$id,$res)=&decode_symb($symb);
 4327:     if ($type eq 'course') {
 4328: 	$res='course';
 4329:     } elsif ($type eq 'map') {
 4330: 	$res=&symbread($map);
 4331:     } else {
 4332: 	$res=$symb;
 4333:     }
 4334:     $cachedkey='';
 4335:     my $firstaccess=&get_first_access($type,$symb,$map);
 4336:     if (!$firstaccess) {
 4337:         my $start = time;
 4338: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4339:                           $udom,$uname);
 4340:         if ($putres eq 'ok') {
 4341:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4342:                  $udom,$uname); 
 4343:             &appenv(
 4344:                      {
 4345:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4346:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4347:                      }
 4348:                   );
 4349:         }
 4350:         return $putres;
 4351:     }
 4352:     return 'already_set';
 4353: }
 4354: }
 4355: # --------------------------------------------- Set Expire Date for Spreadsheet
 4356: 
 4357: sub expirespread {
 4358:     my ($uname,$udom,$stype,$usymb)=@_;
 4359:     my $cid=$env{'request.course.id'}; 
 4360:     if ($cid) {
 4361:        my $now=time;
 4362:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4363:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4364:                             $env{'course.'.$cid.'.num'}.
 4365: 	        	    ':nohist_expirationdates:'.
 4366:                             &escape($key).'='.$now,
 4367:                             $env{'course.'.$cid.'.home'})
 4368:     }
 4369:     return 'ok';
 4370: }
 4371: 
 4372: # ----------------------------------------------------- Devalidate Spreadsheets
 4373: 
 4374: sub devalidate {
 4375:     my ($symb,$uname,$udom)=@_;
 4376:     my $cid=$env{'request.course.id'}; 
 4377:     if ($cid) {
 4378:         # delete the stored spreadsheets for
 4379:         # - the student level sheet of this user in course's homespace
 4380:         # - the assessment level sheet for this resource 
 4381:         #   for this user in user's homespace
 4382: 	# - current conditional state info
 4383: 	my $key=$uname.':'.$udom.':';
 4384:         my $status=
 4385: 	    &del('nohist_calculatedsheets',
 4386: 		 [$key.'studentcalc:'],
 4387: 		 $env{'course.'.$cid.'.domain'},
 4388: 		 $env{'course.'.$cid.'.num'})
 4389: 		.' '.
 4390: 	    &del('nohist_calculatedsheets_'.$cid,
 4391: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4392:         unless ($status eq 'ok ok') {
 4393:            &logthis('Could not devalidate spreadsheet '.
 4394:                     $uname.' at '.$udom.' for '.
 4395: 		    $symb.': '.$status);
 4396:         }
 4397: 	&delenv('user.state.'.$cid);
 4398:     }
 4399: }
 4400: 
 4401: sub get_scalar {
 4402:     my ($string,$end) = @_;
 4403:     my $value;
 4404:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4405: 	$value = $1;
 4406:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4407: 	$value = $1;
 4408:     }
 4409:     return &unescape($value);
 4410: }
 4411: 
 4412: sub array2str {
 4413:   my (@array) = @_;
 4414:   my $result=&arrayref2str(\@array);
 4415:   $result=~s/^__ARRAY_REF__//;
 4416:   $result=~s/__END_ARRAY_REF__$//;
 4417:   return $result;
 4418: }
 4419: 
 4420: sub arrayref2str {
 4421:   my ($arrayref) = @_;
 4422:   my $result='__ARRAY_REF__';
 4423:   foreach my $elem (@$arrayref) {
 4424:     if(ref($elem) eq 'ARRAY') {
 4425:       $result.=&arrayref2str($elem).'&';
 4426:     } elsif(ref($elem) eq 'HASH') {
 4427:       $result.=&hashref2str($elem).'&';
 4428:     } elsif(ref($elem)) {
 4429:       #print("Got a ref of ".(ref($elem))." skipping.");
 4430:     } else {
 4431:       $result.=&escape($elem).'&';
 4432:     }
 4433:   }
 4434:   $result=~s/\&$//;
 4435:   $result .= '__END_ARRAY_REF__';
 4436:   return $result;
 4437: }
 4438: 
 4439: sub hash2str {
 4440:   my (%hash) = @_;
 4441:   my $result=&hashref2str(\%hash);
 4442:   $result=~s/^__HASH_REF__//;
 4443:   $result=~s/__END_HASH_REF__$//;
 4444:   return $result;
 4445: }
 4446: 
 4447: sub hashref2str {
 4448:   my ($hashref)=@_;
 4449:   my $result='__HASH_REF__';
 4450:   foreach my $key (sort(keys(%$hashref))) {
 4451:     if (ref($key) eq 'ARRAY') {
 4452:       $result.=&arrayref2str($key).'=';
 4453:     } elsif (ref($key) eq 'HASH') {
 4454:       $result.=&hashref2str($key).'=';
 4455:     } elsif (ref($key)) {
 4456:       $result.='=';
 4457:       #print("Got a ref of ".(ref($key))." skipping.");
 4458:     } else {
 4459: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4460:     }
 4461: 
 4462:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4463:       $result.=&arrayref2str($hashref->{$key}).'&';
 4464:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4465:       $result.=&hashref2str($hashref->{$key}).'&';
 4466:     } elsif(ref($hashref->{$key})) {
 4467:        $result.='&';
 4468:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4469:     } else {
 4470:       $result.=&escape($hashref->{$key}).'&';
 4471:     }
 4472:   }
 4473:   $result=~s/\&$//;
 4474:   $result .= '__END_HASH_REF__';
 4475:   return $result;
 4476: }
 4477: 
 4478: sub str2hash {
 4479:     my ($string)=@_;
 4480:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4481:     return %$hash;
 4482: }
 4483: 
 4484: sub str2hashref {
 4485:   my ($string) = @_;
 4486: 
 4487:   my %hash;
 4488: 
 4489:   if($string !~ /^__HASH_REF__/) {
 4490:       if (! ($string eq '' || !defined($string))) {
 4491: 	  $hash{'error'}='Not hash reference';
 4492:       }
 4493:       return (\%hash, $string);
 4494:   }
 4495: 
 4496:   $string =~ s/^__HASH_REF__//;
 4497: 
 4498:   while($string !~ /^__END_HASH_REF__/) {
 4499:       #key
 4500:       my $key='';
 4501:       if($string =~ /^__HASH_REF__/) {
 4502:           ($key, $string)=&str2hashref($string);
 4503:           if(defined($key->{'error'})) {
 4504:               $hash{'error'}='Bad data';
 4505:               return (\%hash, $string);
 4506:           }
 4507:       } elsif($string =~ /^__ARRAY_REF__/) {
 4508:           ($key, $string)=&str2arrayref($string);
 4509:           if($key->[0] eq 'Array reference error') {
 4510:               $hash{'error'}='Bad data';
 4511:               return (\%hash, $string);
 4512:           }
 4513:       } else {
 4514:           $string =~ s/^(.*?)=//;
 4515: 	  $key=&unescape($1);
 4516:       }
 4517:       $string =~ s/^=//;
 4518: 
 4519:       #value
 4520:       my $value='';
 4521:       if($string =~ /^__HASH_REF__/) {
 4522:           ($value, $string)=&str2hashref($string);
 4523:           if(defined($value->{'error'})) {
 4524:               $hash{'error'}='Bad data';
 4525:               return (\%hash, $string);
 4526:           }
 4527:       } elsif($string =~ /^__ARRAY_REF__/) {
 4528:           ($value, $string)=&str2arrayref($string);
 4529:           if($value->[0] eq 'Array reference error') {
 4530:               $hash{'error'}='Bad data';
 4531:               return (\%hash, $string);
 4532:           }
 4533:       } else {
 4534: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4535:       }
 4536:       $string =~ s/^&//;
 4537: 
 4538:       $hash{$key}=$value;
 4539:   }
 4540: 
 4541:   $string =~ s/^__END_HASH_REF__//;
 4542: 
 4543:   return (\%hash, $string);
 4544: }
 4545: 
 4546: sub str2array {
 4547:     my ($string)=@_;
 4548:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4549:     return @$array;
 4550: }
 4551: 
 4552: sub str2arrayref {
 4553:   my ($string) = @_;
 4554:   my @array;
 4555: 
 4556:   if($string !~ /^__ARRAY_REF__/) {
 4557:       if (! ($string eq '' || !defined($string))) {
 4558: 	  $array[0]='Array reference error';
 4559:       }
 4560:       return (\@array, $string);
 4561:   }
 4562: 
 4563:   $string =~ s/^__ARRAY_REF__//;
 4564: 
 4565:   while($string !~ /^__END_ARRAY_REF__/) {
 4566:       my $value='';
 4567:       if($string =~ /^__HASH_REF__/) {
 4568:           ($value, $string)=&str2hashref($string);
 4569:           if(defined($value->{'error'})) {
 4570:               $array[0] ='Array reference error';
 4571:               return (\@array, $string);
 4572:           }
 4573:       } elsif($string =~ /^__ARRAY_REF__/) {
 4574:           ($value, $string)=&str2arrayref($string);
 4575:           if($value->[0] eq 'Array reference error') {
 4576:               $array[0] ='Array reference error';
 4577:               return (\@array, $string);
 4578:           }
 4579:       } else {
 4580: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4581:       }
 4582:       $string =~ s/^&//;
 4583: 
 4584:       push(@array, $value);
 4585:   }
 4586: 
 4587:   $string =~ s/^__END_ARRAY_REF__//;
 4588: 
 4589:   return (\@array, $string);
 4590: }
 4591: 
 4592: # -------------------------------------------------------------------Temp Store
 4593: 
 4594: sub tmpreset {
 4595:   my ($symb,$namespace,$domain,$stuname) = @_;
 4596:   if (!$symb) {
 4597:     $symb=&symbread();
 4598:     if (!$symb) { $symb= $env{'request.url'}; }
 4599:   }
 4600:   $symb=escape($symb);
 4601: 
 4602:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4603:   $namespace=~s/\//\_/g;
 4604:   $namespace=~s/\W//g;
 4605: 
 4606:   if (!$domain) { $domain=$env{'user.domain'}; }
 4607:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4608:   if ($domain eq 'public' && $stuname eq 'public') {
 4609:       $stuname=$ENV{'REMOTE_ADDR'};
 4610:   }
 4611:   my $path=LONCAPA::tempdir();
 4612:   my %hash;
 4613:   if (tie(%hash,'GDBM_File',
 4614: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4615: 	  &GDBM_WRCREAT(),0640)) {
 4616:     foreach my $key (keys(%hash)) {
 4617:       if ($key=~ /:$symb/) {
 4618: 	delete($hash{$key});
 4619:       }
 4620:     }
 4621:   }
 4622: }
 4623: 
 4624: sub tmpstore {
 4625:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4626: 
 4627:   if (!$symb) {
 4628:     $symb=&symbread();
 4629:     if (!$symb) { $symb= $env{'request.url'}; }
 4630:   }
 4631:   $symb=escape($symb);
 4632: 
 4633:   if (!$namespace) {
 4634:     # I don't think we would ever want to store this for a course.
 4635:     # it seems this will only be used if we don't have a course.
 4636:     #$namespace=$env{'request.course.id'};
 4637:     #if (!$namespace) {
 4638:       $namespace=$env{'request.state'};
 4639:     #}
 4640:   }
 4641:   $namespace=~s/\//\_/g;
 4642:   $namespace=~s/\W//g;
 4643:   if (!$domain) { $domain=$env{'user.domain'}; }
 4644:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4645:   if ($domain eq 'public' && $stuname eq 'public') {
 4646:       $stuname=$ENV{'REMOTE_ADDR'};
 4647:   }
 4648:   my $now=time;
 4649:   my %hash;
 4650:   my $path=LONCAPA::tempdir();
 4651:   if (tie(%hash,'GDBM_File',
 4652: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4653: 	  &GDBM_WRCREAT(),0640)) {
 4654:     $hash{"version:$symb"}++;
 4655:     my $version=$hash{"version:$symb"};
 4656:     my $allkeys=''; 
 4657:     foreach my $key (keys(%$storehash)) {
 4658:       $allkeys.=$key.':';
 4659:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4660:     }
 4661:     $hash{"$version:$symb:timestamp"}=$now;
 4662:     $allkeys.='timestamp';
 4663:     $hash{"$version:keys:$symb"}=$allkeys;
 4664:     if (untie(%hash)) {
 4665:       return 'ok';
 4666:     } else {
 4667:       return "error:$!";
 4668:     }
 4669:   } else {
 4670:     return "error:$!";
 4671:   }
 4672: }
 4673: 
 4674: # -----------------------------------------------------------------Temp Restore
 4675: 
 4676: sub tmprestore {
 4677:   my ($symb,$namespace,$domain,$stuname) = @_;
 4678: 
 4679:   if (!$symb) {
 4680:     $symb=&symbread();
 4681:     if (!$symb) { $symb= $env{'request.url'}; }
 4682:   }
 4683:   $symb=escape($symb);
 4684: 
 4685:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4686: 
 4687:   if (!$domain) { $domain=$env{'user.domain'}; }
 4688:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4689:   if ($domain eq 'public' && $stuname eq 'public') {
 4690:       $stuname=$ENV{'REMOTE_ADDR'};
 4691:   }
 4692:   my %returnhash;
 4693:   $namespace=~s/\//\_/g;
 4694:   $namespace=~s/\W//g;
 4695:   my %hash;
 4696:   my $path=LONCAPA::tempdir();
 4697:   if (tie(%hash,'GDBM_File',
 4698: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4699: 	  &GDBM_READER(),0640)) {
 4700:     my $version=$hash{"version:$symb"};
 4701:     $returnhash{'version'}=$version;
 4702:     my $scope;
 4703:     for ($scope=1;$scope<=$version;$scope++) {
 4704:       my $vkeys=$hash{"$scope:keys:$symb"};
 4705:       my @keys=split(/:/,$vkeys);
 4706:       my $key;
 4707:       $returnhash{"$scope:keys"}=$vkeys;
 4708:       foreach $key (@keys) {
 4709: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4710: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4711:       }
 4712:     }
 4713:     if (!(untie(%hash))) {
 4714:       return "error:$!";
 4715:     }
 4716:   } else {
 4717:     return "error:$!";
 4718:   }
 4719:   return %returnhash;
 4720: }
 4721: 
 4722: # ----------------------------------------------------------------------- Store
 4723: 
 4724: sub store {
 4725:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4726:     my $home='';
 4727: 
 4728:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4729: 
 4730:     $symb=&symbclean($symb);
 4731:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4732: 
 4733:     if (!$domain) { $domain=$env{'user.domain'}; }
 4734:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4735: 
 4736:     &devalidate($symb,$stuname,$domain);
 4737: 
 4738:     $symb=escape($symb);
 4739:     if (!$namespace) { 
 4740:        unless ($namespace=$env{'request.course.id'}) { 
 4741:           return ''; 
 4742:        } 
 4743:     }
 4744:     if (!$home) { $home=$env{'user.home'}; }
 4745: 
 4746:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4747:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4748: 
 4749:     my $namevalue='';
 4750:     foreach my $key (keys(%$storehash)) {
 4751:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4752:     }
 4753:     $namevalue=~s/\&$//;
 4754:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4755:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4756: }
 4757: 
 4758: # -------------------------------------------------------------- Critical Store
 4759: 
 4760: sub cstore {
 4761:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4762:     my $home='';
 4763: 
 4764:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4765: 
 4766:     $symb=&symbclean($symb);
 4767:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4768: 
 4769:     if (!$domain) { $domain=$env{'user.domain'}; }
 4770:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4771: 
 4772:     &devalidate($symb,$stuname,$domain);
 4773: 
 4774:     $symb=escape($symb);
 4775:     if (!$namespace) { 
 4776:        unless ($namespace=$env{'request.course.id'}) { 
 4777:           return ''; 
 4778:        } 
 4779:     }
 4780:     if (!$home) { $home=$env{'user.home'}; }
 4781: 
 4782:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4783:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4784: 
 4785:     my $namevalue='';
 4786:     foreach my $key (keys(%$storehash)) {
 4787:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4788:     }
 4789:     $namevalue=~s/\&$//;
 4790:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4791:     return critical
 4792:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4793: }
 4794: 
 4795: # --------------------------------------------------------------------- Restore
 4796: 
 4797: sub restore {
 4798:     my ($symb,$namespace,$domain,$stuname) = @_;
 4799:     my $home='';
 4800: 
 4801:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4802: 
 4803:     if (!$symb) {
 4804:       unless ($symb=escape(&symbread())) { return ''; }
 4805:     } else {
 4806:       $symb=&escape(&symbclean($symb));
 4807:     }
 4808:     if (!$namespace) { 
 4809:        unless ($namespace=$env{'request.course.id'}) { 
 4810:           return ''; 
 4811:        } 
 4812:     }
 4813:     if (!$domain) { $domain=$env{'user.domain'}; }
 4814:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4815:     if (!$home) { $home=$env{'user.home'}; }
 4816:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4817: 
 4818:     my %returnhash=();
 4819:     foreach my $line (split(/\&/,$answer)) {
 4820: 	my ($name,$value)=split(/\=/,$line);
 4821:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4822:     }
 4823:     my $version;
 4824:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4825:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4826:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4827:        }
 4828:     }
 4829:     return %returnhash;
 4830: }
 4831: 
 4832: # ---------------------------------------------------------- Course Description
 4833: #
 4834: #  
 4835: 
 4836: sub coursedescription {
 4837:     my ($courseid,$args)=@_;
 4838:     $courseid=~s/^\///;
 4839:     $courseid=~s/\_/\//g;
 4840:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4841:     my $chome=&homeserver($cnum,$cdomain);
 4842:     my $normalid=$cdomain.'_'.$cnum;
 4843:     # need to always cache even if we get errors otherwise we keep 
 4844:     # trying and trying and trying to get the course description.
 4845:     my %envhash=();
 4846:     my %returnhash=();
 4847:     
 4848:     my $expiretime=600;
 4849:     if ($env{'request.course.id'} eq $normalid) {
 4850: 	$expiretime=120;
 4851:     }
 4852: 
 4853:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4854:     if (!$args->{'freshen_cache'}
 4855: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4856: 	foreach my $key (keys(%env)) {
 4857: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4858: 	    my ($setting) = $1;
 4859: 	    $returnhash{$setting} = $env{$key};
 4860: 	}
 4861: 	return %returnhash;
 4862:     }
 4863: 
 4864:     # get the data again
 4865: 
 4866:     if (!$args->{'one_time'}) {
 4867: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4868:     }
 4869: 
 4870:     if ($chome ne 'no_host') {
 4871:        %returnhash=&dump('environment',$cdomain,$cnum);
 4872:        if (!exists($returnhash{'con_lost'})) {
 4873: 	   my $username = $env{'user.name'}; # Defult username
 4874: 	   if(defined $args->{'user'}) {
 4875: 	       $username = $args->{'user'};
 4876: 	   }
 4877:            $returnhash{'home'}= $chome;
 4878: 	   $returnhash{'domain'} = $cdomain;
 4879: 	   $returnhash{'num'} = $cnum;
 4880:            if (!defined($returnhash{'type'})) {
 4881:                $returnhash{'type'} = 'Course';
 4882:            }
 4883:            while (my ($name,$value) = each %returnhash) {
 4884:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4885:            }
 4886:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4887:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4888: 	       $username.'_'.$cdomain.'_'.$cnum;
 4889:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4890:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4891:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4892:        }
 4893:     }
 4894:     if (!$args->{'one_time'}) {
 4895: 	&appenv(\%envhash);
 4896:     }
 4897:     return %returnhash;
 4898: }
 4899: 
 4900: sub update_released_required {
 4901:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4902:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4903:         $cid = $env{'request.course.id'};
 4904:         $cdom = $env{'course.'.$cid.'.domain'};
 4905:         $cnum = $env{'course.'.$cid.'.num'};
 4906:         $chome = $env{'course.'.$cid.'.home'};
 4907:     }
 4908:     if ($needsrelease) {
 4909:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4910:         my $needsupdate;
 4911:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4912:             $needsupdate = 1;
 4913:         } else {
 4914:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4915:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4916:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4917:                 $needsupdate = 1;
 4918:             }
 4919:         }
 4920:         if ($needsupdate) {
 4921:             my %needshash = (
 4922:                              'internal.releaserequired' => $needsrelease,
 4923:                             );
 4924:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4925:             if ($putresult eq 'ok') {
 4926:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4927:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4928:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4929:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4930:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4931:                 }
 4932:             }
 4933:         }
 4934:     }
 4935:     return;
 4936: }
 4937: 
 4938: # -------------------------------------------------See if a user is privileged
 4939: 
 4940: sub privileged {
 4941:     my ($username,$domain)=@_;
 4942: 
 4943:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4944:     my $now = time;
 4945: 
 4946:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4947:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4948:             if (($trole eq 'dc') || ($trole eq 'su')) {
 4949:                 return 1 unless ($tend && $tend < $now) 
 4950:                     or ($tstart && $tstart > $now);
 4951:             }
 4952: 	}
 4953: 
 4954:     return 0;
 4955: }
 4956: 
 4957: # -------------------------------------------------------- Get user privileges
 4958: 
 4959: sub rolesinit {
 4960:     my ($domain, $username) = @_;
 4961:     my %userroles = ('user.login.time' => time);
 4962:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 4963: 
 4964:     # firstaccess and timerinterval are related to timed maps/resources. 
 4965:     # also, blocking can be triggered by an activating timer
 4966:     # it's saved in the user's %env.
 4967:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 4968:     my %timerinterval = &dump('timerinterval', $domain, $username);
 4969:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 4970:         %timerintchk, %timerintenv);
 4971: 
 4972:     foreach my $key (keys(%firstaccess)) {
 4973:         my ($cid, $rest) = split(/\0/, $key);
 4974:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4975:     }
 4976: 
 4977:     foreach my $key (keys(%timerinterval)) {
 4978:         my ($cid,$rest) = split(/\0/,$key);
 4979:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4980:     }
 4981: 
 4982:     my %allroles=();
 4983:     my %allgroups=();
 4984: 
 4985:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 4986:         my $role = $rolesdump{$area};
 4987:         $area =~ s/\_\w\w$//;
 4988: 
 4989:         my ($trole, $tend, $tstart, $group_privs);
 4990: 
 4991:         if ($role =~ /^cr/) {
 4992:         # Custom role, defined by a user 
 4993:         # e.g., user.role.cr/msu/smith/mynewrole
 4994:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4995:                 $trole = $1;
 4996:                 ($tend, $tstart) = split('_', $2);
 4997:             } else {
 4998:                 $trole = $role;
 4999:             }
 5000:         } elsif ($role =~ m|^gr/|) {
 5001:         # Role of member in a group, defined within a course/community
 5002:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5003:             ($trole, $tend, $tstart) = split(/_/, $role);
 5004:             next if $tstart eq '-1';
 5005:             ($trole, $group_privs) = split(/\//, $trole);
 5006:             $group_privs = &unescape($group_privs);
 5007:         } else {
 5008:         # Just a normal role, defined in roles.tab
 5009:             ($trole, $tend, $tstart) = split(/_/,$role);
 5010:         }
 5011: 
 5012:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5013:                  $username);
 5014:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5015: 
 5016:         # role expired or not available yet?
 5017:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5018:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5019: 
 5020:         next if $area eq '' or $trole eq '';
 5021: 
 5022:         my $spec = "$trole.$area";
 5023:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5024: 
 5025:         if ($trole =~ /^cr\//) {
 5026:         # Custom role, defined by a user
 5027:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5028:         } elsif ($trole eq 'gr') {
 5029:         # Role of a member in a group, defined within a course/community
 5030:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5031:             next;
 5032:         } else {
 5033:         # Normal role, defined in roles.tab
 5034:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5035:         }
 5036: 
 5037:         my $cid = $tdomain.'_'.$trest;
 5038:         unless ($firstaccchk{$cid}) {
 5039:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5040:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5041:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5042:                         $coursetimerstarts{$cid}{$item}; 
 5043:                 }
 5044:             }
 5045:             $firstaccchk{$cid} = 1;
 5046:         }
 5047:         unless ($timerintchk{$cid}) {
 5048:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5049:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5050:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5051:                        $coursetimerintervals{$cid}{$item};
 5052:                 }
 5053:             }
 5054:             $timerintchk{$cid} = 1;
 5055:         }
 5056:     }
 5057: 
 5058:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5059:         \%allroles, \%allgroups);
 5060:     $env{'user.adv'} = $userroles{'user.adv'};
 5061: 
 5062:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5063: }
 5064: 
 5065: sub set_arearole {
 5066:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 5067: # log the associated role with the area
 5068:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5069:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5070: }
 5071: 
 5072: sub custom_roleprivs {
 5073:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5074:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5075:     my $homsvr=homeserver($rauthor,$rdomain);
 5076:     if (&hostname($homsvr) ne '') {
 5077:         my ($rdummy,$roledef)=
 5078:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5079:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5080:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5081:             if (defined($syspriv)) {
 5082:                 if ($trest =~ /^$match_community$/) {
 5083:                     $syspriv =~ s/bre\&S//; 
 5084:                 }
 5085:                 $$allroles{'cm./'}.=':'.$syspriv;
 5086:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5087:             }
 5088:             if ($tdomain ne '') {
 5089:                 if (defined($dompriv)) {
 5090:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5091:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5092:                 }
 5093:                 if (($trest ne '') && (defined($coursepriv))) {
 5094:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5095:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5096:                 }
 5097:             }
 5098:         }
 5099:     }
 5100: }
 5101: 
 5102: sub group_roleprivs {
 5103:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5104:     my $access = 1;
 5105:     my $now = time;
 5106:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5107:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5108:     if ($access) {
 5109:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5110:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5111:     }
 5112: }
 5113: 
 5114: sub standard_roleprivs {
 5115:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5116:     if (defined($pr{$trole.':s'})) {
 5117:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5118:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5119:     }
 5120:     if ($tdomain ne '') {
 5121:         if (defined($pr{$trole.':d'})) {
 5122:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5123:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5124:         }
 5125:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5126:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5127:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5128:         }
 5129:     }
 5130: }
 5131: 
 5132: sub set_userprivs {
 5133:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5134:     my $author=0;
 5135:     my $adv=0;
 5136:     my %grouproles = ();
 5137:     if (keys(%{$allgroups}) > 0) {
 5138:         my @groupkeys; 
 5139:         foreach my $role (keys(%{$allroles})) {
 5140:             push(@groupkeys,$role);
 5141:         }
 5142:         if (ref($groups_roles) eq 'HASH') {
 5143:             foreach my $key (keys(%{$groups_roles})) {
 5144:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5145:                     push(@groupkeys,$key);
 5146:                 }
 5147:             }
 5148:         }
 5149:         if (@groupkeys > 0) {
 5150:             foreach my $role (@groupkeys) {
 5151:                 my ($trole,$area,$sec,$extendedarea);
 5152:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5153:                     $trole = $1;
 5154:                     $area = $2;
 5155:                     $sec = $3;
 5156:                     $extendedarea = $area.$sec;
 5157:                     if (exists($$allgroups{$area})) {
 5158:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5159:                             my $spec = $trole.'.'.$extendedarea;
 5160:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5161:                                                 $$allgroups{$area}{$group};
 5162:                         }
 5163:                     }
 5164:                 }
 5165:             }
 5166:         }
 5167:     }
 5168:     foreach my $group (keys(%grouproles)) {
 5169:         $$allroles{$group} = $grouproles{$group};
 5170:     }
 5171:     foreach my $role (keys(%{$allroles})) {
 5172:         my %thesepriv;
 5173:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5174:         foreach my $item (split(/:/,$$allroles{$role})) {
 5175:             if ($item ne '') {
 5176:                 my ($privilege,$restrictions)=split(/&/,$item);
 5177:                 if ($restrictions eq '') {
 5178:                     $thesepriv{$privilege}='F';
 5179:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5180:                     $thesepriv{$privilege}.=$restrictions;
 5181:                 }
 5182:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5183:             }
 5184:         }
 5185:         my $thesestr='';
 5186:         foreach my $priv (sort(keys(%thesepriv))) {
 5187: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5188: 	}
 5189:         $userroles->{'user.priv.'.$role} = $thesestr;
 5190:     }
 5191:     return ($author,$adv);
 5192: }
 5193: 
 5194: sub role_status {
 5195:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5196:     my @pwhere = ();
 5197:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5198:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5199:         unless (!defined($$role) || $$role eq '') {
 5200:             $$where=join('.',@pwhere);
 5201:             $$trolecode=$$role.'.'.$$where;
 5202:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5203:             $$tstatus='is';
 5204:             if ($$tstart && $$tstart>$update) {
 5205:                 $$tstatus='future';
 5206:                 if ($$tstart<$now) {
 5207:                     if ($$tstart && $$tstart>$refresh) {
 5208:                         if (($$where ne '') && ($$role ne '')) {
 5209:                             my (%allroles,%allgroups,$group_privs,
 5210:                                 %groups_roles,@rolecodes);
 5211:                             my %userroles = (
 5212:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5213:                             );
 5214:                             @rolecodes = ('cm'); 
 5215:                             my $spec=$$role.'.'.$$where;
 5216:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5217:                             if ($$role =~ /^cr\//) {
 5218:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5219:                                 push(@rolecodes,'cr');
 5220:                             } elsif ($$role eq 'gr') {
 5221:                                 push(@rolecodes,$$role);
 5222:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5223:                                                     $env{'user.name'});
 5224:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5225:                                 (undef,my $group_privs) = split(/\//,$trole);
 5226:                                 $group_privs = &unescape($group_privs);
 5227:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5228:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5229:                                 &get_groups_roles($tdomain,$trest,
 5230:                                                   \%course_roles,\@rolecodes,
 5231:                                                   \%groups_roles);
 5232:                             } else {
 5233:                                 push(@rolecodes,$$role);
 5234:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5235:                             }
 5236:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5237:                             &appenv(\%userroles,\@rolecodes);
 5238:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5239:                         }
 5240:                     }
 5241:                     $$tstatus = 'is';
 5242:                 }
 5243:             }
 5244:             if ($$tend) {
 5245:                 if ($$tend<$update) {
 5246:                     $$tstatus='expired';
 5247:                 } elsif ($$tend<$now) {
 5248:                     $$tstatus='will_not';
 5249:                 }
 5250:             }
 5251:         }
 5252:     }
 5253: }
 5254: 
 5255: sub get_groups_roles {
 5256:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5257:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5258:                   (ref($rolecodes) eq 'ARRAY') && 
 5259:                   (ref($groups_roles) eq 'HASH')); 
 5260:     if (keys(%{$cdom_courseroles}) > 0) {
 5261:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5262:         if ($cdom ne '' && $cnum ne '') {
 5263:             foreach my $key (keys(%{$cdom_courseroles})) {
 5264:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5265:                     my $crsrole = $1;
 5266:                     my $crssec = $2;
 5267:                     if ($crsrole =~ /^cr/) {
 5268:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5269:                             push(@{$rolecodes},'cr');
 5270:                         }
 5271:                     } else {
 5272:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5273:                             push(@{$rolecodes},$crsrole);
 5274:                         }
 5275:                     }
 5276:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5277:                     if ($crssec ne '') {
 5278:                         $rolekey .= "/$crssec";
 5279:                     }
 5280:                     $rolekey .= './';
 5281:                     $groups_roles->{$rolekey} = $rolecodes;
 5282:                 }
 5283:             }
 5284:         }
 5285:     }
 5286:     return;
 5287: }
 5288: 
 5289: sub delete_env_groupprivs {
 5290:     my ($where,$courseroles,$possroles) = @_;
 5291:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5292:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5293:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5294:         %{$courseroles->{$udom}} =
 5295:             &get_my_roles('','','userroles',['active'],
 5296:                           $possroles,[$udom],1);
 5297:     }
 5298:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5299:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5300:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5301:             my $area = '/'.$cdom.'/'.$cnum;
 5302:             my $privkey = "user.priv.$crsrole.$area";
 5303:             if ($crssec ne '') {
 5304:                 $privkey .= '/'.$crssec;
 5305:             }
 5306:             $privkey .= ".$area/$group";
 5307:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5308:         }
 5309:     }
 5310:     return;
 5311: }
 5312: 
 5313: sub check_adhoc_privs {
 5314:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5315:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5316:     my $setprivs;
 5317:     if ($env{$cckey}) {
 5318:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5319:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5320:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5321:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5322:             $setprivs = 1;
 5323:         }
 5324:     } else {
 5325:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5326:         $setprivs = 1;
 5327:     }
 5328:     return $setprivs;
 5329: }
 5330: 
 5331: sub set_adhoc_privileges {
 5332: # role can be cc or ca
 5333:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5334:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5335:     my $spec = $role.'.'.$area;
 5336:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5337:                                   $env{'user.name'});
 5338:     my %ccrole = ();
 5339:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5340:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5341:     &appenv(\%userroles,[$role,'cm']);
 5342:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5343:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5344:         &appenv( {'request.role'        => $spec,
 5345:                   'request.role.domain' => $dcdom,
 5346:                   'request.course.sec'  => ''
 5347:                  }
 5348:                );
 5349:         my $tadv=0;
 5350:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5351:         &appenv({'request.role.adv'    => $tadv});
 5352:     }
 5353: }
 5354: 
 5355: # --------------------------------------------------------------- get interface
 5356: 
 5357: sub get {
 5358:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5359:    my $items='';
 5360:    foreach my $item (@$storearr) {
 5361:        $items.=&escape($item).'&';
 5362:    }
 5363:    $items=~s/\&$//;
 5364:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5365:    if (!$uname) { $uname=$env{'user.name'}; }
 5366:    my $uhome=&homeserver($uname,$udomain);
 5367: 
 5368:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5369:    my @pairs=split(/\&/,$rep);
 5370:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5371:      return @pairs;
 5372:    }
 5373:    my %returnhash=();
 5374:    my $i=0;
 5375:    foreach my $item (@$storearr) {
 5376:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5377:       $i++;
 5378:    }
 5379:    return %returnhash;
 5380: }
 5381: 
 5382: # --------------------------------------------------------------- del interface
 5383: 
 5384: sub del {
 5385:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5386:    my $items='';
 5387:    foreach my $item (@$storearr) {
 5388:        $items.=&escape($item).'&';
 5389:    }
 5390: 
 5391:    $items=~s/\&$//;
 5392:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5393:    if (!$uname) { $uname=$env{'user.name'}; }
 5394:    my $uhome=&homeserver($uname,$udomain);
 5395:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5396: }
 5397: 
 5398: # -------------------------------------------------------------- dump interface
 5399: 
 5400: sub unserialize {
 5401:     my ($rep, $escapedkeys) = @_;
 5402: 
 5403:     return {} if $rep =~ /^error/;
 5404: 
 5405:     my %returnhash=();
 5406: 	foreach my $item (split /\&/, $rep) {
 5407: 	    my ($key, $value) = split(/=/, $item, 2);
 5408: 	    $key = unescape($key) unless $escapedkeys;
 5409: 	    next if $key =~ /^error: 2 /;
 5410: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5411: 	}
 5412:     #return %returnhash;
 5413:     return \%returnhash;
 5414: }        
 5415: 
 5416: # see Lond::dump_with_regexp
 5417: # if $escapedkeys hash keys won't get unescaped.
 5418: sub dump {
 5419:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5420:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5421:     if (!$uname) { $uname=$env{'user.name'}; }
 5422:     my $uhome=&homeserver($uname,$udomain);
 5423: 
 5424:     my $reply;
 5425:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5426:         # user is hosted on this machine
 5427:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5428:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
 5429:         return %{unserialize($reply, $escapedkeys)};
 5430:     }
 5431:     if ($regexp) {
 5432: 	$regexp=&escape($regexp);
 5433:     } else {
 5434: 	$regexp='.';
 5435:     }
 5436:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5437:     my @pairs=split(/\&/,$rep);
 5438:     my %returnhash=();
 5439:     if (!($rep =~ /^error/ )) {
 5440: 	foreach my $item (@pairs) {
 5441: 	    my ($key,$value)=split(/=/,$item,2);
 5442:         $key = unescape($key) unless $escapedkeys;
 5443:         #$key = &unescape($key);
 5444: 	    next if ($key =~ /^error: 2 /);
 5445: 	    $returnhash{$key}=&thaw_unescape($value);
 5446: 	}
 5447:     }
 5448:     return %returnhash;
 5449: }
 5450: 
 5451: 
 5452: # --------------------------------------------------------- dumpstore interface
 5453: 
 5454: sub dumpstore {
 5455:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5456:    # same as dump but keys must be escaped. They may contain colon separated
 5457:    # lists of values that may themself contain colons (e.g. symbs).
 5458:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5459: }
 5460: 
 5461: # -------------------------------------------------------------- keys interface
 5462: 
 5463: sub getkeys {
 5464:    my ($namespace,$udomain,$uname)=@_;
 5465:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5466:    if (!$uname) { $uname=$env{'user.name'}; }
 5467:    my $uhome=&homeserver($uname,$udomain);
 5468:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5469:    my @keyarray=();
 5470:    foreach my $key (split(/\&/,$rep)) {
 5471:       next if ($key =~ /^error: 2 /);
 5472:       push(@keyarray,&unescape($key));
 5473:    }
 5474:    return @keyarray;
 5475: }
 5476: 
 5477: # --------------------------------------------------------------- currentdump
 5478: sub currentdump {
 5479:    my ($courseid,$sdom,$sname)=@_;
 5480:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5481:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5482:    $sname    = $env{'user.name'}         if (! defined($sname));
 5483:    my $uhome = &homeserver($sname,$sdom);
 5484:    my $rep;
 5485: 
 5486:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5487:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5488:                    $courseid)));
 5489:    } else {
 5490:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5491:    }
 5492: 
 5493:    return if ($rep =~ /^(error:|no_such_host)/);
 5494:    #
 5495:    my %returnhash=();
 5496:    #
 5497:    if ($rep eq "unknown_cmd") { 
 5498:        # an old lond will not know currentdump
 5499:        # Do a dump and make it look like a currentdump
 5500:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5501:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5502:        my %hash = @tmp;
 5503:        @tmp=();
 5504:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5505:    } else {
 5506:        my @pairs=split(/\&/,$rep);
 5507:        foreach my $pair (@pairs) {
 5508:            my ($key,$value)=split(/=/,$pair,2);
 5509:            my ($symb,$param) = split(/:/,$key);
 5510:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5511:                                                         &thaw_unescape($value);
 5512:        }
 5513:    }
 5514:    return %returnhash;
 5515: }
 5516: 
 5517: sub convert_dump_to_currentdump{
 5518:     my %hash = %{shift()};
 5519:     my %returnhash;
 5520:     # Code ripped from lond, essentially.  The only difference
 5521:     # here is the unescaping done by lonnet::dump().  Conceivably
 5522:     # we might run in to problems with parameter names =~ /^v\./
 5523:     while (my ($key,$value) = each(%hash)) {
 5524:         my ($v,$symb,$param) = split(/:/,$key);
 5525: 	$symb  = &unescape($symb);
 5526: 	$param = &unescape($param);
 5527:         next if ($v eq 'version' || $symb eq 'keys');
 5528:         next if (exists($returnhash{$symb}) &&
 5529:                  exists($returnhash{$symb}->{$param}) &&
 5530:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5531:         $returnhash{$symb}->{$param}=$value;
 5532:         $returnhash{$symb}->{'v.'.$param}=$v;
 5533:     }
 5534:     #
 5535:     # Remove all of the keys in the hashes which keep track of
 5536:     # the version of the parameter.
 5537:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5538:         # use a foreach because we are going to delete from the hash.
 5539:         foreach my $key (keys(%$param_hash)) {
 5540:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5541:         }
 5542:     }
 5543:     return \%returnhash;
 5544: }
 5545: 
 5546: # ------------------------------------------------------ critical inc interface
 5547: 
 5548: sub cinc {
 5549:     return &inc(@_,'critical');
 5550: }
 5551: 
 5552: # --------------------------------------------------------------- inc interface
 5553: 
 5554: sub inc {
 5555:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5556:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5557:     if (!$uname) { $uname=$env{'user.name'}; }
 5558:     my $uhome=&homeserver($uname,$udomain);
 5559:     my $items='';
 5560:     if (! ref($store)) {
 5561:         # got a single value, so use that instead
 5562:         $items = &escape($store).'=&';
 5563:     } elsif (ref($store) eq 'SCALAR') {
 5564:         $items = &escape($$store).'=&';        
 5565:     } elsif (ref($store) eq 'ARRAY') {
 5566:         $items = join('=&',map {&escape($_);} @{$store});
 5567:     } elsif (ref($store) eq 'HASH') {
 5568:         while (my($key,$value) = each(%{$store})) {
 5569:             $items.= &escape($key).'='.&escape($value).'&';
 5570:         }
 5571:     }
 5572:     $items=~s/\&$//;
 5573:     if ($critical) {
 5574: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5575:     } else {
 5576: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5577:     }
 5578: }
 5579: 
 5580: # --------------------------------------------------------------- put interface
 5581: 
 5582: sub put {
 5583:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5584:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5585:    if (!$uname) { $uname=$env{'user.name'}; }
 5586:    my $uhome=&homeserver($uname,$udomain);
 5587:    my $items='';
 5588:    foreach my $item (keys(%$storehash)) {
 5589:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5590:    }
 5591:    $items=~s/\&$//;
 5592:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5593: }
 5594: 
 5595: # ------------------------------------------------------------ newput interface
 5596: 
 5597: sub newput {
 5598:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5599:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5600:    if (!$uname) { $uname=$env{'user.name'}; }
 5601:    my $uhome=&homeserver($uname,$udomain);
 5602:    my $items='';
 5603:    foreach my $key (keys(%$storehash)) {
 5604:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5605:    }
 5606:    $items=~s/\&$//;
 5607:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5608: }
 5609: 
 5610: # ---------------------------------------------------------  putstore interface
 5611: 
 5612: sub putstore {
 5613:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5614:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5615:    if (!$uname) { $uname=$env{'user.name'}; }
 5616:    my $uhome=&homeserver($uname,$udomain);
 5617:    my $items='';
 5618:    foreach my $key (keys(%$storehash)) {
 5619:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5620:    }
 5621:    $items=~s/\&$//;
 5622:    my $esc_symb=&escape($symb);
 5623:    my $esc_v=&escape($version);
 5624:    my $reply =
 5625:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5626: 	      $uhome);
 5627:    if ($reply eq 'unknown_cmd') {
 5628:        # gfall back to way things use to be done
 5629:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5630: 			    $uname);
 5631:    }
 5632:    return $reply;
 5633: }
 5634: 
 5635: sub old_putstore {
 5636:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5637:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5638:     if (!$uname) { $uname=$env{'user.name'}; }
 5639:     my $uhome=&homeserver($uname,$udomain);
 5640:     my %newstorehash;
 5641:     foreach my $item (keys(%$storehash)) {
 5642: 	my $key = $version.':'.&escape($symb).':'.$item;
 5643: 	$newstorehash{$key} = $storehash->{$item};
 5644:     }
 5645:     my $items='';
 5646:     my %allitems = ();
 5647:     foreach my $item (keys(%newstorehash)) {
 5648: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5649: 	    my $key = $1.':keys:'.$2;
 5650: 	    $allitems{$key} .= $3.':';
 5651: 	}
 5652: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5653:     }
 5654:     foreach my $item (keys(%allitems)) {
 5655: 	$allitems{$item} =~ s/\:$//;
 5656: 	$items.= $item.'='.$allitems{$item}.'&';
 5657:     }
 5658:     $items=~s/\&$//;
 5659:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5660: }
 5661: 
 5662: # ------------------------------------------------------ critical put interface
 5663: 
 5664: sub cput {
 5665:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5666:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5667:    if (!$uname) { $uname=$env{'user.name'}; }
 5668:    my $uhome=&homeserver($uname,$udomain);
 5669:    my $items='';
 5670:    foreach my $item (keys(%$storehash)) {
 5671:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5672:    }
 5673:    $items=~s/\&$//;
 5674:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5675: }
 5676: 
 5677: # -------------------------------------------------------------- eget interface
 5678: 
 5679: sub eget {
 5680:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5681:    my $items='';
 5682:    foreach my $item (@$storearr) {
 5683:        $items.=&escape($item).'&';
 5684:    }
 5685:    $items=~s/\&$//;
 5686:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5687:    if (!$uname) { $uname=$env{'user.name'}; }
 5688:    my $uhome=&homeserver($uname,$udomain);
 5689:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5690:    my @pairs=split(/\&/,$rep);
 5691:    my %returnhash=();
 5692:    my $i=0;
 5693:    foreach my $item (@$storearr) {
 5694:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5695:       $i++;
 5696:    }
 5697:    return %returnhash;
 5698: }
 5699: 
 5700: # ------------------------------------------------------------ tmpput interface
 5701: sub tmpput {
 5702:     my ($storehash,$server,$context)=@_;
 5703:     my $items='';
 5704:     foreach my $item (keys(%$storehash)) {
 5705: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5706:     }
 5707:     $items=~s/\&$//;
 5708:     if (defined($context)) {
 5709:         $items .= ':'.&escape($context);
 5710:     }
 5711:     return &reply("tmpput:$items",$server);
 5712: }
 5713: 
 5714: # ------------------------------------------------------------ tmpget interface
 5715: sub tmpget {
 5716:     my ($token,$server)=@_;
 5717:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5718:     my $rep=&reply("tmpget:$token",$server);
 5719:     my %returnhash;
 5720:     foreach my $item (split(/\&/,$rep)) {
 5721: 	my ($key,$value)=split(/=/,$item);
 5722:         next if ($key =~ /^error: 2 /);
 5723: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5724:     }
 5725:     return %returnhash;
 5726: }
 5727: 
 5728: # ------------------------------------------------------------ tmpdel interface
 5729: sub tmpdel {
 5730:     my ($token,$server)=@_;
 5731:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5732:     return &reply("tmpdel:$token",$server);
 5733: }
 5734: 
 5735: # ------------------------------------------------------------ get_timebased_id 
 5736: 
 5737: sub get_timebased_id {
 5738:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5739:         $maxtries) = @_;
 5740:     my ($newid,$error,$dellock);
 5741:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5742:         return ('','ok','invalid call to get suffix');
 5743:     }
 5744: 
 5745: # set defaults for any optional args for which values were not supplied
 5746:     if ($who eq '') {
 5747:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5748:     }
 5749:     if (!$locktries) {
 5750:         $locktries = 3;
 5751:     }
 5752:     if (!$maxtries) {
 5753:         $maxtries = 10;
 5754:     }
 5755:     
 5756:     if (($cdom eq '') || ($cnum eq '')) {
 5757:         if ($env{'request.course.id'}) {
 5758:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5759:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5760:         }
 5761:         if (($cdom eq '') || ($cnum eq '')) {
 5762:             return ('','ok','call to get suffix not in course context');
 5763:         }
 5764:     }
 5765: 
 5766: # construct locking item
 5767:     my $lockhash = {
 5768:                       $prefix."\0".'locked_'.$keyid => $who,
 5769:                    };
 5770:     my $tries = 0;
 5771: 
 5772: # attempt to get lock on nohist_$namespace file
 5773:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5774:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5775:         $tries ++;
 5776:         sleep 1;
 5777:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5778:     }
 5779: 
 5780: # attempt to get unique identifier, based on current timestamp
 5781:     if ($gotlock eq 'ok') {
 5782:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5783:         my $id = time;
 5784:         $newid = $id;
 5785:         my $idtries = 0;
 5786:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5787:             if ($idtype eq 'concat') {
 5788:                 $newid = $id.$idtries;
 5789:             } else {
 5790:                 $newid ++;
 5791:             }
 5792:             $idtries ++;
 5793:         }
 5794:         if (!exists($inuse{$prefix."\0".$newid})) {
 5795:             my %new_item =  (
 5796:                               $prefix."\0".$newid => $who,
 5797:                             );
 5798:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5799:                                                  $cdom,$cnum);
 5800:             if ($putresult ne 'ok') {
 5801:                 undef($newid);
 5802:                 $error = 'error saving new item: '.$putresult;
 5803:             }
 5804:         } else {
 5805:              $error = ('error: no unique suffix available for the new item ');
 5806:         }
 5807: #  remove lock
 5808:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5809:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5810:     } else {
 5811:         $error = "error: could not obtain lockfile\n";
 5812:         $dellock = 'ok';
 5813:     }
 5814:     return ($newid,$dellock,$error);
 5815: }
 5816: 
 5817: # -------------------------------------------------- portfolio access checking
 5818: 
 5819: sub portfolio_access {
 5820:     my ($requrl) = @_;
 5821:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5822:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5823:     if ($result) {
 5824:         my %setters;
 5825:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5826:             my ($startblock,$endblock) =
 5827:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5828:             if ($startblock && $endblock) {
 5829:                 return 'B';
 5830:             }
 5831:         } else {
 5832:             my ($startblock,$endblock) =
 5833:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5834:             if ($startblock && $endblock) {
 5835:                 return 'B';
 5836:             }
 5837:         }
 5838:     }
 5839:     if ($result eq 'ok') {
 5840:        return 'F';
 5841:     } elsif ($result =~ /^[^:]+:guest_/) {
 5842:        return 'A';
 5843:     }
 5844:     return '';
 5845: }
 5846: 
 5847: sub get_portfolio_access {
 5848:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5849: 
 5850:     if (!ref($access_hash)) {
 5851: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5852: 	my %access_controls = &get_access_controls($current_perms,$group,
 5853: 						   $file_name);
 5854: 	$access_hash = $access_controls{$file_name};
 5855:     }
 5856: 
 5857:     my ($public,$guest,@domains,@users,@courses,@groups);
 5858:     my $now = time;
 5859:     if (ref($access_hash) eq 'HASH') {
 5860:         foreach my $key (keys(%{$access_hash})) {
 5861:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5862:             if ($start > $now) {
 5863:                 next;
 5864:             }
 5865:             if ($end && $end<$now) {
 5866:                 next;
 5867:             }
 5868:             if ($scope eq 'public') {
 5869:                 $public = $key;
 5870:                 last;
 5871:             } elsif ($scope eq 'guest') {
 5872:                 $guest = $key;
 5873:             } elsif ($scope eq 'domains') {
 5874:                 push(@domains,$key);
 5875:             } elsif ($scope eq 'users') {
 5876:                 push(@users,$key);
 5877:             } elsif ($scope eq 'course') {
 5878:                 push(@courses,$key);
 5879:             } elsif ($scope eq 'group') {
 5880:                 push(@groups,$key);
 5881:             }
 5882:         }
 5883:         if ($public) {
 5884:             return 'ok';
 5885:         }
 5886:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5887:             if ($guest) {
 5888:                 return $guest;
 5889:             }
 5890:         } else {
 5891:             if (@domains > 0) {
 5892:                 foreach my $domkey (@domains) {
 5893:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5894:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5895:                             return 'ok';
 5896:                         }
 5897:                     }
 5898:                 }
 5899:             }
 5900:             if (@users > 0) {
 5901:                 foreach my $userkey (@users) {
 5902:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5903:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5904:                             if (ref($item) eq 'HASH') {
 5905:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5906:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5907:                                     return 'ok';
 5908:                                 }
 5909:                             }
 5910:                         }
 5911:                     } 
 5912:                 }
 5913:             }
 5914:             my %roleshash;
 5915:             my @courses_and_groups = @courses;
 5916:             push(@courses_and_groups,@groups); 
 5917:             if (@courses_and_groups > 0) {
 5918:                 my (%allgroups,%allroles); 
 5919:                 my ($start,$end,$role,$sec,$group);
 5920:                 foreach my $envkey (%env) {
 5921:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5922:                         my $cid = $2.'_'.$3; 
 5923:                         if ($1 eq 'gr') {
 5924:                             $group = $4;
 5925:                             $allgroups{$cid}{$group} = $env{$envkey};
 5926:                         } else {
 5927:                             if ($4 eq '') {
 5928:                                 $sec = 'none';
 5929:                             } else {
 5930:                                 $sec = $4;
 5931:                             }
 5932:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5933:                         }
 5934:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5935:                         my $cid = $2.'_'.$3;
 5936:                         if ($4 eq '') {
 5937:                             $sec = 'none';
 5938:                         } else {
 5939:                             $sec = $4;
 5940:                         }
 5941:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5942:                     }
 5943:                 }
 5944:                 if (keys(%allroles) == 0) {
 5945:                     return;
 5946:                 }
 5947:                 foreach my $key (@courses_and_groups) {
 5948:                     my %content = %{$$access_hash{$key}};
 5949:                     my $cnum = $content{'number'};
 5950:                     my $cdom = $content{'domain'};
 5951:                     my $cid = $cdom.'_'.$cnum;
 5952:                     if (!exists($allroles{$cid})) {
 5953:                         next;
 5954:                     }    
 5955:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5956:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5957:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5958:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5959:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5960:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5961:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5962:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5963:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5964:                                         if (grep/^all$/,@sections) {
 5965:                                             return 'ok';
 5966:                                         } else {
 5967:                                             if (grep/^$sec$/,@sections) {
 5968:                                                 return 'ok';
 5969:                                             }
 5970:                                         }
 5971:                                     }
 5972:                                 }
 5973:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5974:                                     if (grep/^none$/,@groups) {
 5975:                                         return 'ok';
 5976:                                     }
 5977:                                 } else {
 5978:                                     if (grep/^all$/,@groups) {
 5979:                                         return 'ok';
 5980:                                     } 
 5981:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5982:                                         if (grep/^$group$/,@groups) {
 5983:                                             return 'ok';
 5984:                                         }
 5985:                                     }
 5986:                                 } 
 5987:                             }
 5988:                         }
 5989:                     }
 5990:                 }
 5991:             }
 5992:             if ($guest) {
 5993:                 return $guest;
 5994:             }
 5995:         }
 5996:     }
 5997:     return;
 5998: }
 5999: 
 6000: sub course_group_datechecker {
 6001:     my ($dates,$now,$status) = @_;
 6002:     my ($start,$end) = split(/\./,$dates);
 6003:     if (!$start && !$end) {
 6004:         return 'ok';
 6005:     }
 6006:     if (grep/^active$/,@{$status}) {
 6007:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6008:             return 'ok';
 6009:         }
 6010:     }
 6011:     if (grep/^previous$/,@{$status}) {
 6012:         if ($end > $now ) {
 6013:             return 'ok';
 6014:         }
 6015:     }
 6016:     if (grep/^future$/,@{$status}) {
 6017:         if ($start > $now) {
 6018:             return 'ok';
 6019:         }
 6020:     }
 6021:     return; 
 6022: }
 6023: 
 6024: sub parse_portfolio_url {
 6025:     my ($url) = @_;
 6026: 
 6027:     my ($type,$udom,$unum,$group,$file_name);
 6028:     
 6029:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6030: 	$type = 1;
 6031:         $udom = $1;
 6032:         $unum = $2;
 6033:         $file_name = $3;
 6034:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6035: 	$type = 2;
 6036:         $udom = $1;
 6037:         $unum = $2;
 6038:         $group = $3;
 6039:         $file_name = $3.'/'.$4;
 6040:     }
 6041:     if (wantarray) {
 6042: 	return ($type,$udom,$unum,$file_name,$group);
 6043:     }
 6044:     return $type;
 6045: }
 6046: 
 6047: sub is_portfolio_url {
 6048:     my ($url) = @_;
 6049:     return scalar(&parse_portfolio_url($url));
 6050: }
 6051: 
 6052: sub is_portfolio_file {
 6053:     my ($file) = @_;
 6054:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6055:         return 1;
 6056:     }
 6057:     return;
 6058: }
 6059: 
 6060: sub usertools_access {
 6061:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6062:     my ($access,%tools);
 6063:     if ($context eq '') {
 6064:         $context = 'tools';
 6065:     }
 6066:     if ($context eq 'requestcourses') {
 6067:         %tools = (
 6068:                       official   => 1,
 6069:                       unofficial => 1,
 6070:                       community  => 1,
 6071:                  );
 6072:     } elsif ($context eq 'requestauthor') {
 6073:         %tools = (
 6074:                       requestauthor => 1,
 6075:                  );
 6076:     } else {
 6077:         %tools = (
 6078:                       aboutme   => 1,
 6079:                       blog      => 1,
 6080:                       webdav    => 1,
 6081:                       portfolio => 1,
 6082:                  );
 6083:     }
 6084:     return if (!defined($tools{$tool}));
 6085: 
 6086:     if ((!defined($udom)) || (!defined($uname))) {
 6087:         $udom = $env{'user.domain'};
 6088:         $uname = $env{'user.name'};
 6089:     }
 6090: 
 6091:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6092:         if ($action ne 'reload') {
 6093:             if ($context eq 'requestcourses') {
 6094:                 return $env{'environment.canrequest.'.$tool};
 6095:             } elsif ($context eq 'requestauthor') {
 6096:                 return $env{'environment.canrequest.author'};
 6097:             } else {
 6098:                 return $env{'environment.availabletools.'.$tool};
 6099:             }
 6100:         }
 6101:     }
 6102: 
 6103:     my ($toolstatus,$inststatus,$envkey);
 6104:     if ($context eq 'requestauthor') {
 6105:         $envkey = $context; 
 6106:     } else {
 6107:         $envkey = $context.'.'.$tool;
 6108:     }
 6109: 
 6110:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6111:          ($action ne 'reload')) {
 6112:         $toolstatus = $env{'environment.'.$envkey};
 6113:         $inststatus = $env{'environment.inststatus'};
 6114:     } else {
 6115:         if (ref($userenvref) eq 'HASH') {
 6116:             $toolstatus = $userenvref->{$envkey};
 6117:             $inststatus = $userenvref->{'inststatus'};
 6118:         } else {
 6119:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6120:             $toolstatus = $userenv{$envkey};
 6121:             $inststatus = $userenv{'inststatus'};
 6122:         }
 6123:     }
 6124: 
 6125:     if ($toolstatus ne '') {
 6126:         if ($toolstatus) {
 6127:             $access = 1;
 6128:         } else {
 6129:             $access = 0;
 6130:         }
 6131:         return $access;
 6132:     }
 6133: 
 6134:     my ($is_adv,%domdef);
 6135:     if (ref($is_advref) eq 'HASH') {
 6136:         $is_adv = $is_advref->{'is_adv'};
 6137:     } else {
 6138:         $is_adv = &is_advanced_user($udom,$uname);
 6139:     }
 6140:     if (ref($domdefref) eq 'HASH') {
 6141:         %domdef = %{$domdefref};
 6142:     } else {
 6143:         %domdef = &get_domain_defaults($udom);
 6144:     }
 6145:     if (ref($domdef{$tool}) eq 'HASH') {
 6146:         if ($is_adv) {
 6147:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6148:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6149:                     $access = 1;
 6150:                 } else {
 6151:                     $access = 0;
 6152:                 }
 6153:                 return $access;
 6154:             }
 6155:         }
 6156:         if ($inststatus ne '') {
 6157:             my ($hasaccess,$hasnoaccess);
 6158:             foreach my $affiliation (split(/:/,$inststatus)) {
 6159:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6160:                     if ($domdef{$tool}{$affiliation}) {
 6161:                         $hasaccess = 1;
 6162:                     } else {
 6163:                         $hasnoaccess = 1;
 6164:                     }
 6165:                 }
 6166:             }
 6167:             if ($hasaccess || $hasnoaccess) {
 6168:                 if ($hasaccess) {
 6169:                     $access = 1;
 6170:                 } elsif ($hasnoaccess) {
 6171:                     $access = 0; 
 6172:                 }
 6173:                 return $access;
 6174:             }
 6175:         } else {
 6176:             if ($domdef{$tool}{'default'} ne '') {
 6177:                 if ($domdef{$tool}{'default'}) {
 6178:                     $access = 1;
 6179:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6180:                     $access = 0;
 6181:                 }
 6182:                 return $access;
 6183:             }
 6184:         }
 6185:     } else {
 6186:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6187:             $access = 1;
 6188:         } else {
 6189:             $access = 0;
 6190:         }
 6191:         return $access;
 6192:     }
 6193: }
 6194: 
 6195: sub is_course_owner {
 6196:     my ($cdom,$cnum,$udom,$uname) = @_;
 6197:     if (($udom eq '') || ($uname eq '')) {
 6198:         $udom = $env{'user.domain'};
 6199:         $uname = $env{'user.name'};
 6200:     }
 6201:     unless (($udom eq '') || ($uname eq '')) {
 6202:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6203:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6204:                 return 1;
 6205:             } else {
 6206:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6207:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6208:                     return 1;
 6209:                 }
 6210:             }
 6211:         }
 6212:     }
 6213:     return;
 6214: }
 6215: 
 6216: sub is_advanced_user {
 6217:     my ($udom,$uname) = @_;
 6218:     if ($udom ne '' && $uname ne '') {
 6219:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6220:             if (wantarray) {
 6221:                 return ($env{'user.adv'},$env{'user.author'});
 6222:             } else {
 6223:                 return $env{'user.adv'};
 6224:             }
 6225:         }
 6226:     }
 6227:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6228:     my %allroles;
 6229:     my ($is_adv,$is_author);
 6230:     foreach my $role (keys(%roleshash)) {
 6231:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6232:         my $area = '/'.$tdomain.'/'.$trest;
 6233:         if ($sec ne '') {
 6234:             $area .= '/'.$sec;
 6235:         }
 6236:         if (($area ne '') && ($trole ne '')) {
 6237:             my $spec=$trole.'.'.$area;
 6238:             if ($trole =~ /^cr\//) {
 6239:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6240:             } elsif ($trole ne 'gr') {
 6241:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6242:             }
 6243:             if ($trole eq 'au') {
 6244:                 $is_author = 1;
 6245:             }
 6246:         }
 6247:     }
 6248:     foreach my $role (keys(%allroles)) {
 6249:         last if ($is_adv);
 6250:         foreach my $item (split(/:/,$allroles{$role})) {
 6251:             if ($item ne '') {
 6252:                 my ($privilege,$restrictions)=split(/&/,$item);
 6253:                 if ($privilege eq 'adv') {
 6254:                     $is_adv = 1;
 6255:                     last;
 6256:                 }
 6257:             }
 6258:         }
 6259:     }
 6260:     if (wantarray) {
 6261:         return ($is_adv,$is_author);
 6262:     }
 6263:     return $is_adv;
 6264: }
 6265: 
 6266: sub check_can_request {
 6267:     my ($dom,$can_request,$request_domains) = @_;
 6268:     my $canreq = 0;
 6269:     my ($types,$typename) = &Apache::loncommon::course_types();
 6270:     my @options = ('approval','validate','autolimit');
 6271:     my $optregex = join('|',@options);
 6272:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6273:         foreach my $type (@{$types}) {
 6274:             if (&usertools_access($env{'user.name'},
 6275:                                   $env{'user.domain'},
 6276:                                   $type,undef,'requestcourses')) {
 6277:                 $canreq ++;
 6278:                 if (ref($request_domains) eq 'HASH') {
 6279:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6280:                 }
 6281:                 if ($dom eq $env{'user.domain'}) {
 6282:                     $can_request->{$type} = 1;
 6283:                 }
 6284:             }
 6285:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6286:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6287:                 if (@curr > 0) {
 6288:                     foreach my $item (@curr) {
 6289:                         if (ref($request_domains) eq 'HASH') {
 6290:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6291:                             if ($otherdom ne '') {
 6292:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6293:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6294:                                         push(@{$request_domains->{$type}},$otherdom);
 6295:                                     }
 6296:                                 } else {
 6297:                                     push(@{$request_domains->{$type}},$otherdom);
 6298:                                 }
 6299:                             }
 6300:                         }
 6301:                     }
 6302:                     unless($dom eq $env{'user.domain'}) {
 6303:                         $canreq ++;
 6304:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6305:                             $can_request->{$type} = 1;
 6306:                         }
 6307:                     }
 6308:                 }
 6309:             }
 6310:         }
 6311:     }
 6312:     return $canreq;
 6313: }
 6314: 
 6315: # ---------------------------------------------- Custom access rule evaluation
 6316: 
 6317: sub customaccess {
 6318:     my ($priv,$uri)=@_;
 6319:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6320:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6321:     $udom = &LONCAPA::clean_domain($udom);
 6322:     $ucrs = &LONCAPA::clean_username($ucrs);
 6323:     my $access=0;
 6324:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6325: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6326: 	if ($type eq 'user') {
 6327: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6328: 		my ($tdom,$tuname)=split(m{/},$scope);
 6329: 		if ($tdom) {
 6330: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6331: 		}
 6332: 		if ($tuname) {
 6333: 		    if ($tuname ne $env{'user.name'}) { next; }
 6334: 		}
 6335: 		$access=($effect eq 'allow');
 6336: 		last;
 6337: 	    }
 6338: 	} else {
 6339: 	    if ($role) {
 6340: 		if ($role ne $urole) { next; }
 6341: 	    }
 6342: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6343: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6344: 		if ($tdom) {
 6345: 		    if ($tdom ne $udom) { next; }
 6346: 		}
 6347: 		if ($tcrs) {
 6348: 		    if ($tcrs ne $ucrs) { next; }
 6349: 		}
 6350: 		if ($tsec) {
 6351: 		    if ($tsec ne $usec) { next; }
 6352: 		}
 6353: 		$access=($effect eq 'allow');
 6354: 		last;
 6355: 	    }
 6356: 	    if ($realm eq '' && $role eq '') {
 6357: 		$access=($effect eq 'allow');
 6358: 	    }
 6359: 	}
 6360:     }
 6361:     return $access;
 6362: }
 6363: 
 6364: # ------------------------------------------------- Check for a user privilege
 6365: 
 6366: sub allowed {
 6367:     my ($priv,$uri,$symb,$role)=@_;
 6368:     my $ver_orguri=$uri;
 6369:     $uri=&deversion($uri);
 6370:     my $orguri=$uri;
 6371:     $uri=&declutter($uri);
 6372: 
 6373:     if ($priv eq 'evb') {
 6374: # Evade communication block restrictions for specified role in a course
 6375:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6376:             return $1;
 6377:         } else {
 6378:             return;
 6379:         }
 6380:     }
 6381: 
 6382:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6383: # Free bre access to adm and meta resources
 6384:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6385: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6386: 	&& ($priv eq 'bre')) {
 6387: 	return 'F';
 6388:     }
 6389: 
 6390: # Free bre access to user's own portfolio contents
 6391:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6392:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6393: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6394:         my %setters;
 6395:         my ($startblock,$endblock) = 
 6396:             &Apache::loncommon::blockcheck(\%setters,'port');
 6397:         if ($startblock && $endblock) {
 6398:             return 'B';
 6399:         } else {
 6400:             return 'F';
 6401:         }
 6402:     }
 6403: 
 6404: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6405:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6406:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6407:         if (exists($env{'request.course.id'})) {
 6408:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6409:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6410:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6411:                 my $courseprivid=$env{'request.course.id'};
 6412:                 $courseprivid=~s/\_/\//;
 6413:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6414:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6415:                     return $1; 
 6416:                 } else {
 6417:                     if ($env{'request.course.sec'}) {
 6418:                         $courseprivid.='/'.$env{'request.course.sec'};
 6419:                     }
 6420:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6421:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6422:                         return $2;
 6423:                     }
 6424:                 }
 6425:             }
 6426:         }
 6427:     }
 6428: 
 6429: # Free bre to public access
 6430: 
 6431:     if ($priv eq 'bre') {
 6432:         my $copyright=&metadata($uri,'copyright');
 6433: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6434:            return 'F'; 
 6435:         }
 6436:         if ($copyright eq 'priv') {
 6437:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6438: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6439: 		return '';
 6440:             }
 6441:         }
 6442:         if ($copyright eq 'domain') {
 6443:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6444: 	    unless (($env{'user.domain'} eq $1) ||
 6445:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6446: 		return '';
 6447:             }
 6448:         }
 6449:         if ($env{'request.role'}=~ /li\.\//) {
 6450:             # Library role, so allow browsing of resources in this domain.
 6451:             return 'F';
 6452:         }
 6453:         if ($copyright eq 'custom') {
 6454: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6455:         }
 6456:     }
 6457:     # Domain coordinator is trying to create a course
 6458:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6459:         # uri is the requested domain in this case.
 6460:         # comparison to 'request.role.domain' shows if the user has selected
 6461:         # a role of dc for the domain in question.
 6462:         return 'F' if ($uri eq $env{'request.role.domain'});
 6463:     }
 6464: 
 6465:     my $thisallowed='';
 6466:     my $statecond=0;
 6467:     my $courseprivid='';
 6468: 
 6469:     my $ownaccess;
 6470:     # Community Coordinator or Assistant Co-author browsing resource space.
 6471:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6472:         if ($uri eq '') {
 6473:             $ownaccess = 1;
 6474:         } else {
 6475:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6476:                 my $udom = $env{'user.domain'};
 6477:                 my $uname = $env{'user.name'};
 6478:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6479:                     $ownaccess = 1;
 6480:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6481:                     unless ($uri =~ m{\.\./}) {
 6482:                         $ownaccess = 1;
 6483:                     }
 6484:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6485:                     my $now = time;
 6486:                     if ($uri =~ m{^([^/]+)/?$}) {
 6487:                         my $adom = $1;
 6488:                         foreach my $key (keys(%env)) {
 6489:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6490:                                 my ($start,$end) = split('.',$env{$key});
 6491:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6492:                                     $ownaccess = 1;
 6493:                                     last;
 6494:                                 }
 6495:                             }
 6496:                         }
 6497:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6498:                         my $adom = $1;
 6499:                         my $aname = $2;
 6500:                         foreach my $role ('ca','aa') { 
 6501:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6502:                                 my ($start,$end) =
 6503:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6504:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6505:                                     $ownaccess = 1;
 6506:                                     last;
 6507:                                 }
 6508:                             }
 6509:                         }
 6510:                     }
 6511:                 }
 6512:             }
 6513:         }
 6514:     }
 6515: 
 6516: # Course
 6517: 
 6518:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6519:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6520:             $thisallowed.=$1;
 6521:         }
 6522:     }
 6523: 
 6524: # Domain
 6525: 
 6526:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6527:        =~/\Q$priv\E\&([^\:]*)/) {
 6528:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6529:             $thisallowed.=$1;
 6530:         }
 6531:     }
 6532: 
 6533: # User who is not author or co-author might still be able to edit
 6534: # resource of an author in the domain (e.g., if Domain Coordinator).
 6535:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6536:         (&allowed('mdc',$env{'request.course.id'}))) {
 6537:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6538:             $thisallowed.=$1;
 6539:         }
 6540:     }
 6541: 
 6542: # Course: uri itself is a course
 6543:     my $courseuri=$uri;
 6544:     $courseuri=~s/\_(\d)/\/$1/;
 6545:     $courseuri=~s/^([^\/])/\/$1/;
 6546: 
 6547:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6548:        =~/\Q$priv\E\&([^\:]*)/) {
 6549:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6550:             $thisallowed.=$1;
 6551:         }
 6552:     }
 6553: 
 6554: # URI is an uploaded document for this course, default permissions don't matter
 6555: # not allowing 'edit' access (editupload) to uploaded course docs
 6556:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6557: 	$thisallowed='';
 6558:         my ($match)=&is_on_map($uri);
 6559:         if ($match) {
 6560:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6561:                   =~/\Q$priv\E\&([^\:]*)/) {
 6562:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6563:                 if (@blockers > 0) {
 6564:                     $thisallowed = 'B';
 6565:                 } else {
 6566:                     $thisallowed.=$1;
 6567:                 }
 6568:             }
 6569:         } else {
 6570:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6571:             if ($refuri) {
 6572:                 if ($refuri =~ m|^/adm/|) {
 6573:                     $thisallowed='F';
 6574:                 } else {
 6575:                     $refuri=&declutter($refuri);
 6576:                     my ($match) = &is_on_map($refuri);
 6577:                     if ($match) {
 6578:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6579:                         if (@blockers > 0) {
 6580:                             $thisallowed = 'B';
 6581:                         } else {
 6582:                             $thisallowed='F';
 6583:                         }
 6584:                     }
 6585:                 }
 6586:             }
 6587:         }
 6588:     }
 6589: 
 6590:     if ($priv eq 'bre'
 6591: 	&& $thisallowed ne 'F' 
 6592: 	&& $thisallowed ne '2'
 6593: 	&& &is_portfolio_url($uri)) {
 6594: 	$thisallowed = &portfolio_access($uri);
 6595:     }
 6596:     
 6597: # Full access at system, domain or course-wide level? Exit.
 6598:     if ($thisallowed=~/F/) {
 6599: 	return 'F';
 6600:     }
 6601: 
 6602: # If this is generating or modifying users, exit with special codes
 6603: 
 6604:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6605: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6606: 	    my ($audom,$auname)=split('/',$uri);
 6607: # no author name given, so this just checks on the general right to make a co-author in this domain
 6608: 	    unless ($auname) { return $thisallowed; }
 6609: # an author name is given, so we are about to actually make a co-author for a certain account
 6610: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6611: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6612: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6613: 	}
 6614: 	return $thisallowed;
 6615:     }
 6616: #
 6617: # Gathered so far: system, domain and course wide privileges
 6618: #
 6619: # Course: See if uri or referer is an individual resource that is part of 
 6620: # the course
 6621: 
 6622:     if ($env{'request.course.id'}) {
 6623: 
 6624:        $courseprivid=$env{'request.course.id'};
 6625:        if ($env{'request.course.sec'}) {
 6626:           $courseprivid.='/'.$env{'request.course.sec'};
 6627:        }
 6628:        $courseprivid=~s/\_/\//;
 6629:        my $checkreferer=1;
 6630:        my ($match,$cond)=&is_on_map($uri);
 6631:        if ($match) {
 6632:            $statecond=$cond;
 6633:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6634:                =~/\Q$priv\E\&([^\:]*)/) {
 6635:                my $value = $1;
 6636:                if ($priv eq 'bre') {
 6637:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6638:                    if (@blockers > 0) {
 6639:                        $thisallowed = 'B';
 6640:                    } else {
 6641:                        $thisallowed.=$value;
 6642:                    }
 6643:                } else {
 6644:                    $thisallowed.=$value;
 6645:                }
 6646:                $checkreferer=0;
 6647:            }
 6648:        }
 6649:        
 6650:        if ($checkreferer) {
 6651: 	  my $refuri=$env{'httpref.'.$orguri};
 6652:             unless ($refuri) {
 6653:                 foreach my $key (keys(%env)) {
 6654: 		    if ($key=~/^httpref\..*\*/) {
 6655: 			my $pattern=$key;
 6656:                         $pattern=~s/^httpref\.\/res\///;
 6657:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6658:                         $pattern=~s/\//\\\//g;
 6659:                         if ($orguri=~/$pattern/) {
 6660: 			    $refuri=$env{$key};
 6661:                         }
 6662:                     }
 6663:                 }
 6664:             }
 6665: 
 6666:          if ($refuri) { 
 6667: 	  $refuri=&declutter($refuri);
 6668:           my ($match,$cond)=&is_on_map($refuri);
 6669:             if ($match) {
 6670:               my $refstatecond=$cond;
 6671:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6672:                   =~/\Q$priv\E\&([^\:]*)/) {
 6673:                   my $value = $1;
 6674:                   if ($priv eq 'bre') {
 6675:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6676:                       if (@blockers > 0) {
 6677:                           $thisallowed = 'B';
 6678:                       } else {
 6679:                           $thisallowed.=$value;
 6680:                       }
 6681:                   } else {
 6682:                       $thisallowed.=$value;
 6683:                   }
 6684:                   $uri=$refuri;
 6685:                   $statecond=$refstatecond;
 6686:               }
 6687:           }
 6688:         }
 6689:        }
 6690:    }
 6691: 
 6692: #
 6693: # Gathered now: all privileges that could apply, and condition number
 6694: # 
 6695: #
 6696: # Full or no access?
 6697: #
 6698: 
 6699:     if ($thisallowed=~/F/) {
 6700: 	return 'F';
 6701:     }
 6702: 
 6703:     unless ($thisallowed) {
 6704:         return '';
 6705:     }
 6706: 
 6707: # Restrictions exist, deal with them
 6708: #
 6709: #   C:according to course preferences
 6710: #   R:according to resource settings
 6711: #   L:unless locked
 6712: #   X:according to user session state
 6713: #
 6714: 
 6715: # Possibly locked functionality, check all courses
 6716: # Locks might take effect only after 10 minutes cache expiration for other
 6717: # courses, and 2 minutes for current course
 6718: 
 6719:     my $envkey;
 6720:     if ($thisallowed=~/L/) {
 6721:         foreach $envkey (keys(%env)) {
 6722:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6723:                my $courseid=$2;
 6724:                my $roleid=$1.'.'.$2;
 6725:                $courseid=~s/^\///;
 6726:                my $expiretime=600;
 6727:                if ($env{'request.role'} eq $roleid) {
 6728: 		  $expiretime=120;
 6729:                }
 6730: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6731:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6732:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6733: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6734:                }
 6735:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6736:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6737: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6738:                        &log($env{'user.domain'},$env{'user.name'},
 6739:                             $env{'user.home'},
 6740:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6741:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6742:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6743: 		       return '';
 6744:                    }
 6745:                }
 6746:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6747:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6748: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6749:                        &log($env{'user.domain'},$env{'user.name'},
 6750:                             $env{'user.home'},
 6751:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6752:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6753:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6754: 		       return '';
 6755:                    }
 6756:                }
 6757: 	   }
 6758:        }
 6759:     }
 6760:    
 6761: #
 6762: # Rest of the restrictions depend on selected course
 6763: #
 6764: 
 6765:     unless ($env{'request.course.id'}) {
 6766: 	if ($thisallowed eq 'A') {
 6767: 	    return 'A';
 6768:         } elsif ($thisallowed eq 'B') {
 6769:             return 'B';
 6770: 	} else {
 6771: 	    return '1';
 6772: 	}
 6773:     }
 6774: 
 6775: #
 6776: # Now user is definitely in a course
 6777: #
 6778: 
 6779: 
 6780: # Course preferences
 6781: 
 6782:    if ($thisallowed=~/C/) {
 6783:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6784:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6785:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6786: 	   =~/\Q$rolecode\E/) {
 6787: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6788: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6789: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6790: 			$env{'request.course.id'});
 6791: 	   }
 6792:            return '';
 6793:        }
 6794: 
 6795:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6796: 	   =~/\Q$unamedom\E/) {
 6797: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6798: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6799: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6800: 			$env{'request.course.id'});
 6801: 	   }
 6802:            return '';
 6803:        }
 6804:    }
 6805: 
 6806: # Resource preferences
 6807: 
 6808:    if ($thisallowed=~/R/) {
 6809:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6810:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6811: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6812: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6813: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6814: 	   }
 6815: 	   return '';
 6816:        }
 6817:    }
 6818: 
 6819: # Restricted by state or randomout?
 6820: 
 6821:    if ($thisallowed=~/X/) {
 6822:       if ($env{'acc.randomout'}) {
 6823: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6824:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6825:             return ''; 
 6826:          }
 6827:       }
 6828:       if (&condval($statecond)) {
 6829: 	 return '2';
 6830:       } else {
 6831:          return '';
 6832:       }
 6833:    }
 6834: 
 6835:     if ($thisallowed eq 'A') {
 6836: 	return 'A';
 6837:     } elsif ($thisallowed eq 'B') {
 6838:         return 'B';
 6839:     }
 6840:    return 'F';
 6841: }
 6842: 
 6843: # ------------------------------------------- Check construction space access
 6844: 
 6845: sub constructaccess {
 6846:     my ($url,$setpriv)=@_;
 6847: 
 6848: # We do not allow editing of previous versions of files
 6849:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6850: 
 6851: # Get username and domain from URL
 6852:     my ($ownername,$ownerdomain,$ownerhome);
 6853: 
 6854:     ($ownerdomain,$ownername) =
 6855:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6856: 
 6857: # The URL does not really point to any authorspace, forget it
 6858:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6859: 
 6860: # Now we need to see if the user has access to the authorspace of
 6861: # $ownername at $ownerdomain
 6862: 
 6863:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6864: # Real author for this?
 6865:        $ownerhome = $env{'user.home'};
 6866:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6867:           return ($ownername,$ownerdomain,$ownerhome);
 6868:        }
 6869:     } else {
 6870: # Co-author for this?
 6871:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6872:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6873:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6874:             return ($ownername,$ownerdomain,$ownerhome);
 6875:         }
 6876:     }
 6877: 
 6878: # We don't have any access right now. If we are not possibly going to do anything about this,
 6879: # we might as well leave
 6880:    unless ($setpriv) { return ''; }
 6881: 
 6882: # Backdoor access?
 6883:     my $allowed=&allowed('eco',$ownerdomain);
 6884: # Nope
 6885:     unless ($allowed) { return ''; }
 6886: # Looks like we may have access, but could be locked by the owner of the construction space
 6887:     if ($allowed eq 'U') {
 6888:         my %blocked=&get('environment',['domcoord.author'],
 6889:                          $ownerdomain,$ownername);
 6890: # Is blocked by owner
 6891:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 6892:     }
 6893:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 6894: # Grant temporary access
 6895:         my $then=$env{'user.login.time'};
 6896:         my $update=$env{'user.update.time'};
 6897:         if (!$update) { $update = $then; }
 6898:         my $refresh=$env{'user.refresh.time'};
 6899:         if (!$refresh) { $refresh = $update; }
 6900:         my $now = time;
 6901:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 6902:                            $now,'ca','constructaccess');
 6903:         $ownerhome = &homeserver($ownername,$ownerdomain);
 6904:         return($ownername,$ownerdomain,$ownerhome);
 6905:     }
 6906: # No business here
 6907:     return '';
 6908: }
 6909: 
 6910: sub get_comm_blocks {
 6911:     my ($cdom,$cnum) = @_;
 6912:     if ($cdom eq '' || $cnum eq '') {
 6913:         return unless ($env{'request.course.id'});
 6914:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6915:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6916:     }
 6917:     my %commblocks;
 6918:     my $hashid=$cdom.'_'.$cnum;
 6919:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6920:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6921:         %commblocks = %{$blocksref};
 6922:     } else {
 6923:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6924:         my $cachetime = 600;
 6925:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6926:     }
 6927:     return %commblocks;
 6928: }
 6929: 
 6930: sub has_comm_blocking {
 6931:     my ($priv,$symb,$uri,$blocks) = @_;
 6932:     return unless ($env{'request.course.id'});
 6933:     return unless ($priv eq 'bre');
 6934:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6935:     my %commblocks;
 6936:     if (ref($blocks) eq 'HASH') {
 6937:         %commblocks = %{$blocks};
 6938:     } else {
 6939:         %commblocks = &get_comm_blocks();
 6940:     }
 6941:     return unless (keys(%commblocks) > 0);
 6942:     if (!$symb) { $symb=&symbread($uri,1); }
 6943:     my ($map,$resid,undef)=&decode_symb($symb);
 6944:     my %tocheck = (
 6945:                     maps      => $map,
 6946:                     resources => $symb,
 6947:                   );
 6948:     my @blockers;
 6949:     my $now = time;
 6950:     my $navmap = Apache::lonnavmaps::navmap->new();
 6951:     foreach my $block (keys(%commblocks)) {
 6952:         if ($block =~ /^(\d+)____(\d+)$/) {
 6953:             my ($start,$end) = ($1,$2);
 6954:             if ($start <= $now && $end >= $now) {
 6955:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6956:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6957:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6958:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6959:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6960:                                     push(@blockers,$block);
 6961:                                 }
 6962:                             }
 6963:                         }
 6964:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6965:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6966:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6967:                                     push(@blockers,$block);
 6968:                                 }
 6969:                             }
 6970:                         }
 6971:                     }
 6972:                 }
 6973:             }
 6974:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6975:             my $item = $1;
 6976:             my @to_test;
 6977:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6978:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6979:                     my $check_interval;
 6980:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6981:                         my @interval;
 6982:                         my $type = 'map';
 6983:                         if ($item eq 'course') {
 6984:                             $type = 'course';
 6985:                             @interval=&EXT("resource.0.interval");
 6986:                         } else {
 6987:                             if ($item =~ /___\d+___/) {
 6988:                                 $type = 'resource';
 6989:                                 @interval=&EXT("resource.0.interval",$item);
 6990:                                 if (ref($navmap)) {                        
 6991:                                     my $res = $navmap->getBySymb($item); 
 6992:                                     push(@to_test,$res);
 6993:                                 }
 6994:                             } else {
 6995:                                 my $mapsymb = &symbread($item,1);
 6996:                                 if ($mapsymb) {
 6997:                                     if (ref($navmap)) {
 6998:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6999:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7000:                                         foreach my $res (@to_test) {
 7001:                                             my $symb = $res->symb();
 7002:                                             next if ($symb eq $mapsymb);
 7003:                                             if ($symb ne '') {
 7004:                                                 @interval=&EXT("resource.0.interval",$symb);
 7005:                                                 last;
 7006:                                             }
 7007:                                         }
 7008:                                     }
 7009:                                 }
 7010:                             }
 7011:                         }
 7012:                         if ($interval[0] =~ /\d+/) {
 7013:                             my $first_access;
 7014:                             if ($type eq 'resource') {
 7015:                                 $first_access=&get_first_access($interval[1],$item);
 7016:                             } elsif ($type eq 'map') {
 7017:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7018:                             } else {
 7019:                                 $first_access=&get_first_access($interval[1]);
 7020:                             }
 7021:                             if ($first_access) {
 7022:                                 my $timesup = $first_access+$interval[0];
 7023:                                 if ($timesup > $now) {
 7024:                                     foreach my $res (@to_test) {
 7025:                                         if ($res->is_problem()) {
 7026:                                             if ($res->completable()) {
 7027:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7028:                                                     push(@blockers,$block);
 7029:                                                 }
 7030:                                                 last;
 7031:                                             }
 7032:                                         }
 7033:                                     }
 7034:                                 }
 7035:                             }
 7036:                         }
 7037:                     }
 7038:                 }
 7039:             }
 7040:         }
 7041:     }
 7042:     return @blockers;
 7043: }
 7044: 
 7045: sub check_docs_block {
 7046:     my ($docsblock,$tocheck) =@_;
 7047:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7048:         return;
 7049:     }
 7050:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7051:         if ($tocheck->{'maps'}) {
 7052:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7053:                 return 1;
 7054:             }
 7055:         }
 7056:     }
 7057:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7058:         if ($tocheck->{'resources'}) {
 7059:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7060:                 return 1;
 7061:             }
 7062:         }
 7063:     }
 7064:     return;
 7065: }
 7066: 
 7067: #
 7068: #   Removes the versino from a URI and
 7069: #   splits it in to its filename and path to the filename.
 7070: #   Seems like File::Basename could have done this more clearly.
 7071: #   Parameters:
 7072: #      $uri   - input URI
 7073: #   Returns:
 7074: #     Two element list consisting of 
 7075: #     $pathname  - the URI up to and excluding the trailing /
 7076: #     $filename  - The part of the URI following the last /
 7077: #  NOTE:
 7078: #    Another realization of this is simply:
 7079: #    use File::Basename;
 7080: #    ...
 7081: #    $uri = shift;
 7082: #    $filename = basename($uri);
 7083: #    $path     = dirname($uri);
 7084: #    return ($filename, $path);
 7085: #
 7086: #     The implementation below is probably faster however.
 7087: #
 7088: sub split_uri_for_cond {
 7089:     my $uri=&deversion(&declutter(shift));
 7090:     my @uriparts=split(/\//,$uri);
 7091:     my $filename=pop(@uriparts);
 7092:     my $pathname=join('/',@uriparts);
 7093:     return ($pathname,$filename);
 7094: }
 7095: # --------------------------------------------------- Is a resource on the map?
 7096: 
 7097: sub is_on_map {
 7098:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7099:     #Trying to find the conditional for the file
 7100:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7101: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7102:     if ($match) {
 7103: 	return (1,$1);
 7104:     } else {
 7105: 	return (0,0);
 7106:     }
 7107: }
 7108: 
 7109: # --------------------------------------------------------- Get symb from alias
 7110: 
 7111: sub get_symb_from_alias {
 7112:     my $symb=shift;
 7113:     my ($map,$resid,$url)=&decode_symb($symb);
 7114: # Already is a symb
 7115:     if ($url) { return $symb; }
 7116: # Must be an alias
 7117:     my $aliassymb='';
 7118:     my %bighash;
 7119:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7120:                             &GDBM_READER(),0640)) {
 7121:         my $rid=$bighash{'mapalias_'.$symb};
 7122: 	if ($rid) {
 7123: 	    my ($mapid,$resid)=split(/\./,$rid);
 7124: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7125: 				    $resid,$bighash{'src_'.$rid});
 7126: 	}
 7127:         untie %bighash;
 7128:     }
 7129:     return $aliassymb;
 7130: }
 7131: 
 7132: # ----------------------------------------------------------------- Define Role
 7133: 
 7134: sub definerole {
 7135:   if (allowed('mcr','/')) {
 7136:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7137:     foreach my $role (split(':',$sysrole)) {
 7138: 	my ($crole,$cqual)=split(/\&/,$role);
 7139:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7140:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7141: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7142:                return "refused:s:$crole&$cqual"; 
 7143:             }
 7144:         }
 7145:     }
 7146:     foreach my $role (split(':',$domrole)) {
 7147: 	my ($crole,$cqual)=split(/\&/,$role);
 7148:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7149:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7150: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7151:                return "refused:d:$crole&$cqual"; 
 7152:             }
 7153:         }
 7154:     }
 7155:     foreach my $role (split(':',$courole)) {
 7156: 	my ($crole,$cqual)=split(/\&/,$role);
 7157:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7158:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7159: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7160:                return "refused:c:$crole&$cqual"; 
 7161:             }
 7162:         }
 7163:     }
 7164:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7165:                 "$env{'user.domain'}:$env{'user.name'}:".
 7166: 	        "rolesdef_$rolename=".
 7167:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7168:     return reply($command,$env{'user.home'});
 7169:   } else {
 7170:     return 'refused';
 7171:   }
 7172: }
 7173: 
 7174: # ---------------- Make a metadata query against the network of library servers
 7175: 
 7176: sub metadata_query {
 7177:     my ($query,$custom,$customshow,$server_array)=@_;
 7178:     my %rhash;
 7179:     my %libserv = &all_library();
 7180:     my @server_list = (defined($server_array) ? @$server_array
 7181:                                               : keys(%libserv) );
 7182:     for my $server (@server_list) {
 7183: 	unless ($custom or $customshow) {
 7184: 	    my $reply=&reply("querysend:".&escape($query),$server);
 7185: 	    $rhash{$server}=$reply;
 7186: 	}
 7187: 	else {
 7188: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7189: 			     &escape($custom).':'.&escape($customshow),
 7190: 			     $server);
 7191: 	    $rhash{$server}=$reply;
 7192: 	}
 7193:     }
 7194:     return \%rhash;
 7195: }
 7196: 
 7197: # ----------------------------------------- Send log queries and wait for reply
 7198: 
 7199: sub log_query {
 7200:     my ($uname,$udom,$query,%filters)=@_;
 7201:     my $uhome=&homeserver($uname,$udom);
 7202:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7203:     my $uhost=&hostname($uhome);
 7204:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7205:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7206:                        $uhome);
 7207:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7208:     return get_query_reply($queryid);
 7209: }
 7210: 
 7211: # -------------------------- Update MySQL table for portfolio file
 7212: 
 7213: sub update_portfolio_table {
 7214:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7215:     if ($group ne '') {
 7216:         $file_name =~s /^\Q$group\E//;
 7217:     }
 7218:     my $homeserver = &homeserver($uname,$udom);
 7219:     my $queryid=
 7220:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7221:                ':'.&escape($file_name).':'.$action,$homeserver);
 7222:     my $reply = &get_query_reply($queryid);
 7223:     return $reply;
 7224: }
 7225: 
 7226: # -------------------------- Update MySQL allusers table
 7227: 
 7228: sub update_allusers_table {
 7229:     my ($uname,$udom,$names) = @_;
 7230:     my $homeserver = &homeserver($uname,$udom);
 7231:     my $queryid=
 7232:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7233:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7234:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7235:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7236:                'generation='.&escape($names->{'generation'}).'%%'.
 7237:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7238:                'id='.&escape($names->{'id'}),$homeserver);
 7239:     return;
 7240: }
 7241: 
 7242: # ------- Request retrieval of institutional classlists for course(s)
 7243: 
 7244: sub fetch_enrollment_query {
 7245:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7246:     my $homeserver;
 7247:     my $maxtries = 1;
 7248:     if ($context eq 'automated') {
 7249:         $homeserver = $perlvar{'lonHostID'};
 7250:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7251:     } else {
 7252:         $homeserver = &homeserver($cnum,$dom);
 7253:     }
 7254:     my $host=&hostname($homeserver);
 7255:     my $cmd = '';
 7256:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7257:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7258:     }
 7259:     $cmd =~ s/%%$//;
 7260:     $cmd = &escape($cmd);
 7261:     my $query = 'fetchenrollment';
 7262:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7263:     unless ($queryid=~/^\Q$host\E\_/) { 
 7264:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7265:         return 'error: '.$queryid;
 7266:     }
 7267:     my $reply = &get_query_reply($queryid);
 7268:     my $tries = 1;
 7269:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7270:         $reply = &get_query_reply($queryid);
 7271:         $tries ++;
 7272:     }
 7273:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7274:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7275:     } else {
 7276:         my @responses = split(/:/,$reply);
 7277:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7278:             foreach my $line (@responses) {
 7279:                 my ($key,$value) = split(/=/,$line,2);
 7280:                 $$replyref{$key} = $value;
 7281:             }
 7282:         } else {
 7283:             my $pathname = LONCAPA::tempdir();
 7284:             foreach my $line (@responses) {
 7285:                 my ($key,$value) = split(/=/,$line);
 7286:                 $$replyref{$key} = $value;
 7287:                 if ($value > 0) {
 7288:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7289:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7290:                         my $destname = $pathname.'/'.$filename;
 7291:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7292:                         if ($xml_classlist =~ /^error/) {
 7293:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7294:                         } else {
 7295:                             if ( open(FILE,">$destname") ) {
 7296:                                 print FILE &unescape($xml_classlist);
 7297:                                 close(FILE);
 7298:                             } else {
 7299:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7300:                             }
 7301:                         }
 7302:                     }
 7303:                 }
 7304:             }
 7305:         }
 7306:         return 'ok';
 7307:     }
 7308:     return 'error';
 7309: }
 7310: 
 7311: sub get_query_reply {
 7312:     my $queryid=shift;
 7313:     my $replyfile=LONCAPA::tempdir().$queryid;
 7314:     my $reply='';
 7315:     for (1..100) {
 7316: 	sleep 2;
 7317:         if (-e $replyfile.'.end') {
 7318: 	    if (open(my $fh,$replyfile)) {
 7319: 		$reply = join('',<$fh>);
 7320: 		close($fh);
 7321: 	   } else { return 'error: reply_file_error'; }
 7322:            return &unescape($reply);
 7323: 	}
 7324:     }
 7325:     return 'timeout:'.$queryid;
 7326: }
 7327: 
 7328: sub courselog_query {
 7329: #
 7330: # possible filters:
 7331: # url: url or symb
 7332: # username
 7333: # domain
 7334: # action: view, submit, grade
 7335: # start: timestamp
 7336: # end: timestamp
 7337: #
 7338:     my (%filters)=@_;
 7339:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7340:     if ($filters{'url'}) {
 7341: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7342:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7343:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7344:     }
 7345:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7346:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7347:     return &log_query($cname,$cdom,'courselog',%filters);
 7348: }
 7349: 
 7350: sub userlog_query {
 7351: #
 7352: # possible filters:
 7353: # action: log check role
 7354: # start: timestamp
 7355: # end: timestamp
 7356: #
 7357:     my ($uname,$udom,%filters)=@_;
 7358:     return &log_query($uname,$udom,'userlog',%filters);
 7359: }
 7360: 
 7361: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7362: 
 7363: sub auto_run {
 7364:     my ($cnum,$cdom) = @_;
 7365:     my $response = 0;
 7366:     my $settings;
 7367:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7368:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7369:         $settings = $domconfig{'autoenroll'};
 7370:         if ($settings->{'run'} eq '1') {
 7371:             $response = 1;
 7372:         }
 7373:     } else {
 7374:         my $homeserver;
 7375:         if (&is_course($cdom,$cnum)) {
 7376:             $homeserver = &homeserver($cnum,$cdom);
 7377:         } else {
 7378:             $homeserver = &domain($cdom,'primary');
 7379:         }
 7380:         if ($homeserver ne 'no_host') {
 7381:             $response = &reply('autorun:'.$cdom,$homeserver);
 7382:         }
 7383:     }
 7384:     return $response;
 7385: }
 7386: 
 7387: sub auto_get_sections {
 7388:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7389:     my $homeserver;
 7390:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7391:         $homeserver = &homeserver($cnum,$cdom);
 7392:     }
 7393:     if (!defined($homeserver)) { 
 7394:         if ($cdom =~ /^$match_domain$/) {
 7395:             $homeserver = &domain($cdom,'primary');
 7396:         }
 7397:     }
 7398:     my @secs;
 7399:     if (defined($homeserver)) {
 7400:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7401:         unless ($response eq 'refused') {
 7402:             @secs = split(/:/,$response);
 7403:         }
 7404:     }
 7405:     return @secs;
 7406: }
 7407: 
 7408: sub auto_new_course {
 7409:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7410:     my $homeserver = &homeserver($cnum,$cdom);
 7411:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7412:     return $response;
 7413: }
 7414: 
 7415: sub auto_validate_courseID {
 7416:     my ($cnum,$cdom,$inst_course_id) = @_;
 7417:     my $homeserver = &homeserver($cnum,$cdom);
 7418:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7419:     return $response;
 7420: }
 7421: 
 7422: sub auto_validate_instcode {
 7423:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7424:     my ($homeserver,$response);
 7425:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7426:         $homeserver = &homeserver($cnum,$cdom);
 7427:     }
 7428:     if (!defined($homeserver)) {
 7429:         if ($cdom =~ /^$match_domain$/) {
 7430:             $homeserver = &domain($cdom,'primary');
 7431:         }
 7432:     }
 7433:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7434:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7435:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 7436:     return ($outcome,$description);
 7437: }
 7438: 
 7439: sub auto_create_password {
 7440:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7441:     my ($homeserver,$response);
 7442:     my $create_passwd = 0;
 7443:     my $authchk = '';
 7444:     if ($udom =~ /^$match_domain$/) {
 7445:         $homeserver = &domain($udom,'primary');
 7446:     }
 7447:     if ($homeserver eq '') {
 7448:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7449:             $homeserver = &homeserver($cnum,$cdom);
 7450:         }
 7451:     }
 7452:     if ($homeserver eq '') {
 7453:         $authchk = 'nodomain';
 7454:     } else {
 7455:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7456:         if ($response eq 'refused') {
 7457:             $authchk = 'refused';
 7458:         } else {
 7459:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7460:         }
 7461:     }
 7462:     return ($authparam,$create_passwd,$authchk);
 7463: }
 7464: 
 7465: sub auto_photo_permission {
 7466:     my ($cnum,$cdom,$students) = @_;
 7467:     my $homeserver = &homeserver($cnum,$cdom);
 7468:     my ($outcome,$perm_reqd,$conditions) = 
 7469: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7470:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7471: 	return (undef,undef);
 7472:     }
 7473:     return ($outcome,$perm_reqd,$conditions);
 7474: }
 7475: 
 7476: sub auto_checkphotos {
 7477:     my ($uname,$udom,$pid) = @_;
 7478:     my $homeserver = &homeserver($uname,$udom);
 7479:     my ($result,$resulttype);
 7480:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7481: 				   &escape($uname).':'.&escape($pid),
 7482: 				   $homeserver));
 7483:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7484: 	return (undef,undef);
 7485:     }
 7486:     if ($outcome) {
 7487:         ($result,$resulttype) = split(/:/,$outcome);
 7488:     } 
 7489:     return ($result,$resulttype);
 7490: }
 7491: 
 7492: sub auto_photochoice {
 7493:     my ($cnum,$cdom) = @_;
 7494:     my $homeserver = &homeserver($cnum,$cdom);
 7495:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7496: 						       &escape($cdom),
 7497: 						       $homeserver)));
 7498:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7499: 	return (undef,undef);
 7500:     }
 7501:     return ($update,$comment);
 7502: }
 7503: 
 7504: sub auto_photoupdate {
 7505:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7506:     my $homeserver = &homeserver($cnum,$dom);
 7507:     my $host=&hostname($homeserver);
 7508:     my $cmd = '';
 7509:     my $maxtries = 1;
 7510:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7511:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7512:     }
 7513:     $cmd =~ s/%%$//;
 7514:     $cmd = &escape($cmd);
 7515:     my $query = 'institutionalphotos';
 7516:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7517:     unless ($queryid=~/^\Q$host\E\_/) {
 7518:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7519:         return 'error: '.$queryid;
 7520:     }
 7521:     my $reply = &get_query_reply($queryid);
 7522:     my $tries = 1;
 7523:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7524:         $reply = &get_query_reply($queryid);
 7525:         $tries ++;
 7526:     }
 7527:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7528:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7529:     } else {
 7530:         my @responses = split(/:/,$reply);
 7531:         my $outcome = shift(@responses); 
 7532:         foreach my $item (@responses) {
 7533:             my ($key,$value) = split(/=/,$item);
 7534:             $$photo{$key} = $value;
 7535:         }
 7536:         return $outcome;
 7537:     }
 7538:     return 'error';
 7539: }
 7540: 
 7541: sub auto_instcode_format {
 7542:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7543: 	$cat_order) = @_;
 7544:     my $courses = '';
 7545:     my @homeservers;
 7546:     if ($caller eq 'global') {
 7547: 	my %servers = &get_servers($codedom,'library');
 7548: 	foreach my $tryserver (keys(%servers)) {
 7549: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7550: 		push(@homeservers,$tryserver);
 7551: 	    }
 7552:         }
 7553:     } elsif ($caller eq 'requests') {
 7554:         if ($codedom =~ /^$match_domain$/) {
 7555:             my $chome = &domain($codedom,'primary');
 7556:             unless ($chome eq 'no_host') {
 7557:                 push(@homeservers,$chome);
 7558:             }
 7559:         }
 7560:     } else {
 7561:         push(@homeservers,&homeserver($caller,$codedom));
 7562:     }
 7563:     foreach my $code (keys(%{$instcodes})) {
 7564:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7565:     }
 7566:     chop($courses);
 7567:     my $ok_response = 0;
 7568:     my $response;
 7569:     while (@homeservers > 0 && $ok_response == 0) {
 7570:         my $server = shift(@homeservers); 
 7571:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7572:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7573:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7574: 		split(/:/,$response);
 7575:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7576:             push(@{$codetitles},&str2array($codetitles_str));
 7577:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7578:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7579:             $ok_response = 1;
 7580:         }
 7581:     }
 7582:     if ($ok_response) {
 7583:         return 'ok';
 7584:     } else {
 7585:         return $response;
 7586:     }
 7587: }
 7588: 
 7589: sub auto_instcode_defaults {
 7590:     my ($domain,$returnhash,$code_order) = @_;
 7591:     my @homeservers;
 7592: 
 7593:     my %servers = &get_servers($domain,'library');
 7594:     foreach my $tryserver (keys(%servers)) {
 7595: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7596: 	    push(@homeservers,$tryserver);
 7597: 	}
 7598:     }
 7599: 
 7600:     my $response;
 7601:     foreach my $server (@homeservers) {
 7602:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7603:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7604: 	
 7605: 	foreach my $pair (split(/\&/,$response)) {
 7606: 	    my ($name,$value)=split(/\=/,$pair);
 7607: 	    if ($name eq 'code_order') {
 7608: 		@{$code_order} = split(/\&/,&unescape($value));
 7609: 	    } else {
 7610: 		$returnhash->{&unescape($name)}=&unescape($value);
 7611: 	    }
 7612: 	}
 7613: 	return 'ok';
 7614:     }
 7615: 
 7616:     return $response;
 7617: }
 7618: 
 7619: sub auto_possible_instcodes {
 7620:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7621:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7622:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7623:         return;
 7624:     }
 7625:     my (@homeservers,$uhome);
 7626:     if (defined(&domain($domain,'primary'))) {
 7627:         $uhome=&domain($domain,'primary');
 7628:         push(@homeservers,&domain($domain,'primary'));
 7629:     } else {
 7630:         my %servers = &get_servers($domain,'library');
 7631:         foreach my $tryserver (keys(%servers)) {
 7632:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7633:                 push(@homeservers,$tryserver);
 7634:             }
 7635:         }
 7636:     }
 7637:     my $response;
 7638:     foreach my $server (@homeservers) {
 7639:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7640:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7641:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7642:             split(':',$response);
 7643:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7644:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7645:         foreach my $item (split('&',$cat_title)) {   
 7646:             my ($name,$value)=split('=',$item);
 7647:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7648:         }
 7649:         foreach my $item (split('&',$cat_order)) {
 7650:             my ($name,$value)=split('=',$item);
 7651:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7652:         }
 7653:         return 'ok';
 7654:     }
 7655:     return $response;
 7656: }
 7657: 
 7658: sub auto_courserequest_checks {
 7659:     my ($dom) = @_;
 7660:     my ($homeserver,%validations);
 7661:     if ($dom =~ /^$match_domain$/) {
 7662:         $homeserver = &domain($dom,'primary');
 7663:     }
 7664:     unless ($homeserver eq 'no_host') {
 7665:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7666:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7667:             my @items = split(/&/,$response);
 7668:             foreach my $item (@items) {
 7669:                 my ($key,$value) = split('=',$item);
 7670:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7671:             }
 7672:         }
 7673:     }
 7674:     return %validations; 
 7675: }
 7676: 
 7677: sub auto_courserequest_validation {
 7678:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7679:     my ($homeserver,$response);
 7680:     if ($dom =~ /^$match_domain$/) {
 7681:         $homeserver = &domain($dom,'primary');
 7682:     }
 7683:     unless ($homeserver eq 'no_host') {  
 7684:           
 7685:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7686:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7687:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7688:                                     $homeserver));
 7689:     }
 7690:     return $response;
 7691: }
 7692: 
 7693: sub auto_validate_class_sec {
 7694:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7695:     my $homeserver = &homeserver($cnum,$cdom);
 7696:     my $ownerlist;
 7697:     if (ref($owners) eq 'ARRAY') {
 7698:         $ownerlist = join(',',@{$owners});
 7699:     } else {
 7700:         $ownerlist = $owners;
 7701:     }
 7702:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7703:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7704:     return $response;
 7705: }
 7706: 
 7707: # ------------------------------------------------------- Course Group routines
 7708: 
 7709: sub get_coursegroups {
 7710:     my ($cdom,$cnum,$group,$namespace) = @_;
 7711:     return(&dump($namespace,$cdom,$cnum,$group));
 7712: }
 7713: 
 7714: sub modify_coursegroup {
 7715:     my ($cdom,$cnum,$groupsettings) = @_;
 7716:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7717: }
 7718: 
 7719: sub toggle_coursegroup_status {
 7720:     my ($cdom,$cnum,$group,$action) = @_;
 7721:     my ($from_namespace,$to_namespace);
 7722:     if ($action eq 'delete') {
 7723:         $from_namespace = 'coursegroups';
 7724:         $to_namespace = 'deleted_groups';
 7725:     } else {
 7726:         $from_namespace = 'deleted_groups';
 7727:         $to_namespace = 'coursegroups';
 7728:     }
 7729:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7730:     if (my $tmp = &error(%curr_group)) {
 7731:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7732:         return ('read error',$tmp);
 7733:     } else {
 7734:         my %savedsettings = %curr_group; 
 7735:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7736:         my $deloutcome;
 7737:         if ($result eq 'ok') {
 7738:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7739:         } else {
 7740:             return ('write error',$result);
 7741:         }
 7742:         if ($deloutcome eq 'ok') {
 7743:             return 'ok';
 7744:         } else {
 7745:             return ('delete error',$deloutcome);
 7746:         }
 7747:     }
 7748: }
 7749: 
 7750: sub modify_group_roles {
 7751:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7752:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7753:     my $role = 'gr/'.&escape($userprivs);
 7754:     my ($uname,$udom) = split(/:/,$user);
 7755:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7756:     if ($result eq 'ok') {
 7757:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7758:     }
 7759:     return $result;
 7760: }
 7761: 
 7762: sub modify_coursegroup_membership {
 7763:     my ($cdom,$cnum,$membership) = @_;
 7764:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7765:     return $result;
 7766: }
 7767: 
 7768: sub get_active_groups {
 7769:     my ($udom,$uname,$cdom,$cnum) = @_;
 7770:     my $now = time;
 7771:     my %groups = ();
 7772:     foreach my $key (keys(%env)) {
 7773:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7774:             my ($start,$end) = split(/\./,$env{$key});
 7775:             if (($end!=0) && ($end<$now)) { next; }
 7776:             if (($start!=0) && ($start>$now)) { next; }
 7777:             if ($1 eq $cdom && $2 eq $cnum) {
 7778:                 $groups{$3} = $env{$key} ;
 7779:             }
 7780:         }
 7781:     }
 7782:     return %groups;
 7783: }
 7784: 
 7785: sub get_group_membership {
 7786:     my ($cdom,$cnum,$group) = @_;
 7787:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7788: }
 7789: 
 7790: sub get_users_groups {
 7791:     my ($udom,$uname,$courseid) = @_;
 7792:     my @usersgroups;
 7793:     my $cachetime=1800;
 7794: 
 7795:     my $hashid="$udom:$uname:$courseid";
 7796:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7797:     if (defined($cached)) {
 7798:         @usersgroups = split(/:/,$grouplist);
 7799:     } else {  
 7800:         $grouplist = '';
 7801:         my $courseurl = &courseid_to_courseurl($courseid);
 7802:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7803:         my $access_end = $env{'course.'.$courseid.
 7804:                               '.default_enrollment_end_date'};
 7805:         my $now = time;
 7806:         foreach my $key (keys(%roleshash)) {
 7807:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7808:                 my $group = $1;
 7809:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7810:                     my $start = $2;
 7811:                     my $end = $1;
 7812:                     if ($start == -1) { next; } # deleted from group
 7813:                     if (($start!=0) && ($start>$now)) { next; }
 7814:                     if (($end!=0) && ($end<$now)) {
 7815:                         if ($access_end && $access_end < $now) {
 7816:                             if ($access_end - $end < 86400) {
 7817:                                 push(@usersgroups,$group);
 7818:                             }
 7819:                         }
 7820:                         next;
 7821:                     }
 7822:                     push(@usersgroups,$group);
 7823:                 }
 7824:             }
 7825:         }
 7826:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7827:         $grouplist = join(':',@usersgroups);
 7828:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7829:     }
 7830:     return @usersgroups;
 7831: }
 7832: 
 7833: sub devalidate_getgroups_cache {
 7834:     my ($udom,$uname,$cdom,$cnum)=@_;
 7835:     my $courseid = $cdom.'_'.$cnum;
 7836: 
 7837:     my $hashid="$udom:$uname:$courseid";
 7838:     &devalidate_cache_new('getgroups',$hashid);
 7839: }
 7840: 
 7841: # ------------------------------------------------------------------ Plain Text
 7842: 
 7843: sub plaintext {
 7844:     my ($short,$type,$cid,$forcedefault) = @_;
 7845:     if ($short =~ m{^cr/}) {
 7846: 	return (split('/',$short))[-1];
 7847:     }
 7848:     if (!defined($cid)) {
 7849:         $cid = $env{'request.course.id'};
 7850:     }
 7851:     my %rolenames = (
 7852:                       Course    => 'std',
 7853:                       Community => 'alt1',
 7854:                     );
 7855:     if ($cid ne '') {
 7856:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7857:             unless ($forcedefault) {
 7858:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7859:                 &Apache::lonlocal::mt_escape(\$roletext);
 7860:                 return &Apache::lonlocal::mt($roletext);
 7861:             }
 7862:         }
 7863:     }
 7864:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7865:         (defined($rolenames{$type})) && 
 7866:         (defined($prp{$short}{$rolenames{$type}}))) {
 7867:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7868:     } elsif ($cid ne '') {
 7869:         my $crstype = $env{'course.'.$cid.'.type'};
 7870:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7871:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7872:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7873:         }
 7874:     }
 7875:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7876: }
 7877: 
 7878: # ----------------------------------------------------------------- Assign Role
 7879: 
 7880: sub assignrole {
 7881:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7882:         $context)=@_;
 7883:     my $mrole;
 7884:     if ($role =~ /^cr\//) {
 7885:         my $cwosec=$url;
 7886:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7887: 	unless (&allowed('ccr',$cwosec)) {
 7888:            my $refused = 1;
 7889:            if ($context eq 'requestcourses') {
 7890:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7891:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7892:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7893:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7894:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7895:                            if ($crsenv{'internal.courseowner'} eq
 7896:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7897:                                $refused = '';
 7898:                            }
 7899:                        }
 7900:                    }
 7901:                }
 7902:            }
 7903:            if ($refused) {
 7904:                &logthis('Refused custom assignrole: '.
 7905:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7906:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7907:                return 'refused';
 7908:            }
 7909:         }
 7910:         $mrole='cr';
 7911:     } elsif ($role =~ /^gr\//) {
 7912:         my $cwogrp=$url;
 7913:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7914:         unless (&allowed('mdg',$cwogrp)) {
 7915:             &logthis('Refused group assignrole: '.
 7916:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7917:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7918:             return 'refused';
 7919:         }
 7920:         $mrole='gr';
 7921:     } else {
 7922:         my $cwosec=$url;
 7923:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7924:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7925:             my $refused;
 7926:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7927:                 if (!(&allowed('c'.$role,$url))) {
 7928:                     $refused = 1;
 7929:                 }
 7930:             } else {
 7931:                 $refused = 1;
 7932:             }
 7933:             if ($refused) {
 7934:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7935:                 if (!$selfenroll && $context eq 'course') {
 7936:                     my %crsenv;
 7937:                     if ($role eq 'cc' || $role eq 'co') {
 7938:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7939:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7940:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7941:                                 if ($crsenv{'internal.courseowner'} eq 
 7942:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7943:                                     $refused = '';
 7944:                                 }
 7945:                             }
 7946:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7947:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7948:                                 if ($crsenv{'internal.courseowner'} eq 
 7949:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7950:                                     $refused = '';
 7951:                                 }
 7952:                             }
 7953:                         }
 7954:                     }
 7955:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7956:                     $refused = '';
 7957:                 } elsif ($context eq 'requestcourses') {
 7958:                     my @possroles = ('st','ta','ep','in','cc','co');
 7959:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7960:                         my $wrongcc;
 7961:                         if ($cnum =~ /^$match_community$/) {
 7962:                             $wrongcc = 1 if ($role eq 'cc');
 7963:                         } else {
 7964:                             $wrongcc = 1 if ($role eq 'co');
 7965:                         }
 7966:                         unless ($wrongcc) {
 7967:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7968:                             if ($crsenv{'internal.courseowner'} eq 
 7969:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7970:                                 $refused = '';
 7971:                             }
 7972:                         }
 7973:                     }
 7974:                 } elsif ($context eq 'requestauthor') {
 7975:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 7976:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 7977:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 7978:                             $refused = '';
 7979:                         } else {
 7980:                             my %domdefaults = &get_domain_defaults($udom);
 7981:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 7982:                                 my $checkbystatus;
 7983:                                 if ($env{'user.adv'}) { 
 7984:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 7985:                                     if ($disposition eq 'automatic') {
 7986:                                         $refused = '';
 7987:                                     } elsif ($disposition eq '') {
 7988:                                         $checkbystatus = 1;
 7989:                                     } 
 7990:                                 } else {
 7991:                                     $checkbystatus = 1;
 7992:                                 }
 7993:                                 if ($checkbystatus) {
 7994:                                     if ($env{'environment.inststatus'}) {
 7995:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 7996:                                         foreach my $type (@inststatuses) {
 7997:                                             if (($type ne '') &&
 7998:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 7999:                                                 $refused = '';
 8000:                                             }
 8001:                                         }
 8002:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8003:                                         $refused = '';
 8004:                                     }
 8005:                                 }
 8006:                             }
 8007:                         }
 8008:                     }
 8009:                 }
 8010:                 if ($refused) {
 8011:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8012:                              ' '.$role.' '.$end.' '.$start.' by '.
 8013: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8014:                     return 'refused';
 8015:                 }
 8016:             }
 8017:         } elsif ($role eq 'au') {
 8018:             if ($url ne '/'.$udom.'/') {
 8019:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8020:                          ' to assign author role for '.$uname.':'.$udom.
 8021:                          ' in domain: '.$url.' refused (wrong domain).');
 8022:                 return 'refused';
 8023:             }
 8024:         }
 8025:         $mrole=$role;
 8026:     }
 8027:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8028:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8029:     if ($end) { $command.='_'.$end; }
 8030:     if ($start) {
 8031: 	if ($end) { 
 8032:            $command.='_'.$start; 
 8033:         } else {
 8034:            $command.='_0_'.$start;
 8035:         }
 8036:     }
 8037:     my $origstart = $start;
 8038:     my $origend = $end;
 8039:     my $delflag;
 8040: # actually delete
 8041:     if ($deleteflag) {
 8042: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8043: # modify command to delete the role
 8044:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8045:                 "$udom:$uname:$url".'_'."$mrole";
 8046: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8047: # set start and finish to negative values for userrolelog
 8048:            $start=-1;
 8049:            $end=-1;
 8050:            $delflag = 1;
 8051:         }
 8052:     }
 8053: # send command
 8054:     my $answer=&reply($command,&homeserver($uname,$udom));
 8055: # log new user role if status is ok
 8056:     if ($answer eq 'ok') {
 8057: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8058:         if (($role eq 'cc') || ($role eq 'in') ||
 8059:             ($role eq 'ep') || ($role eq 'ad') ||
 8060:             ($role eq 'ta') || ($role eq 'st') ||
 8061:             ($role=~/^cr/) || ($role eq 'gr') ||
 8062:             ($role eq 'co')) {
 8063: # for course roles, perform group memberships changes triggered by role change.
 8064:             unless ($role =~ /^gr/) {
 8065:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8066:                                                  $origstart,$selfenroll,$context);
 8067:             }
 8068:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8069:                            $selfenroll,$context);
 8070:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8071:                  ($role eq 'au') || ($role eq 'dc')) {
 8072:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8073:                            $context);
 8074:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8075:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8076:                              $context); 
 8077:         }
 8078:         if ($role eq 'cc') {
 8079:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8080:         }
 8081:     }
 8082:     return $answer;
 8083: }
 8084: 
 8085: sub autoupdate_coowners {
 8086:     my ($url,$end,$start,$uname,$udom) = @_;
 8087:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8088:     if (($cdom ne '') && ($cnum ne '')) {
 8089:         my $now = time;
 8090:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8091:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8092:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8093:             my $instcode = $coursehash{'internal.coursecode'};
 8094:             if ($instcode ne '') {
 8095:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8096:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8097:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8098:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8099:                         if ($result eq 'valid') {
 8100:                             if ($coursehash{'internal.co-owners'}) {
 8101:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8102:                                     push(@newcoowners,$coowner);
 8103:                                 }
 8104:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8105:                                     push(@newcoowners,$uname.':'.$udom);
 8106:                                 }
 8107:                                 @newcoowners = sort(@newcoowners);
 8108:                             } else {
 8109:                                 push(@newcoowners,$uname.':'.$udom);
 8110:                             }
 8111:                         } else {
 8112:                             if ($coursehash{'internal.co-owners'}) {
 8113:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8114:                                     unless ($coowner eq $uname.':'.$udom) {
 8115:                                         push(@newcoowners,$coowner);
 8116:                                     }
 8117:                                 }
 8118:                                 unless (@newcoowners > 0) {
 8119:                                     $delcoowners = 1;
 8120:                                     $coowners = '';
 8121:                                 }
 8122:                             }
 8123:                         }
 8124:                         if (@newcoowners || $delcoowners) {
 8125:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8126:                                             $delcoowners,@newcoowners);
 8127:                         }
 8128:                     }
 8129:                 }
 8130:             }
 8131:         }
 8132:     }
 8133: }
 8134: 
 8135: sub store_coowners {
 8136:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8137:     my $cid = $cdom.'_'.$cnum;
 8138:     my ($coowners,$delresult,$putresult);
 8139:     if (@newcoowners) {
 8140:         $coowners = join(',',@newcoowners);
 8141:         my %coownershash = (
 8142:                             'internal.co-owners' => $coowners,
 8143:                            );
 8144:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8145:         if ($putresult eq 'ok') {
 8146:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8147:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8148:             }
 8149:         }
 8150:     }
 8151:     if ($delcoowners) {
 8152:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8153:         if ($delresult eq 'ok') {
 8154:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8155:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8156:             }
 8157:         }
 8158:     }
 8159:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8160:         my %crsinfo =
 8161:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8162:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8163:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8164:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8165:         }
 8166:     }
 8167: }
 8168: 
 8169: # -------------------------------------------------- Modify user authentication
 8170: # Overrides without validation
 8171: 
 8172: sub modifyuserauth {
 8173:     my ($udom,$uname,$umode,$upass)=@_;
 8174:     my $uhome=&homeserver($uname,$udom);
 8175:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8176:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8177:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8178:              ' in domain '.$env{'request.role.domain'});  
 8179:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8180: 		     &escape($upass),$uhome);
 8181:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8182:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8183:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8184:     &log($udom,,$uname,$uhome,
 8185:         'Authentication changed by '.$env{'user.domain'}.', '.
 8186:                                      $env{'user.name'}.', '.$umode.
 8187:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8188:     unless ($reply eq 'ok') {
 8189:         &logthis('Authentication mode error: '.$reply);
 8190: 	return 'error: '.$reply;
 8191:     }   
 8192:     return 'ok';
 8193: }
 8194: 
 8195: # --------------------------------------------------------------- Modify a user
 8196: 
 8197: sub modifyuser {
 8198:     my ($udom,    $uname, $uid,
 8199:         $umode,   $upass, $first,
 8200:         $middle,  $last,  $gene,
 8201:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8202:     $udom= &LONCAPA::clean_domain($udom);
 8203:     $uname=&LONCAPA::clean_username($uname);
 8204:     my $showcandelete = 'none';
 8205:     if (ref($candelete) eq 'ARRAY') {
 8206:         if (@{$candelete} > 0) {
 8207:             $showcandelete = join(', ',@{$candelete});
 8208:         }
 8209:     }
 8210:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8211:              $umode.', '.$first.', '.$middle.', '.
 8212: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8213:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8214:                                      ' desiredhome not specified'). 
 8215:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8216:              ' in domain '.$env{'request.role.domain'});
 8217:     my $uhome=&homeserver($uname,$udom,'true');
 8218:     my $newuser;
 8219:     if ($uhome eq 'no_host') {
 8220:         $newuser = 1;
 8221:     }
 8222: # ----------------------------------------------------------------- Create User
 8223:     if (($uhome eq 'no_host') && 
 8224: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8225:         my $unhome='';
 8226:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8227:             $unhome = $desiredhome;
 8228: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8229: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8230:         } else { # load balancing routine for determining $unhome
 8231:             my $loadm=10000000;
 8232: 	    my %servers = &get_servers($udom,'library');
 8233: 	    foreach my $tryserver (keys(%servers)) {
 8234: 		my $answer=reply('load',$tryserver);
 8235: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8236: 		    $loadm=$answer;
 8237: 		    $unhome=$tryserver;
 8238: 		}
 8239: 	    }
 8240:         }
 8241:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8242: 	    return 'error: unable to find a home server for '.$uname.
 8243:                    ' in domain '.$udom;
 8244:         }
 8245:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8246:                          &escape($upass),$unhome);
 8247: 	unless ($reply eq 'ok') {
 8248:             return 'error: '.$reply;
 8249:         }   
 8250:         $uhome=&homeserver($uname,$udom,'true');
 8251:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8252: 	    return 'error: unable verify users home machine.';
 8253:         }
 8254:     }   # End of creation of new user
 8255: # ---------------------------------------------------------------------- Add ID
 8256:     if ($uid) {
 8257:        $uid=~tr/A-Z/a-z/;
 8258:        my %uidhash=&idrget($udom,$uname);
 8259:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8260:          && (!$forceid)) {
 8261: 	  unless ($uid eq $uidhash{$uname}) {
 8262: 	      return 'error: user id "'.$uid.'" does not match '.
 8263:                   'current user id "'.$uidhash{$uname}.'".';
 8264:           }
 8265:        } else {
 8266: 	  &idput($udom,($uname => $uid));
 8267:        }
 8268:     }
 8269: # -------------------------------------------------------------- Add names, etc
 8270:     my @tmp=&get('environment',
 8271: 		   ['firstname','middlename','lastname','generation','id',
 8272:                     'permanentemail','inststatus'],
 8273: 		   $udom,$uname);
 8274:     my (%names,%oldnames);
 8275:     if ($tmp[0] =~ m/^error:.*/) { 
 8276:         %names=(); 
 8277:     } else {
 8278:         %names = @tmp;
 8279:         %oldnames = %names;
 8280:     }
 8281: #
 8282: # If name, email and/or uid are blank (e.g., because an uploaded file
 8283: # of users did not contain them), do not overwrite existing values
 8284: # unless field is in $candelete array ref.  
 8285: #
 8286: 
 8287:     my @fields = ('firstname','middlename','lastname','generation',
 8288:                   'permanentemail','id');
 8289:     my %newvalues;
 8290:     if (ref($candelete) eq 'ARRAY') {
 8291:         foreach my $field (@fields) {
 8292:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8293:                 if ($field eq 'firstname') {
 8294:                     $names{$field} = $first;
 8295:                 } elsif ($field eq 'middlename') {
 8296:                     $names{$field} = $middle;
 8297:                 } elsif ($field eq 'lastname') {
 8298:                     $names{$field} = $last;
 8299:                 } elsif ($field eq 'generation') { 
 8300:                     $names{$field} = $gene;
 8301:                 } elsif ($field eq 'permanentemail') {
 8302:                     $names{$field} = $email;
 8303:                 } elsif ($field eq 'id') {
 8304:                     $names{$field}  = $uid;
 8305:                 }
 8306:             }
 8307:         }
 8308:     }
 8309:     if ($first)  { $names{'firstname'}  = $first; }
 8310:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8311:     if ($last)   { $names{'lastname'}   = $last; }
 8312:     if (defined($gene))   { $names{'generation'} = $gene; }
 8313:     if ($email) {
 8314:        $email=~s/[^\w\@\.\-\,]//gs;
 8315:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8316:     }
 8317:     if ($uid) { $names{'id'}  = $uid; }
 8318:     if (defined($inststatus)) {
 8319:         $names{'inststatus'} = '';
 8320:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8321:         if (ref($usertypes) eq 'HASH') {
 8322:             my @okstatuses; 
 8323:             foreach my $item (split(/:/,$inststatus)) {
 8324:                 if (defined($usertypes->{$item})) {
 8325:                     push(@okstatuses,$item);  
 8326:                 }
 8327:             }
 8328:             if (@okstatuses) {
 8329:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8330:             }
 8331:         }
 8332:     }
 8333:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8334:                  $umode.', '.$first.', '.$middle.', '.
 8335:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8336:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8337:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8338:     } else {
 8339:         $logmsg .= ' during self creation';
 8340:     }
 8341:     my $changed;
 8342:     if ($newuser) {
 8343:         $changed = 1;
 8344:     } else {
 8345:         foreach my $field (@fields) {
 8346:             if ($names{$field} ne $oldnames{$field}) {
 8347:                 $changed = 1;
 8348:                 last;
 8349:             }
 8350:         }
 8351:     }
 8352:     unless ($changed) {
 8353:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8354:         &logthis($logmsg);
 8355:         return 'ok';
 8356:     }
 8357:     my $reply = &put('environment', \%names, $udom,$uname);
 8358:     if ($reply ne 'ok') { 
 8359:         return 'error: '.$reply;
 8360:     }
 8361:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8362:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8363:     }
 8364:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8365:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8366:     $logmsg = 'Success modifying user '.$logmsg;
 8367:     &logthis($logmsg);
 8368:     return 'ok';
 8369: }
 8370: 
 8371: # -------------------------------------------------------------- Modify student
 8372: 
 8373: sub modifystudent {
 8374:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8375:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8376:         $selfenroll,$context,$inststatus)=@_;
 8377:     if (!$cid) {
 8378: 	unless ($cid=$env{'request.course.id'}) {
 8379: 	    return 'not_in_class';
 8380: 	}
 8381:     }
 8382: # --------------------------------------------------------------- Make the user
 8383:     my $reply=&modifyuser
 8384: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8385:          $desiredhome,$email,$inststatus);
 8386:     unless ($reply eq 'ok') { return $reply; }
 8387:     # This will cause &modify_student_enrollment to get the uid from the
 8388:     # students environment
 8389:     $uid = undef if (!$forceid);
 8390:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8391: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 8392:     return $reply;
 8393: }
 8394: 
 8395: sub modify_student_enrollment {
 8396:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 8397:     my ($cdom,$cnum,$chome);
 8398:     if (!$cid) {
 8399: 	unless ($cid=$env{'request.course.id'}) {
 8400: 	    return 'not_in_class';
 8401: 	}
 8402: 	$cdom=$env{'course.'.$cid.'.domain'};
 8403: 	$cnum=$env{'course.'.$cid.'.num'};
 8404:     } else {
 8405: 	($cdom,$cnum)=split(/_/,$cid);
 8406:     }
 8407:     $chome=$env{'course.'.$cid.'.home'};
 8408:     if (!$chome) {
 8409: 	$chome=&homeserver($cnum,$cdom);
 8410:     }
 8411:     if (!$chome) { return 'unknown_course'; }
 8412:     # Make sure the user exists
 8413:     my $uhome=&homeserver($uname,$udom);
 8414:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8415: 	return 'error: no such user';
 8416:     }
 8417:     # Get student data if we were not given enough information
 8418:     if (!defined($first)  || $first  eq '' || 
 8419:         !defined($last)   || $last   eq '' || 
 8420:         !defined($uid)    || $uid    eq '' || 
 8421:         !defined($middle) || $middle eq '' || 
 8422:         !defined($gene)   || $gene   eq '') {
 8423:         # They did not supply us with enough data to enroll the student, so
 8424:         # we need to pick up more information.
 8425:         my %tmp = &get('environment',
 8426:                        ['firstname','middlename','lastname', 'generation','id']
 8427:                        ,$udom,$uname);
 8428: 
 8429:         #foreach my $key (keys(%tmp)) {
 8430:         #    &logthis("key $key = ".$tmp{$key});
 8431:         #}
 8432:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8433:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8434:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8435:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8436:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8437:     }
 8438:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8439:     my $user = "$uname:$udom";
 8440:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8441:     my $reply=cput('classlist',
 8442: 		   {$user => 
 8443: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 8444: 		   $cdom,$cnum);
 8445:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8446:         &devalidate_getsection_cache($udom,$uname,$cid);
 8447:     } else { 
 8448: 	return 'error: '.$reply;
 8449:     }
 8450:     # Add student role to user
 8451:     my $uurl='/'.$cid;
 8452:     $uurl=~s/\_/\//g;
 8453:     if ($usec) {
 8454: 	$uurl.='/'.$usec;
 8455:     }
 8456:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8457:                              $selfenroll,$context);
 8458:     if ($result ne 'ok') {
 8459:         if ($old_entry{$user} ne '') {
 8460:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8461:         } else {
 8462:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8463:         }
 8464:     }
 8465:     return $result; 
 8466: }
 8467: 
 8468: sub format_name {
 8469:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8470:     my $name;
 8471:     if ($first ne 'lastname') {
 8472: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8473:     } else {
 8474: 	if ($lastname=~/\S/) {
 8475: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8476: 	    $name=~s/\s+,/,/;
 8477: 	} else {
 8478: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8479: 	}
 8480:     }
 8481:     $name=~s/^\s+//;
 8482:     $name=~s/\s+$//;
 8483:     $name=~s/\s+/ /g;
 8484:     return $name;
 8485: }
 8486: 
 8487: # ------------------------------------------------- Write to course preferences
 8488: 
 8489: sub writecoursepref {
 8490:     my ($courseid,%prefs)=@_;
 8491:     $courseid=~s/^\///;
 8492:     $courseid=~s/\_/\//g;
 8493:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8494:     my $chome=homeserver($cnum,$cdomain);
 8495:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8496: 	return 'error: no such course';
 8497:     }
 8498:     my $cstring='';
 8499:     foreach my $pref (keys(%prefs)) {
 8500: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8501:     }
 8502:     $cstring=~s/\&$//;
 8503:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8504: }
 8505: 
 8506: # ---------------------------------------------------------- Make/modify course
 8507: 
 8508: sub createcourse {
 8509:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8510:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8511:     $url=&declutter($url);
 8512:     my $cid='';
 8513:     if ($context eq 'requestcourses') {
 8514:         my $can_create = 0;
 8515:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8516:         if ($udom eq $ownerdom) {
 8517:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8518:                                   $context)) {
 8519:                 $can_create = 1;
 8520:             }
 8521:         } else {
 8522:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8523:                                            $category);
 8524:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8525:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8526:                 if (@curr > 0) {
 8527:                     my @options = qw(approval validate autolimit);
 8528:                     my $optregex = join('|',@options);
 8529:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8530:                         $can_create = 1;
 8531:                     }
 8532:                 }
 8533:             }
 8534:         }
 8535:         if ($can_create) {
 8536:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8537:                 unless (&allowed('ccc',$udom)) {
 8538:                     return 'refused'; 
 8539:                 }
 8540:             }
 8541:         } else {
 8542:             return 'refused';
 8543:         }
 8544:     } elsif (!&allowed('ccc',$udom)) {
 8545:         return 'refused';
 8546:     }
 8547: # --------------------------------------------------------------- Get Unique ID
 8548:     my $uname;
 8549:     if ($cnum =~ /^$match_courseid$/) {
 8550:         my $chome=&homeserver($cnum,$udom,'true');
 8551:         if (($chome eq '') || ($chome eq 'no_host')) {
 8552:             $uname = $cnum;
 8553:         } else {
 8554:             $uname = &generate_coursenum($udom,$crstype);
 8555:         }
 8556:     } else {
 8557:         $uname = &generate_coursenum($udom,$crstype);
 8558:     }
 8559:     return $uname if ($uname =~ /^error/);
 8560: # -------------------------------------------------- Check supplied server name
 8561:     if (!defined($course_server)) {
 8562:         if (defined(&domain($udom,'primary'))) {
 8563:             $course_server = &domain($udom,'primary');
 8564:         } else {
 8565:             $course_server = $env{'user.home'}; 
 8566:         }
 8567:     }
 8568:     my %host_servers =
 8569:         &Apache::lonnet::get_servers($udom,'library');
 8570:     unless ($host_servers{$course_server}) {
 8571:         return 'error: invalid home server for course: '.$course_server;
 8572:     }
 8573: # ------------------------------------------------------------- Make the course
 8574:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8575:                       $course_server);
 8576:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8577:     my $uhome=&homeserver($uname,$udom,'true');
 8578:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8579: 	return 'error: no such course';
 8580:     }
 8581: # ----------------------------------------------------------------- Course made
 8582: # log existence
 8583:     my $now = time;
 8584:     my $newcourse = {
 8585:                     $udom.'_'.$uname => {
 8586:                                      description => $description,
 8587:                                      inst_code   => $inst_code,
 8588:                                      owner       => $course_owner,
 8589:                                      type        => $crstype,
 8590:                                      creator     => $env{'user.name'}.':'.
 8591:                                                     $env{'user.domain'},
 8592:                                      created     => $now,
 8593:                                      context     => $context,
 8594:                                                 },
 8595:                     };
 8596:     &courseidput($udom,$newcourse,$uhome,'notime');
 8597: # set toplevel url
 8598:     my $topurl=$url;
 8599:     unless ($nonstandard) {
 8600: # ------------------------------------------ For standard courses, make top url
 8601:         my $mapurl=&clutter($url);
 8602:         if ($mapurl eq '/res/') { $mapurl=''; }
 8603:         $env{'form.initmap'}=(<<ENDINITMAP);
 8604: <map>
 8605: <resource id="1" type="start"></resource>
 8606: <resource id="2" src="$mapurl"></resource>
 8607: <resource id="3" type="finish"></resource>
 8608: <link index="1" from="1" to="2"></link>
 8609: <link index="2" from="2" to="3"></link>
 8610: </map>
 8611: ENDINITMAP
 8612:         $topurl=&declutter(
 8613:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8614:                           );
 8615:     }
 8616: # ----------------------------------------------------------- Write preferences
 8617:     &writecoursepref($udom.'_'.$uname,
 8618:                      ('description'              => $description,
 8619:                       'url'                      => $topurl,
 8620:                       'internal.creator'         => $env{'user.name'}.':'.
 8621:                                                     $env{'user.domain'},
 8622:                       'internal.created'         => $now,
 8623:                       'internal.creationcontext' => $context)
 8624:                     );
 8625:     return '/'.$udom.'/'.$uname;
 8626: }
 8627: 
 8628: # ------------------------------------------------------------------- Create ID
 8629: sub generate_coursenum {
 8630:     my ($udom,$crstype) = @_;
 8631:     my $domdesc = &domain($udom);
 8632:     return 'error: invalid domain' if ($domdesc eq '');
 8633:     my $first;
 8634:     if ($crstype eq 'Community') {
 8635:         $first = '0';
 8636:     } else {
 8637:         $first = int(1+rand(9)); 
 8638:     } 
 8639:     my $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: # ----------------------------------------------- Make sure that does not exist
 8644:     my $uhome=&homeserver($uname,$udom,'true');
 8645:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8646:         if ($crstype eq 'Community') {
 8647:             $first = '0';
 8648:         } else {
 8649:             $first = int(1+rand(9));
 8650:         }
 8651:         $uname=$first.
 8652:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8653:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8654:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8655:         $uhome=&homeserver($uname,$udom,'true');
 8656:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8657:             return 'error: unable to generate unique course-ID';
 8658:         }
 8659:     }
 8660:     return $uname;
 8661: }
 8662: 
 8663: sub is_course {
 8664:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8665:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8666: 
 8667:     return unless $cdom and $cnum;
 8668: 
 8669:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8670:         '.');
 8671: 
 8672:     return unless exists($courses{$cdom.'_'.$cnum});
 8673:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8674: }
 8675: 
 8676: sub store_userdata {
 8677:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8678:     my $result;
 8679:     if ($datakey ne '') {
 8680:         if (ref($storehash) eq 'HASH') {
 8681:             if ($udom eq '' || $uname eq '') {
 8682:                 $udom = $env{'user.domain'};
 8683:                 $uname = $env{'user.name'};
 8684:             }
 8685:             my $uhome=&homeserver($uname,$udom);
 8686:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8687:                 $result = 'error: no_host';
 8688:             } else {
 8689:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8690:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8691: 
 8692:                 my $namevalue='';
 8693:                 foreach my $key (keys(%{$storehash})) {
 8694:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8695:                 }
 8696:                 $namevalue=~s/\&$//;
 8697:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8698:                                   $namevalue,$uhome);
 8699:             }
 8700:         } else {
 8701:             $result = 'error: data to store was not a hash reference'; 
 8702:         }
 8703:     } else {
 8704:         $result= 'error: invalid requestkey'; 
 8705:     }
 8706:     return $result;
 8707: }
 8708: 
 8709: # ---------------------------------------------------------- Assign Custom Role
 8710: 
 8711: sub assigncustomrole {
 8712:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8713:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8714:                        $end,$start,$deleteflag,$selfenroll,$context);
 8715: }
 8716: 
 8717: # ----------------------------------------------------------------- Revoke Role
 8718: 
 8719: sub revokerole {
 8720:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8721:     my $now=time;
 8722:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8723: }
 8724: 
 8725: # ---------------------------------------------------------- Revoke Custom Role
 8726: 
 8727: sub revokecustomrole {
 8728:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8729:     my $now=time;
 8730:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8731:            $deleteflag,$selfenroll,$context);
 8732: }
 8733: 
 8734: # ------------------------------------------------------------ Disk usage
 8735: sub diskusage {
 8736:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8737:     $directorypath =~ s/\/$//;
 8738:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8739:                        .&escape($getpropath).':'.&escape($uname).':'
 8740:                        .&escape($udom),homeserver($uname,$udom));
 8741:     if ($listing eq 'unknown_cmd') {
 8742:         if ($getpropath) {
 8743:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8744:         }
 8745:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8746:     }
 8747:     return $listing;
 8748: }
 8749: 
 8750: sub is_locked {
 8751:     my ($file_name, $domain, $user, $which) = @_;
 8752:     my @check;
 8753:     my $is_locked;
 8754:     push (@check,$file_name);
 8755:     my %locked = &get('file_permissions',\@check,
 8756: 		      $env{'user.domain'},$env{'user.name'});
 8757:     my ($tmp)=keys(%locked);
 8758:     if ($tmp=~/^error:/) { undef(%locked); }
 8759:     
 8760:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8761:         $is_locked = 'false';
 8762:         foreach my $entry (@{$locked{$file_name}}) {
 8763:            if (ref($entry) eq 'ARRAY') {
 8764:                $is_locked = 'true';
 8765:                if (ref($which) eq 'ARRAY') {
 8766:                    push(@{$which},$entry);
 8767:                } else {
 8768:                    last;
 8769:                }
 8770:            }
 8771:        }
 8772:     } else {
 8773:         $is_locked = 'false';
 8774:     }
 8775:     return $is_locked;
 8776: }
 8777: 
 8778: sub declutter_portfile {
 8779:     my ($file) = @_;
 8780:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8781:     return $file;
 8782: }
 8783: 
 8784: # ------------------------------------------------------------- Mark as Read Only
 8785: 
 8786: sub mark_as_readonly {
 8787:     my ($domain,$user,$files,$what) = @_;
 8788:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8789:     my ($tmp)=keys(%current_permissions);
 8790:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8791:     foreach my $file (@{$files}) {
 8792: 	$file = &declutter_portfile($file);
 8793:         push(@{$current_permissions{$file}},$what);
 8794:     }
 8795:     &put('file_permissions',\%current_permissions,$domain,$user);
 8796:     return;
 8797: }
 8798: 
 8799: # ------------------------------------------------------------Save Selected Files
 8800: 
 8801: sub save_selected_files {
 8802:     my ($user, $path, @files) = @_;
 8803:     my $filename = $user."savedfiles";
 8804:     my @other_files = &files_not_in_path($user, $path);
 8805:     open (OUT, '>'.$tmpdir.$filename);
 8806:     foreach my $file (@files) {
 8807:         print (OUT $env{'form.currentpath'}.$file."\n");
 8808:     }
 8809:     foreach my $file (@other_files) {
 8810:         print (OUT $file."\n");
 8811:     }
 8812:     close (OUT);
 8813:     return 'ok';
 8814: }
 8815: 
 8816: sub clear_selected_files {
 8817:     my ($user) = @_;
 8818:     my $filename = $user."savedfiles";
 8819:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8820:     print (OUT undef);
 8821:     close (OUT);
 8822:     return ("ok");    
 8823: }
 8824: 
 8825: sub files_in_path {
 8826:     my ($user, $path) = @_;
 8827:     my $filename = $user."savedfiles";
 8828:     my %return_files;
 8829:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8830:     while (my $line_in = <IN>) {
 8831:         chomp ($line_in);
 8832:         my @paths_and_file = split (m!/!, $line_in);
 8833:         my $file_part = pop (@paths_and_file);
 8834:         my $path_part = join ('/', @paths_and_file);
 8835:         $path_part.='/';
 8836:         my $path_and_file = $path_part.$file_part;
 8837:         if ($path_part eq $path) {
 8838:             $return_files{$file_part}= 'selected';
 8839:         }
 8840:     }
 8841:     close (IN);
 8842:     return (\%return_files);
 8843: }
 8844: 
 8845: # called in portfolio select mode, to show files selected NOT in current directory
 8846: sub files_not_in_path {
 8847:     my ($user, $path) = @_;
 8848:     my $filename = $user."savedfiles";
 8849:     my @return_files;
 8850:     my $path_part;
 8851:     open(IN, '<'.LONCAPA::.$filename);
 8852:     while (my $line = <IN>) {
 8853:         #ok, I know it's clunky, but I want it to work
 8854:         my @paths_and_file = split(m|/|, $line);
 8855:         my $file_part = pop(@paths_and_file);
 8856:         chomp($file_part);
 8857:         my $path_part = join('/', @paths_and_file);
 8858:         $path_part .= '/';
 8859:         my $path_and_file = $path_part.$file_part;
 8860:         if ($path_part ne $path) {
 8861:             push(@return_files, ($path_and_file));
 8862:         }
 8863:     }
 8864:     close(OUT);
 8865:     return (@return_files);
 8866: }
 8867: 
 8868: #----------------------------------------------Get portfolio file permissions
 8869: 
 8870: sub get_portfile_permissions {
 8871:     my ($domain,$user) = @_;
 8872:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8873:     my ($tmp)=keys(%current_permissions);
 8874:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8875:     return \%current_permissions;
 8876: }
 8877: 
 8878: #---------------------------------------------Get portfolio file access controls
 8879: 
 8880: sub get_access_controls {
 8881:     my ($current_permissions,$group,$file) = @_;
 8882:     my %access;
 8883:     my $real_file = $file;
 8884:     $file =~ s/\.meta$//;
 8885:     if (defined($file)) {
 8886:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8887:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8888:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8889:             }
 8890:         }
 8891:     } else {
 8892:         foreach my $key (keys(%{$current_permissions})) {
 8893:             if ($key =~ /\0accesscontrol$/) {
 8894:                 if (defined($group)) {
 8895:                     if ($key !~ m-^\Q$group\E/-) {
 8896:                         next;
 8897:                     }
 8898:                 }
 8899:                 my ($fullpath) = split(/\0/,$key);
 8900:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8901:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8902:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8903:                     }
 8904:                 }
 8905:             }
 8906:         }
 8907:     }
 8908:     return %access;
 8909: }
 8910: 
 8911: sub modify_access_controls {
 8912:     my ($file_name,$changes,$domain,$user)=@_;
 8913:     my ($outcome,$deloutcome);
 8914:     my %store_permissions;
 8915:     my %new_values;
 8916:     my %new_control;
 8917:     my %translation;
 8918:     my @deletions = ();
 8919:     my $now = time;
 8920:     if (exists($$changes{'activate'})) {
 8921:         if (ref($$changes{'activate'}) eq 'HASH') {
 8922:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8923:             my $numnew = scalar(@newitems);
 8924:             for (my $i=0; $i<$numnew; $i++) {
 8925:                 my $newkey = $newitems[$i];
 8926:                 my $newid = &Apache::loncommon::get_cgi_id();
 8927:                 if ($newkey =~ /^\d+:/) { 
 8928:                     $newkey =~ s/^(\d+)/$newid/;
 8929:                     $translation{$1} = $newid;
 8930:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8931:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8932:                     $translation{$1} = $newid;
 8933:                 }
 8934:                 $new_values{$file_name."\0".$newkey} = 
 8935:                                           $$changes{'activate'}{$newitems[$i]};
 8936:                 $new_control{$newkey} = $now;
 8937:             }
 8938:         }
 8939:     }
 8940:     my %todelete;
 8941:     my %changed_items;
 8942:     foreach my $action ('delete','update') {
 8943:         if (exists($$changes{$action})) {
 8944:             if (ref($$changes{$action}) eq 'HASH') {
 8945:                 foreach my $key (keys(%{$$changes{$action}})) {
 8946:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8947:                     if ($action eq 'delete') { 
 8948:                         $todelete{$itemnum} = 1;
 8949:                     } else {
 8950:                         $changed_items{$itemnum} = $key;
 8951:                     }
 8952:                 }
 8953:             }
 8954:         }
 8955:     }
 8956:     # get lock on access controls for file.
 8957:     my $lockhash = {
 8958:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8959:                                                        ':'.$env{'user.domain'},
 8960:                    }; 
 8961:     my $tries = 0;
 8962:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8963:    
 8964:     while (($gotlock ne 'ok') && $tries <3) {
 8965:         $tries ++;
 8966:         sleep 1;
 8967:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8968:     }
 8969:     if ($gotlock eq 'ok') {
 8970:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8971:         my ($tmp)=keys(%curr_permissions);
 8972:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8973:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8974:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8975:             if (ref($curr_controls) eq 'HASH') {
 8976:                 foreach my $control_item (keys(%{$curr_controls})) {
 8977:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8978:                     if (defined($todelete{$itemnum})) {
 8979:                         push(@deletions,$file_name."\0".$control_item);
 8980:                     } else {
 8981:                         if (defined($changed_items{$itemnum})) {
 8982:                             $new_control{$changed_items{$itemnum}} = $now;
 8983:                             push(@deletions,$file_name."\0".$control_item);
 8984:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8985:                         } else {
 8986:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8987:                         }
 8988:                     }
 8989:                 }
 8990:             }
 8991:         }
 8992:         my ($group);
 8993:         if (&is_course($domain,$user)) {
 8994:             ($group,my $file) = split(/\//,$file_name,2);
 8995:         }
 8996:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8997:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8998:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8999:         #  remove lock
 9000:         my @del_lock = ($file_name."\0".'locked_access_records');
 9001:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9002:         my $sqlresult =
 9003:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9004:                                     $group);
 9005:     } else {
 9006:         $outcome = "error: could not obtain lockfile\n";  
 9007:     }
 9008:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9009: }
 9010: 
 9011: sub make_public_indefinitely {
 9012:     my ($requrl) = @_;
 9013:     my $now = time;
 9014:     my $action = 'activate';
 9015:     my $aclnum = 0;
 9016:     if (&is_portfolio_url($requrl)) {
 9017:         my (undef,$udom,$unum,$file_name,$group) =
 9018:             &parse_portfolio_url($requrl);
 9019:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9020:         my %access_controls = &get_access_controls($current_perms,
 9021:                                                    $group,$file_name);
 9022:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9023:             my ($num,$scope,$end,$start) = 
 9024:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9025:             if ($scope eq 'public') {
 9026:                 if ($start <= $now && $end == 0) {
 9027:                     $action = 'none';
 9028:                 } else {
 9029:                     $action = 'update';
 9030:                     $aclnum = $num;
 9031:                 }
 9032:                 last;
 9033:             }
 9034:         }
 9035:         if ($action eq 'none') {
 9036:              return 'ok';
 9037:         } else {
 9038:             my %changes;
 9039:             my $newend = 0;
 9040:             my $newstart = $now;
 9041:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9042:             $changes{$action}{$newkey} = {
 9043:                 type => 'public',
 9044:                 time => {
 9045:                     start => $newstart,
 9046:                     end   => $newend,
 9047:                 },
 9048:             };
 9049:             my ($outcome,$deloutcome,$new_values,$translation) =
 9050:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9051:             return $outcome;
 9052:         }
 9053:     } else {
 9054:         return 'invalid';
 9055:     }
 9056: }
 9057: 
 9058: #------------------------------------------------------Get Marked as Read Only
 9059: 
 9060: sub get_marked_as_readonly {
 9061:     my ($domain,$user,$what,$group) = @_;
 9062:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9063:     my @readonly_files;
 9064:     my $cmp1=$what;
 9065:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9066:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9067:         if (defined($group)) {
 9068:             if ($file_name !~ m-^\Q$group\E/-) {
 9069:                 next;
 9070:             }
 9071:         }
 9072:         if (ref($value) eq "ARRAY"){
 9073:             foreach my $stored_what (@{$value}) {
 9074:                 my $cmp2=$stored_what;
 9075:                 if (ref($stored_what) eq 'ARRAY') {
 9076:                     $cmp2=join('',@{$stored_what});
 9077:                 }
 9078:                 if ($cmp1 eq $cmp2) {
 9079:                     push(@readonly_files, $file_name);
 9080:                     last;
 9081:                 } elsif (!defined($what)) {
 9082:                     push(@readonly_files, $file_name);
 9083:                     last;
 9084:                 }
 9085:             }
 9086:         }
 9087:     }
 9088:     return @readonly_files;
 9089: }
 9090: #-----------------------------------------------------------Get Marked as Read Only Hash
 9091: 
 9092: sub get_marked_as_readonly_hash {
 9093:     my ($current_permissions,$group,$what) = @_;
 9094:     my %readonly_files;
 9095:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9096:         if (defined($group)) {
 9097:             if ($file_name !~ m-^\Q$group\E/-) {
 9098:                 next;
 9099:             }
 9100:         }
 9101:         if (ref($value) eq "ARRAY"){
 9102:             foreach my $stored_what (@{$value}) {
 9103:                 if (ref($stored_what) eq 'ARRAY') {
 9104:                     foreach my $lock_descriptor(@{$stored_what}) {
 9105:                         if ($lock_descriptor eq 'graded') {
 9106:                             $readonly_files{$file_name} = 'graded';
 9107:                         } elsif ($lock_descriptor eq 'handback') {
 9108:                             $readonly_files{$file_name} = 'handback';
 9109:                         } else {
 9110:                             if (!exists($readonly_files{$file_name})) {
 9111:                                 $readonly_files{$file_name} = 'locked';
 9112:                             }
 9113:                         }
 9114:                     }
 9115:                 } 
 9116:             }
 9117:         } 
 9118:     }
 9119:     return %readonly_files;
 9120: }
 9121: # ------------------------------------------------------------ Unmark as Read Only
 9122: 
 9123: sub unmark_as_readonly {
 9124:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9125:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9126:     my ($domain,$user,$what,$file_name,$group) = @_;
 9127:     $file_name = &declutter_portfile($file_name);
 9128:     my $symb_crs = $what;
 9129:     if (ref($what)) { $symb_crs=join('',@$what); }
 9130:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9131:     my ($tmp)=keys(%current_permissions);
 9132:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9133:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9134:     foreach my $file (@readonly_files) {
 9135: 	my $clean_file = &declutter_portfile($file);
 9136: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9137: 	my $current_locks = $current_permissions{$file};
 9138:         my @new_locks;
 9139:         my @del_keys;
 9140:         if (ref($current_locks) eq "ARRAY"){
 9141:             foreach my $locker (@{$current_locks}) {
 9142:                 my $compare=$locker;
 9143:                 if (ref($locker) eq 'ARRAY') {
 9144:                     $compare=join('',@{$locker});
 9145:                     if ($compare ne $symb_crs) {
 9146:                         push(@new_locks, $locker);
 9147:                     }
 9148:                 }
 9149:             }
 9150:             if (scalar(@new_locks) > 0) {
 9151:                 $current_permissions{$file} = \@new_locks;
 9152:             } else {
 9153:                 push(@del_keys, $file);
 9154:                 &del('file_permissions',\@del_keys, $domain, $user);
 9155:                 delete($current_permissions{$file});
 9156:             }
 9157:         }
 9158:     }
 9159:     &put('file_permissions',\%current_permissions,$domain,$user);
 9160:     return;
 9161: }
 9162: 
 9163: # ------------------------------------------------------------ Directory lister
 9164: 
 9165: sub dirlist {
 9166:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9167:     $uri=~s/^\///;
 9168:     $uri=~s/\/$//;
 9169:     my ($udom, $uname);
 9170:     if ($getuserdir) {
 9171:         $udom = $userdomain;
 9172:         $uname = $username;
 9173:     } else {
 9174:         (undef,$udom,$uname)=split(/\//,$uri);
 9175:         if(defined($userdomain)) {
 9176:             $udom = $userdomain;
 9177:         }
 9178:         if(defined($username)) {
 9179:             $uname = $username;
 9180:         }
 9181:     }
 9182:     my ($dirRoot,$listing,@listing_results);
 9183: 
 9184:     $dirRoot = $perlvar{'lonDocRoot'};
 9185:     if (defined($getpropath)) {
 9186:         $dirRoot = &propath($udom,$uname);
 9187:         $dirRoot =~ s/\/$//;
 9188:     } elsif (defined($getuserdir)) {
 9189:         my $subdir=$uname.'__';
 9190:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9191:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9192:                    ."/$udom/$subdir/$uname";
 9193:     } elsif (defined($alternateRoot)) {
 9194:         $dirRoot = $alternateRoot;
 9195:     }
 9196: 
 9197:     if($udom) {
 9198:         if($uname) {
 9199:             my $uhome = &homeserver($uname,$udom);
 9200:             if ($uhome eq 'no_host') {
 9201:                 return ([],'no_host');
 9202:             }
 9203:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9204:                               .$getuserdir.':'.&escape($dirRoot)
 9205:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9206:             if ($listing eq 'unknown_cmd') {
 9207:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9208:             } else {
 9209:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9210:             }
 9211:             if ($listing eq 'unknown_cmd') {
 9212:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9213:                 @listing_results = split(/:/,$listing);
 9214:             } else {
 9215:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9216:             }
 9217:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9218:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9219:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9220:                 return ([],$listing);
 9221:             } else {
 9222:                 return (\@listing_results);
 9223:             }
 9224:         } elsif(!$alternateRoot) {
 9225:             my (%allusers,%listerror);
 9226: 	    my %servers = &get_servers($udom,'library');
 9227:  	    foreach my $tryserver (keys(%servers)) {
 9228:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9229:                                   &escape($udom),$tryserver);
 9230:                 if ($listing eq 'unknown_cmd') {
 9231: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9232: 				      $udom, $tryserver);
 9233:                 } else {
 9234:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9235:                 }
 9236: 		if ($listing eq 'unknown_cmd') {
 9237: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9238: 				      $udom, $tryserver);
 9239: 		    @listing_results = split(/:/,$listing);
 9240: 		} else {
 9241: 		    @listing_results =
 9242: 			map { &unescape($_); } split(/:/,$listing);
 9243: 		}
 9244:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9245:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9246:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9247:                     $listerror{$tryserver} = $listing;
 9248:                 } else {
 9249: 		    foreach my $line (@listing_results) {
 9250: 			my ($entry) = split(/&/,$line,2);
 9251: 			$allusers{$entry} = 1;
 9252: 		    }
 9253: 		}
 9254:             }
 9255:             my @alluserslist=();
 9256:             foreach my $user (sort(keys(%allusers))) {
 9257:                 push(@alluserslist,$user.'&user');
 9258:             }
 9259:             return (\@alluserslist);
 9260:         } else {
 9261:             return ([],'missing username');
 9262:         }
 9263:     } elsif(!defined($getpropath)) {
 9264:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9265:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9266:         return (\@all_domains);
 9267:     } else {
 9268:         return ([],'missing domain');
 9269:     }
 9270: }
 9271: 
 9272: # --------------------------------------------- GetFileTimestamp
 9273: # This function utilizes dirlist and returns the date stamp for
 9274: # when it was last modified.  It will also return an error of -1
 9275: # if an error occurs
 9276: 
 9277: sub GetFileTimestamp {
 9278:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9279:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9280:     $studentName   = &LONCAPA::clean_username($studentName);
 9281:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9282:                                     undef,$getuserdir);
 9283:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9284:         return -1;
 9285:     }
 9286:     if (ref($fileref) eq 'ARRAY') {
 9287:         my @stats = split('&',$fileref->[0]);
 9288:         # @stats contains first the filename, then the stat output
 9289:         return $stats[10]; # so this is 10 instead of 9.
 9290:     } else {
 9291:         return -1;
 9292:     }
 9293: }
 9294: 
 9295: sub stat_file {
 9296:     my ($uri) = @_;
 9297:     $uri = &clutter_with_no_wrapper($uri);
 9298: 
 9299:     my ($udom,$uname,$file);
 9300:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9301: 	($udom,$uname,$file) =
 9302: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9303: 	$file = 'userfiles/'.$file;
 9304:     }
 9305:     if ($uri =~ m-^/res/-) {
 9306: 	($udom,$uname) = 
 9307: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9308: 	$file = $uri;
 9309:     }
 9310: 
 9311:     if (!$udom || !$uname || !$file) {
 9312: 	# unable to handle the uri
 9313: 	return ();
 9314:     }
 9315:     my $getpropath;
 9316:     if ($file =~ /^userfiles\//) {
 9317:         $getpropath = 1;
 9318:     }
 9319:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9320:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9321:         return ();
 9322:     } else {
 9323:         if (ref($listref) eq 'ARRAY') {
 9324:             my @stats = split('&',$listref->[0]);
 9325: 	    shift(@stats); #filename is first
 9326: 	    return @stats;
 9327:         }
 9328:     }
 9329:     return ();
 9330: }
 9331: 
 9332: # -------------------------------------------------------- Value of a Condition
 9333: 
 9334: # gets the value of a specific preevaluated condition
 9335: #    stored in the string  $env{user.state.<cid>}
 9336: # or looks up a condition reference in the bighash and if if hasn't
 9337: # already been evaluated recurses into docondval to get the value of
 9338: # the condition, then memoizing it to 
 9339: #   $env{user.state.<cid>.<condition>}
 9340: sub directcondval {
 9341:     my $number=shift;
 9342:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9343: 	&Apache::lonuserstate::evalstate();
 9344:     }
 9345:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9346: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9347:     } elsif ($number =~ /^_/) {
 9348: 	my $sub_condition;
 9349: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9350: 		&GDBM_READER(),0640)) {
 9351: 	    $sub_condition=$bighash{'conditions'.$number};
 9352: 	    untie(%bighash);
 9353: 	}
 9354: 	my $value = &docondval($sub_condition);
 9355: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9356: 	return $value;
 9357:     }
 9358:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9359:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9360:     } else {
 9361:        return 2;
 9362:     }
 9363: }
 9364: 
 9365: # get the collection of conditions for this resource
 9366: sub condval {
 9367:     my $condidx=shift;
 9368:     my $allpathcond='';
 9369:     foreach my $cond (split(/\|/,$condidx)) {
 9370: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9371: 	    $allpathcond.=
 9372: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9373: 	}
 9374:     }
 9375:     $allpathcond=~s/\|$//;
 9376:     return &docondval($allpathcond);
 9377: }
 9378: 
 9379: #evaluates an expression of conditions
 9380: sub docondval {
 9381:     my ($allpathcond) = @_;
 9382:     my $result=0;
 9383:     if ($env{'request.course.id'}
 9384: 	&& defined($allpathcond)) {
 9385: 	my $operand='|';
 9386: 	my @stack;
 9387: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9388: 	    if ($chunk eq '(') {
 9389: 		push @stack,($operand,$result);
 9390: 	    } elsif ($chunk eq ')') {
 9391: 		my $before=pop @stack;
 9392: 		if (pop @stack eq '&') {
 9393: 		    $result=$result>$before?$before:$result;
 9394: 		} else {
 9395: 		    $result=$result>$before?$result:$before;
 9396: 		}
 9397: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9398: 		$operand=$chunk;
 9399: 	    } else {
 9400: 		my $new=directcondval($chunk);
 9401: 		if ($operand eq '&') {
 9402: 		    $result=$result>$new?$new:$result;
 9403: 		} else {
 9404: 		    $result=$result>$new?$result:$new;
 9405: 		}
 9406: 	    }
 9407: 	}
 9408:     }
 9409:     return $result;
 9410: }
 9411: 
 9412: # ---------------------------------------------------- Devalidate courseresdata
 9413: 
 9414: sub devalidatecourseresdata {
 9415:     my ($coursenum,$coursedomain)=@_;
 9416:     my $hashid=$coursenum.':'.$coursedomain;
 9417:     &devalidate_cache_new('courseres',$hashid);
 9418: }
 9419: 
 9420: 
 9421: # --------------------------------------------------- Course Resourcedata Query
 9422: #
 9423: #  Parameters:
 9424: #      $coursenum    - Number of the course.
 9425: #      $coursedomain - Domain at which the course was created.
 9426: #  Returns:
 9427: #     A hash of the course parameters along (I think) with timestamps
 9428: #     and version info.
 9429: 
 9430: sub get_courseresdata {
 9431:     my ($coursenum,$coursedomain)=@_;
 9432:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9433:     my $hashid=$coursenum.':'.$coursedomain;
 9434:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9435:     my %dumpreply;
 9436:     unless (defined($cached)) {
 9437: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9438: 	$result=\%dumpreply;
 9439: 	my ($tmp) = keys(%dumpreply);
 9440: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9441: 	    &do_cache_new('courseres',$hashid,$result,600);
 9442: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9443: 	    return $tmp;
 9444: 	} elsif ($tmp =~ /^(error)/) {
 9445: 	    $result=undef;
 9446: 	    &do_cache_new('courseres',$hashid,$result,600);
 9447: 	}
 9448:     }
 9449:     return $result;
 9450: }
 9451: 
 9452: sub devalidateuserresdata {
 9453:     my ($uname,$udom)=@_;
 9454:     my $hashid="$udom:$uname";
 9455:     &devalidate_cache_new('userres',$hashid);
 9456: }
 9457: 
 9458: sub get_userresdata {
 9459:     my ($uname,$udom)=@_;
 9460:     #most student don\'t have any data set, check if there is some data
 9461:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9462: 
 9463:     my $hashid="$udom:$uname";
 9464:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9465:     if (!defined($cached)) {
 9466: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9467: 	$result=\%resourcedata;
 9468: 	&do_cache_new('userres',$hashid,$result,600);
 9469:     }
 9470:     my ($tmp)=keys(%$result);
 9471:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9472: 	return $result;
 9473:     }
 9474:     #error 2 occurs when the .db doesn't exist
 9475:     if ($tmp!~/error: 2 /) {
 9476: 	&logthis("<font color=\"blue\">WARNING:".
 9477: 		 " Trying to get resource data for ".
 9478: 		 $uname." at ".$udom.": ".
 9479: 		 $tmp."</font>");
 9480:     } elsif ($tmp=~/error: 2 /) {
 9481: 	#&EXT_cache_set($udom,$uname);
 9482: 	&do_cache_new('userres',$hashid,undef,600);
 9483: 	undef($tmp); # not really an error so don't send it back
 9484:     }
 9485:     return $tmp;
 9486: }
 9487: #----------------------------------------------- resdata - return resource data
 9488: #  Purpose:
 9489: #    Return resource data for either users or for a course.
 9490: #  Parameters:
 9491: #     $name      - Course/user name.
 9492: #     $domain    - Name of the domain the user/course is registered on.
 9493: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9494: #     @which     - Array of names of resources desired.
 9495: #  Returns:
 9496: #     The value of the first reasource in @which that is found in the
 9497: #     resource hash.
 9498: #  Exceptional Conditions:
 9499: #     If the $type passed in is not valid (not the string 'course' or 
 9500: #     'user', an undefined  reference is returned.
 9501: #     If none of the resources are found, an undef is returned
 9502: sub resdata {
 9503:     my ($name,$domain,$type,@which)=@_;
 9504:     my $result;
 9505:     if ($type eq 'course') {
 9506: 	$result=&get_courseresdata($name,$domain);
 9507:     } elsif ($type eq 'user') {
 9508: 	$result=&get_userresdata($name,$domain);
 9509:     }
 9510:     if (!ref($result)) { return $result; }    
 9511:     foreach my $item (@which) {
 9512: 	if (defined($result->{$item->[0]})) {
 9513: 	    return [$result->{$item->[0]},$item->[1]];
 9514: 	}
 9515:     }
 9516:     return undef;
 9517: }
 9518: 
 9519: #
 9520: # EXT resource caching routines
 9521: #
 9522: 
 9523: sub clear_EXT_cache_status {
 9524:     &delenv('cache.EXT.');
 9525: }
 9526: 
 9527: sub EXT_cache_status {
 9528:     my ($target_domain,$target_user) = @_;
 9529:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9530:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9531:         # We know already the user has no data
 9532:         return 1;
 9533:     } else {
 9534:         return 0;
 9535:     }
 9536: }
 9537: 
 9538: sub EXT_cache_set {
 9539:     my ($target_domain,$target_user) = @_;
 9540:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9541:     #&appenv({$cachename => time});
 9542: }
 9543: 
 9544: # --------------------------------------------------------- Value of a Variable
 9545: sub EXT {
 9546: 
 9547:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 9548:     unless ($varname) { return ''; }
 9549:     #get real user name/domain, courseid and symb
 9550:     my $courseid;
 9551:     my $publicuser;
 9552:     if ($symbparm) {
 9553: 	$symbparm=&get_symb_from_alias($symbparm);
 9554:     }
 9555:     if (!($uname && $udom)) {
 9556:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9557:       if (!$symbparm) {	$symbparm=$cursymb; }
 9558:     } else {
 9559: 	$courseid=$env{'request.course.id'};
 9560:     }
 9561:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9562:     my $rest;
 9563:     if (defined($therest[0])) {
 9564:        $rest=join('.',@therest);
 9565:     } else {
 9566:        $rest='';
 9567:     }
 9568: 
 9569:     my $qualifierrest=$qualifier;
 9570:     if ($rest) { $qualifierrest.='.'.$rest; }
 9571:     my $spacequalifierrest=$space;
 9572:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9573:     if ($realm eq 'user') {
 9574: # --------------------------------------------------------------- user.resource
 9575: 	if ($space eq 'resource') {
 9576: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9577: 		  || defined($Apache::lonhomework::parsing_a_task))
 9578: 		 &&
 9579: 		 ($symbparm eq &symbread()) ) {	
 9580: 		# if we are in the middle of processing the resource the
 9581: 		# get the value we are planning on committing
 9582:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9583:                     return $Apache::lonhomework::results{$qualifierrest};
 9584:                 } else {
 9585:                     return $Apache::lonhomework::history{$qualifierrest};
 9586:                 }
 9587: 	    } else {
 9588: 		my %restored;
 9589: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9590: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9591: 		} else {
 9592: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9593: 		}
 9594: 		return $restored{$qualifierrest};
 9595: 	    }
 9596: # ----------------------------------------------------------------- user.access
 9597:         } elsif ($space eq 'access') {
 9598: 	    # FIXME - not supporting calls for a specific user
 9599:             return &allowed($qualifier,$rest);
 9600: # ------------------------------------------ user.preferences, user.environment
 9601:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9602: 	    if (($uname eq $env{'user.name'}) &&
 9603: 		($udom eq $env{'user.domain'})) {
 9604: 		return $env{join('.',('environment',$qualifierrest))};
 9605: 	    } else {
 9606: 		my %returnhash;
 9607: 		if (!$publicuser) {
 9608: 		    %returnhash=&userenvironment($udom,$uname,
 9609: 						 $qualifierrest);
 9610: 		}
 9611: 		return $returnhash{$qualifierrest};
 9612: 	    }
 9613: # ----------------------------------------------------------------- user.course
 9614:         } elsif ($space eq 'course') {
 9615: 	    # FIXME - not supporting calls for a specific user
 9616:             return $env{join('.',('request.course',$qualifier))};
 9617: # ------------------------------------------------------------------- user.role
 9618:         } elsif ($space eq 'role') {
 9619: 	    # FIXME - not supporting calls for a specific user
 9620:             my ($role,$where)=split(/\./,$env{'request.role'});
 9621:             if ($qualifier eq 'value') {
 9622: 		return $role;
 9623:             } elsif ($qualifier eq 'extent') {
 9624:                 return $where;
 9625:             }
 9626: # ----------------------------------------------------------------- user.domain
 9627:         } elsif ($space eq 'domain') {
 9628:             return $udom;
 9629: # ------------------------------------------------------------------- user.name
 9630:         } elsif ($space eq 'name') {
 9631:             return $uname;
 9632: # ---------------------------------------------------- Any other user namespace
 9633:         } else {
 9634: 	    my %reply;
 9635: 	    if (!$publicuser) {
 9636: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9637: 	    }
 9638: 	    return $reply{$qualifierrest};
 9639:         }
 9640:     } elsif ($realm eq 'query') {
 9641: # ---------------------------------------------- pull stuff out of query string
 9642:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9643: 						[$spacequalifierrest]);
 9644: 	return $env{'form.'.$spacequalifierrest}; 
 9645:    } elsif ($realm eq 'request') {
 9646: # ------------------------------------------------------------- request.browser
 9647:         if ($space eq 'browser') {
 9648:             return $env{'browser.'.$qualifier};
 9649: # ------------------------------------------------------------ request.filename
 9650:         } else {
 9651:             return $env{'request.'.$spacequalifierrest};
 9652:         }
 9653:     } elsif ($realm eq 'course') {
 9654: # ---------------------------------------------------------- course.description
 9655:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9656:     } elsif ($realm eq 'resource') {
 9657: 
 9658: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9659: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9660: 	}
 9661: 
 9662: 	if ($space eq 'title') {
 9663: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9664: 	    return &gettitle($symbparm);
 9665: 	}
 9666: 	
 9667: 	if ($space eq 'map') {
 9668: 	    my ($map) = &decode_symb($symbparm);
 9669: 	    return &symbread($map);
 9670: 	}
 9671: 	if ($space eq 'filename') {
 9672: 	    if ($symbparm) {
 9673: 		return &clutter((&decode_symb($symbparm))[2]);
 9674: 	    }
 9675: 	    return &hreflocation('',$env{'request.filename'});
 9676: 	}
 9677: 
 9678: 	my ($section, $group, @groups);
 9679: 	my ($courselevelm,$courselevel);
 9680: 	if ($symbparm && defined($courseid) && 
 9681: 	    $courseid eq $env{'request.course.id'}) {
 9682: 
 9683: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9684: 
 9685: # ----------------------------------------------------- Cascading lookup scheme
 9686: 	    my $symbp=$symbparm;
 9687: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9688: 
 9689: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9690: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9691: 
 9692: 	    if (($env{'user.name'} eq $uname) &&
 9693: 		($env{'user.domain'} eq $udom)) {
 9694: 		$section=$env{'request.course.sec'};
 9695:                 @groups = split(/:/,$env{'request.course.groups'});  
 9696:                 @groups=&sort_course_groups($courseid,@groups); 
 9697: 	    } else {
 9698: 		if (! defined($usection)) {
 9699: 		    $section=&getsection($udom,$uname,$courseid);
 9700: 		} else {
 9701: 		    $section = $usection;
 9702: 		}
 9703:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9704: 	    }
 9705: 
 9706: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9707: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9708: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9709: 
 9710: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9711: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9712: 	    $courselevelm=$courseid.'.'.$mapparm;
 9713: 
 9714: # ----------------------------------------------------------- first, check user
 9715: 
 9716: 	    my $userreply=&resdata($uname,$udom,'user',
 9717: 				       ([$courselevelr,'resource'],
 9718: 					[$courselevelm,'map'     ],
 9719: 					[$courselevel, 'course'  ]));
 9720: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9721: 
 9722: # ------------------------------------------------ second, check some of course
 9723:             my $coursereply;
 9724:             if (@groups > 0) {
 9725:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9726:                                        $mapparm,$spacequalifierrest);
 9727:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9728:             }
 9729: 
 9730: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9731: 				  $env{'course.'.$courseid.'.domain'},
 9732: 				  'course',
 9733: 				  ([$seclevelr,   'resource'],
 9734: 				   [$seclevelm,   'map'     ],
 9735: 				   [$seclevel,    'course'  ],
 9736: 				   [$courselevelr,'resource']));
 9737: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9738: 
 9739: # ------------------------------------------------------ third, check map parms
 9740: 	    my %parmhash=();
 9741: 	    my $thisparm='';
 9742: 	    if (tie(%parmhash,'GDBM_File',
 9743: 		    $env{'request.course.fn'}.'_parms.db',
 9744: 		    &GDBM_READER(),0640)) {
 9745: 		$thisparm=$parmhash{$symbparm};
 9746: 		untie(%parmhash);
 9747: 	    }
 9748: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9749: 	}
 9750: # ------------------------------------------ fourth, look in resource metadata
 9751: 
 9752: 	$spacequalifierrest=~s/\./\_/;
 9753: 	my $filename;
 9754: 	if (!$symbparm) { $symbparm=&symbread(); }
 9755: 	if ($symbparm) {
 9756: 	    $filename=(&decode_symb($symbparm))[2];
 9757: 	} else {
 9758: 	    $filename=$env{'request.filename'};
 9759: 	}
 9760: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9761: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9762: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9763: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9764: 
 9765: # ---------------------------------------------- fourth, look in rest of course
 9766: 	if ($symbparm && defined($courseid) && 
 9767: 	    $courseid eq $env{'request.course.id'}) {
 9768: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9769: 				     $env{'course.'.$courseid.'.domain'},
 9770: 				     'course',
 9771: 				     ([$courselevelm,'map'   ],
 9772: 				      [$courselevel, 'course']));
 9773: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9774: 	}
 9775: # ------------------------------------------------------------------ Cascade up
 9776: 	unless ($space eq '0') {
 9777: 	    my @parts=split(/_/,$space);
 9778: 	    my $id=pop(@parts);
 9779: 	    my $part=join('_',@parts);
 9780: 	    if ($part eq '') { $part='0'; }
 9781: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9782: 				 $symbparm,$udom,$uname,$section,1);
 9783: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9784: 	}
 9785: 	if ($recurse) { return undef; }
 9786: 	my $pack_def=&packages_tab_default($filename,$varname);
 9787: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9788: # ---------------------------------------------------- Any other user namespace
 9789:     } elsif ($realm eq 'environment') {
 9790: # ----------------------------------------------------------------- environment
 9791: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9792: 	    return $env{'environment.'.$spacequalifierrest};
 9793: 	} else {
 9794: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9795: 		return '';
 9796: 	    }
 9797: 	    my %returnhash=&userenvironment($udom,$uname,
 9798: 					    $spacequalifierrest);
 9799: 	    return $returnhash{$spacequalifierrest};
 9800: 	}
 9801:     } elsif ($realm eq 'system') {
 9802: # ----------------------------------------------------------------- system.time
 9803: 	if ($space eq 'time') {
 9804: 	    return time;
 9805:         }
 9806:     } elsif ($realm eq 'server') {
 9807: # ----------------------------------------------------------------- system.time
 9808: 	if ($space eq 'name') {
 9809: 	    return $ENV{'SERVER_NAME'};
 9810:         }
 9811:     }
 9812:     return '';
 9813: }
 9814: 
 9815: sub get_reply {
 9816:     my ($reply_value) = @_;
 9817:     if (ref($reply_value) eq 'ARRAY') {
 9818:         if (wantarray) {
 9819: 	    return @$reply_value;
 9820:         }
 9821:         return $reply_value->[0];
 9822:     } else {
 9823:         return $reply_value;
 9824:     }
 9825: }
 9826: 
 9827: sub check_group_parms {
 9828:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9829:     my @groupitems = ();
 9830:     my $resultitem;
 9831:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9832:     foreach my $group (@{$groups}) {
 9833:         foreach my $level (@levels) {
 9834:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9835:              push(@groupitems,[$item,$level->[1]]);
 9836:         }
 9837:     }
 9838:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9839:                             $env{'course.'.$courseid.'.domain'},
 9840:                                      'course',@groupitems);
 9841:     return $coursereply;
 9842: }
 9843: 
 9844: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9845:     my ($courseid,@groups) = @_;
 9846:     @groups = sort(@groups);
 9847:     return @groups;
 9848: }
 9849: 
 9850: sub packages_tab_default {
 9851:     my ($uri,$varname)=@_;
 9852:     my (undef,$part,$name)=split(/\./,$varname);
 9853: 
 9854:     my (@extension,@specifics,$do_default);
 9855:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9856: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9857: 	if ($pack_type eq 'default') {
 9858: 	    $do_default=1;
 9859: 	} elsif ($pack_type eq 'extension') {
 9860: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9861: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9862: 	    # only look at packages defaults for packages that this id is
 9863: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9864: 	}
 9865:     }
 9866:     # first look for a package that matches the requested part id
 9867:     foreach my $package (@specifics) {
 9868: 	my (undef,$pack_type,$pack_part)=@{$package};
 9869: 	next if ($pack_part ne $part);
 9870: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9871: 	    return $packagetab{"$pack_type&$name&default"};
 9872: 	}
 9873:     }
 9874:     # look for any possible matching non extension_ package
 9875:     foreach my $package (@specifics) {
 9876: 	my (undef,$pack_type,$pack_part)=@{$package};
 9877: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9878: 	    return $packagetab{"$pack_type&$name&default"};
 9879: 	}
 9880: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9881: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9882: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9883: 	}
 9884:     }
 9885:     # look for any posible extension_ match
 9886:     foreach my $package (@extension) {
 9887: 	my ($package,$pack_type)=@{$package};
 9888: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9889: 	    return $packagetab{"$pack_type&$name&default"};
 9890: 	}
 9891: 	if (defined($packagetab{$package."&$name&default"})) {
 9892: 	    return $packagetab{$package."&$name&default"};
 9893: 	}
 9894:     }
 9895:     # look for a global default setting
 9896:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9897: 	return $packagetab{"default&$name&default"};
 9898:     }
 9899:     return undef;
 9900: }
 9901: 
 9902: sub add_prefix_and_part {
 9903:     my ($prefix,$part)=@_;
 9904:     my $keyroot;
 9905:     if (defined($prefix) && $prefix !~ /^__/) {
 9906: 	# prefix that has a part already
 9907: 	$keyroot=$prefix;
 9908:     } elsif (defined($prefix)) {
 9909: 	# prefix that is missing a part
 9910: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9911:     } else {
 9912: 	# no prefix at all
 9913: 	if (defined($part)) { $keyroot='_'.$part; }
 9914:     }
 9915:     return $keyroot;
 9916: }
 9917: 
 9918: # ---------------------------------------------------------------- Get metadata
 9919: 
 9920: my %metaentry;
 9921: my %importedpartids;
 9922: sub metadata {
 9923:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9924:     $uri=&declutter($uri);
 9925:     # if it is a non metadata possible uri return quickly
 9926:     if (($uri eq '') || 
 9927: 	(($uri =~ m|^/*adm/|) && 
 9928: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9929:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9930: 	return undef;
 9931:     }
 9932:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9933: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9934: 	return undef;
 9935:     }
 9936:     my $filename=$uri;
 9937:     $uri=~s/\.meta$//;
 9938: #
 9939: # Is the metadata already cached?
 9940: # Look at timestamp of caching
 9941: # Everything is cached by the main uri, libraries are never directly cached
 9942: #
 9943:     if (!defined($liburi)) {
 9944: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9945: 	if (defined($cached)) { return $result->{':'.$what}; }
 9946:     }
 9947:     {
 9948: # Imported parts would go here
 9949:         my %importedids=();
 9950:         my @origfileimportpartids=();
 9951:         my $importedparts=0;
 9952: #
 9953: # Is this a recursive call for a library?
 9954: #
 9955: #	if (! exists($metacache{$uri})) {
 9956: #	    $metacache{$uri}={};
 9957: #	}
 9958: 	my $cachetime = 60*60;
 9959:         if ($liburi) {
 9960: 	    $liburi=&declutter($liburi);
 9961:             $filename=$liburi;
 9962:         } else {
 9963: 	    &devalidate_cache_new('meta',$uri);
 9964: 	    undef(%metaentry);
 9965: 	}
 9966:         my %metathesekeys=();
 9967:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9968: 	my $metastring;
 9969: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9970: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9971: 	    $metastring = 
 9972: 		&Apache::lonnet::ssi_body($which,
 9973: 					  ('grade_target' => 'meta'));
 9974: 	    $cachetime = 1; # only want this cached in the child not long term
 9975: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9976:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9977: 	    my $file=&filelocation('',&clutter($filename));
 9978: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9979: 	    $metastring=&getfile($file);
 9980: 	}
 9981:         my $parser=HTML::LCParser->new(\$metastring);
 9982:         my $token;
 9983:         undef %metathesekeys;
 9984:         while ($token=$parser->get_token) {
 9985: 	    if ($token->[0] eq 'S') {
 9986: 		if (defined($token->[2]->{'package'})) {
 9987: #
 9988: # This is a package - get package info
 9989: #
 9990: 		    my $package=$token->[2]->{'package'};
 9991: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9992: 		    if (defined($token->[2]->{'id'})) { 
 9993: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9994: 		    }
 9995: 		    if ($metaentry{':packages'}) {
 9996: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9997: 		    } else {
 9998: 			$metaentry{':packages'}=$package.$keyroot;
 9999: 		    }
10000: 		    foreach my $pack_entry (keys(%packagetab)) {
10001: 			my $part=$keyroot;
10002: 			$part=~s/^\_//;
10003: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10004: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10005: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10006: 			    # ignore package.tab specified default values
10007:                             # here &package_tab_default() will fetch those
10008: 			    if ($subp eq 'default') { next; }
10009: 			    my $value=$packagetab{$pack_entry};
10010: 			    my $unikey;
10011: 			    if ($pack =~ /_0$/) {
10012: 				$unikey='parameter_0_'.$name;
10013: 				$part=0;
10014: 			    } else {
10015: 				$unikey='parameter'.$keyroot.'_'.$name;
10016: 			    }
10017: 			    if ($subp eq 'display') {
10018: 				$value.=' [Part: '.$part.']';
10019: 			    }
10020: 			    $metaentry{':'.$unikey.'.part'}=$part;
10021: 			    $metathesekeys{$unikey}=1;
10022: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10023: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10024: 			    }
10025: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10026: 				$metaentry{':'.$unikey}=
10027: 				    $metaentry{':'.$unikey.'.default'};
10028: 			    }
10029: 			}
10030: 		    }
10031: 		} else {
10032: #
10033: # This is not a package - some other kind of start tag
10034: #
10035: 		    my $entry=$token->[1];
10036: 		    my $unikey='';
10037: 
10038: 		    if ($entry eq 'import') {
10039: #
10040: # Importing a library here
10041: #
10042:                         my $location=$parser->get_text('/import');
10043:                         my $dir=$filename;
10044:                         $dir=~s|[^/]*$||;
10045:                         $location=&filelocation($dir,$location);
10046:                        
10047:                         my $importmode=$token->[2]->{'importmode'};
10048:                         if ($importmode eq 'problem') {
10049: # Import as problem/response
10050:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10051:                         } elsif ($importmode eq 'part') {
10052: # Import as part(s)
10053:                            $importedparts=1;
10054: # We need to get the original file and the imported file to get the part order correct
10055: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10056: # Load and inspect original file
10057:                            if ($#origfileimportpartids<0) {
10058:                               undef(%importedpartids);
10059:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10060:                               my $origfile=&getfile($origfilelocation);
10061:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10062:                            }
10063: 
10064: # Load and inspect imported file
10065:                            my $impfile=&getfile($location);
10066:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10067:                            if ($#impfilepartids>=0) {
10068: # This problem had parts
10069:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10070:                            } else {
10071: # Importing by turning a single problem into a problem part
10072: # It gets the import-tags ID as part-ID
10073:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10074:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10075:                            }
10076:                         } else {
10077: # Normal import
10078:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10079:                            if (defined($token->[2]->{'id'})) {
10080:                               $unikey.='_'.$token->[2]->{'id'};
10081:                            }
10082:                         }
10083: 
10084: 			if ($depthcount<20) {
10085: 			    my $metadata = 
10086: 				&metadata($uri,'keys', $location,$unikey,
10087: 					  $depthcount+1);
10088: 			    foreach my $meta (split(',',$metadata)) {
10089: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10090: 				$metathesekeys{$meta}=1;
10091: 			    }
10092: 			
10093:                         }
10094: 		    } else {
10095: #
10096: # Not importing, some other kind of non-package, non-library start tag
10097: # 
10098:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10099:                         if (defined($token->[2]->{'id'})) {
10100:                             $unikey.='_'.$token->[2]->{'id'};
10101:                         }
10102: 			if (defined($token->[2]->{'name'})) { 
10103: 			    $unikey.='_'.$token->[2]->{'name'}; 
10104: 			}
10105: 			$metathesekeys{$unikey}=1;
10106: 			foreach my $param (@{$token->[3]}) {
10107: 			    $metaentry{':'.$unikey.'.'.$param} =
10108: 				$token->[2]->{$param};
10109: 			}
10110: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10111: 			my $default=$metaentry{':'.$unikey.'.default'};
10112: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10113: 		 # only ws inside the tag, and not in default, so use default
10114: 		 # as value
10115: 			    $metaentry{':'.$unikey}=$default;
10116: 			} elsif ( $internaltext =~ /\S/ ) {
10117: 		  # something interesting inside the tag
10118: 			    $metaentry{':'.$unikey}=$internaltext;
10119: 			} else {
10120: 		  # no interesting values, don't set a default
10121: 			}
10122: # end of not-a-package not-a-library import
10123: 		    }
10124: # end of not-a-package start tag
10125: 		}
10126: # the next is the end of "start tag"
10127: 	    }
10128: 	}
10129: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10130: 	$extension = lc($extension);
10131: 	if ($extension eq 'htm') { $extension='html'; }
10132: 
10133: 	foreach my $key (keys(%packagetab)) {
10134: 	    #no specific packages #how's our extension
10135: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10136: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10137: 					 \%metathesekeys);
10138: 	}
10139: 
10140: 	if (!exists($metaentry{':packages'})
10141: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10142: 	    foreach my $key (keys(%packagetab)) {
10143: 		#no specific packages well let's get default then
10144: 		if ($key!~/^default&/) { next; }
10145: 		&metadata_create_package_def($uri,$key,'default',
10146: 					     \%metathesekeys);
10147: 	    }
10148: 	}
10149: # are there custom rights to evaluate
10150: 	if ($metaentry{':copyright'} eq 'custom') {
10151: 
10152:     #
10153:     # Importing a rights file here
10154:     #
10155: 	    unless ($depthcount) {
10156: 		my $location=$metaentry{':customdistributionfile'};
10157: 		my $dir=$filename;
10158: 		$dir=~s|[^/]*$||;
10159: 		$location=&filelocation($dir,$location);
10160: 		my $rights_metadata =
10161: 		    &metadata($uri,'keys',$location,'_rights',
10162: 			      $depthcount+1);
10163: 		foreach my $rights (split(',',$rights_metadata)) {
10164: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10165: 		    $metathesekeys{$rights}=1;
10166: 		}
10167: 	    }
10168: 	}
10169: 	# uniqifiy package listing
10170: 	my %seen;
10171: 	my @uniq_packages =
10172: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10173: 	$metaentry{':packages'} = join(',',@uniq_packages);
10174: 
10175:         if ($importedparts) {
10176: # We had imported parts and need to rebuild partorder
10177:            $metaentry{':partorder'}='';
10178:            $metathesekeys{'partorder'}=1;
10179:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10180:                if ($origfileimportpartids[$index] eq 'part') {
10181: # original part, part of the problem
10182:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10183:                } else {
10184: # we have imported parts at this position
10185:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10186:                }
10187:            }
10188:            $metaentry{':partorder'}=~s/^\,//;
10189:         }
10190: 
10191: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10192: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10193: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10194: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10195: # this is the end of "was not already recently cached
10196:     }
10197:     return $metaentry{':'.$what};
10198: }
10199: 
10200: sub metadata_create_package_def {
10201:     my ($uri,$key,$package,$metathesekeys)=@_;
10202:     my ($pack,$name,$subp)=split(/\&/,$key);
10203:     if ($subp eq 'default') { next; }
10204:     
10205:     if (defined($metaentry{':packages'})) {
10206: 	$metaentry{':packages'}.=','.$package;
10207:     } else {
10208: 	$metaentry{':packages'}=$package;
10209:     }
10210:     my $value=$packagetab{$key};
10211:     my $unikey;
10212:     $unikey='parameter_0_'.$name;
10213:     $metaentry{':'.$unikey.'.part'}=0;
10214:     $$metathesekeys{$unikey}=1;
10215:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10216: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10217:     }
10218:     if (defined($metaentry{':'.$unikey.'.default'})) {
10219: 	$metaentry{':'.$unikey}=
10220: 	    $metaentry{':'.$unikey.'.default'};
10221:     }
10222: }
10223: 
10224: sub metadata_generate_part0 {
10225:     my ($metadata,$metacache,$uri) = @_;
10226:     my %allnames;
10227:     foreach my $metakey (keys(%$metadata)) {
10228: 	if ($metakey=~/^parameter\_(.*)/) {
10229: 	  my $part=$$metacache{':'.$metakey.'.part'};
10230: 	  my $name=$$metacache{':'.$metakey.'.name'};
10231: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10232: 	    $allnames{$name}=$part;
10233: 	  }
10234: 	}
10235:     }
10236:     foreach my $name (keys(%allnames)) {
10237:       $$metadata{"parameter_0_$name"}=1;
10238:       my $key=":parameter_0_$name";
10239:       $$metacache{"$key.part"}='0';
10240:       $$metacache{"$key.name"}=$name;
10241:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10242: 					   $allnames{$name}.'_'.$name.
10243: 					   '.type'};
10244:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10245: 			     '.display'};
10246:       my $expr='[Part: '.$allnames{$name}.']';
10247:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10248:       $$metacache{"$key.display"}=$olddis;
10249:     }
10250: }
10251: 
10252: # ------------------------------------------------------ Devalidate title cache
10253: 
10254: sub devalidate_title_cache {
10255:     my ($url)=@_;
10256:     if (!$env{'request.course.id'}) { return; }
10257:     my $symb=&symbread($url);
10258:     if (!$symb) { return; }
10259:     my $key=$env{'request.course.id'}."\0".$symb;
10260:     &devalidate_cache_new('title',$key);
10261: }
10262: 
10263: # ------------------------------------------------- Get the title of a course
10264: 
10265: sub current_course_title {
10266:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10267: }
10268: # ------------------------------------------------- Get the title of a resource
10269: 
10270: sub gettitle {
10271:     my $urlsymb=shift;
10272:     my $symb=&symbread($urlsymb);
10273:     if ($symb) {
10274: 	my $key=$env{'request.course.id'}."\0".$symb;
10275: 	my ($result,$cached)=&is_cached_new('title',$key);
10276: 	if (defined($cached)) { 
10277: 	    return $result;
10278: 	}
10279: 	my ($map,$resid,$url)=&decode_symb($symb);
10280: 	my $title='';
10281: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10282: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10283: 	} else {
10284: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10285: 		    &GDBM_READER(),0640)) {
10286: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10287: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10288: 		untie(%bighash);
10289: 	    }
10290: 	}
10291: 	$title=~s/\&colon\;/\:/gs;
10292: 	if ($title) {
10293: # Remember both $symb and $title for dynamic metadata
10294:             $accesshash{$symb.'___crstitle'}=$title;
10295:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10296: # Cache this title and then return it
10297: 	    return &do_cache_new('title',$key,$title,600);
10298: 	}
10299: 	$urlsymb=$url;
10300:     }
10301:     my $title=&metadata($urlsymb,'title');
10302:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10303:     return $title;
10304: }
10305: 
10306: sub getdocspath {
10307:     my ($symb) = @_;
10308:     my $path;
10309:     if ($symb) {
10310:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
10311:         if ($resurl=~/\.(sequence|page)$/) {
10312:             $mapurl=$resurl;
10313:         } elsif ($resurl eq 'adm/navmaps') {
10314:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
10315:         }
10316:         my $mapresobj;
10317:         my $navmap = Apache::lonnavmaps::navmap->new();
10318:         if (ref($navmap)) {
10319:             $mapresobj = $navmap->getResourceByUrl($mapurl);
10320:         }
10321:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
10322:         my $type=$2;
10323:         if (ref($mapresobj)) {
10324:             my $pcslist = $mapresobj->map_hierarchy();
10325:             if ($pcslist ne '') {
10326:                 foreach my $pc (split(/,/,$pcslist)) {
10327:                     next if ($pc <= 1);
10328:                     my $res = $navmap->getByMapPc($pc);
10329:                     if (ref($res)) {
10330:                         my $thisurl = $res->src();
10331:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
10332:                         my $thistitle = $res->title();
10333:                         $path .= '&'.
10334:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
10335:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
10336:                                  ':'.$res->randompick().
10337:                                  ':'.$res->randomout().
10338:                                  ':'.$res->encrypted().
10339:                                  ':'.$res->randomorder().
10340:                                  ':'.$res->is_page();
10341:                     }
10342:                 }
10343:             }
10344:             $path =~ s/^\&//;
10345:             my $maptitle = $mapresobj->title();
10346:             if ($mapurl eq 'default') {
10347:                 $maptitle = 'Main Course Documents';
10348:             }
10349:             $path .= ($path ne '')? '&' : ''.
10350:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10351:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
10352:                     ':'.$mapresobj->randompick().
10353:                     ':'.$mapresobj->randomout().
10354:                     ':'.$mapresobj->encrypted().
10355:                     ':'.$mapresobj->randomorder().
10356:                     ':'.$mapresobj->is_page();
10357:         } else {
10358:             my $maptitle = &gettitle($mapurl);
10359:             my $ispage;
10360:             if ($mapurl =~ /\.page$/) {
10361:                 $ispage = 1;
10362:             }
10363:             if ($mapurl eq 'default') {
10364:                 $maptitle = 'Main Course Documents';
10365:             }
10366:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10367:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
10368:         }
10369:         unless ($mapurl eq 'default') {
10370:             $path = 'default&'.
10371:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
10372:                     ':::::&'.$path;
10373:         }
10374:     }
10375:     return $path;
10376: }
10377: 
10378: sub get_slot {
10379:     my ($which,$cnum,$cdom)=@_;
10380:     if (!$cnum || !$cdom) {
10381: 	(undef,my $courseid)=&whichuser();
10382: 	$cdom=$env{'course.'.$courseid.'.domain'};
10383: 	$cnum=$env{'course.'.$courseid.'.num'};
10384:     }
10385:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10386:     my %slotinfo;
10387:     if (exists($remembered{$key})) {
10388: 	$slotinfo{$which} = $remembered{$key};
10389:     } else {
10390: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10391: 	&Apache::lonhomework::showhash(%slotinfo);
10392: 	my ($tmp)=keys(%slotinfo);
10393: 	if ($tmp=~/^error:/) { return (); }
10394: 	$remembered{$key} = $slotinfo{$which};
10395:     }
10396:     if (ref($slotinfo{$which}) eq 'HASH') {
10397: 	return %{$slotinfo{$which}};
10398:     }
10399:     return $slotinfo{$which};
10400: }
10401: 
10402: sub get_reservable_slots {
10403:     my ($cnum,$cdom,$uname,$udom) = @_;
10404:     my $now = time;
10405:     my $reservable_info;
10406:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10407:     if (exists($remembered{$key})) {
10408:         $reservable_info = $remembered{$key};
10409:     } else {
10410:         my %resv;
10411:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10412:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10413:         $reservable_info = \%resv;
10414:         $remembered{$key} = $reservable_info;
10415:     }
10416:     return $reservable_info;
10417: }
10418: 
10419: sub get_course_slots {
10420:     my ($cnum,$cdom) = @_;
10421:     my $hashid=$cnum.':'.$cdom;
10422:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10423:     if (defined($cached)) {
10424:         if (ref($result) eq 'HASH') {
10425:             return %{$result};
10426:         }
10427:     } else {
10428:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10429:         my ($tmp) = keys(%slots);
10430:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10431:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
10432:             return %slots;
10433:         }
10434:     }
10435:     return;
10436: }
10437: 
10438: sub devalidate_slots_cache {
10439:     my ($cnum,$cdom)=@_;
10440:     my $hashid=$cnum.':'.$cdom;
10441:     &devalidate_cache_new('allslots',$hashid);
10442: }
10443: 
10444: sub get_coursechange {
10445:     my ($cdom,$cnum) = @_;
10446:     if ($cdom eq '' || $cnum eq '') {
10447:         return unless ($env{'request.course.id'});
10448:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10449:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10450:     }
10451:     my $hashid=$cdom.'_'.$cnum;
10452:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10453:     if ((defined($cached)) && ($change ne '')) {
10454:         return $change;
10455:     } else {
10456:         my %crshash;
10457:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10458:         if ($crshash{'internal.contentchange'} eq '') {
10459:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10460:             if ($change eq '') {
10461:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10462:                 $change = $crshash{'internal.created'};
10463:             }
10464:         } else {
10465:             $change = $crshash{'internal.contentchange'};
10466:         }
10467:         my $cachetime = 600;
10468:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10469:     }
10470:     return $change;
10471: }
10472: 
10473: sub devalidate_coursechange_cache {
10474:     my ($cnum,$cdom)=@_;
10475:     my $hashid=$cnum.':'.$cdom;
10476:     &devalidate_cache_new('crschange',$hashid);
10477: }
10478: 
10479: # ------------------------------------------------- Update symbolic store links
10480: 
10481: sub symblist {
10482:     my ($mapname,%newhash)=@_;
10483:     $mapname=&deversion(&declutter($mapname));
10484:     my %hash;
10485:     if (($env{'request.course.fn'}) && (%newhash)) {
10486:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10487:                       &GDBM_WRCREAT(),0640)) {
10488: 	    foreach my $url (keys(%newhash)) {
10489: 		next if ($url eq 'last_known'
10490: 			 && $env{'form.no_update_last_known'});
10491: 		$hash{declutter($url)}=&encode_symb($mapname,
10492: 						    $newhash{$url}->[1],
10493: 						    $newhash{$url}->[0]);
10494:             }
10495:             if (untie(%hash)) {
10496: 		return 'ok';
10497:             }
10498:         }
10499:     }
10500:     return 'error';
10501: }
10502: 
10503: # --------------------------------------------------------------- Verify a symb
10504: 
10505: sub symbverify {
10506:     my ($symb,$thisurl,$encstate)=@_;
10507:     my $thisfn=$thisurl;
10508:     $thisfn=&declutter($thisfn);
10509: # direct jump to resource in page or to a sequence - will construct own symbs
10510:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10511: # check URL part
10512:     my ($map,$resid,$url)=&decode_symb($symb);
10513: 
10514:     unless ($url eq $thisfn) { return 0; }
10515: 
10516:     $symb=&symbclean($symb);
10517:     $thisurl=&deversion($thisurl);
10518:     $thisfn=&deversion($thisfn);
10519: 
10520:     my %bighash;
10521:     my $okay=0;
10522: 
10523:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10524:                             &GDBM_READER(),0640)) {
10525:         my $noclutter;
10526:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10527:             $thisurl =~ s/\?.+$//;
10528:             if ($map =~ m{^uploaded/.+\.page$}) {
10529:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10530:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10531:                 $noclutter = 1;
10532:             }
10533:         }
10534:         my $ids;
10535:         if ($noclutter) {
10536:             $ids=$bighash{'ids_'.$thisurl};
10537:         } else {
10538:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10539:         }
10540:         unless ($ids) {
10541:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10542:             $ids=$bighash{$idkey};
10543:         }
10544:         if ($ids) {
10545: # ------------------------------------------------------------------- Has ID(s)
10546:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10547:                 $symb =~ s/\?.+$//;
10548:             }
10549: 	    foreach my $id (split(/\,/,$ids)) {
10550: 	       my ($mapid,$resid)=split(/\./,$id);
10551:                if (
10552:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10553:    eq $symb) {
10554:                    if (ref($encstate)) {
10555:                        $$encstate = $bighash{'encrypted_'.$id};
10556:                    }
10557: 		   if (($env{'request.role.adv'}) ||
10558: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10559:                        ($thisurl eq '/adm/navmaps')) {
10560: 		       $okay=1;
10561:                        last;
10562: 		   }
10563: 	       }
10564: 	   }
10565:         }
10566: 	untie(%bighash);
10567:     }
10568:     return $okay;
10569: }
10570: 
10571: # --------------------------------------------------------------- Clean-up symb
10572: 
10573: sub symbclean {
10574:     my $symb=shift;
10575:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10576: # remove version from map
10577:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10578: 
10579: # remove version from URL
10580:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10581: 
10582: # remove wrapper
10583: 
10584:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10585:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10586:     return $symb;
10587: }
10588: 
10589: # ---------------------------------------------- Split symb to find map and url
10590: 
10591: sub encode_symb {
10592:     my ($map,$resid,$url)=@_;
10593:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10594: }
10595: 
10596: sub decode_symb {
10597:     my $symb=shift;
10598:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10599:     my ($map,$resid,$url)=split(/___/,$symb);
10600:     return (&fixversion($map),$resid,&fixversion($url));
10601: }
10602: 
10603: sub fixversion {
10604:     my $fn=shift;
10605:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10606:     my %bighash;
10607:     my $uri=&clutter($fn);
10608:     my $key=$env{'request.course.id'}.'_'.$uri;
10609: # is this cached?
10610:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10611:     if (defined($cached)) { return $result; }
10612: # unfortunately not cached, or expired
10613:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10614: 	    &GDBM_READER(),0640)) {
10615:  	if ($bighash{'version_'.$uri}) {
10616:  	    my $version=$bighash{'version_'.$uri};
10617:  	    unless (($version eq 'mostrecent') || 
10618: 		    ($version==&getversion($uri))) {
10619:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10620:  	    }
10621:  	}
10622:  	untie %bighash;
10623:     }
10624:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10625: }
10626: 
10627: sub deversion {
10628:     my $url=shift;
10629:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10630:     return $url;
10631: }
10632: 
10633: # ------------------------------------------------------ Return symb list entry
10634: 
10635: sub symbread {
10636:     my ($thisfn,$donotrecurse)=@_;
10637:     my $cache_str;
10638:     if ($thisfn ne '') {
10639:         $cache_str='request.symbread.cached.'.$thisfn;
10640:         if ($env{$cache_str} ne '') {
10641:             return $env{$cache_str};
10642:         }
10643:     } else {
10644: # no filename provided? try from environment
10645:         if ($env{'request.symb'}) {
10646: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10647: 	}
10648: 	$thisfn=$env{'request.filename'};
10649:     }
10650:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10651: # is that filename actually a symb? Verify, clean, and return
10652:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10653: 	if (&symbverify($thisfn,$1)) {
10654: 	    return $env{$cache_str}=&symbclean($thisfn);
10655: 	}
10656:     }
10657:     $thisfn=declutter($thisfn);
10658:     my %hash;
10659:     my %bighash;
10660:     my $syval='';
10661:     if (($env{'request.course.fn'}) && ($thisfn)) {
10662:         my $targetfn = $thisfn;
10663:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10664:             $targetfn = 'adm/wrapper/'.$thisfn;
10665:         }
10666: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10667: 	    $targetfn=$1;
10668: 	}
10669:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10670:                       &GDBM_READER(),0640)) {
10671: 	    $syval=$hash{$targetfn};
10672:             untie(%hash);
10673:         }
10674: # ---------------------------------------------------------- There was an entry
10675:         if ($syval) {
10676: 	    #unless ($syval=~/\_\d+$/) {
10677: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10678: 		    #&appenv({'request.ambiguous' => $thisfn});
10679: 		    #return $env{$cache_str}='';
10680: 		#}    
10681: 		#$syval.=$1;
10682: 	    #}
10683:         } else {
10684: # ------------------------------------------------------- Was not in symb table
10685:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10686:                             &GDBM_READER(),0640)) {
10687: # ---------------------------------------------- Get ID(s) for current resource
10688:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10689:               unless ($ids) { 
10690:                  $ids=$bighash{'ids_/'.$thisfn};
10691:               }
10692:               unless ($ids) {
10693: # alias?
10694: 		  $ids=$bighash{'mapalias_'.$thisfn};
10695:               }
10696:               if ($ids) {
10697: # ------------------------------------------------------------------- Has ID(s)
10698:                  my @possibilities=split(/\,/,$ids);
10699:                  if ($#possibilities==0) {
10700: # ----------------------------------------------- There is only one possibility
10701: 		     my ($mapid,$resid)=split(/\./,$ids);
10702: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10703: 						    $resid,$thisfn);
10704:                  } elsif (!$donotrecurse) {
10705: # ------------------------------------------ There is more than one possibility
10706:                      my $realpossible=0;
10707:                      foreach my $id (@possibilities) {
10708: 			 my $file=$bighash{'src_'.$id};
10709:                          if (&allowed('bre',$file)) {
10710:          		    my ($mapid,$resid)=split(/\./,$id);
10711:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10712: 				$realpossible++;
10713:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10714: 						    $resid,$thisfn);
10715:                             }
10716: 			 }
10717:                      }
10718: 		     if ($realpossible!=1) { $syval=''; }
10719:                  } else {
10720:                      $syval='';
10721:                  }
10722: 	      }
10723:               untie(%bighash)
10724:            }
10725:         }
10726:         if ($syval) {
10727: 	    return $env{$cache_str}=$syval;
10728:         }
10729:     }
10730:     &appenv({'request.ambiguous' => $thisfn});
10731:     return $env{$cache_str}='';
10732: }
10733: 
10734: # ---------------------------------------------------------- Return random seed
10735: 
10736: sub numval {
10737:     my $txt=shift;
10738:     $txt=~tr/A-J/0-9/;
10739:     $txt=~tr/a-j/0-9/;
10740:     $txt=~tr/K-T/0-9/;
10741:     $txt=~tr/k-t/0-9/;
10742:     $txt=~tr/U-Z/0-5/;
10743:     $txt=~tr/u-z/0-5/;
10744:     $txt=~s/\D//g;
10745:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10746:     return int($txt);
10747: }
10748: 
10749: sub numval2 {
10750:     my $txt=shift;
10751:     $txt=~tr/A-J/0-9/;
10752:     $txt=~tr/a-j/0-9/;
10753:     $txt=~tr/K-T/0-9/;
10754:     $txt=~tr/k-t/0-9/;
10755:     $txt=~tr/U-Z/0-5/;
10756:     $txt=~tr/u-z/0-5/;
10757:     $txt=~s/\D//g;
10758:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10759:     my $total;
10760:     foreach my $val (@txts) { $total+=$val; }
10761:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10762:     return int($total);
10763: }
10764: 
10765: sub numval3 {
10766:     use integer;
10767:     my $txt=shift;
10768:     $txt=~tr/A-J/0-9/;
10769:     $txt=~tr/a-j/0-9/;
10770:     $txt=~tr/K-T/0-9/;
10771:     $txt=~tr/k-t/0-9/;
10772:     $txt=~tr/U-Z/0-5/;
10773:     $txt=~tr/u-z/0-5/;
10774:     $txt=~s/\D//g;
10775:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10776:     my $total;
10777:     foreach my $val (@txts) { $total+=$val; }
10778:     if ($_64bit) { $total=(($total<<32)>>32); }
10779:     return $total;
10780: }
10781: 
10782: sub digest {
10783:     my ($data)=@_;
10784:     my $digest=&Digest::MD5::md5($data);
10785:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10786:     my ($e,$f);
10787:     {
10788:         use integer;
10789:         $e=($a+$b);
10790:         $f=($c+$d);
10791:         if ($_64bit) {
10792:             $e=(($e<<32)>>32);
10793:             $f=(($f<<32)>>32);
10794:         }
10795:     }
10796:     if (wantarray) {
10797: 	return ($e,$f);
10798:     } else {
10799: 	my $g;
10800: 	{
10801: 	    use integer;
10802: 	    $g=($e+$f);
10803: 	    if ($_64bit) {
10804: 		$g=(($g<<32)>>32);
10805: 	    }
10806: 	}
10807: 	return $g;
10808:     }
10809: }
10810: 
10811: sub latest_rnd_algorithm_id {
10812:     return '64bit5';
10813: }
10814: 
10815: sub get_rand_alg {
10816:     my ($courseid)=@_;
10817:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10818:     if ($courseid) {
10819: 	return $env{"course.$courseid.rndseed"};
10820:     }
10821:     return &latest_rnd_algorithm_id();
10822: }
10823: 
10824: sub validCODE {
10825:     my ($CODE)=@_;
10826:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10827:     return 0;
10828: }
10829: 
10830: sub getCODE {
10831:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10832:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10833: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10834: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10835: 	return $Apache::lonhomework::history{'resource.CODE'};
10836:     }
10837:     return undef;
10838: }
10839: #
10840: #  Determines the random seed for a specific context:
10841: #
10842: # parameters:
10843: #   symb      - in course context the symb for the seed.
10844: #   course_id - The course id of the form domain_coursenum.
10845: #   domain    - Domain for the user.
10846: #   course    - Course for the user.
10847: #   cenv      - environment of the course.
10848: #
10849: # NOTE:
10850: #   All parameters are picked out of the environment if missing
10851: #   or not defined.
10852: #   If a symb cannot be determined the current time is used instead.
10853: #
10854: #  For a given well defined symb, courside, domain, username,
10855: #  and course environment, the seed is reproducible.
10856: #
10857: sub rndseed {
10858:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10859:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10860:     if (!defined($symb)) {
10861: 	unless ($symb=$wsymb) { return time; }
10862:     }
10863:     if (!defined $courseid) { 
10864: 	$courseid=$wcourseid; 
10865:     }
10866:     if (!defined $domain) { $domain=$wdomain; }
10867:     if (!defined $username) { $username=$wusername }
10868: 
10869:     my $which;
10870:     if (defined($cenv->{'rndseed'})) {
10871: 	$which = $cenv->{'rndseed'};
10872:     } else {
10873: 	$which =&get_rand_alg($courseid);
10874:     }
10875:     if (defined(&getCODE())) {
10876: 
10877: 	if ($which eq '64bit5') {
10878: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10879: 	} elsif ($which eq '64bit4') {
10880: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10881: 	} else {
10882: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10883: 	}
10884:     } elsif ($which eq '64bit5') {
10885: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10886:     } elsif ($which eq '64bit4') {
10887: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10888:     } elsif ($which eq '64bit3') {
10889: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10890:     } elsif ($which eq '64bit2') {
10891: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10892:     } elsif ($which eq '64bit') {
10893: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10894:     }
10895:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10896: }
10897: 
10898: sub rndseed_32bit {
10899:     my ($symb,$courseid,$domain,$username)=@_;
10900:     {
10901: 	use integer;
10902: 	my $symbchck=unpack("%32C*",$symb) << 27;
10903: 	my $symbseed=numval($symb) << 22;
10904: 	my $namechck=unpack("%32C*",$username) << 17;
10905: 	my $nameseed=numval($username) << 12;
10906: 	my $domainseed=unpack("%32C*",$domain) << 7;
10907: 	my $courseseed=unpack("%32C*",$courseid);
10908: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10909: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10910: 	#&logthis("rndseed :$num:$symb");
10911: 	if ($_64bit) { $num=(($num<<32)>>32); }
10912: 	return $num;
10913:     }
10914: }
10915: 
10916: sub rndseed_64bit {
10917:     my ($symb,$courseid,$domain,$username)=@_;
10918:     {
10919: 	use integer;
10920: 	my $symbchck=unpack("%32S*",$symb) << 21;
10921: 	my $symbseed=numval($symb) << 10;
10922: 	my $namechck=unpack("%32S*",$username);
10923: 	
10924: 	my $nameseed=numval($username) << 21;
10925: 	my $domainseed=unpack("%32S*",$domain) << 10;
10926: 	my $courseseed=unpack("%32S*",$courseid);
10927: 	
10928: 	my $num1=$symbchck+$symbseed+$namechck;
10929: 	my $num2=$nameseed+$domainseed+$courseseed;
10930: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10931: 	#&logthis("rndseed :$num:$symb");
10932: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10933: 	return "$num1,$num2";
10934:     }
10935: }
10936: 
10937: sub rndseed_64bit2 {
10938:     my ($symb,$courseid,$domain,$username)=@_;
10939:     {
10940: 	use integer;
10941: 	# strings need to be an even # of cahracters long, it it is odd the
10942:         # last characters gets thrown away
10943: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10944: 	my $symbseed=numval($symb) << 10;
10945: 	my $namechck=unpack("%32S*",$username.' ');
10946: 	
10947: 	my $nameseed=numval($username) << 21;
10948: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10949: 	my $courseseed=unpack("%32S*",$courseid.' ');
10950: 	
10951: 	my $num1=$symbchck+$symbseed+$namechck;
10952: 	my $num2=$nameseed+$domainseed+$courseseed;
10953: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10954: 	#&logthis("rndseed :$num:$symb");
10955: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10956: 	return "$num1,$num2";
10957:     }
10958: }
10959: 
10960: sub rndseed_64bit3 {
10961:     my ($symb,$courseid,$domain,$username)=@_;
10962:     {
10963: 	use integer;
10964: 	# strings need to be an even # of cahracters long, it it is odd the
10965:         # last characters gets thrown away
10966: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10967: 	my $symbseed=numval2($symb) << 10;
10968: 	my $namechck=unpack("%32S*",$username.' ');
10969: 	
10970: 	my $nameseed=numval2($username) << 21;
10971: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10972: 	my $courseseed=unpack("%32S*",$courseid.' ');
10973: 	
10974: 	my $num1=$symbchck+$symbseed+$namechck;
10975: 	my $num2=$nameseed+$domainseed+$courseseed;
10976: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10977: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10978: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10979: 	
10980: 	return "$num1:$num2";
10981:     }
10982: }
10983: 
10984: sub rndseed_64bit4 {
10985:     my ($symb,$courseid,$domain,$username)=@_;
10986:     {
10987: 	use integer;
10988: 	# strings need to be an even # of cahracters long, it it is odd the
10989:         # last characters gets thrown away
10990: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10991: 	my $symbseed=numval3($symb) << 10;
10992: 	my $namechck=unpack("%32S*",$username.' ');
10993: 	
10994: 	my $nameseed=numval3($username) << 21;
10995: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10996: 	my $courseseed=unpack("%32S*",$courseid.' ');
10997: 	
10998: 	my $num1=$symbchck+$symbseed+$namechck;
10999: 	my $num2=$nameseed+$domainseed+$courseseed;
11000: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11001: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11002: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11003: 	
11004: 	return "$num1:$num2";
11005:     }
11006: }
11007: 
11008: sub rndseed_64bit5 {
11009:     my ($symb,$courseid,$domain,$username)=@_;
11010:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11011:     return "$num1:$num2";
11012: }
11013: 
11014: sub rndseed_CODE_64bit {
11015:     my ($symb,$courseid,$domain,$username)=@_;
11016:     {
11017: 	use integer;
11018: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11019: 	my $symbseed=numval2($symb);
11020: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11021: 	my $CODEseed=numval(&getCODE());
11022: 	my $courseseed=unpack("%32S*",$courseid.' ');
11023: 	my $num1=$symbseed+$CODEchck;
11024: 	my $num2=$CODEseed+$courseseed+$symbchck;
11025: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11026: 	#&logthis("rndseed :$num1:$num2:$symb");
11027: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11028: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11029: 	return "$num1:$num2";
11030:     }
11031: }
11032: 
11033: sub rndseed_CODE_64bit4 {
11034:     my ($symb,$courseid,$domain,$username)=@_;
11035:     {
11036: 	use integer;
11037: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11038: 	my $symbseed=numval3($symb);
11039: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11040: 	my $CODEseed=numval3(&getCODE());
11041: 	my $courseseed=unpack("%32S*",$courseid.' ');
11042: 	my $num1=$symbseed+$CODEchck;
11043: 	my $num2=$CODEseed+$courseseed+$symbchck;
11044: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11045: 	#&logthis("rndseed :$num1:$num2:$symb");
11046: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11047: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11048: 	return "$num1:$num2";
11049:     }
11050: }
11051: 
11052: sub rndseed_CODE_64bit5 {
11053:     my ($symb,$courseid,$domain,$username)=@_;
11054:     my $code = &getCODE();
11055:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11056:     return "$num1:$num2";
11057: }
11058: 
11059: sub setup_random_from_rndseed {
11060:     my ($rndseed)=@_;
11061:     if ($rndseed =~/([,:])/) {
11062: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11063: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11064:     } else {
11065: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11066:     }
11067: }
11068: 
11069: sub latest_receipt_algorithm_id {
11070:     return 'receipt3';
11071: }
11072: 
11073: sub recunique {
11074:     my $fucourseid=shift;
11075:     my $unique;
11076:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11077: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11078: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11079:     } else {
11080: 	$unique=$perlvar{'lonReceipt'};
11081:     }
11082:     return unpack("%32C*",$unique);
11083: }
11084: 
11085: sub recprefix {
11086:     my $fucourseid=shift;
11087:     my $prefix;
11088:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11089: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11090: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11091:     } else {
11092: 	$prefix=$perlvar{'lonHostID'};
11093:     }
11094:     return unpack("%32C*",$prefix);
11095: }
11096: 
11097: sub ireceipt {
11098:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11099: 
11100:     my $return =&recprefix($fucourseid).'-';
11101: 
11102:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11103: 	$env{'request.state'} eq 'construct') {
11104: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11105: 	return $return;
11106:     }
11107: 
11108:     my $cuname=unpack("%32C*",$funame);
11109:     my $cudom=unpack("%32C*",$fudom);
11110:     my $cucourseid=unpack("%32C*",$fucourseid);
11111:     my $cusymb=unpack("%32C*",$fusymb);
11112:     my $cunique=&recunique($fucourseid);
11113:     my $cpart=unpack("%32S*",$part);
11114:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11115: 
11116: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11117: 			       
11118: 	$return.= ($cunique%$cuname+
11119: 		   $cunique%$cudom+
11120: 		   $cusymb%$cuname+
11121: 		   $cusymb%$cudom+
11122: 		   $cucourseid%$cuname+
11123: 		   $cucourseid%$cudom+
11124: 		   $cpart%$cuname+
11125: 		   $cpart%$cudom);
11126:     } else {
11127: 	$return.= ($cunique%$cuname+
11128: 		   $cunique%$cudom+
11129: 		   $cusymb%$cuname+
11130: 		   $cusymb%$cudom+
11131: 		   $cucourseid%$cuname+
11132: 		   $cucourseid%$cudom);
11133:     }
11134:     return $return;
11135: }
11136: 
11137: sub receipt {
11138:     my ($part)=@_;
11139:     my ($symb,$courseid,$domain,$name) = &whichuser();
11140:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11141: }
11142: 
11143: sub whichuser {
11144:     my ($passedsymb)=@_;
11145:     my ($symb,$courseid,$domain,$name,$publicuser);
11146:     if (defined($env{'form.grade_symb'})) {
11147: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11148: 	my $allowed=&allowed('vgr',$tmp_courseid);
11149: 	if (!$allowed &&
11150: 	    exists($env{'request.course.sec'}) &&
11151: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11152: 	    $allowed=&allowed('vgr',$tmp_courseid.
11153: 			      '/'.$env{'request.course.sec'});
11154: 	}
11155: 	if ($allowed) {
11156: 	    ($symb)=&get_env_multiple('form.grade_symb');
11157: 	    $courseid=$tmp_courseid;
11158: 	    ($domain)=&get_env_multiple('form.grade_domain');
11159: 	    ($name)=&get_env_multiple('form.grade_username');
11160: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11161: 	}
11162:     }
11163:     if (!$passedsymb) {
11164: 	$symb=&symbread();
11165:     } else {
11166: 	$symb=$passedsymb;
11167:     }
11168:     $courseid=$env{'request.course.id'};
11169:     $domain=$env{'user.domain'};
11170:     $name=$env{'user.name'};
11171:     if ($name eq 'public' && $domain eq 'public') {
11172: 	if (!defined($env{'form.username'})) {
11173: 	    $env{'form.username'}.=time.rand(10000000);
11174: 	}
11175: 	$name.=$env{'form.username'};
11176:     }
11177:     return ($symb,$courseid,$domain,$name,$publicuser);
11178: 
11179: }
11180: 
11181: # ------------------------------------------------------------ Serves up a file
11182: # returns either the contents of the file or 
11183: # -1 if the file doesn't exist
11184: #
11185: # if the target is a file that was uploaded via DOCS, 
11186: # a check will be made to see if a current copy exists on the local server,
11187: # if it does this will be served, otherwise a copy will be retrieved from
11188: # the home server for the course and stored in /home/httpd/html/userfiles on
11189: # the local server.   
11190: 
11191: sub getfile {
11192:     my ($file) = @_;
11193:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11194:     &repcopy($file);
11195:     return &readfile($file);
11196: }
11197: 
11198: sub repcopy_userfile {
11199:     my ($file)=@_;
11200:     my $londocroot = $perlvar{'lonDocRoot'};
11201:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11202:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11203:     my ($cdom,$cnum,$filename) = 
11204: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11205:     my $uri="/uploaded/$cdom/$cnum/$filename";
11206:     if (-e "$file") {
11207: # we already have a local copy, check it out
11208: 	my @fileinfo = stat($file);
11209: 	my $rtncode;
11210: 	my $info;
11211: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11212: 	if ($lwpresp ne 'ok') {
11213: # there is no such file anymore, even though we had a local copy
11214: 	    if ($rtncode eq '404') {
11215: 		unlink($file);
11216: 	    }
11217: 	    return -1;
11218: 	}
11219: 	if ($info < $fileinfo[9]) {
11220: # nice, the file we have is up-to-date, just say okay
11221: 	    return 'ok';
11222: 	} else {
11223: # the file is outdated, get rid of it
11224: 	    unlink($file);
11225: 	}
11226:     }
11227: # one way or the other, at this point, we don't have the file
11228: # construct the correct path for the file
11229:     my @parts = ($cdom,$cnum); 
11230:     if ($filename =~ m|^(.+)/[^/]+$|) {
11231: 	push @parts, split(/\//,$1);
11232:     }
11233:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11234:     foreach my $part (@parts) {
11235: 	$path .= '/'.$part;
11236: 	if (!-e $path) {
11237: 	    mkdir($path,0770);
11238: 	}
11239:     }
11240: # now the path exists for sure
11241: # get a user agent
11242:     my $ua=new LWP::UserAgent;
11243:     my $transferfile=$file.'.in.transfer';
11244: # FIXME: this should flock
11245:     if (-e $transferfile) { return 'ok'; }
11246:     my $request;
11247:     $uri=~s/^\///;
11248:     my $homeserver = &homeserver($cnum,$cdom);
11249:     my $protocol = $protocol{$homeserver};
11250:     $protocol = 'http' if ($protocol ne 'https');
11251:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11252:     my $response=$ua->request($request,$transferfile);
11253: # did it work?
11254:     if ($response->is_error()) {
11255: 	unlink($transferfile);
11256: 	&logthis("Userfile repcopy failed for $uri");
11257: 	return -1;
11258:     }
11259: # worked, rename the transfer file
11260:     rename($transferfile,$file);
11261:     return 'ok';
11262: }
11263: 
11264: sub tokenwrapper {
11265:     my $uri=shift;
11266:     $uri=~s|^https?\://([^/]+)||;
11267:     $uri=~s|^/||;
11268:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11269:     my $token=$1;
11270:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11271:     if ($udom && $uname && $file) {
11272: 	$file=~s|(\?\.*)*$||;
11273:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11274:         my $homeserver = &homeserver($uname,$udom);
11275:         my $protocol = $protocol{$homeserver};
11276:         $protocol = 'http' if ($protocol ne 'https');
11277:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11278:                (($uri=~/\?/)?'&':'?').'token='.$token.
11279:                                '&tokenissued='.$perlvar{'lonHostID'};
11280:     } else {
11281:         return '/adm/notfound.html';
11282:     }
11283: }
11284: 
11285: # call with reqtype HEAD: get last modification time
11286: # call with reqtype GET: get the file contents
11287: # Do not call this with reqtype GET for large files! It loads everything into memory
11288: #
11289: sub getuploaded {
11290:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11291:     $uri=~s/^\///;
11292:     my $homeserver = &homeserver($cnum,$cdom);
11293:     my $protocol = $protocol{$homeserver};
11294:     $protocol = 'http' if ($protocol ne 'https');
11295:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11296:     my $ua=new LWP::UserAgent;
11297:     my $request=new HTTP::Request($reqtype,$uri);
11298:     my $response=$ua->request($request);
11299:     $$rtncode = $response->code;
11300:     if (! $response->is_success()) {
11301: 	return 'failed';
11302:     }      
11303:     if ($reqtype eq 'HEAD') {
11304: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11305:     } elsif ($reqtype eq 'GET') {
11306: 	$$info = $response->content;
11307:     }
11308:     return 'ok';
11309: }
11310: 
11311: sub readfile {
11312:     my $file = shift;
11313:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11314:     my $fh;
11315:     open($fh,"<$file");
11316:     my $a='';
11317:     while (my $line = <$fh>) { $a .= $line; }
11318:     return $a;
11319: }
11320: 
11321: sub filelocation {
11322:     my ($dir,$file) = @_;
11323:     my $location;
11324:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11325: 
11326:     if ($file =~ m-^/adm/-) {
11327: 	$file=~s-^/adm/wrapper/-/-;
11328: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11329:     }
11330: 
11331:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11332:         $location = $file;
11333:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11334:         my ($udom,$uname,$filename)=
11335:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11336:         my $home=&homeserver($uname,$udom);
11337:         my $is_me=0;
11338:         my @ids=&current_machine_ids();
11339:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11340:         if ($is_me) {
11341:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11342:         } else {
11343:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11344:   	      $udom.'/'.$uname.'/'.$filename;
11345:         }
11346:     } elsif ($file =~ m-^/adm/-) {
11347: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11348:     } else {
11349:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11350:         $file=~s:^/(res|priv)/:/:;
11351:         my $space=$1;
11352:         if ( !( $file =~ m:^/:) ) {
11353:             $location = $dir. '/'.$file;
11354:         } else {
11355:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11356:         }
11357:     }
11358:     $location=~s://+:/:g; # remove duplicate /
11359:     while ($location=~m{/\.\./}) {
11360: 	if ($location =~ m{/[^/]+/\.\./}) {
11361: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11362: 	} else {
11363: 	    $location=~ s{/\.\./}{/}g;
11364: 	}
11365:     } #remove dir/..
11366:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11367:     return $location;
11368: }
11369: 
11370: sub hreflocation {
11371:     my ($dir,$file)=@_;
11372:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11373: 	$file=filelocation($dir,$file);
11374:     } elsif ($file=~m-^/adm/-) {
11375: 	$file=~s-^/adm/wrapper/-/-;
11376: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11377:     }
11378:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11379: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11380:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11381: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11382: 	        {/uploaded/$1/$2/}x;
11383:     }
11384:     if ($file=~ m{^/userfiles/}) {
11385: 	$file =~ s{^/userfiles/}{/uploaded/};
11386:     }
11387:     return $file;
11388: }
11389: 
11390: 
11391: 
11392: 
11393: 
11394: sub current_machine_domains {
11395:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11396: }
11397: 
11398: sub machine_domains {
11399:     my ($hostname) = @_;
11400:     my @domains;
11401:     my %hostname = &all_hostnames();
11402:     while( my($id, $name) = each(%hostname)) {
11403: #	&logthis("-$id-$name-$hostname-");
11404: 	if ($hostname eq $name) {
11405: 	    push(@domains,&host_domain($id));
11406: 	}
11407:     }
11408:     return @domains;
11409: }
11410: 
11411: sub current_machine_ids {
11412:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11413: }
11414: 
11415: sub machine_ids {
11416:     my ($hostname) = @_;
11417:     $hostname ||= &hostname($perlvar{'lonHostID'});
11418:     my @ids;
11419:     my %name_to_host = &all_names();
11420:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11421: 	return @{ $name_to_host{$hostname} };
11422:     }
11423:     return;
11424: }
11425: 
11426: sub additional_machine_domains {
11427:     my @domains;
11428:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11429:     while( my $line = <$fh>) {
11430:         $line =~ s/\s//g;
11431:         push(@domains,$line);
11432:     }
11433:     return @domains;
11434: }
11435: 
11436: sub default_login_domain {
11437:     my $domain = $perlvar{'lonDefDomain'};
11438:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11439:     foreach my $posdom (&current_machine_domains(),
11440:                         &additional_machine_domains()) {
11441:         if (lc($posdom) eq lc($testdomain)) {
11442:             $domain=$posdom;
11443:             last;
11444:         }
11445:     }
11446:     return $domain;
11447: }
11448: 
11449: # ------------------------------------------------------------- Declutters URLs
11450: 
11451: sub declutter {
11452:     my $thisfn=shift;
11453:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11454:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11455:     $thisfn=~s/^\///;
11456:     $thisfn=~s|^adm/wrapper/||;
11457:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11458:     $thisfn=~s/^res\///;
11459:     $thisfn=~s/^priv\///;
11460:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11461:         $thisfn=~s/\?.+$//;
11462:     }
11463:     return $thisfn;
11464: }
11465: 
11466: # ------------------------------------------------------------- Clutter up URLs
11467: 
11468: sub clutter {
11469:     my $thisfn='/'.&declutter(shift);
11470:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11471: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11472:        $thisfn='/res'.$thisfn; 
11473:     }
11474:     if ($thisfn !~m|^/adm|) {
11475: 	if ($thisfn =~ m|^/ext/|) {
11476: 	    $thisfn='/adm/wrapper'.$thisfn;
11477: 	} else {
11478: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11479: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11480: 	    if ($embstyle eq 'ssi'
11481: 		|| ($embstyle eq 'hdn')
11482: 		|| ($embstyle eq 'rat')
11483: 		|| ($embstyle eq 'prv')
11484: 		|| ($embstyle eq 'ign')) {
11485: 		#do nothing with these
11486: 	    } elsif (($embstyle eq 'img') 
11487: 		|| ($embstyle eq 'emb')
11488: 		|| ($embstyle eq 'wrp')) {
11489: 		$thisfn='/adm/wrapper'.$thisfn;
11490: 	    } elsif ($embstyle eq 'unk'
11491: 		     && $thisfn!~/\.(sequence|page)$/) {
11492: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11493: 	    } else {
11494: #		&logthis("Got a blank emb style");
11495: 	    }
11496: 	}
11497:     }
11498:     return $thisfn;
11499: }
11500: 
11501: sub clutter_with_no_wrapper {
11502:     my $uri = &clutter(shift);
11503:     if ($uri =~ m-^/adm/-) {
11504: 	$uri =~ s-^/adm/wrapper/-/-;
11505: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11506:     }
11507:     return $uri;
11508: }
11509: 
11510: sub freeze_escape {
11511:     my ($value)=@_;
11512:     if (ref($value)) {
11513: 	$value=&nfreeze($value);
11514: 	return '__FROZEN__'.&escape($value);
11515:     }
11516:     return &escape($value);
11517: }
11518: 
11519: 
11520: sub thaw_unescape {
11521:     my ($value)=@_;
11522:     if ($value =~ /^__FROZEN__/) {
11523: 	substr($value,0,10,undef);
11524: 	$value=&unescape($value);
11525: 	return &thaw($value);
11526:     }
11527:     return &unescape($value);
11528: }
11529: 
11530: sub correct_line_ends {
11531:     my ($result)=@_;
11532:     $$result =~s/\r\n/\n/mg;
11533:     $$result =~s/\r/\n/mg;
11534: }
11535: # ================================================================ Main Program
11536: 
11537: sub goodbye {
11538:    &logthis("Starting Shut down");
11539: #not converted to using infrastruture and probably shouldn't be
11540:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11541: #converted
11542: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11543:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11544: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11545: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11546: #1.1 only
11547: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11548: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11549: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11550: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11551:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11552:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11553:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11554:    &flushcourselogs();
11555:    &logthis("Shutting down");
11556: }
11557: 
11558: sub get_dns {
11559:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11560:     if (!$ignore_cache) {
11561: 	my ($content,$cached)=
11562: 	    &Apache::lonnet::is_cached_new('dns',$url);
11563: 	if ($cached) {
11564: 	    &$func($content,$hashref);
11565: 	    return;
11566: 	}
11567:     }
11568: 
11569:     my %alldns;
11570:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11571:     foreach my $dns (<$config>) {
11572: 	next if ($dns !~ /^\^(\S*)/x);
11573:         my $line = $1;
11574:         my ($host,$protocol) = split(/:/,$line);
11575:         if ($protocol ne 'https') {
11576:             $protocol = 'http';
11577:         }
11578: 	$alldns{$host} = $protocol;
11579:     }
11580:     while (%alldns) {
11581: 	my ($dns) = keys(%alldns);
11582: 	my $ua=new LWP::UserAgent;
11583:         $ua->timeout(30);
11584: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11585: 	my $response=$ua->request($request);
11586:         delete($alldns{$dns});
11587: 	next if ($response->is_error());
11588: 	my @content = split("\n",$response->content);
11589: 	unless ($nocache) {
11590: 	    &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
11591: 	}
11592: 	&$func(\@content,$hashref);
11593: 	return;
11594:     }
11595:     close($config);
11596:     my $which = (split('/',$url))[3];
11597:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11598:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11599:     my @content = <$config>;
11600:     &$func(\@content,$hashref);
11601:     return;
11602: }
11603: 
11604: # ------------------------------------------------------Get DNS checksums file
11605: sub write_dns_checksums_tab {
11606:     my ($lines,$hashref) = @_;
11607:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11608:     my $loncaparev = &get_server_loncaparev($machine_dom);
11609:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11610:     my (%chksum,%revnum);
11611:     if (ref($lines) eq 'ARRAY') {
11612:         chomp(@{$lines});
11613:         my $versions = shift(@{$lines});
11614:         my %supported;
11615:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
11616:             my $releaseslist = $1;
11617:             if ($releaseslist =~ /,/) {
11618:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
11619:             } elsif ($releaseslist) {
11620:                 $supported{$releaseslist} = 1;
11621:             }
11622:         }
11623:         if ($supported{$release}) {  
11624:             my $matchthis = 0;
11625:             foreach my $line (@{$lines}) {
11626:                 if ($line =~ /^(\d[\w\.]+)$/) {
11627:                     if ($matchthis) {
11628:                         last;
11629:                     } elsif ($1 eq $release) {
11630:                         $matchthis = 1;
11631:                     }
11632:                 } elsif ($matchthis) {
11633:                     my ($file,$version,$shasum) = split(/,/,$line);
11634:                     $chksum{$file} = $shasum;
11635:                     $revnum{$file} = $version;
11636:                 }
11637:             }
11638:             if (ref($hashref) eq 'HASH') {
11639:                 %{$hashref} = (
11640:                                 sums     => \%chksum,
11641:                                 versions => \%revnum,
11642:                               );
11643:             }
11644:         }
11645:     }
11646:     return;
11647: }
11648: 
11649: sub fetch_dns_checksums {
11650:     my %checksums; 
11651:         &get_dns('/adm/dns/checksums',\&write_dns_checksums_tab,1,1,
11652:                  \%checksums);
11653:     return \%checksums;
11654: }
11655: 
11656: # ------------------------------------------------------------ Read domain file
11657: {
11658:     my $loaded;
11659:     my %domain;
11660: 
11661:     sub parse_domain_tab {
11662: 	my ($lines) = @_;
11663: 	foreach my $line (@$lines) {
11664: 	    next if ($line =~ /^(\#|\s*$ )/x);
11665: 
11666: 	    chomp($line);
11667: 	    my ($name,@elements) = split(/:/,$line,9);
11668: 	    my %this_domain;
11669: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11670: 			       'lang_def', 'city', 'longi', 'lati',
11671: 			       'primary') {
11672: 		$this_domain{$field} = shift(@elements);
11673: 	    }
11674: 	    $domain{$name} = \%this_domain;
11675: 	}
11676:     }
11677: 
11678:     sub reset_domain_info {
11679: 	undef($loaded);
11680: 	undef(%domain);
11681:     }
11682: 
11683:     sub load_domain_tab {
11684: 	my ($ignore_cache) = @_;
11685: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11686: 	my $fh;
11687: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11688: 	    my @lines = <$fh>;
11689: 	    &parse_domain_tab(\@lines);
11690: 	}
11691: 	close($fh);
11692: 	$loaded = 1;
11693:     }
11694: 
11695:     sub domain {
11696: 	&load_domain_tab() if (!$loaded);
11697: 
11698: 	my ($name,$what) = @_;
11699: 	return if ( !exists($domain{$name}) );
11700: 
11701: 	if (!$what) {
11702: 	    return $domain{$name}{'description'};
11703: 	}
11704: 	return $domain{$name}{$what};
11705:     }
11706: 
11707:     sub domain_info {
11708:         &load_domain_tab() if (!$loaded);
11709:         return %domain;
11710:     }
11711: 
11712: }
11713: 
11714: 
11715: # ------------------------------------------------------------- Read hosts file
11716: {
11717:     my %hostname;
11718:     my %hostdom;
11719:     my %libserv;
11720:     my $loaded;
11721:     my %name_to_host;
11722:     my %internetdom;
11723:     my %LC_dns_serv;
11724: 
11725:     sub parse_hosts_tab {
11726: 	my ($file) = @_;
11727: 	foreach my $configline (@$file) {
11728: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11729:             chomp($configline);
11730: 	    if ($configline =~ /^\^/) {
11731:                 if ($configline =~ /^\^([\w.\-]+)/) {
11732:                     $LC_dns_serv{$1} = 1;
11733:                 }
11734:                 next;
11735:             }
11736: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11737: 	    $name=~s/\s//g;
11738: 	    if ($id && $domain && $role && $name) {
11739: 		$hostname{$id}=$name;
11740: 		push(@{$name_to_host{$name}}, $id);
11741: 		$hostdom{$id}=$domain;
11742: 		if ($role eq 'library') { $libserv{$id}=$name; }
11743:                 if (defined($protocol)) {
11744:                     if ($protocol eq 'https') {
11745:                         $protocol{$id} = $protocol;
11746:                     } else {
11747:                         $protocol{$id} = 'http'; 
11748:                     }
11749:                 } else {
11750:                     $protocol{$id} = 'http';
11751:                 }
11752:                 if (defined($intdom)) {
11753:                     $internetdom{$id} = $intdom;
11754:                 }
11755: 	    }
11756: 	}
11757:     }
11758:     
11759:     sub reset_hosts_info {
11760: 	&purge_remembered();
11761: 	&reset_domain_info();
11762: 	&reset_hosts_ip_info();
11763: 	undef(%name_to_host);
11764: 	undef(%hostname);
11765: 	undef(%hostdom);
11766: 	undef(%libserv);
11767: 	undef($loaded);
11768:     }
11769: 
11770:     sub load_hosts_tab {
11771: 	my ($ignore_cache) = @_;
11772: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11773: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11774: 	my @config = <$config>;
11775: 	&parse_hosts_tab(\@config);
11776: 	close($config);
11777: 	$loaded=1;
11778:     }
11779: 
11780:     sub hostname {
11781: 	&load_hosts_tab() if (!$loaded);
11782: 
11783: 	my ($lonid) = @_;
11784: 	return $hostname{$lonid};
11785:     }
11786: 
11787:     sub all_hostnames {
11788: 	&load_hosts_tab() if (!$loaded);
11789: 
11790: 	return %hostname;
11791:     }
11792: 
11793:     sub all_names {
11794: 	&load_hosts_tab() if (!$loaded);
11795: 
11796: 	return %name_to_host;
11797:     }
11798: 
11799:     sub all_host_domain {
11800:         &load_hosts_tab() if (!$loaded);
11801:         return %hostdom;
11802:     }
11803: 
11804:     sub is_library {
11805: 	&load_hosts_tab() if (!$loaded);
11806: 
11807: 	return exists($libserv{$_[0]});
11808:     }
11809: 
11810:     sub all_library {
11811: 	&load_hosts_tab() if (!$loaded);
11812: 
11813: 	return %libserv;
11814:     }
11815: 
11816:     sub unique_library {
11817: 	#2x reverse removes all hostnames that appear more than once
11818:         my %unique = reverse &all_library();
11819:         return reverse %unique;
11820:     }
11821: 
11822:     sub get_servers {
11823: 	&load_hosts_tab() if (!$loaded);
11824: 
11825: 	my ($domain,$type) = @_;
11826: 	my %possible_hosts = ($type eq 'library') ? %libserv
11827: 	                                          : %hostname;
11828: 	my %result;
11829: 	if (ref($domain) eq 'ARRAY') {
11830: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11831: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11832: 		    $result{$host} = $hostname;
11833: 		}
11834: 	    }
11835: 	} else {
11836: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11837: 		if ($hostdom{$host} eq $domain) {
11838: 		    $result{$host} = $hostname;
11839: 		}
11840: 	    }
11841: 	}
11842: 	return %result;
11843:     }
11844: 
11845:     sub get_unique_servers {
11846:         my %unique = reverse &get_servers(@_);
11847: 	return reverse %unique;
11848:     }
11849: 
11850:     sub host_domain {
11851: 	&load_hosts_tab() if (!$loaded);
11852: 
11853: 	my ($lonid) = @_;
11854: 	return $hostdom{$lonid};
11855:     }
11856: 
11857:     sub all_domains {
11858: 	&load_hosts_tab() if (!$loaded);
11859: 
11860: 	my %seen;
11861: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11862: 	return @uniq;
11863:     }
11864: 
11865:     sub internet_dom {
11866:         &load_hosts_tab() if (!$loaded);
11867: 
11868:         my ($lonid) = @_;
11869:         return $internetdom{$lonid};
11870:     }
11871: 
11872:     sub is_LC_dns {
11873:         &load_hosts_tab() if (!$loaded);
11874: 
11875:         my ($hostname) = @_;
11876:         return exists($LC_dns_serv{$hostname});
11877:     }
11878: 
11879: }
11880: 
11881: { 
11882:     my %iphost;
11883:     my %name_to_ip;
11884:     my %lonid_to_ip;
11885: 
11886:     sub get_hosts_from_ip {
11887: 	my ($ip) = @_;
11888: 	my %iphosts = &get_iphost();
11889: 	if (ref($iphosts{$ip})) {
11890: 	    return @{$iphosts{$ip}};
11891: 	}
11892: 	return;
11893:     }
11894:     
11895:     sub reset_hosts_ip_info {
11896: 	undef(%iphost);
11897: 	undef(%name_to_ip);
11898: 	undef(%lonid_to_ip);
11899:     }
11900: 
11901:     sub get_host_ip {
11902: 	my ($lonid) = @_;
11903: 	if (exists($lonid_to_ip{$lonid})) {
11904: 	    return $lonid_to_ip{$lonid};
11905: 	}
11906: 	my $name=&hostname($lonid);
11907:    	my $ip = gethostbyname($name);
11908: 	return if (!$ip || length($ip) ne 4);
11909: 	$ip=inet_ntoa($ip);
11910: 	$name_to_ip{$name}   = $ip;
11911: 	$lonid_to_ip{$lonid} = $ip;
11912: 	return $ip;
11913:     }
11914:     
11915:     sub get_iphost {
11916: 	my ($ignore_cache) = @_;
11917: 
11918: 	if (!$ignore_cache) {
11919: 	    if (%iphost) {
11920: 		return %iphost;
11921: 	    }
11922: 	    my ($ip_info,$cached)=
11923: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11924: 	    if ($cached) {
11925: 		%iphost      = %{$ip_info->[0]};
11926: 		%name_to_ip  = %{$ip_info->[1]};
11927: 		%lonid_to_ip = %{$ip_info->[2]};
11928: 		return %iphost;
11929: 	    }
11930: 	}
11931: 
11932: 	# get yesterday's info for fallback
11933: 	my %old_name_to_ip;
11934: 	my ($ip_info,$cached)=
11935: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11936: 	if ($cached) {
11937: 	    %old_name_to_ip = %{$ip_info->[1]};
11938: 	}
11939: 
11940: 	my %name_to_host = &all_names();
11941: 	foreach my $name (keys(%name_to_host)) {
11942: 	    my $ip;
11943: 	    if (!exists($name_to_ip{$name})) {
11944: 		$ip = gethostbyname($name);
11945: 		if (!$ip || length($ip) ne 4) {
11946: 		    if (defined($old_name_to_ip{$name})) {
11947: 			$ip = $old_name_to_ip{$name};
11948: 			&logthis("Can't find $name defaulting to old $ip");
11949: 		    } else {
11950: 			&logthis("Name $name no IP found");
11951: 			next;
11952: 		    }
11953: 		} else {
11954: 		    $ip=inet_ntoa($ip);
11955: 		}
11956: 		$name_to_ip{$name} = $ip;
11957: 	    } else {
11958: 		$ip = $name_to_ip{$name};
11959: 	    }
11960: 	    foreach my $id (@{ $name_to_host{$name} }) {
11961: 		$lonid_to_ip{$id} = $ip;
11962: 	    }
11963: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11964: 	}
11965: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11966: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11967: 				      48*60*60);
11968: 
11969: 	return %iphost;
11970:     }
11971: 
11972:     #
11973:     #  Given a DNS returns the loncapa host name for that DNS 
11974:     # 
11975:     sub host_from_dns {
11976:         my ($dns) = @_;
11977:         my @hosts;
11978:         my $ip;
11979: 
11980:         if (exists($name_to_ip{$dns})) {
11981:             $ip = $name_to_ip{$dns};
11982:         }
11983:         if (!$ip) {
11984:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11985:             if (length($ip) == 4) { 
11986: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11987:             }
11988:         }
11989:         if ($ip) {
11990: 	    @hosts = get_hosts_from_ip($ip);
11991: 	    return $hosts[0];
11992:         }
11993:         return undef;
11994:     }
11995: 
11996:     sub get_internet_names {
11997:         my ($lonid) = @_;
11998:         return if ($lonid eq '');
11999:         my ($idnref,$cached)=
12000:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12001:         if ($cached) {
12002:             return $idnref;
12003:         }
12004:         my $ip = &get_host_ip($lonid);
12005:         my @hosts = &get_hosts_from_ip($ip);
12006:         my %iphost = &get_iphost();
12007:         my (@idns,%seen);
12008:         foreach my $id (@hosts) {
12009:             my $dom = &host_domain($id);
12010:             my $prim_id = &domain($dom,'primary');
12011:             my $prim_ip = &get_host_ip($prim_id);
12012:             next if ($seen{$prim_ip});
12013:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12014:                 foreach my $id (@{$iphost{$prim_ip}}) {
12015:                     my $intdom = &internet_dom($id);
12016:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12017:                         push(@idns,$intdom);
12018:                     }
12019:                 }
12020:             }
12021:             $seen{$prim_ip} = 1;
12022:         }
12023:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12024:     }
12025: 
12026: }
12027: 
12028: sub all_loncaparevs {
12029:     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);
12030: }
12031: 
12032: BEGIN {
12033: 
12034: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12035:     unless ($readit) {
12036: {
12037:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12038:     %perlvar = (%perlvar,%{$configvars});
12039: }
12040: 
12041: 
12042: # ------------------------------------------------------ Read spare server file
12043: {
12044:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12045: 
12046:     while (my $configline=<$config>) {
12047:        chomp($configline);
12048:        if ($configline) {
12049: 	   my ($host,$type) = split(':',$configline,2);
12050: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12051: 	   push(@{ $spareid{$type} }, $host);
12052:        }
12053:     }
12054:     close($config);
12055: }
12056: # ------------------------------------------------------------ Read permissions
12057: {
12058:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12059: 
12060:     while (my $configline=<$config>) {
12061: 	chomp($configline);
12062: 	if ($configline) {
12063: 	    my ($role,$perm)=split(/ /,$configline);
12064: 	    if ($perm ne '') { $pr{$role}=$perm; }
12065: 	}
12066:     }
12067:     close($config);
12068: }
12069: 
12070: # -------------------------------------------- Read plain texts for permissions
12071: {
12072:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12073: 
12074:     while (my $configline=<$config>) {
12075: 	chomp($configline);
12076: 	if ($configline) {
12077: 	    my ($short,@plain)=split(/:/,$configline);
12078:             %{$prp{$short}} = ();
12079: 	    if (@plain > 0) {
12080:                 $prp{$short}{'std'} = $plain[0];
12081:                 for (my $i=1; $i<@plain; $i++) {
12082:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12083:                 }
12084:             }
12085: 	}
12086:     }
12087:     close($config);
12088: }
12089: 
12090: # ---------------------------------------------------------- Read package table
12091: {
12092:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12093: 
12094:     while (my $configline=<$config>) {
12095: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12096: 	chomp($configline);
12097: 	my ($short,$plain)=split(/:/,$configline);
12098: 	my ($pack,$name)=split(/\&/,$short);
12099: 	if ($plain ne '') {
12100: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12101: 	    $packagetab{$short}=$plain; 
12102: 	}
12103:     }
12104:     close($config);
12105: }
12106: 
12107: # ---------------------------------------------------------- Read loncaparev table
12108: {
12109:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12110:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12111:             while (my $configline=<$config>) {
12112:                 chomp($configline);
12113:                 my ($hostid,$loncaparev)=split(/:/,$configline);
12114:                 $loncaparevs{$hostid}=$loncaparev;
12115:             }
12116:             close($config);
12117:         }
12118:     }
12119: }
12120: 
12121: # ---------------------------------------------------------- Read serverhostID table
12122: {
12123:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12124:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12125:             while (my $configline=<$config>) {
12126:                 chomp($configline);
12127:                 my ($name,$id)=split(/:/,$configline);
12128:                 $serverhomeIDs{$name}=$id;
12129:             }
12130:             close($config);
12131:         }
12132:     }
12133: }
12134: 
12135: {
12136:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12137:     if (-e $file) {
12138:         my $parser = HTML::LCParser->new($file);
12139:         while (my $token = $parser->get_token()) {
12140:             if ($token->[0] eq 'S') {
12141:                 my $item = $token->[1];
12142:                 my $name = $token->[2]{'name'};
12143:                 my $value = $token->[2]{'value'};
12144:                 if ($item ne '' && $name ne '' && $value ne '') {
12145:                     my $release = $parser->get_text();
12146:                     $release =~ s/(^\s*|\s*$ )//gx;
12147:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12148:                 }
12149:             }
12150:         }
12151:     }
12152: }
12153: 
12154: # ---------------------------------------------------------- Read managers table
12155: {
12156:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12157:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12158:             while (my $configline=<$config>) {
12159:                 chomp($configline);
12160:                 next if ($configline =~ /^\#/);
12161:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12162:                     $managerstab{$configline} = 1;
12163:                 }
12164:             }
12165:             close($config);
12166:         }
12167:     }
12168: }
12169: 
12170: # ------------- set up temporary directory
12171: {
12172:     $tmpdir = LONCAPA::tempdir();
12173: 
12174: }
12175: 
12176: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12177: 				'compress_threshold'=> 20_000,
12178:  			        });
12179: 
12180: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12181: $dumpcount=0;
12182: $locknum=0;
12183: 
12184: &logtouch();
12185: &logthis('<font color="yellow">INFO: Read configuration</font>');
12186: $readit=1;
12187:     {
12188: 	use integer;
12189: 	my $test=(2**32)+1;
12190: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12191: 	&logthis(" Detected 64bit platform ($_64bit)");
12192:     }
12193: }
12194: }
12195: 
12196: 1;
12197: __END__
12198: 
12199: =pod
12200: 
12201: =head1 NAME
12202: 
12203: Apache::lonnet - Subroutines to ask questions about things in the network.
12204: 
12205: =head1 SYNOPSIS
12206: 
12207: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12208: 
12209:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12210: 
12211: Common parameters:
12212: 
12213: =over 4
12214: 
12215: =item *
12216: 
12217: $uname : an internal username (if $cname expecting a course Id specifically)
12218: 
12219: =item *
12220: 
12221: $udom : a domain (if $cdom expecting a course's domain specifically)
12222: 
12223: =item *
12224: 
12225: $symb : a resource instance identifier
12226: 
12227: =item *
12228: 
12229: $namespace : the name of a .db file that contains the data needed or
12230: being set.
12231: 
12232: =back
12233: 
12234: =head1 OVERVIEW
12235: 
12236: lonnet provides subroutines which interact with the
12237: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12238: about classes, users, and resources.
12239: 
12240: For many of these objects you can also use this to store data about
12241: them or modify them in various ways.
12242: 
12243: =head2 Symbs
12244: 
12245: To identify a specific instance of a resource, LON-CAPA uses symbols
12246: or "symbs"X<symb>. These identifiers are built from the URL of the
12247: map, the resource number of the resource in the map, and the URL of
12248: the resource itself. The latter is somewhat redundant, but might help
12249: if maps change.
12250: 
12251: An example is
12252: 
12253:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12254: 
12255: The respective map entry is
12256: 
12257:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12258:   title="Problem 2">
12259:  </resource>
12260: 
12261: Symbs are used by the random number generator, as well as to store and
12262: restore data specific to a certain instance of for example a problem.
12263: 
12264: =head2 Storing And Retrieving Data
12265: 
12266: X<store()>X<cstore()>X<restore()>Three of the most important functions
12267: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12268: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12269: is is the non-critical message twin of cstore. These functions are for
12270: handlers to store a perl hash to a user's permanent data space in an
12271: easy manner, and to retrieve it again on another call. It is expected
12272: that a handler would use this once at the beginning to retrieve data,
12273: and then again once at the end to send only the new data back.
12274: 
12275: The data is stored in the user's data directory on the user's
12276: homeserver under the ID of the course.
12277: 
12278: The hash that is returned by restore will have all of the previous
12279: value for all of the elements of the hash.
12280: 
12281: Example:
12282: 
12283:  #creating a hash
12284:  my %hash;
12285:  $hash{'foo'}='bar';
12286: 
12287:  #storing it
12288:  &Apache::lonnet::cstore(\%hash);
12289: 
12290:  #changing a value
12291:  $hash{'foo'}='notbar';
12292: 
12293:  #adding a new value
12294:  $hash{'bar'}='foo';
12295:  &Apache::lonnet::cstore(\%hash);
12296: 
12297:  #retrieving the hash
12298:  my %history=&Apache::lonnet::restore();
12299: 
12300:  #print the hash
12301:  foreach my $key (sort(keys(%history))) {
12302:    print("\%history{$key} = $history{$key}");
12303:  }
12304: 
12305: Will print out:
12306: 
12307:  %history{1:foo} = bar
12308:  %history{1:keys} = foo:timestamp
12309:  %history{1:timestamp} = 990455579
12310:  %history{2:bar} = foo
12311:  %history{2:foo} = notbar
12312:  %history{2:keys} = foo:bar:timestamp
12313:  %history{2:timestamp} = 990455580
12314:  %history{bar} = foo
12315:  %history{foo} = notbar
12316:  %history{timestamp} = 990455580
12317:  %history{version} = 2
12318: 
12319: Note that the special hash entries C<keys>, C<version> and
12320: C<timestamp> were added to the hash. C<version> will be equal to the
12321: total number of versions of the data that have been stored. The
12322: C<timestamp> attribute will be the UNIX time the hash was
12323: stored. C<keys> is available in every historical section to list which
12324: keys were added or changed at a specific historical revision of a
12325: hash.
12326: 
12327: B<Warning>: do not store the hash that restore returns directly. This
12328: will cause a mess since it will restore the historical keys as if the
12329: were new keys. I.E. 1:foo will become 1:1:foo etc.
12330: 
12331: Calling convention:
12332: 
12333:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
12334:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
12335: 
12336: For more detailed information, see lonnet specific documentation.
12337: 
12338: =head1 RETURN MESSAGES
12339: 
12340: =over 4
12341: 
12342: =item * B<con_lost>: unable to contact remote host
12343: 
12344: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12345: when the connection is brought back up
12346: 
12347: =item * B<con_failed>: unable to contact remote host and unable to save message
12348: for later delivery
12349: 
12350: =item * B<error:>: an error a occurred, a description of the error follows the :
12351: 
12352: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12353: that was requested
12354: 
12355: =back
12356: 
12357: =head1 PUBLIC SUBROUTINES
12358: 
12359: =head2 Session Environment Functions
12360: 
12361: =over 4
12362: 
12363: =item * 
12364: X<appenv()>
12365: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12366: the user envirnoment file, and will be restored for each access this
12367: user makes during this session, also modifies the %env for the current
12368: process. Optional rolesarrayref - if defined contains a reference to an array
12369: of roles which are exempt from the restriction on modifying user.role entries 
12370: in the user's environment.db and in %env.    
12371: 
12372: =item *
12373: X<delenv()>
12374: B<delenv($delthis,$regexp)>: removes all items from the session
12375: environment file that begin with $delthis. If the 
12376: optional second arg - $regexp - is true, $delthis is treated as a 
12377: regular expression, otherwise \Q$delthis\E is used. 
12378: The values are also deleted from the current processes %env.
12379: 
12380: =item * get_env_multiple($name) 
12381: 
12382: gets $name from the %env hash, it seemlessly handles the cases where multiple
12383: values may be defined and end up as an array ref.
12384: 
12385: returns an array of values
12386: 
12387: =back
12388: 
12389: =head2 User Information
12390: 
12391: =over 4
12392: 
12393: =item *
12394: X<queryauthenticate()>
12395: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12396: authentication scheme
12397: 
12398: =item *
12399: X<authenticate()>
12400: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12401: authenticate user from domain's lib servers (first use the current
12402: one). C<$upass> should be the users password.
12403: $checkdefauth is optional (value is 1 if a check should be made to
12404:    authenticate user using default authentication method, and allow
12405:    account creation if username does not have account in the domain).
12406: $clientcancheckhost is optional (value is 1 if checking whether the
12407:    server can host will occur on the client side in lonauth.pm).   
12408: 
12409: =item *
12410: X<homeserver()>
12411: B<homeserver($uname,$udom)>: find the server which has
12412: the user's directory and files (there must be only one), this caches
12413: the answer, and also caches if there is a borken connection.
12414: 
12415: =item *
12416: X<idget()>
12417: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12418: (IDs are a unique resource in a domain, there must be only 1 ID per
12419: username, and only 1 username per ID in a specific domain) (returns
12420: hash: id=>name,id=>name)
12421: 
12422: =item *
12423: X<idrget()>
12424: B<idrget($udom,@unames)>: find the IDs behind a list of
12425: usernames (returns hash: name=>id,name=>id)
12426: 
12427: =item *
12428: X<idput()>
12429: B<idput($udom,%ids)>: store away a list of names and associated IDs
12430: 
12431: =item *
12432: X<rolesinit()>
12433: B<rolesinit($udom,$username)>: get user privileges.
12434: returns user role, first access and timer interval hashes
12435: 
12436: =item *
12437: X<privileged()>
12438: B<privileged($username,$domain)>: returns a true if user has a
12439: privileged and active role (i.e. su or dc), false otherwise.
12440: 
12441: =item *
12442: X<getsection()>
12443: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12444: course $cname, return section name/number or '' for "not in course"
12445: and '-1' for "no section"
12446: 
12447: =item *
12448: X<userenvironment()>
12449: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12450: passed in @what from the requested user's environment, returns a hash
12451: 
12452: =item * 
12453: X<userlog_query()>
12454: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12455: activity.log file. %filters defines filters applied when parsing the
12456: log file. These can be start or end timestamps, or the type of action
12457: - log to look for Login or Logout events, check for Checkin or
12458: Checkout, role for role selection. The response is in the form
12459: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12460: escaped strings of the action recorded in the activity.log file.
12461: 
12462: =back
12463: 
12464: =head2 User Roles
12465: 
12466: =over 4
12467: 
12468: =item *
12469: 
12470: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12471:  F: full access
12472:  U,I,K: authentication modes (cxx only)
12473:  '': forbidden
12474:  1: user needs to choose course
12475:  2: browse allowed
12476:  A: passphrase authentication needed
12477: 
12478: =item *
12479: 
12480: constructaccess($url,$setpriv) : check for access to construction space URL
12481: 
12482: See if the owner domain and name in the URL match those in the
12483: expected environment.  If so, return three element list
12484: ($ownername,$ownerdomain,$ownerhome).
12485: 
12486: Otherwise return the null string.
12487: 
12488: If second argument 'setpriv' is true, it assigns the privileges,
12489: and returns the same three element list, unless the owner has
12490: blocked "ad hoc" Domain Coordinator access to the Author Space,
12491: in which case the null string is returned.
12492: 
12493: =item *
12494: 
12495: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12496: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12497: and course level
12498: 
12499: =item *
12500: 
12501: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12502: (rolesplain.tab); plain text explanation of a user role term.
12503: $type is Course (default) or Community.
12504: If $forcedefault evaluates to true, text returned will be default 
12505: text for $type. Otherwise, if this is a course, the text returned 
12506: will be a custom name for the role (if defined in the course's 
12507: environment).  If no custom name is defined the default is returned.
12508:    
12509: =item *
12510: 
12511: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
12512: All arguments are optional. Returns a hash of a roles, either for
12513: co-author/assistant author roles for a user's Construction Space
12514: (default), or if $context is 'userroles', roles for the user himself,
12515: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12516: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12517: For each key, value is set to colon-separated start and end times for
12518: the role.  If no username and domain are specified, will default to
12519: current user/domain. Types, roles, and roledoms are references to arrays
12520: of role statuses (active, future or previous), roles 
12521: (e.g., cc,in, st etc.) and domains of the roles which can be used
12522: to restrict the list of roles reported. If no array ref is 
12523: provided for types, will default to return only active roles.
12524: 
12525: =item *
12526: 
12527: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12528: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12529: 
12530: Additional optional arguments are: $type (if role checking is to be restricted 
12531: to certain user status types -- previous (expired roles), active (currently
12532: available roles) or future (roles available in the future), and
12533: $hideprivileged -- if true will not report course roles for users who
12534: have active Domain Coordinator or Super User roles.
12535: 
12536: =back
12537: 
12538: =head2 User Modification
12539: 
12540: =over 4
12541: 
12542: =item *
12543: 
12544: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12545: user for the level given by URL.  Optional start and end dates (leave empty
12546: string or zero for "no date")
12547: 
12548: =item *
12549: 
12550: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12551: change a users, password, possible return values are: ok,
12552: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12553: refused
12554: 
12555: =item *
12556: 
12557: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12558: 
12559: =item *
12560: 
12561: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12562:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12563: 
12564: will update user information (firstname,middlename,lastname,generation,
12565: permanentemail), and if forceid is true, student/employee ID also.
12566: A user's institutional affiliation(s) can also be updated.
12567: User information fields will not be overwritten with empty entries 
12568: unless the field is included in the $candelete array reference.
12569: This array is included when a single user is modified via "Manage Users",
12570: or when Autoupdate.pl is run by cron in a domain.
12571: 
12572: =item *
12573: 
12574: modifystudent
12575: 
12576: modify a student's enrollment and identification information.
12577: The course id is resolved based on the current users environment.  
12578: This means the envoking user must be a course coordinator or otherwise
12579: associated with a course.
12580: 
12581: This call is essentially a wrapper for lonnet::modifyuser and
12582: lonnet::modify_student_enrollment
12583: 
12584: Inputs: 
12585: 
12586: =over 4
12587: 
12588: =item B<$udom> Student's loncapa domain
12589: 
12590: =item B<$uname> Student's loncapa login name
12591: 
12592: =item B<$uid> Student/Employee ID
12593: 
12594: =item B<$umode> Student's authentication mode
12595: 
12596: =item B<$upass> Student's password
12597: 
12598: =item B<$first> Student's first name
12599: 
12600: =item B<$middle> Student's middle name
12601: 
12602: =item B<$last> Student's last name
12603: 
12604: =item B<$gene> Student's generation
12605: 
12606: =item B<$usec> Student's section in course
12607: 
12608: =item B<$end> Unix time of the roles expiration
12609: 
12610: =item B<$start> Unix time of the roles start date
12611: 
12612: =item B<$forceid> If defined, allow $uid to be changed
12613: 
12614: =item B<$desiredhome> server to use as home server for student
12615: 
12616: =item B<$email> Student's permanent e-mail address
12617: 
12618: =item B<$type> Type of enrollment (auto or manual)
12619: 
12620: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12621: 
12622: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12623: 
12624: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12625: 
12626: =item B<$context> role change context (shown in User Management Logs display in a course)
12627: 
12628: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
12629: 
12630: =back
12631: 
12632: =item *
12633: 
12634: modify_student_enrollment
12635: 
12636: Change a students enrollment status in a class.  The environment variable
12637: 'role.request.course' must be defined for this function to proceed.
12638: 
12639: Inputs:
12640: 
12641: =over 4
12642: 
12643: =item $udom, students domain
12644: 
12645: =item $uname, students name
12646: 
12647: =item $uid, students user id
12648: 
12649: =item $first, students first name
12650: 
12651: =item $middle
12652: 
12653: =item $last
12654: 
12655: =item $gene
12656: 
12657: =item $usec
12658: 
12659: =item $end
12660: 
12661: =item $start
12662: 
12663: =item $type
12664: 
12665: =item $locktype
12666: 
12667: =item $cid
12668: 
12669: =item $selfenroll
12670: 
12671: =item $context
12672: 
12673: =back
12674: 
12675: 
12676: =item *
12677: 
12678: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12679: custom role; give a custom role to a user for the level given by URL.  Specify
12680: name and domain of role author, and role name
12681: 
12682: =item *
12683: 
12684: revokerole($udom,$uname,$url,$role) : revoke a role for url
12685: 
12686: =item *
12687: 
12688: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12689: 
12690: =back
12691: 
12692: =head2 Course Infomation
12693: 
12694: =over 4
12695: 
12696: =item *
12697: 
12698: coursedescription($courseid,$options) : returns a hash of information about the
12699: specified course id, including all environment settings for the
12700: course, the description of the course will be in the hash under the
12701: key 'description'
12702: 
12703: $options is an optional parameter that if supplied is a hash reference that controls
12704: what how this function works.  It has the following key/values:
12705: 
12706: =over 4
12707: 
12708: =item freshen_cache
12709: 
12710: If defined, and the environment cache for the course is valid, it is 
12711: returned in the returned hash.
12712: 
12713: =item one_time
12714: 
12715: If defined, the last cache time is set to _now_
12716: 
12717: =item user
12718: 
12719: If defined, the supplied username is used instead of the current user.
12720: 
12721: 
12722: =back
12723: 
12724: =item *
12725: 
12726: resdata($name,$domain,$type,@which) : request for current parameter
12727: setting for a specific $type, where $type is either 'course' or 'user',
12728: @what should be a list of parameters to ask about. This routine caches
12729: answers for 5 minutes.
12730: 
12731: =item *
12732: 
12733: get_courseresdata($courseid, $domain) : dump the entire course resource
12734: data base, returning a hash that is keyed by the resource name and has
12735: values that are the resource value.  I believe that the timestamps and
12736: versions are also returned.
12737: 
12738: =back
12739: 
12740: =head2 Course Modification
12741: 
12742: =over 4
12743: 
12744: =item *
12745: 
12746: writecoursepref($courseid,%prefs) : write preferences (environment
12747: database) for a course
12748: 
12749: =item *
12750: 
12751: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12752: 
12753: =item *
12754: 
12755: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12756: 
12757: =item *
12758: 
12759: is_course($courseid), is_course($cdom, $cnum)
12760: 
12761: Accepts either a combined $courseid (in the form of domain_courseid) or the
12762: two component version $cdom, $cnum. It checks if the specified course exists.
12763: 
12764: Returns:
12765:     undef if the course doesn't exist, otherwise
12766:     in scalar context the combined courseid.
12767:     in list context the two components of the course identifier, domain and 
12768:     courseid.    
12769: 
12770: =back
12771: 
12772: =head2 Resource Subroutines
12773: 
12774: =over 4
12775: 
12776: =item *
12777: 
12778: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12779: 
12780: =item *
12781: 
12782: repcopy($filename) : subscribes to the requested file, and attempts to
12783: replicate from the owning library server, Might return
12784: 'unavailable', 'not_found', 'forbidden', 'ok', or
12785: 'bad_request', also attempts to grab the metadata for the
12786: resource. Expects the local filesystem pathname
12787: (/home/httpd/html/res/....)
12788: 
12789: =back
12790: 
12791: =head2 Resource Information
12792: 
12793: =over 4
12794: 
12795: =item *
12796: 
12797: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12798: a vairety of different possible values, $varname should be a request
12799: string, and the other parameters can be used to specify who and what
12800: one is asking about.
12801: 
12802: Possible values for $varname are environment.lastname (or other item
12803: from the envirnment hash), user.name (or someother aspect about the
12804: user), resource.0.maxtries (or some other part and parameter of a
12805: resource)
12806: 
12807: =item *
12808: 
12809: directcondval($number) : get current value of a condition; reads from a state
12810: string
12811: 
12812: =item *
12813: 
12814: condval($condidx) : value of condition index based on state
12815: 
12816: =item *
12817: 
12818: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12819: resource's metadata, $what should be either a specific key, or either
12820: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12821: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12822: 
12823: this function automatically caches all requests
12824: 
12825: =item *
12826: 
12827: metadata_query($query,$custom,$customshow) : make a metadata query against the
12828: network of library servers; returns file handle of where SQL and regex results
12829: will be stored for query
12830: 
12831: =item *
12832: 
12833: symbread($filename) : return symbolic list entry (filename argument optional);
12834: returns the data handle
12835: 
12836: =item *
12837: 
12838: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12839: and is a possible symb for the URL in $thisfn, and if is an encrypted
12840: resource that the user accessed using /enc/ returns a 1 on success, 0
12841: on failure, user must be in a course, as it assumes the existence of
12842: the course initial hash, and uses $env('request.course.id'}.  The third
12843: arg is an optional reference to a scalar.  If this arg is passed in the 
12844: call to symbverify, it will be set to 1 if the symb has been set to be 
12845: encrypted; otherwise it will be null.  
12846: 
12847: =item *
12848: 
12849: symbclean($symb) : removes versions numbers from a symb, returns the
12850: cleaned symb
12851: 
12852: =item *
12853: 
12854: is_on_map($uri) : checks if the $uri is somewhere on the current
12855: course map, user must be in a course for it to work.
12856: 
12857: =item *
12858: 
12859: numval($salt) : return random seed value (addend for rndseed)
12860: 
12861: =item *
12862: 
12863: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12864: a random seed, all arguments are optional, if they aren't sent it uses the
12865: environment to derive them. Note: if symb isn't sent and it can't get one
12866: from &symbread it will use the current time as its return value
12867: 
12868: =item *
12869: 
12870: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12871: unfakeable, receipt
12872: 
12873: =item *
12874: 
12875: receipt() : API to ireceipt working off of env values; given out to users
12876: 
12877: =item *
12878: 
12879: countacc($url) : count the number of accesses to a given URL
12880: 
12881: =item *
12882: 
12883: 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
12884: 
12885: =item *
12886: 
12887: 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)
12888: 
12889: =item *
12890: 
12891: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12892: 
12893: =item *
12894: 
12895: devalidate($symb) : devalidate temporary spreadsheet calculations,
12896: forcing spreadsheet to reevaluate the resource scores next time.
12897: 
12898: =item * 
12899: 
12900: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
12901: when viewing in course context.
12902: 
12903:  input: six args -- filename (decluttered), course number, course domain,
12904:                     url, symb (if registered) and group (if this is a 
12905:                     group item -- e.g., bulletin board, group page etc.).
12906: 
12907:  output: array of five scalars --
12908:          $cfile -- url for file editing if editable on current server
12909:          $home -- homeserver of resource (i.e., for author if published,
12910:                                           or course if uploaded.).
12911:          $switchserver --  1 if server switch will be needed.
12912:          $forceedit -- 1 if icon/link should be to go to edit mode 
12913:          $forceview -- 1 if icon/link should be to go to view mode
12914: 
12915: =item *
12916: 
12917: is_course_upload($file,$cnum,$cdom)
12918: 
12919: Used in course context to determine if current file was uploaded to 
12920: the course (i.e., would be found in /userfiles/docs on the course's 
12921: homeserver.
12922: 
12923:   input: 3 args -- filename (decluttered), course number and course domain.
12924:   output: boolean -- 1 if file was uploaded.
12925: 
12926: =back
12927: 
12928: =head2 Storing/Retreiving Data
12929: 
12930: =over 4
12931: 
12932: =item *
12933: 
12934: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12935: for this url; hashref needs to be given and should be a \%hashname; the
12936: remaining args aren't required and if they aren't passed or are '' they will
12937: be derived from the env
12938: 
12939: =item *
12940: 
12941: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12942: uses critical subroutine
12943: 
12944: =item *
12945: 
12946: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12947: all args are optional
12948: 
12949: =item *
12950: 
12951: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12952: dumps the complete (or key matching regexp) namespace into a hash
12953: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12954: normally &store()ed into
12955: 
12956: $range should be either an integer '100' (give me the first 100
12957:                                            matching records)
12958:               or be  two integers sperated by a - with no spaces
12959:                  '30-50' (give me the 30th through the 50th matching
12960:                           records)
12961: 
12962: 
12963: =item *
12964: 
12965: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12966: replaces a &store() version of data with a replacement set of data
12967: for a particular resource in a namespace passed in the $storehash hash 
12968: reference
12969: 
12970: =item *
12971: 
12972: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12973: works very similar to store/cstore, but all data is stored in a
12974: temporary location and can be reset using tmpreset, $storehash should
12975: be a hash reference, returns nothing on success
12976: 
12977: =item *
12978: 
12979: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12980: similar to restore, but all data is stored in a temporary location and
12981: can be reset using tmpreset. Returns a hash of values on success,
12982: error string otherwise.
12983: 
12984: =item *
12985: 
12986: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12987: deltes all keys for $symb form the temporary storage hash.
12988: 
12989: =item *
12990: 
12991: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12992: reference filled in from namesp ($udom and $uname are optional)
12993: 
12994: =item *
12995: 
12996: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12997: namesp ($udom and $uname are optional)
12998: 
12999: =item *
13000: 
13001: dump($namespace,$udom,$uname,$regexp,$range) : 
13002: dumps the complete (or key matching regexp) namespace into a hash
13003: ($udom, $uname, $regexp, $range are optional)
13004: 
13005: $range should be either an integer '100' (give me the first 100
13006:                                            matching records)
13007:               or be  two integers sperated by a - with no spaces
13008:                  '30-50' (give me the 30th through the 50th matching
13009:                           records)
13010: =item *
13011: 
13012: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13013: $store can be a scalar, an array reference, or if the amount to be 
13014: incremented is > 1, a hash reference.
13015: 
13016: ($udom and $uname are optional)
13017: 
13018: =item *
13019: 
13020: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13021: ($udom and $uname are optional)
13022: 
13023: =item *
13024: 
13025: cput($namespace,$storehash,$udom,$uname) : critical put
13026: ($udom and $uname are optional)
13027: 
13028: =item *
13029: 
13030: newput($namespace,$storehash,$udom,$uname) :
13031: 
13032: Attempts to store the items in the $storehash, but only if they don't
13033: currently exist, if this succeeds you can be certain that you have 
13034: successfully created a new key value pair in the $namespace db.
13035: 
13036: 
13037: Args:
13038:  $namespace: name of database to store values to
13039:  $storehash: hashref to store to the db
13040:  $udom: (optional) domain of user containing the db
13041:  $uname: (optional) name of user caontaining the db
13042: 
13043: Returns:
13044:  'ok' -> succeeded in storing all keys of $storehash
13045:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13046:                         least <key> already existed in the db (other
13047:                         requested keys may also already exist)
13048:  'error: <msg>' -> unable to tie the DB or other error occurred
13049:  'con_lost' -> unable to contact request server
13050:  'refused' -> action was not allowed by remote machine
13051: 
13052: 
13053: =item *
13054: 
13055: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13056: reference filled in from namesp (encrypts the return communication)
13057: ($udom and $uname are optional)
13058: 
13059: =item *
13060: 
13061: log($udom,$name,$home,$message) : write to permanent log for user; use
13062: critical subroutine
13063: 
13064: =item *
13065: 
13066: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13067: array reference filled in from namespace found in domain level on either
13068: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13069: 
13070: =item *
13071: 
13072: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13073: domain level either on specified domain server ($uhome) or primary domain 
13074: server ($udom and $uhome are optional)
13075: 
13076: =item * 
13077: 
13078: get_domain_defaults($target_domain) : returns hash with defaults for
13079: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
13080: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
13081: or localauth), initial password or a kerberos realm, language (e.g., en-us).
13082: Values are retrieved from cache (if current), or from domain's configuration.db
13083: (if available), or lastly from values in lonTabs/dns_domain,tab, 
13084: or lonTabs/domain.tab. 
13085: 
13086: %domdefaults = &get_auth_defaults($target_domain);
13087: 
13088: =back
13089: 
13090: =head2 Network Status Functions
13091: 
13092: =over 4
13093: 
13094: =item *
13095: 
13096: dirlist() : return directory list based on URI (first arg).
13097: 
13098: Inputs: 1 required, 5 optional.
13099: 
13100: =over
13101: 
13102: =item 
13103: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13104: 
13105: =item
13106: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13107: 
13108: =item
13109: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13110: 
13111: =item
13112: $getpropath - boolean: 1 if prepend path using &propath(). 
13113: 
13114: =item
13115: $getuserdir - boolean: 1 if prepend path for "userfiles".
13116: 
13117: =item 
13118: $alternateRoot - path to prepend in place of path from $uri.
13119: 
13120: =back
13121: 
13122: Returns: Array of up to two items.
13123: 
13124: =over
13125: 
13126: a reference to an array of files/subdirectories
13127: 
13128: =over
13129: 
13130: Each element in the array of files/subdirectories is a & separated list of
13131: item name and the result of running stat on the item.  If dirlist was requested
13132: for a file instead of a directory, the item name will be ''. For a directory 
13133: listing, if the item is a metadata file, the element will end &N&M 
13134: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13135: default copyright set (1).  
13136: 
13137: =back
13138: 
13139: a scalar containing error condition (if encountered).
13140: 
13141: =over
13142: 
13143: =item 
13144: no_host (no homeserver identified for $username:$domain).
13145: 
13146: =item 
13147: no_such_host (server contacted for listing not identified as valid host).
13148: 
13149: =item 
13150: con_lost (connection to remote server failed).
13151: 
13152: =item 
13153: refused (invalid $username:$domain received on lond side).
13154: 
13155: =item 
13156: no_such_dir (directory at specified path on lond side does not exist). 
13157: 
13158: =item 
13159: empty (directory at specified path on lond side is empty).
13160: 
13161: =over
13162: 
13163: This is currently not encountered because the &ls3, &ls2, 
13164: &ls (_handler) routines on the lond side do not filter out
13165: . and .. from a directory listing. 
13166: 
13167: =back
13168: 
13169: =back
13170: 
13171: =back
13172: 
13173: =item *
13174: 
13175: spareserver() : find server with least workload from spare.tab
13176: 
13177: 
13178: =item *
13179: 
13180: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13181: if there is no corresponding loncapa host.
13182: 
13183: =back
13184: 
13185: 
13186: =head2 Apache Request
13187: 
13188: =over 4
13189: 
13190: =item *
13191: 
13192: ssi($url,%hash) : server side include, does a complete request cycle on url to
13193: localhost, posts hash
13194: 
13195: =back
13196: 
13197: =head2 Data to String to Data
13198: 
13199: =over 4
13200: 
13201: =item *
13202: 
13203: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13204: and '&' separators, supports elements that are arrayrefs and hashrefs
13205: 
13206: =item *
13207: 
13208: hashref2str($hashref) : convert a hashref into a string complete with
13209: escaping and '=' and '&' separators, supports elements that are
13210: arrayrefs and hashrefs
13211: 
13212: =item *
13213: 
13214: arrayref2str($arrayref) : convert an arrayref into a string complete
13215: with escaping and '&' separators, supports elements that are arrayrefs
13216: and hashrefs
13217: 
13218: =item *
13219: 
13220: str2hash($string) : convert string to hash using unescaping and
13221: splitting on '=' and '&', supports elements that are arrayrefs and
13222: hashrefs
13223: 
13224: =item *
13225: 
13226: str2array($string) : convert string to hash using unescaping and
13227: splitting on '&', supports elements that are arrayrefs and hashrefs
13228: 
13229: =back
13230: 
13231: =head2 Logging Routines
13232: 
13233: 
13234: These routines allow one to make log messages in the lonnet.log and
13235: lonnet.perm logfiles.
13236: 
13237: =over 4
13238: 
13239: =item *
13240: 
13241: logtouch() : make sure the logfile, lonnet.log, exists
13242: 
13243: =item *
13244: 
13245: logthis() : append message to the normal lonnet.log file, it gets
13246: preiodically rolled over and deleted.
13247: 
13248: =item *
13249: 
13250: logperm() : append a permanent message to lonnet.perm.log, this log
13251: file never gets deleted by any automated portion of the system, only
13252: messages of critical importance should go in here.
13253: 
13254: 
13255: =back
13256: 
13257: =head2 General File Helper Routines
13258: 
13259: =over 4
13260: 
13261: =item *
13262: 
13263: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13264: (a) files in /uploaded
13265:   (i) If a local copy of the file exists - 
13266:       compares modification date of local copy with last-modified date for 
13267:       definitive version stored on home server for course. If local copy is 
13268:       stale, requests a new version from the home server and stores it. 
13269:       If the original has been removed from the home server, then local copy 
13270:       is unlinked.
13271:   (ii) If local copy does not exist -
13272:       requests the file from the home server and stores it. 
13273:   
13274:   If $caller is 'uploadrep':  
13275:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13276:     for request for files originally uploaded via DOCS. 
13277:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13278:   
13279:   Otherwise:
13280:      This indicates a call from the content generation phase of the request.
13281:      -  returns the entire contents of the file or -1.
13282:      
13283: (b) files in /res
13284:    - returns the entire contents of a file or -1; 
13285:    it properly subscribes to and replicates the file if neccessary.
13286: 
13287: 
13288: =item *
13289: 
13290: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13291:                   reference
13292: 
13293: returns either a stat() list of data about the file or an empty list
13294: if the file doesn't exist or couldn't find out about it (connection
13295: problems or user unknown)
13296: 
13297: =item *
13298: 
13299: filelocation($dir,$file) : returns file system location of a file
13300: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13301: directory that relative $file lookups are to looked in ($dir of /a/dir
13302: and a file of ../bob will become /a/bob)
13303: 
13304: =item *
13305: 
13306: hreflocation($dir,$file) : returns file system location or a URL; same as
13307: filelocation except for hrefs
13308: 
13309: =item *
13310: 
13311: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13312: 
13313: =back
13314: 
13315: =head2 Usererfile file routines (/uploaded*)
13316: 
13317: =over 4
13318: 
13319: =item *
13320: 
13321: userfileupload(): main rotine for putting a file in a user or course's
13322:                   filespace, arguments are,
13323: 
13324:  formname - required - this is the name of the element in $env where the
13325:            filename, and the contents of the file to create/modifed exist
13326:            the filename is in $env{'form.'.$formname.'.filename'} and the
13327:            contents of the file is located in $env{'form.'.$formname}
13328:  context - if coursedoc, store the file in the course of the active role
13329:              of the current user; 
13330:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13331:            if 'canceloverwrite': delete file in tmp/overwrites directory
13332:  subdir - required - subdirectory to put the file in under ../userfiles/
13333:          if undefined, it will be placed in "unknown"
13334: 
13335:  (This routine calls clean_filename() to remove any dangerous
13336:  characters from the filename, and then calls finuserfileupload() to
13337:  complete the transaction)
13338: 
13339:  returns either the url of the uploaded file (/uploaded/....) if successful
13340:  and /adm/notfound.html if unsuccessful
13341: 
13342: =item *
13343: 
13344: clean_filename(): routine for cleaing a filename up for storage in
13345:                  userfile space, argument is:
13346: 
13347:  filename - proposed filename
13348: 
13349: returns: the new clean filename
13350: 
13351: =item *
13352: 
13353: finishuserfileupload(): routine that creates and sends the file to
13354: userspace, probably shouldn't be called directly
13355: 
13356:   docuname: username or courseid of destination for the file
13357:   docudom: domain of user/course of destination for the file
13358:   formname: same as for userfileupload()
13359:   fname: filename (including subdirectories) for the file
13360:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13361:   allfiles: reference to hash used to store objects found by parser
13362:   codebase: reference to hash used for codebases of java objects found by parser
13363:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13364:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13365:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13366:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13367:   context: if 'overwrite', will move the uploaded file from its temporary location to
13368:             userfiles to facilitate overwriting a previously uploaded file with same name.
13369:   mimetype: reference to scalar to accommodate mime type determined
13370:             from File::MMagic if $parser = parse.
13371: 
13372:  returns either the url of the uploaded file (/uploaded/....) if successful
13373:  and /adm/notfound.html if unsuccessful (or an error message if context 
13374:  was 'overwrite').
13375:  
13376: 
13377: =item *
13378: 
13379: renameuserfile(): renames an existing userfile to a new name
13380: 
13381:   Args:
13382:    docuname: username or courseid of destination for the file
13383:    docudom: domain of user/course of destination for the file
13384:    old: current file name (including any subdirs under userfiles)
13385:    new: desired file name (including any subdirs under userfiles)
13386: 
13387: =item *
13388: 
13389: mkdiruserfile(): creates a directory is a userfiles dir
13390: 
13391:   Args:
13392:    docuname: username or courseid of destination for the file
13393:    docudom: domain of user/course of destination for the file
13394:    dir: dir to create (including any subdirs under userfiles)
13395: 
13396: =item *
13397: 
13398: removeuserfile(): removes a file that exists in userfiles
13399: 
13400:   Args:
13401:    docuname: username or courseid of destination for the file
13402:    docudom: domain of user/course of destination for the file
13403:    fname: filname to delete (including any subdirs under userfiles)
13404: 
13405: =item *
13406: 
13407: removeuploadedurl(): convience function for removeuserfile()
13408: 
13409:   Args:
13410:    url:  a full /uploaded/... url to delete
13411: 
13412: =item * 
13413: 
13414: get_portfile_permissions():
13415:   Args:
13416:     domain: domain of user or course contain the portfolio files
13417:     user: name of user or num of course contain the portfolio files
13418:   Returns:
13419:     hashref of a dump of the proper file_permissions.db
13420:    
13421: 
13422: =item * 
13423: 
13424: get_access_controls():
13425: 
13426: Args:
13427:   current_permissions: the hash ref returned from get_portfile_permissions()
13428:   group: (optional) the group you want the files associated with
13429:   file: (optional) the file you want access info on
13430: 
13431: Returns:
13432:     a hash (keys are file names) of hashes containing
13433:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13434:         values are XML containing access control settings (see below) 
13435: 
13436: Internal notes:
13437: 
13438:  access controls are stored in file_permissions.db as key=value pairs.
13439:     key -> path to file/file_name\0uniqueID:scope_end_start
13440:         where scope -> public,guest,course,group,domains or users.
13441:               end -> UNIX time for end of access (0 -> no end date)
13442:               start -> UNIX time for start of access
13443: 
13444:     value -> XML description of access control
13445:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13446:             <start></start>
13447:             <end></end>
13448: 
13449:             <password></password>  for scope type = guest
13450: 
13451:             <domain></domain>     for scope type = course or group
13452:             <number></number>
13453:             <roles id="">
13454:              <role></role>
13455:              <access></access>
13456:              <section></section>
13457:              <group></group>
13458:             </roles>
13459: 
13460:             <dom></dom>         for scope type = domains
13461: 
13462:             <users>             for scope type = users
13463:              <user>
13464:               <uname></uname>
13465:               <udom></udom>
13466:              </user>
13467:             </users>
13468:            </scope> 
13469:               
13470:  Access data is also aggregated for each file in an additional key=value pair:
13471:  key -> path to file/file_name\0accesscontrol 
13472:  value -> reference to hash
13473:           hash contains key = value pairs
13474:           where key = uniqueID:scope_end_start
13475:                 value = UNIX time record was last updated
13476: 
13477:           Used to improve speed of look-ups of access controls for each file.  
13478:  
13479:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13480: 
13481: =item *
13482: 
13483: modify_access_controls():
13484: 
13485: Modifies access controls for a portfolio file
13486: Args
13487: 1. file name
13488: 2. reference to hash of required changes,
13489: 3. domain
13490: 4. username
13491:   where domain,username are the domain of the portfolio owner 
13492:   (either a user or a course) 
13493: 
13494: Returns:
13495: 1. result of additions or updates ('ok' or 'error', with error message). 
13496: 2. result of deletions ('ok' or 'error', with error message).
13497: 3. reference to hash of any new or updated access controls.
13498: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13499:    key = integer (inbound ID)
13500:    value = uniqueID
13501: 
13502: =item *
13503: 
13504: get_timebased_id():
13505: 
13506: Attempts to get a unique timestamp-based suffix for use with items added to a 
13507: course via the Course Editor (e.g., folders, composite pages, 
13508: group bulletin boards).
13509: 
13510: Args: (first three required; six others optional)
13511: 
13512: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13513:    docssequence, or name of group
13514: 
13515: 2. keyid (alphanumeric): name of temporary locking key in hash,
13516:    e.g., num, boardids
13517: 
13518: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13519:    file will be named nohist_namespace.db
13520: 
13521: 4. cdom: domain of course; default is current course domain from %env
13522: 
13523: 5. cnum: course number; default is current course number from %env
13524: 
13525: 6. idtype: set to concat if an additional digit is to be appended to the 
13526:    unix timestamp to form the suffix, if the plain timestamp is already
13527:    in use.  Default is to not do this, but simply increment the unix 
13528:    timestamp by 1 until a unique key is obtained.
13529: 
13530: 7. who: holder of locking key; defaults to user:domain for user.
13531: 
13532: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13533:    retrying); default is 3.
13534: 
13535: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13536: 
13537: Returns:
13538: 
13539: 1. suffix obtained (numeric)
13540: 
13541: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13542: 
13543: 3. error: contains (localized) error message if an error occurred.
13544: 
13545: 
13546: =back
13547: 
13548: =head2 HTTP Helper Routines
13549: 
13550: =over 4
13551: 
13552: =item *
13553: 
13554: escape() : unpack non-word characters into CGI-compatible hex codes
13555: 
13556: =item *
13557: 
13558: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13559: 
13560: =back
13561: 
13562: =head1 PRIVATE SUBROUTINES
13563: 
13564: =head2 Underlying communication routines (Shouldn't call)
13565: 
13566: =over 4
13567: 
13568: =item *
13569: 
13570: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13571: 
13572: =item *
13573: 
13574: reply() : uses subreply to send a message to remote machine, logs all failures
13575: 
13576: =item *
13577: 
13578: critical() : passes a critical message to another server; if cannot
13579: get through then place message in connection buffer directory and
13580: returns con_delayed, if incapable of saving message, returns
13581: con_failed
13582: 
13583: =item *
13584: 
13585: reconlonc() : tries to reconnect lonc client processes.
13586: 
13587: =back
13588: 
13589: =head2 Resource Access Logging
13590: 
13591: =over 4
13592: 
13593: =item *
13594: 
13595: flushcourselogs() : flush (save) buffer logs and access logs
13596: 
13597: =item *
13598: 
13599: courselog($what) : save message for course in hash
13600: 
13601: =item *
13602: 
13603: courseacclog($what) : save message for course using &courselog().  Perform
13604: special processing for specific resource types (problems, exams, quizzes, etc).
13605: 
13606: =item *
13607: 
13608: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13609: as a PerlChildExitHandler
13610: 
13611: =back
13612: 
13613: =head2 Other
13614: 
13615: =over 4
13616: 
13617: =item *
13618: 
13619: symblist($mapname,%newhash) : update symbolic storage links
13620: 
13621: =back
13622: 
13623: =cut
13624: 

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