File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1215: download - view: text, annotated - select for diffs
Thu Feb 14 16:52:11 2013 UTC (11 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- DC's selection of temporary adhoc role does not need to be preserved in
  nohist_userroles.db.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1215 2013/02/14 16:52:11 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
   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:     if (($r->user() eq '') && ($apache >= 2.4)) {
  638:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
  639:             $r->user($disk_env{'user.name'});
  640:         } else {
  641:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
  642:         }
  643:     }
  644:     return $handle;
  645: }
  646: 
  647: sub timed_flock {
  648:     my ($file,$lock_type) = @_;
  649:     my $failed=0;
  650:     eval {
  651: 	local $SIG{__DIE__}='DEFAULT';
  652: 	local $SIG{ALRM}=sub {
  653: 	    $failed=1;
  654: 	    die("failed lock");
  655: 	};
  656: 	alarm(13);
  657: 	flock($file,$lock_type);
  658: 	alarm(0);
  659:     };
  660:     if ($failed) {
  661: 	return undef;
  662:     } else {
  663: 	return 1;
  664:     }
  665: }
  666: 
  667: # ---------------------------------------------------------- Append Environment
  668: 
  669: sub appenv {
  670:     my ($newenv,$roles) = @_;
  671:     if (ref($newenv) eq 'HASH') {
  672:         foreach my $key (keys(%{$newenv})) {
  673:             my $refused = 0;
  674: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  675:                 $refused = 1;
  676:                 if (ref($roles) eq 'ARRAY') {
  677:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  678:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  679:                         $refused = 0;
  680:                     }
  681:                 }
  682:             }
  683:             if ($refused) {
  684:                 &logthis("<font color=\"blue\">WARNING: ".
  685:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  686:                          .'</font>');
  687: 	        delete($newenv->{$key});
  688:             } else {
  689:                 $env{$key}=$newenv->{$key};
  690:             }
  691:         }
  692:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  693:         if ($opened
  694: 	    && &timed_flock($env_file,LOCK_EX)
  695: 	    &&
  696: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  697: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  698: 	    while (my ($key,$value) = each(%{$newenv})) {
  699: 	        $disk_env{$key} = $value;
  700: 	    }
  701: 	    untie(%disk_env);
  702:         }
  703:     }
  704:     return 'ok';
  705: }
  706: # ----------------------------------------------------- Delete from Environment
  707: 
  708: sub delenv {
  709:     my ($delthis,$regexp,$roles) = @_;
  710:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  711:         my $refused = 1;
  712:         if (ref($roles) eq 'ARRAY') {
  713:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  714:             if (grep(/^\Q$role\E$/,@{$roles})) {
  715:                 $refused = 0;
  716:             }
  717:         }
  718:         if ($refused) {
  719:             &logthis("<font color=\"blue\">WARNING: ".
  720:                      "Attempt to delete from environment ".$delthis);
  721:             return 'error';
  722:         }
  723:     }
  724:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  725:     if ($opened
  726: 	&& &timed_flock($env_file,LOCK_EX)
  727: 	&&
  728: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  729: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  730: 	foreach my $key (keys(%disk_env)) {
  731: 	    if ($regexp) {
  732:                 if ($key=~/^$delthis/) {
  733:                     delete($env{$key});
  734:                     delete($disk_env{$key});
  735:                 } 
  736:             } else {
  737:                 if ($key=~/^\Q$delthis\E/) {
  738: 		    delete($env{$key});
  739: 		    delete($disk_env{$key});
  740: 	        }
  741:             }
  742: 	}
  743: 	untie(%disk_env);
  744:     }
  745:     return 'ok';
  746: }
  747: 
  748: sub get_env_multiple {
  749:     my ($name) = @_;
  750:     my @values;
  751:     if (defined($env{$name})) {
  752:         # exists is it an array
  753:         if (ref($env{$name})) {
  754:             @values=@{ $env{$name} };
  755:         } else {
  756:             $values[0]=$env{$name};
  757:         }
  758:     }
  759:     return(@values);
  760: }
  761: 
  762: # ------------------------------------------------------------------- Locking
  763: 
  764: sub set_lock {
  765:     my ($text)=@_;
  766:     $locknum++;
  767:     my $id=$$.'-'.$locknum;
  768:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  769:              'session.lock.'.$id => $text});
  770:     return $id;
  771: }
  772: 
  773: sub get_locks {
  774:     my $num=0;
  775:     my %texts=();
  776:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  777:        if ($lock=~/\w/) {
  778:           $num++;
  779:           $texts{$lock}=$env{'session.lock.'.$lock};
  780:        }
  781:    }
  782:    return ($num,%texts);
  783: }
  784: 
  785: sub remove_lock {
  786:     my ($id)=@_;
  787:     my $newlocks='';
  788:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  789:        if (($lock=~/\w/) && ($lock ne $id)) {
  790:           $newlocks.=','.$lock;
  791:        }
  792:     }
  793:     &appenv({'session.locks' => $newlocks});
  794:     &delenv('session.lock.'.$id);
  795: }
  796: 
  797: sub remove_all_locks {
  798:     my $activelocks=$env{'session.locks'};
  799:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  800:        if ($lock=~/\w/) {
  801:           &remove_lock($lock);
  802:        }
  803:     }
  804: }
  805: 
  806: 
  807: # ------------------------------------------ Find out current server userload
  808: sub userload {
  809:     my $numusers=0;
  810:     {
  811: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  812: 	my $filename;
  813: 	my $curtime=time;
  814: 	while ($filename=readdir(LONIDS)) {
  815: 	    next if ($filename eq '.' || $filename eq '..');
  816: 	    next if ($filename =~ /publicuser_\d+\.id/);
  817: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  818: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  819: 	}
  820: 	closedir(LONIDS);
  821:     }
  822:     my $userloadpercent=0;
  823:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  824:     if ($maxuserload) {
  825: 	$userloadpercent=100*$numusers/$maxuserload;
  826:     }
  827:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  828:     return $userloadpercent;
  829: }
  830: 
  831: # ------------------------------ Find server with least workload from spare.tab
  832: 
  833: sub spareserver {
  834:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  835:     my $spare_server;
  836:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  837:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  838:                                                      :  $userloadpercent;
  839:     my ($uint_dom,$remotesessions);
  840:     if (($udom ne '') && (&domain($udom) ne '')) {
  841:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  842:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  843:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  844:         $remotesessions = $udomdefaults{'remotesessions'};
  845:     }
  846:     my $spareshash = &this_host_spares($udom);
  847:     if (ref($spareshash) eq 'HASH') {
  848:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  849:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  850:                 if ($uint_dom) {
  851:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  852:                                                  $try_server));
  853:                 }
  854: 	        ($spare_server, $lowest_load) =
  855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  856:             }
  857:         }
  858: 
  859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  860: 
  861:         if (!$found_server) {
  862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  864:                     if ($uint_dom) {
  865:                         next unless (&spare_can_host($udom,$uint_dom,
  866:                                                      $remotesessions,$try_server));
  867:                     }
  868: 	            ($spare_server, $lowest_load) =
  869: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  870:                 }
  871: 	    }
  872:         }
  873:     }
  874: 
  875:     if (!$want_server_name) {
  876:         my $protocol = 'http';
  877:         if ($protocol{$spare_server} eq 'https') {
  878:             $protocol = $protocol{$spare_server};
  879:         }
  880:         if (defined($spare_server)) {
  881:             my $hostname = &hostname($spare_server);
  882:             if (defined($hostname)) {
  883: 	        $spare_server = $protocol.'://'.$hostname;
  884:             }
  885:         }
  886:     }
  887:     return $spare_server;
  888: }
  889: 
  890: sub compare_server_load {
  891:     my ($try_server, $spare_server, $lowest_load) = @_;
  892: 
  893:     my $loadans     = &reply('load',    $try_server);
  894:     my $userloadans = &reply('userload',$try_server);
  895: 
  896:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  897: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  898:     }
  899: 
  900:     my $load;
  901:     if ($loadans =~ /\d/) {
  902: 	if ($userloadans =~ /\d/) {
  903: 	    #both are numbers, pick the bigger one
  904: 	    $load = ($loadans > $userloadans) ? $loadans 
  905: 		                              : $userloadans;
  906: 	} else {
  907: 	    $load = $loadans;
  908: 	}
  909:     } else {
  910: 	$load = $userloadans;
  911:     }
  912: 
  913:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  914: 	$spare_server = $try_server;
  915: 	$lowest_load  = $load;
  916:     }
  917:     return ($spare_server,$lowest_load);
  918: }
  919: 
  920: # --------------------------- ask offload servers if user already has a session
  921: sub find_existing_session {
  922:     my ($udom,$uname) = @_;
  923:     my $spareshash = &this_host_spares($udom);
  924:     if (ref($spareshash) eq 'HASH') {
  925:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  926:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  927:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  928:             }
  929:         }
  930:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  931:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  932:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  933:             }
  934:         }
  935:     }
  936:     return;
  937: }
  938: 
  939: # -------------------------------- ask if server already has a session for user
  940: sub has_user_session {
  941:     my ($lonid,$udom,$uname) = @_;
  942:     my $result = &reply(join(':','userhassession',
  943: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  944:     return 1 if ($result eq 'ok');
  945: 
  946:     return 0;
  947: }
  948: 
  949: # --------- determine least loaded server in a user's domain which allows login
  950: 
  951: sub choose_server {
  952:     my ($udom,$checkloginvia) = @_;
  953:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  954:     my %servers = &get_servers($udom);
  955:     my $lowest_load = 30000;
  956:     my ($login_host,$hostname,$portal_path,$isredirect);
  957:     foreach my $lonhost (keys(%servers)) {
  958:         my $loginvia;
  959:         if ($checkloginvia) {
  960:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  961:             if ($loginvia) {
  962:                 my ($server,$path) = split(/:/,$loginvia);
  963:                 ($login_host, $lowest_load) =
  964:                     &compare_server_load($server, $login_host, $lowest_load);
  965:                 if ($login_host eq $server) {
  966:                     $portal_path = $path;
  967:                     $isredirect = 1;
  968:                 }
  969:             } else {
  970:                 ($login_host, $lowest_load) =
  971:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  972:                 if ($login_host eq $lonhost) {
  973:                     $portal_path = '';
  974:                     $isredirect = ''; 
  975:                 }
  976:             }
  977:         } else {
  978:             ($login_host, $lowest_load) =
  979:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  980:         }
  981:     }
  982:     if ($login_host ne '') {
  983:         $hostname = &hostname($login_host);
  984:     }
  985:     return ($login_host,$hostname,$portal_path,$isredirect);
  986: }
  987: 
  988: # --------------------------------------------- Try to change a user's password
  989: 
  990: sub changepass {
  991:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  992:     $currentpass = &escape($currentpass);
  993:     $newpass     = &escape($newpass);
  994:     my $lonhost = $perlvar{'lonHostID'};
  995:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  996: 		       $server);
  997:     if (! $answer) {
  998: 	&logthis("No reply on password change request to $server ".
  999: 		 "by $uname in domain $udom.");
 1000:     } elsif ($answer =~ "^ok") {
 1001:         &logthis("$uname in $udom successfully changed their password ".
 1002: 		 "on $server.");
 1003:     } elsif ($answer =~ "^pwchange_failure") {
 1004: 	&logthis("$uname in $udom was unable to change their password ".
 1005: 		 "on $server.  The action was blocked by either lcpasswd ".
 1006: 		 "or pwchange");
 1007:     } elsif ($answer =~ "^non_authorized") {
 1008:         &logthis("$uname in $udom did not get their password correct when ".
 1009: 		 "attempting to change it on $server.");
 1010:     } elsif ($answer =~ "^auth_mode_error") {
 1011:         &logthis("$uname in $udom attempted to change their password despite ".
 1012: 		 "not being locally or internally authenticated on $server.");
 1013:     } elsif ($answer =~ "^unknown_user") {
 1014:         &logthis("$uname in $udom attempted to change their password ".
 1015: 		 "on $server but were unable to because $server is not ".
 1016: 		 "their home server.");
 1017:     } elsif ($answer =~ "^refused") {
 1018: 	&logthis("$server refused to change $uname in $udom password because ".
 1019: 		 "it was sent an unencrypted request to change the password.");
 1020:     } elsif ($answer =~ "invalid_client") {
 1021:         &logthis("$server refused to change $uname in $udom password because ".
 1022:                  "it was a reset by e-mail originating from an invalid server.");
 1023:     }
 1024:     return $answer;
 1025: }
 1026: 
 1027: # ----------------------- Try to determine user's current authentication scheme
 1028: 
 1029: sub queryauthenticate {
 1030:     my ($uname,$udom)=@_;
 1031:     my $uhome=&homeserver($uname,$udom);
 1032:     if (!$uhome) {
 1033: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1034: 	return 'no_host';
 1035:     }
 1036:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1037:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1038: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1039:     }
 1040:     return $answer;
 1041: }
 1042: 
 1043: # --------- Try to authenticate user from domain's lib servers (first this one)
 1044: 
 1045: sub authenticate {
 1046:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1047:     $upass=&escape($upass);
 1048:     $uname= &LONCAPA::clean_username($uname);
 1049:     my $uhome=&homeserver($uname,$udom,1);
 1050:     my $newhome;
 1051:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1052: # Maybe the machine was offline and only re-appeared again recently?
 1053:         &reconlonc();
 1054: # One more
 1055: 	$uhome=&homeserver($uname,$udom,1);
 1056:         if (($uhome eq 'no_host') && $checkdefauth) {
 1057:             if (defined(&domain($udom,'primary'))) {
 1058:                 $newhome=&domain($udom,'primary');
 1059:             }
 1060:             if ($newhome ne '') {
 1061:                 $uhome = $newhome;
 1062:             }
 1063:         }
 1064: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1065: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1066: 	    return 'no_host';
 1067:         }
 1068:     }
 1069:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1070:     if ($answer eq 'authorized') {
 1071:         if ($newhome) {
 1072:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1073:             return 'no_account_on_host'; 
 1074:         } else {
 1075:             &logthis("User $uname at $udom authorized by $uhome");
 1076:             return $uhome;
 1077:         }
 1078:     }
 1079:     if ($answer eq 'non_authorized') {
 1080: 	&logthis("User $uname at $udom rejected by $uhome");
 1081: 	return 'no_host'; 
 1082:     }
 1083:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1084:     return 'no_host';
 1085: }
 1086: 
 1087: sub can_host_session {
 1088:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1089:     my $canhost = 1;
 1090:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1091:     if (ref($remotesessions) eq 'HASH') {
 1092:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1094:                 $canhost = 0;
 1095:             } else {
 1096:                 $canhost = 1;
 1097:             }
 1098:         }
 1099:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1100:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1101:                 $canhost = 1;
 1102:             } else {
 1103:                 $canhost = 0;
 1104:             }
 1105:         }
 1106:         if ($canhost) {
 1107:             if ($remotesessions->{'version'} ne '') {
 1108:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1109:                 if ($reqmajor ne '' && $reqminor ne '') {
 1110:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1111:                         my $major = $1;
 1112:                         my $minor = $2;
 1113:                         if (($major < $reqmajor ) ||
 1114:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1115:                             $canhost = 0;
 1116:                         }
 1117:                     } else {
 1118:                         $canhost = 0;
 1119:                     }
 1120:                 }
 1121:             }
 1122:         }
 1123:     }
 1124:     if ($canhost) {
 1125:         if (ref($hostedsessions) eq 'HASH') {
 1126:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1127:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1128:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1129:                 if (($uint_dom ne '') && 
 1130:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1131:                     $canhost = 0;
 1132:                 } else {
 1133:                     $canhost = 1;
 1134:                 }
 1135:             }
 1136:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1137:                 if (($uint_dom ne '') && 
 1138:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1139:                     $canhost = 1;
 1140:                 } else {
 1141:                     $canhost = 0;
 1142:                 }
 1143:             }
 1144:         }
 1145:     }
 1146:     return $canhost;
 1147: }
 1148: 
 1149: sub spare_can_host {
 1150:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1151:     my $canhost=1;
 1152:     my @intdoms;
 1153:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1154:     if (ref($internet_names) eq 'ARRAY') {
 1155:         @intdoms = @{$internet_names};
 1156:     }
 1157:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1158:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1159:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1160:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1161:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1162:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1163:                                      $remotesessions,
 1164:                                      $defdomdefaults{'hostedsessions'});
 1165:     }
 1166:     return $canhost;
 1167: }
 1168: 
 1169: sub this_host_spares {
 1170:     my ($dom) = @_;
 1171:     my ($dom_in_use,$lonhost_in_use,$result);
 1172:     my @hosts = &current_machine_ids();
 1173:     foreach my $lonhost (@hosts) {
 1174:         if (&host_domain($lonhost) eq $dom) {
 1175:             $dom_in_use = $dom;
 1176:             $lonhost_in_use = $lonhost;
 1177:             last;
 1178:         }
 1179:     }
 1180:     if ($dom_in_use ne '') {
 1181:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1182:     }
 1183:     if (ref($result) ne 'HASH') {
 1184:         $lonhost_in_use = $perlvar{'lonHostID'};
 1185:         $dom_in_use = &host_domain($lonhost_in_use);
 1186:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1187:         if (ref($result) ne 'HASH') {
 1188:             $result = \%spareid;
 1189:         }
 1190:     }
 1191:     return $result;
 1192: }
 1193: 
 1194: sub spares_for_offload  {
 1195:     my ($dom_in_use,$lonhost_in_use) = @_;
 1196:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1197:     if (defined($cached)) {
 1198:         return $result;
 1199:     } else {
 1200:         my $cachetime = 60*60*24;
 1201:         my %domconfig =
 1202:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1203:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1204:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1205:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1206:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1207:                 }
 1208:             }
 1209:         }
 1210:     }
 1211:     return;
 1212: }
 1213: 
 1214: sub get_lonbalancer_config {
 1215:     my ($servers) = @_;
 1216:     my ($currbalancer,$currtargets);
 1217:     if (ref($servers) eq 'HASH') {
 1218:         foreach my $server (keys(%{$servers})) {
 1219:             my %what = (
 1220:                          spareid => 1,
 1221:                          perlvar => 1,
 1222:                        );
 1223:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1224:             if ($result eq 'ok') {
 1225:                 if (ref($returnhash) eq 'HASH') {
 1226:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1227:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1228:                             $currbalancer = $server;
 1229:                             $currtargets = {};
 1230:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1231:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1232:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1233:                                 }
 1234:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1235:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1236:                                 }
 1237:                             }
 1238:                             last;
 1239:                         }
 1240:                     }
 1241:                 }
 1242:             }
 1243:         }
 1244:     }
 1245:     return ($currbalancer,$currtargets);
 1246: }
 1247: 
 1248: sub check_loadbalancing {
 1249:     my ($uname,$udom) = @_;
 1250:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1251:         $rule_in_effect,$offloadto,$otherserver);
 1252:     my $lonhost = $perlvar{'lonHostID'};
 1253:     my @hosts = &current_machine_ids();
 1254:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1255:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1256:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1257:     my $serverhomedom = &host_domain($lonhost);
 1258: 
 1259:     my $cachetime = 60*60*24;
 1260: 
 1261:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1262:         $dom_in_use = $udom;
 1263:         $homeintdom = 1;
 1264:     } else {
 1265:         $dom_in_use = $serverhomedom;
 1266:     }
 1267:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1268:     unless (defined($cached)) {
 1269:         my %domconfig =
 1270:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1271:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1272:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1273:         }
 1274:     }
 1275:     if (ref($result) eq 'HASH') {
 1276:         ($is_balancer,$currtargets,$currrules) = 
 1277:             &check_balancer_result($result,@hosts);
 1278:         if ($is_balancer) {
 1279:             if (ref($currrules) eq 'HASH') {
 1280:                 if ($homeintdom) {
 1281:                     if ($uname ne '') {
 1282:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1283:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1284:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1285:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1286:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1287:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1288:                             }
 1289:                         }
 1290:                         if ($rule_in_effect eq '') {
 1291:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1292:                             if ($userenv{'inststatus'} ne '') {
 1293:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1294:                                 my ($othertitle,$usertypes,$types) =
 1295:                                     &Apache::loncommon::sorted_inst_types($udom);
 1296:                                 if (ref($types) eq 'ARRAY') {
 1297:                                     foreach my $type (@{$types}) {
 1298:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1299:                                             if (exists($currrules->{$type})) {
 1300:                                                 $rule_in_effect = $currrules->{$type};
 1301:                                             }
 1302:                                         }
 1303:                                     }
 1304:                                 }
 1305:                             } else {
 1306:                                 if (exists($currrules->{'default'})) {
 1307:                                     $rule_in_effect = $currrules->{'default'};
 1308:                                 }
 1309:                             }
 1310:                         }
 1311:                     } else {
 1312:                         if (exists($currrules->{'default'})) {
 1313:                             $rule_in_effect = $currrules->{'default'};
 1314:                         }
 1315:                     }
 1316:                 } else {
 1317:                     if ($currrules->{'_LC_external'} ne '') {
 1318:                         $rule_in_effect = $currrules->{'_LC_external'};
 1319:                     }
 1320:                 }
 1321:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1322:                                                        $uname,$udom);
 1323:             }
 1324:         }
 1325:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1326:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1327:         unless (defined($cached)) {
 1328:             my %domconfig =
 1329:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1330:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1331:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1332:             }
 1333:         }
 1334:         if (ref($result) eq 'HASH') {
 1335:             ($is_balancer,$currtargets,$currrules) = 
 1336:                 &check_balancer_result($result,@hosts);
 1337:             if ($is_balancer) {
 1338:                 if (ref($currrules) eq 'HASH') {
 1339:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1340:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1341:                     }
 1342:                 }
 1343:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1344:                                                        $uname,$udom);
 1345:             }
 1346:         } else {
 1347:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1348:                 $is_balancer = 1;
 1349:                 $offloadto = &this_host_spares($dom_in_use);
 1350:             }
 1351:         }
 1352:     } else {
 1353:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1354:             $is_balancer = 1;
 1355:             $offloadto = &this_host_spares($dom_in_use);
 1356:         }
 1357:     }
 1358:     if ($is_balancer) {
 1359:         my $lowest_load = 30000;
 1360:         if (ref($offloadto) eq 'HASH') {
 1361:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1362:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1363:                     ($otherserver,$lowest_load) =
 1364:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1365:                 }
 1366:             }
 1367:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1368: 
 1369:             if (!$found_server) {
 1370:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1371:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1372:                         ($otherserver,$lowest_load) =
 1373:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1374:                     }
 1375:                 }
 1376:             }
 1377:         } elsif (ref($offloadto) eq 'ARRAY') {
 1378:             if (@{$offloadto} == 1) {
 1379:                 $otherserver = $offloadto->[0];
 1380:             } elsif (@{$offloadto} > 1) {
 1381:                 foreach my $try_server (@{$offloadto}) {
 1382:                     ($otherserver,$lowest_load) =
 1383:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1384:                 }
 1385:             }
 1386:         }
 1387:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1388:             $is_balancer = 0;
 1389:             if ($uname ne '' && $udom ne '') {
 1390:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1391:                     
 1392:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1393:                              'user.loadbalcheck.time' => time});
 1394:                 }
 1395:             }
 1396:         }
 1397:     }
 1398:     return ($is_balancer,$otherserver);
 1399: }
 1400: 
 1401: sub check_balancer_result {
 1402:     my ($result,@hosts) = @_;
 1403:     my ($is_balancer,$currtargets,$currrules);
 1404:     if (ref($result) eq 'HASH') {
 1405:         if ($result->{'lonhost'} ne '') {
 1406:             my $currbalancer = $result->{'lonhost'};
 1407:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1408:                 $is_balancer = 1;
 1409:                 $currtargets = $result->{'targets'};
 1410:                 $currrules = $result->{'rules'};
 1411:             }
 1412:         } else {
 1413:             foreach my $key (keys(%{$result})) {
 1414:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1415:                     (ref($result->{$key}) eq 'HASH')) {
 1416:                     $is_balancer = 1;
 1417:                     $currrules = $result->{$key}{'rules'};
 1418:                     $currtargets = $result->{$key}{'targets'};
 1419:                     last;
 1420:                 }
 1421:             }
 1422:         }
 1423:     }
 1424:     return ($is_balancer,$currtargets,$currrules);
 1425: }
 1426: 
 1427: sub get_loadbalancer_targets {
 1428:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1429:     my $offloadto;
 1430:     if ($rule_in_effect eq 'none') {
 1431:         return [$perlvar{'lonHostID'}];
 1432:     } elsif ($rule_in_effect eq '') {
 1433:         $offloadto = $currtargets;
 1434:     } else {
 1435:         if ($rule_in_effect eq 'homeserver') {
 1436:             my $homeserver = &homeserver($uname,$udom);
 1437:             if ($homeserver ne 'no_host') {
 1438:                 $offloadto = [$homeserver];
 1439:             }
 1440:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1441:             my %domconfig =
 1442:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1443:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1444:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1445:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1446:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1447:                     }
 1448:                 }
 1449:             } else {
 1450:                 my %servers = &internet_dom_servers($udom);
 1451:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1452:                 if (&hostname($remotebalancer) ne '') {
 1453:                     $offloadto = [$remotebalancer];
 1454:                 }
 1455:             }
 1456:         } elsif (&hostname($rule_in_effect) ne '') {
 1457:             $offloadto = [$rule_in_effect];
 1458:         }
 1459:     }
 1460:     return $offloadto;
 1461: }
 1462: 
 1463: sub internet_dom_servers {
 1464:     my ($dom) = @_;
 1465:     my (%uniqservers,%servers);
 1466:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1467:     my @machinedoms = &machine_domains($primaryserver);
 1468:     foreach my $mdom (@machinedoms) {
 1469:         my %currservers = %servers;
 1470:         my %server = &get_servers($mdom);
 1471:         %servers = (%currservers,%server);
 1472:     }
 1473:     my %by_hostname;
 1474:     foreach my $id (keys(%servers)) {
 1475:         push(@{$by_hostname{$servers{$id}}},$id);
 1476:     }
 1477:     foreach my $hostname (sort(keys(%by_hostname))) {
 1478:         if (@{$by_hostname{$hostname}} > 1) {
 1479:             my $match = 0;
 1480:             foreach my $id (@{$by_hostname{$hostname}}) {
 1481:                 if (&host_domain($id) eq $dom) {
 1482:                     $uniqservers{$id} = $hostname;
 1483:                     $match = 1;
 1484:                 }
 1485:             }
 1486:             unless ($match) {
 1487:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1488:             }
 1489:         } else {
 1490:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1491:         }
 1492:     }
 1493:     return %uniqservers;
 1494: }
 1495: 
 1496: # ---------------------- Find the homebase for a user from domain's lib servers
 1497: 
 1498: my %homecache;
 1499: sub homeserver {
 1500:     my ($uname,$udom,$ignoreBadCache)=@_;
 1501:     my $index="$uname:$udom";
 1502: 
 1503:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1504: 
 1505:     my %servers = &get_servers($udom,'library');
 1506:     foreach my $tryserver (keys(%servers)) {
 1507:         next if ($ignoreBadCache ne 'true' && 
 1508: 		 exists($badServerCache{$tryserver}));
 1509: 
 1510: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1511: 	if ($answer eq 'found') {
 1512: 	    delete($badServerCache{$tryserver}); 
 1513: 	    return $homecache{$index}=$tryserver;
 1514: 	} elsif ($answer eq 'no_host') {
 1515: 	    $badServerCache{$tryserver}=1;
 1516: 	}
 1517:     }    
 1518:     return 'no_host';
 1519: }
 1520: 
 1521: # ------------------------------------- Find the usernames behind a list of IDs
 1522: 
 1523: sub idget {
 1524:     my ($udom,@ids)=@_;
 1525:     my %returnhash=();
 1526:     
 1527:     my %servers = &get_servers($udom,'library');
 1528:     foreach my $tryserver (keys(%servers)) {
 1529: 	my $idlist=join('&',@ids);
 1530: 	$idlist=~tr/A-Z/a-z/; 
 1531: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1532: 	my @answer=();
 1533: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1534: 	    @answer=split(/\&/,$reply);
 1535: 	}                    ;
 1536: 	my $i;
 1537: 	for ($i=0;$i<=$#ids;$i++) {
 1538: 	    if ($answer[$i]) {
 1539: 		$returnhash{$ids[$i]}=$answer[$i];
 1540: 	    } 
 1541: 	}
 1542:     } 
 1543:     return %returnhash;
 1544: }
 1545: 
 1546: # ------------------------------------- Find the IDs behind a list of usernames
 1547: 
 1548: sub idrget {
 1549:     my ($udom,@unames)=@_;
 1550:     my %returnhash=();
 1551:     foreach my $uname (@unames) {
 1552:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1553:     }
 1554:     return %returnhash;
 1555: }
 1556: 
 1557: # ------------------------------- Store away a list of names and associated IDs
 1558: 
 1559: sub idput {
 1560:     my ($udom,%ids)=@_;
 1561:     my %servers=();
 1562:     foreach my $uname (keys(%ids)) {
 1563: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1564:         my $uhom=&homeserver($uname,$udom);
 1565:         if ($uhom ne 'no_host') {
 1566:             my $id=&escape($ids{$uname});
 1567:             $id=~tr/A-Z/a-z/;
 1568:             my $esc_unam=&escape($uname);
 1569: 	    if ($servers{$uhom}) {
 1570: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1571:             } else {
 1572:                 $servers{$uhom}=$id.'='.$esc_unam;
 1573:             }
 1574:         }
 1575:     }
 1576:     foreach my $server (keys(%servers)) {
 1577:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1578:     }
 1579: }
 1580: 
 1581: # ------------------------------dump from db file owned by domainconfig user
 1582: sub dump_dom {
 1583:     my ($namespace, $udom, $regexp) = @_;
 1584: 
 1585:     $udom ||= $env{'user.domain'};
 1586: 
 1587:     return () unless $udom;
 1588: 
 1589:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1590: }
 1591: 
 1592: # ------------------------------------------ get items from domain db files   
 1593: 
 1594: sub get_dom {
 1595:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1596:     my $items='';
 1597:     foreach my $item (@$storearr) {
 1598:         $items.=&escape($item).'&';
 1599:     }
 1600:     $items=~s/\&$//;
 1601:     if (!$udom) {
 1602:         $udom=$env{'user.domain'};
 1603:         if (defined(&domain($udom,'primary'))) {
 1604:             $uhome=&domain($udom,'primary');
 1605:         } else {
 1606:             undef($uhome);
 1607:         }
 1608:     } else {
 1609:         if (!$uhome) {
 1610:             if (defined(&domain($udom,'primary'))) {
 1611:                 $uhome=&domain($udom,'primary');
 1612:             }
 1613:         }
 1614:     }
 1615:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1616:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1617:         my %returnhash;
 1618:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1619:             return %returnhash;
 1620:         }
 1621:         my @pairs=split(/\&/,$rep);
 1622:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1623:             return @pairs;
 1624:         }
 1625:         my $i=0;
 1626:         foreach my $item (@$storearr) {
 1627:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1628:             $i++;
 1629:         }
 1630:         return %returnhash;
 1631:     } else {
 1632:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1633:     }
 1634: }
 1635: 
 1636: # -------------------------------------------- put items in domain db files 
 1637: 
 1638: sub put_dom {
 1639:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1640:     if (!$udom) {
 1641:         $udom=$env{'user.domain'};
 1642:         if (defined(&domain($udom,'primary'))) {
 1643:             $uhome=&domain($udom,'primary');
 1644:         } else {
 1645:             undef($uhome);
 1646:         }
 1647:     } else {
 1648:         if (!$uhome) {
 1649:             if (defined(&domain($udom,'primary'))) {
 1650:                 $uhome=&domain($udom,'primary');
 1651:             }
 1652:         }
 1653:     } 
 1654:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1655:         my $items='';
 1656:         foreach my $item (keys(%$storehash)) {
 1657:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1658:         }
 1659:         $items=~s/\&$//;
 1660:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1661:     } else {
 1662:         &logthis("put_dom failed - no homeserver and/or domain");
 1663:     }
 1664: }
 1665: 
 1666: # --------------------- newput for items in db file owned by domainconfig user
 1667: sub newput_dom {
 1668:     my ($namespace,$storehash,$udom) = @_;
 1669:     my $result;
 1670:     if (!$udom) {
 1671:         $udom=$env{'user.domain'};
 1672:     }
 1673:     if ($udom) {
 1674:         my $uname = &get_domainconfiguser($udom);
 1675:         $result = &newput($namespace,$storehash,$udom,$uname);
 1676:     }
 1677:     return $result;
 1678: }
 1679: 
 1680: # --------------------- delete for items in db file owned by domainconfig user
 1681: sub del_dom {
 1682:     my ($namespace,$storearr,$udom)=@_;
 1683:     if (ref($storearr) eq 'ARRAY') {
 1684:         if (!$udom) {
 1685:             $udom=$env{'user.domain'};
 1686:         }
 1687:         if ($udom) {
 1688:             my $uname = &get_domainconfiguser($udom); 
 1689:             return &del($namespace,$storearr,$udom,$uname);
 1690:         }
 1691:     }
 1692: }
 1693: 
 1694: # ----------------------------------construct domainconfig user for a domain 
 1695: sub get_domainconfiguser {
 1696:     my ($udom) = @_;
 1697:     return $udom.'-domainconfig';
 1698: }
 1699: 
 1700: sub retrieve_inst_usertypes {
 1701:     my ($udom) = @_;
 1702:     my (%returnhash,@order);
 1703:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1704:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1705:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1706:         %returnhash = %{$domdefs{'inststatustypes'}};
 1707:         @order = @{$domdefs{'inststatusorder'}};
 1708:     } else {
 1709:         if (defined(&domain($udom,'primary'))) {
 1710:             my $uhome=&domain($udom,'primary');
 1711:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1712:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1713:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1714:                 return (\%returnhash,\@order);
 1715:             }
 1716:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1717:             my @pairs=split(/\&/,$hashitems);
 1718:             foreach my $item (@pairs) {
 1719:                 my ($key,$value)=split(/=/,$item,2);
 1720:                 $key = &unescape($key);
 1721:                 next if ($key =~ /^error: 2 /);
 1722:                 $returnhash{$key}=&thaw_unescape($value);
 1723:             }
 1724:             my @esc_order = split(/\&/,$orderitems);
 1725:             foreach my $item (@esc_order) {
 1726:                 push(@order,&unescape($item));
 1727:             }
 1728:         } else {
 1729:             &logthis("get_dom failed - no primary domain server for $udom");
 1730:         }
 1731:     }
 1732:     return (\%returnhash,\@order);
 1733: }
 1734: 
 1735: sub is_domainimage {
 1736:     my ($url) = @_;
 1737:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1738:         if (&domain($1) ne '') {
 1739:             return '1';
 1740:         }
 1741:     }
 1742:     return;
 1743: }
 1744: 
 1745: sub inst_directory_query {
 1746:     my ($srch) = @_;
 1747:     my $udom = $srch->{'srchdomain'};
 1748:     my %results;
 1749:     my $homeserver = &domain($udom,'primary');
 1750:     my $outcome;
 1751:     if ($homeserver ne '') {
 1752: 	my $queryid=&reply("querysend:instdirsearch:".
 1753: 			   &escape($srch->{'srchby'}).':'.
 1754: 			   &escape($srch->{'srchterm'}).':'.
 1755: 			   &escape($srch->{'srchtype'}),$homeserver);
 1756: 	my $host=&hostname($homeserver);
 1757: 	if ($queryid !~/^\Q$host\E\_/) {
 1758: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1759: 	    return;
 1760: 	}
 1761: 	my $response = &get_query_reply($queryid);
 1762: 	my $maxtries = 5;
 1763: 	my $tries = 1;
 1764: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1765: 	    $response = &get_query_reply($queryid);
 1766: 	    $tries ++;
 1767: 	}
 1768: 
 1769:         if (!&error($response) && $response ne 'refused') {
 1770:             if ($response eq 'unavailable') {
 1771:                 $outcome = $response;
 1772:             } else {
 1773:                 $outcome = 'ok';
 1774:                 my @matches = split(/\n/,$response);
 1775:                 foreach my $match (@matches) {
 1776:                     my ($key,$value) = split(/=/,$match);
 1777:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1778:                 }
 1779:             }
 1780:         }
 1781:     }
 1782:     return ($outcome,%results);
 1783: }
 1784: 
 1785: sub usersearch {
 1786:     my ($srch) = @_;
 1787:     my $dom = $srch->{'srchdomain'};
 1788:     my %results;
 1789:     my %libserv = &all_library();
 1790:     my $query = 'usersearch';
 1791:     foreach my $tryserver (keys(%libserv)) {
 1792:         if (&host_domain($tryserver) eq $dom) {
 1793:             my $host=&hostname($tryserver);
 1794:             my $queryid=
 1795:                 &reply("querysend:".&escape($query).':'.
 1796:                        &escape($srch->{'srchby'}).':'.
 1797:                        &escape($srch->{'srchtype'}).':'.
 1798:                        &escape($srch->{'srchterm'}),$tryserver);
 1799:             if ($queryid !~/^\Q$host\E\_/) {
 1800:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1801:                 next;
 1802:             }
 1803:             my $reply = &get_query_reply($queryid);
 1804:             my $maxtries = 1;
 1805:             my $tries = 1;
 1806:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1807:                 $reply = &get_query_reply($queryid);
 1808:                 $tries ++;
 1809:             }
 1810:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1811:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1812:             } else {
 1813:                 my @matches;
 1814:                 if ($reply =~ /\n/) {
 1815:                     @matches = split(/\n/,$reply);
 1816:                 } else {
 1817:                     @matches = split(/\&/,$reply);
 1818:                 }
 1819:                 foreach my $match (@matches) {
 1820:                     my ($uname,$udom,%userhash);
 1821:                     foreach my $entry (split(/:/,$match)) {
 1822:                         my ($key,$value) =
 1823:                             map {&unescape($_);} split(/=/,$entry);
 1824:                         $userhash{$key} = $value;
 1825:                         if ($key eq 'username') {
 1826:                             $uname = $value;
 1827:                         } elsif ($key eq 'domain') {
 1828:                             $udom = $value;
 1829:                         }
 1830:                     }
 1831:                     $results{$uname.':'.$udom} = \%userhash;
 1832:                 }
 1833:             }
 1834:         }
 1835:     }
 1836:     return %results;
 1837: }
 1838: 
 1839: sub get_instuser {
 1840:     my ($udom,$uname,$id) = @_;
 1841:     my $homeserver = &domain($udom,'primary');
 1842:     my ($outcome,%results);
 1843:     if ($homeserver ne '') {
 1844:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1845:                            &escape($id).':'.&escape($udom),$homeserver);
 1846:         my $host=&hostname($homeserver);
 1847:         if ($queryid !~/^\Q$host\E\_/) {
 1848:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1849:             return;
 1850:         }
 1851:         my $response = &get_query_reply($queryid);
 1852:         my $maxtries = 5;
 1853:         my $tries = 1;
 1854:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1855:             $response = &get_query_reply($queryid);
 1856:             $tries ++;
 1857:         }
 1858:         if (!&error($response) && $response ne 'refused') {
 1859:             if ($response eq 'unavailable') {
 1860:                 $outcome = $response;
 1861:             } else {
 1862:                 $outcome = 'ok';
 1863:                 my @matches = split(/\n/,$response);
 1864:                 foreach my $match (@matches) {
 1865:                     my ($key,$value) = split(/=/,$match);
 1866:                     $results{&unescape($key)} = &thaw_unescape($value);
 1867:                 }
 1868:             }
 1869:         }
 1870:     }
 1871:     my %userinfo;
 1872:     if (ref($results{$uname}) eq 'HASH') {
 1873:         %userinfo = %{$results{$uname}};
 1874:     } 
 1875:     return ($outcome,%userinfo);
 1876: }
 1877: 
 1878: sub inst_rulecheck {
 1879:     my ($udom,$uname,$id,$item,$rules) = @_;
 1880:     my %returnhash;
 1881:     if ($udom ne '') {
 1882:         if (ref($rules) eq 'ARRAY') {
 1883:             @{$rules} = map {&escape($_);} (@{$rules});
 1884:             my $rulestr = join(':',@{$rules});
 1885:             my $homeserver=&domain($udom,'primary');
 1886:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1887:                 my $response;
 1888:                 if ($item eq 'username') {                
 1889:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1890:                                               ':'.&escape($uname).':'.$rulestr,
 1891:                                               $homeserver));
 1892:                 } elsif ($item eq 'id') {
 1893:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1894:                                               ':'.&escape($id).':'.$rulestr,
 1895:                                               $homeserver));
 1896:                 } elsif ($item eq 'selfcreate') {
 1897:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1898:                                                &escape($udom).':'.&escape($uname).
 1899:                                               ':'.$rulestr,$homeserver));
 1900:                 }
 1901:                 if ($response ne 'refused') {
 1902:                     my @pairs=split(/\&/,$response);
 1903:                     foreach my $item (@pairs) {
 1904:                         my ($key,$value)=split(/=/,$item,2);
 1905:                         $key = &unescape($key);
 1906:                         next if ($key =~ /^error: 2 /);
 1907:                         $returnhash{$key}=&thaw_unescape($value);
 1908:                     }
 1909:                 }
 1910:             }
 1911:         }
 1912:     }
 1913:     return %returnhash;
 1914: }
 1915: 
 1916: sub inst_userrules {
 1917:     my ($udom,$check) = @_;
 1918:     my (%ruleshash,@ruleorder);
 1919:     if ($udom ne '') {
 1920:         my $homeserver=&domain($udom,'primary');
 1921:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1922:             my $response;
 1923:             if ($check eq 'id') {
 1924:                 $response=&reply('instidrules:'.&escape($udom),
 1925:                                  $homeserver);
 1926:             } elsif ($check eq 'email') {
 1927:                 $response=&reply('instemailrules:'.&escape($udom),
 1928:                                  $homeserver);
 1929:             } else {
 1930:                 $response=&reply('instuserrules:'.&escape($udom),
 1931:                                  $homeserver);
 1932:             }
 1933:             if (($response ne 'refused') && ($response ne 'error') && 
 1934:                 ($response ne 'unknown_cmd') && 
 1935:                 ($response ne 'no_such_host')) {
 1936:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1937:                 my @pairs=split(/\&/,$hashitems);
 1938:                 foreach my $item (@pairs) {
 1939:                     my ($key,$value)=split(/=/,$item,2);
 1940:                     $key = &unescape($key);
 1941:                     next if ($key =~ /^error: 2 /);
 1942:                     $ruleshash{$key}=&thaw_unescape($value);
 1943:                 }
 1944:                 my @esc_order = split(/\&/,$orderitems);
 1945:                 foreach my $item (@esc_order) {
 1946:                     push(@ruleorder,&unescape($item));
 1947:                 }
 1948:             }
 1949:         }
 1950:     }
 1951:     return (\%ruleshash,\@ruleorder);
 1952: }
 1953: 
 1954: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1955: 
 1956: sub get_domain_defaults {
 1957:     my ($domain) = @_;
 1958:     my $cachetime = 60*60*24;
 1959:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1960:     if (defined($cached)) {
 1961:         if (ref($result) eq 'HASH') {
 1962:             return %{$result};
 1963:         }
 1964:     }
 1965:     my %domdefaults;
 1966:     my %domconfig =
 1967:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1968:                                   'requestcourses','inststatus',
 1969:                                   'coursedefaults','usersessions',
 1970:                                   'requestauthor'],$domain);
 1971:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1972:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1973:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1974:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1975:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1976:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1977:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1978:     } else {
 1979:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1980:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1981:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1982:     }
 1983:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1984:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1985:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1986:         } else {
 1987:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1988:         } 
 1989:         my @usertools = ('aboutme','blog','webdav','portfolio');
 1990:         foreach my $item (@usertools) {
 1991:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1992:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1993:             }
 1994:         }
 1995:     }
 1996:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1997:         foreach my $item ('official','unofficial','community') {
 1998:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1999:         }
 2000:     }
 2001:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2002:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2003:     }
 2004:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2005:         foreach my $item ('inststatustypes','inststatusorder') {
 2006:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2007:         }
 2008:     }
 2009:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2010:         foreach my $item ('canuse_pdfforms') {
 2011:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 2012:         }
 2013:     }
 2014:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2015:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2016:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2017:         }
 2018:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2019:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2020:         }
 2021:     }
 2022:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 2023:                                   $cachetime);
 2024:     return %domdefaults;
 2025: }
 2026: 
 2027: # --------------------------------------------------- Assign a key to a student
 2028: 
 2029: sub assign_access_key {
 2030: #
 2031: # a valid key looks like uname:udom#comments
 2032: # comments are being appended
 2033: #
 2034:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2035:     $kdom=
 2036:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2037:     $knum=
 2038:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2039:     $cdom=
 2040:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2041:     $cnum=
 2042:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2043:     $udom=$env{'user.name'} unless (defined($udom));
 2044:     $uname=$env{'user.domain'} unless (defined($uname));
 2045:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2046:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2047:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2048:                                                   # assigned to this person
 2049:                                                   # - this should not happen,
 2050:                                                   # unless something went wrong
 2051:                                                   # the first time around
 2052: # ready to assign
 2053:         $logentry=$1.'; '.$logentry;
 2054:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2055:                                                  $kdom,$knum) eq 'ok') {
 2056: # key now belongs to user
 2057: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2058:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2059:                 &appenv({'environment.'.$envkey => $ckey});
 2060:                 return 'ok';
 2061:             } else {
 2062:                 return 
 2063:   'error: Count not permanently assign key, will need to be re-entered later.';
 2064: 	    }
 2065:         } else {
 2066:             return 'error: Could not assign key, try again later.';
 2067:         }
 2068:     } elsif (!$existing{$ckey}) {
 2069: # the key does not exist
 2070: 	return 'error: The key does not exist';
 2071:     } else {
 2072: # the key is somebody else's
 2073: 	return 'error: The key is already in use';
 2074:     }
 2075: }
 2076: 
 2077: # ------------------------------------------ put an additional comment on a key
 2078: 
 2079: sub comment_access_key {
 2080: #
 2081: # a valid key looks like uname:udom#comments
 2082: # comments are being appended
 2083: #
 2084:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2085:     $cdom=
 2086:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2087:     $cnum=
 2088:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2089:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2090:     if ($existing{$ckey}) {
 2091:         $existing{$ckey}.='; '.$logentry;
 2092: # ready to assign
 2093:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2094:                                                  $cdom,$cnum) eq 'ok') {
 2095: 	    return 'ok';
 2096:         } else {
 2097: 	    return 'error: Count not store comment.';
 2098:         }
 2099:     } else {
 2100: # the key does not exist
 2101: 	return 'error: The key does not exist';
 2102:     }
 2103: }
 2104: 
 2105: # ------------------------------------------------------ Generate a set of keys
 2106: 
 2107: sub generate_access_keys {
 2108:     my ($number,$cdom,$cnum,$logentry)=@_;
 2109:     $cdom=
 2110:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2111:     $cnum=
 2112:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2113:     unless (&allowed('mky',$cdom)) { return 0; }
 2114:     unless (($cdom) && ($cnum)) { return 0; }
 2115:     if ($number>10000) { return 0; }
 2116:     sleep(2); # make sure don't get same seed twice
 2117:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2118:     my $total=0;
 2119:     for (my $i=1;$i<=$number;$i++) {
 2120:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2121:                   sprintf("%lx",int(100000*rand)).'-'.
 2122:                   sprintf("%lx",int(100000*rand));
 2123:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2124:        $newkey=~s/0/h/g; # and also 0 and O
 2125:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2126:        if ($existing{$newkey}) {
 2127:            $i--;
 2128:        } else {
 2129: 	  if (&put('accesskeys',
 2130:               { $newkey => '# generated '.localtime().
 2131:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2132:                            '; '.$logentry },
 2133: 		   $cdom,$cnum) eq 'ok') {
 2134:               $total++;
 2135: 	  }
 2136:        }
 2137:     }
 2138:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2139:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2140:     return $total;
 2141: }
 2142: 
 2143: # ------------------------------------------------------- Validate an accesskey
 2144: 
 2145: sub validate_access_key {
 2146:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2147:     $cdom=
 2148:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2149:     $cnum=
 2150:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2151:     $udom=$env{'user.domain'} unless (defined($udom));
 2152:     $uname=$env{'user.name'} unless (defined($uname));
 2153:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2154:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2155: }
 2156: 
 2157: # ------------------------------------- Find the section of student in a course
 2158: sub devalidate_getsection_cache {
 2159:     my ($udom,$unam,$courseid)=@_;
 2160:     my $hashid="$udom:$unam:$courseid";
 2161:     &devalidate_cache_new('getsection',$hashid);
 2162: }
 2163: 
 2164: sub courseid_to_courseurl {
 2165:     my ($courseid) = @_;
 2166:     #already url style courseid
 2167:     return $courseid if ($courseid =~ m{^/});
 2168: 
 2169:     if (exists($env{'course.'.$courseid.'.num'})) {
 2170: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2171: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2172: 	return "/$cdom/$cnum";
 2173:     }
 2174: 
 2175:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2176:     if (exists($courseinfo{'num'})) {
 2177: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2178:     }
 2179: 
 2180:     return undef;
 2181: }
 2182: 
 2183: sub getsection {
 2184:     my ($udom,$unam,$courseid)=@_;
 2185:     my $cachetime=1800;
 2186: 
 2187:     my $hashid="$udom:$unam:$courseid";
 2188:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2189:     if (defined($cached)) { return $result; }
 2190: 
 2191:     my %Pending; 
 2192:     my %Expired;
 2193:     #
 2194:     # Each role can either have not started yet (pending), be active, 
 2195:     #    or have expired.
 2196:     #
 2197:     # If there is an active role, we are done.
 2198:     #
 2199:     # If there is more than one role which has not started yet, 
 2200:     #     choose the one which will start sooner
 2201:     # If there is one role which has not started yet, return it.
 2202:     #
 2203:     # If there is more than one expired role, choose the one which ended last.
 2204:     # If there is a role which has expired, return it.
 2205:     #
 2206:     $courseid = &courseid_to_courseurl($courseid);
 2207:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2208:     foreach my $key (keys(%roleshash)) {
 2209:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2210:         my $section=$1;
 2211:         if ($key eq $courseid.'_st') { $section=''; }
 2212:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2213:         my $now=time;
 2214:         if (defined($end) && $end && ($now > $end)) {
 2215:             $Expired{$end}=$section;
 2216:             next;
 2217:         }
 2218:         if (defined($start) && $start && ($now < $start)) {
 2219:             $Pending{$start}=$section;
 2220:             next;
 2221:         }
 2222:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2223:     }
 2224:     #
 2225:     # Presumedly there will be few matching roles from the above
 2226:     # loop and the sorting time will be negligible.
 2227:     if (scalar(keys(%Pending))) {
 2228:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2229:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2230:     } 
 2231:     if (scalar(keys(%Expired))) {
 2232:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2233:         my $time = pop(@sorted);
 2234:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2235:     }
 2236:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2237: }
 2238: 
 2239: sub save_cache {
 2240:     &purge_remembered();
 2241:     #&Apache::loncommon::validate_page();
 2242:     undef(%env);
 2243:     undef($env_loaded);
 2244: }
 2245: 
 2246: my $to_remember=-1;
 2247: my %remembered;
 2248: my %accessed;
 2249: my $kicks=0;
 2250: my $hits=0;
 2251: sub make_key {
 2252:     my ($name,$id) = @_;
 2253:     if (length($id) > 65 
 2254: 	&& length(&escape($id)) > 200) {
 2255: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2256:     }
 2257:     return &escape($name.':'.$id);
 2258: }
 2259: 
 2260: sub devalidate_cache_new {
 2261:     my ($name,$id,$debug) = @_;
 2262:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2263:     $id=&make_key($name,$id);
 2264:     $memcache->delete($id);
 2265:     delete($remembered{$id});
 2266:     delete($accessed{$id});
 2267: }
 2268: 
 2269: sub is_cached_new {
 2270:     my ($name,$id,$debug) = @_;
 2271:     $id=&make_key($name,$id);
 2272:     if (exists($remembered{$id})) {
 2273: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2274: 	$accessed{$id}=[&gettimeofday()];
 2275: 	$hits++;
 2276: 	return ($remembered{$id},1);
 2277:     }
 2278:     my $value = $memcache->get($id);
 2279:     if (!(defined($value))) {
 2280: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2281: 	return (undef,undef);
 2282:     }
 2283:     if ($value eq '__undef__') {
 2284: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2285: 	$value=undef;
 2286:     }
 2287:     &make_room($id,$value,$debug);
 2288:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2289:     return ($value,1);
 2290: }
 2291: 
 2292: sub do_cache_new {
 2293:     my ($name,$id,$value,$time,$debug) = @_;
 2294:     $id=&make_key($name,$id);
 2295:     my $setvalue=$value;
 2296:     if (!defined($setvalue)) {
 2297: 	$setvalue='__undef__';
 2298:     }
 2299:     if (!defined($time) ) {
 2300: 	$time=600;
 2301:     }
 2302:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2303:     my $result = $memcache->set($id,$setvalue,$time);
 2304:     if (! $result) {
 2305: 	&logthis("caching of id -> $id  failed");
 2306: 	$memcache->disconnect_all();
 2307:     }
 2308:     # need to make a copy of $value
 2309:     &make_room($id,$value,$debug);
 2310:     return $value;
 2311: }
 2312: 
 2313: sub make_room {
 2314:     my ($id,$value,$debug)=@_;
 2315: 
 2316:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2317:                                     : $value;
 2318:     if ($to_remember<0) { return; }
 2319:     $accessed{$id}=[&gettimeofday()];
 2320:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2321:     my $to_kick;
 2322:     my $max_time=0;
 2323:     foreach my $other (keys(%accessed)) {
 2324: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2325: 	    $to_kick=$other;
 2326: 	    $max_time=&tv_interval($accessed{$other});
 2327: 	}
 2328:     }
 2329:     delete($remembered{$to_kick});
 2330:     delete($accessed{$to_kick});
 2331:     $kicks++;
 2332:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2333:     return;
 2334: }
 2335: 
 2336: sub purge_remembered {
 2337:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2338:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2339:     undef(%remembered);
 2340:     undef(%accessed);
 2341: }
 2342: # ------------------------------------- Read an entry from a user's environment
 2343: 
 2344: sub userenvironment {
 2345:     my ($udom,$unam,@what)=@_;
 2346:     my $items;
 2347:     foreach my $item (@what) {
 2348:         $items.=&escape($item).'&';
 2349:     }
 2350:     $items=~s/\&$//;
 2351:     my %returnhash=();
 2352:     my $uhome = &homeserver($unam,$udom);
 2353:     unless ($uhome eq 'no_host') {
 2354:         my @answer=split(/\&/, 
 2355:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2356:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2357:             return %returnhash;
 2358:         }
 2359:         my $i;
 2360:         for ($i=0;$i<=$#what;$i++) {
 2361: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2362:         }
 2363:     }
 2364:     return %returnhash;
 2365: }
 2366: 
 2367: # ---------------------------------------------------------- Get a studentphoto
 2368: sub studentphoto {
 2369:     my ($udom,$unam,$ext) = @_;
 2370:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2371:     if (defined($env{'request.course.id'})) {
 2372:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2373:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2374:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2375:             } else {
 2376:                 my ($result,$perm_reqd)=
 2377: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2378:                 if ($result eq 'ok') {
 2379:                     if (!($perm_reqd eq 'yes')) {
 2380:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2381:                     }
 2382:                 }
 2383:             }
 2384:         }
 2385:     } else {
 2386:         my ($result,$perm_reqd) = 
 2387: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2388:         if ($result eq 'ok') {
 2389:             if (!($perm_reqd eq 'yes')) {
 2390:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2391:             }
 2392:         }
 2393:     }
 2394:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2395: }
 2396: 
 2397: sub retrievestudentphoto {
 2398:     my ($udom,$unam,$ext,$type) = @_;
 2399:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2400:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2401:     if ($ret eq 'ok') {
 2402:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2403:         if ($type eq 'thumbnail') {
 2404:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2405:         }
 2406:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2407:         return $tokenurl;
 2408:     } else {
 2409:         if ($type eq 'thumbnail') {
 2410:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2411:         } else { 
 2412:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2413:         }
 2414:     }
 2415: }
 2416: 
 2417: # -------------------------------------------------------------------- New chat
 2418: 
 2419: sub chatsend {
 2420:     my ($newentry,$anon,$group)=@_;
 2421:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2422:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2423:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2424:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2425: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2426: 		   &escape($newentry)).':'.$group,$chome);
 2427: }
 2428: 
 2429: # ------------------------------------------ Find current version of a resource
 2430: 
 2431: sub getversion {
 2432:     my $fname=&clutter(shift);
 2433:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2434:     return &currentversion(&filelocation('',$fname));
 2435: }
 2436: 
 2437: sub currentversion {
 2438:     my $fname=shift;
 2439:     my $author=$fname;
 2440:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2441:     my ($udom,$uname)=split(/\//,$author);
 2442:     my $home=&homeserver($uname,$udom);
 2443:     if ($home eq 'no_host') { 
 2444:         return -1; 
 2445:     }
 2446:     my $answer=&reply("currentversion:$fname",$home);
 2447:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2448: 	return -1;
 2449:     }
 2450:     return $answer;
 2451: }
 2452: 
 2453: #
 2454: # Return special version number of resource if set by override, empty otherwise
 2455: #
 2456: sub usedversion {
 2457:     my $fname=shift;
 2458:     unless ($fname) { $fname=$env{'request.uri'}; }
 2459:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2460:     if ($urlversion) { return $urlversion; }
 2461:     return '';
 2462: }
 2463: 
 2464: # ----------------------------- Subscribe to a resource, return URL if possible
 2465: 
 2466: sub subscribe {
 2467:     my $fname=shift;
 2468:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2469:     $fname=~s/[\n\r]//g;
 2470:     my $author=$fname;
 2471:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2472:     my ($udom,$uname)=split(/\//,$author);
 2473:     my $home=homeserver($uname,$udom);
 2474:     if ($home eq 'no_host') {
 2475:         return 'not_found';
 2476:     }
 2477:     my $answer=reply("sub:$fname",$home);
 2478:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2479: 	$answer.=' by '.$home;
 2480:     }
 2481:     return $answer;
 2482: }
 2483:     
 2484: # -------------------------------------------------------------- Replicate file
 2485: 
 2486: sub repcopy {
 2487:     my $filename=shift;
 2488:     $filename=~s/\/+/\//g;
 2489:     my $londocroot = $perlvar{'lonDocRoot'};
 2490:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2491:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2492:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2493: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2494: 	return &repcopy_userfile($filename);
 2495:     }
 2496:     $filename=~s/[\n\r]//g;
 2497:     my $transname="$filename.in.transfer";
 2498: # FIXME: this should flock
 2499:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2500:     my $remoteurl=subscribe($filename);
 2501:     if ($remoteurl =~ /^con_lost by/) {
 2502: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2503:            return 'unavailable';
 2504:     } elsif ($remoteurl eq 'not_found') {
 2505: 	   #&logthis("Subscribe returned not_found: $filename");
 2506: 	   return 'not_found';
 2507:     } elsif ($remoteurl =~ /^rejected by/) {
 2508: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2509:            return 'forbidden';
 2510:     } elsif ($remoteurl eq 'directory') {
 2511:            return 'ok';
 2512:     } else {
 2513:         my $author=$filename;
 2514:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2515:         my ($udom,$uname)=split(/\//,$author);
 2516:         my $home=homeserver($uname,$udom);
 2517:         unless ($home eq $perlvar{'lonHostID'}) {
 2518:            my @parts=split(/\//,$filename);
 2519:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2520:            if ($path ne "$londocroot/res") {
 2521:                &logthis("Malconfiguration for replication: $filename");
 2522: 	       return 'bad_request';
 2523:            }
 2524:            my $count;
 2525:            for ($count=5;$count<$#parts;$count++) {
 2526:                $path.="/$parts[$count]";
 2527:                if ((-e $path)!=1) {
 2528: 		   mkdir($path,0777);
 2529:                }
 2530:            }
 2531:            my $ua=new LWP::UserAgent;
 2532:            my $request=new HTTP::Request('GET',"$remoteurl");
 2533:            my $response=$ua->request($request,$transname);
 2534:            if ($response->is_error()) {
 2535: 	       unlink($transname);
 2536:                my $message=$response->status_line;
 2537:                &logthis("<font color=\"blue\">WARNING:"
 2538:                        ." LWP get: $message: $filename</font>");
 2539:                return 'unavailable';
 2540:            } else {
 2541: 	       if ($remoteurl!~/\.meta$/) {
 2542:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2543:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2544:                   if ($mresponse->is_error()) {
 2545: 		      unlink($filename.'.meta');
 2546:                       &logthis(
 2547:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2548:                   }
 2549: 	       }
 2550:                rename($transname,$filename);
 2551:                return 'ok';
 2552:            }
 2553:        }
 2554:     }
 2555: }
 2556: 
 2557: # ------------------------------------------------ Get server side include body
 2558: sub ssi_body {
 2559:     my ($filelink,%form)=@_;
 2560:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2561:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2562:     }
 2563:     my $output='';
 2564:     my $response;
 2565:     if ($filelink=~/^https?\:/) {
 2566:        ($output,$response)=&externalssi($filelink);
 2567:     } else {
 2568:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2569:        $filelink .= 'inhibitmenu=yes';
 2570:        ($output,$response)=&ssi($filelink,%form);
 2571:     }
 2572:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2573:     $output=~s/^.*?\<body[^\>]*\>//si;
 2574:     $output=~s/\<\/body\s*\>.*?$//si;
 2575:     if (wantarray) {
 2576:         return ($output, $response);
 2577:     } else {
 2578:         return $output;
 2579:     }
 2580: }
 2581: 
 2582: # --------------------------------------------------------- Server Side Include
 2583: 
 2584: sub absolute_url {
 2585:     my ($host_name) = @_;
 2586:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2587:     if ($host_name eq '') {
 2588: 	$host_name = $ENV{'SERVER_NAME'};
 2589:     }
 2590:     return $protocol.$host_name;
 2591: }
 2592: 
 2593: #
 2594: #   Server side include.
 2595: # Parameters:
 2596: #  fn     Possibly encrypted resource name/id.
 2597: #  form   Hash that describes how the rendering should be done
 2598: #         and other things.
 2599: # Returns:
 2600: #   Scalar context: The content of the response.
 2601: #   Array context:  2 element list of the content and the full response object.
 2602: #     
 2603: sub ssi {
 2604: 
 2605:     my ($fn,%form)=@_;
 2606:     my $ua=new LWP::UserAgent;
 2607:     my $request;
 2608: 
 2609:     $form{'no_update_last_known'}=1;
 2610:     &Apache::lonenc::check_encrypt(\$fn);
 2611:     if (%form) {
 2612:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2613:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2614:     } else {
 2615:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2616:     }
 2617: 
 2618:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2619:     my $response= $ua->request($request);
 2620:     my $content = $response->content;
 2621: 
 2622: 
 2623:     if (wantarray) {
 2624: 	return ($content, $response);
 2625:     } else {
 2626: 	return $content;
 2627:     }
 2628: }
 2629: 
 2630: sub externalssi {
 2631:     my ($url)=@_;
 2632:     my $ua=new LWP::UserAgent;
 2633:     my $request=new HTTP::Request('GET',$url);
 2634:     my $response=$ua->request($request);
 2635:     if (wantarray) {
 2636:         return ($response->content, $response);
 2637:     } else {
 2638:         return $response->content;
 2639:     }
 2640: }
 2641: 
 2642: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2643: 
 2644: sub allowuploaded {
 2645:     my ($srcurl,$url)=@_;
 2646:     $url=&clutter(&declutter($url));
 2647:     my $dir=$url;
 2648:     $dir=~s/\/[^\/]+$//;
 2649:     my %httpref=();
 2650:     my $httpurl=&hreflocation('',$url);
 2651:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2652:     &Apache::lonnet::appenv(\%httpref);
 2653: }
 2654: 
 2655: #
 2656: # Determine if the current user should be able to edit a particular resource,
 2657: # when viewing in course context.
 2658: # (a) When viewing resource used to determine if "Edit" item is included in 
 2659: #     Functions.
 2660: # (b) When displaying folder contents in course editor, used to determine if
 2661: #     "Edit" link will be displayed alongside resource.
 2662: #
 2663: #  input: six args -- filename (decluttered), course number, course domain,
 2664: #                   url, symb (if registered) and group (if this is a group
 2665: #                   item -- e.g., bulletin board, group page etc.).
 2666: #  output: array of five scalars -- 
 2667: #          $cfile -- url for file editing if editable on current server
 2668: #          $home -- homeserver of resource (i.e., for author if published,
 2669: #                                           or course if uploaded.).
 2670: #          $switchserver --  1 if server switch will be needed.
 2671: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2672: #          $forceview -- 1 if icon/link should be to go to view mode
 2673: #
 2674: 
 2675: sub can_edit_resource {
 2676:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2677:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2678: #
 2679: # For aboutme pages user can only edit his/her own.
 2680: #
 2681:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2682:         my ($sdom,$sname) = ($1,$2);
 2683:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2684:             $home = $env{'user.home'};
 2685:             $cfile = $resurl;
 2686:             if ($env{'form.forceedit'}) {
 2687:                 $forceview = 1;
 2688:             } else {
 2689:                 $forceedit = 1;
 2690:             }
 2691:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2692:         } else {
 2693:             return;
 2694:         }
 2695:     }
 2696: 
 2697:     if ($env{'request.course.id'}) {
 2698:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2699:         if ($group ne '') {
 2700: # if this is a group homepage or group bulletin board, check group privs
 2701:             my $allowed = 0;
 2702:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2703:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2704:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2705:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2706:                     $allowed = 1;
 2707:                 }
 2708:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2709:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2710:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2711:                     $allowed = 1;
 2712:                 }
 2713:             }
 2714:             if ($allowed) {
 2715:                 $home=&homeserver($cnum,$cdom);
 2716:                 if ($env{'form.forceedit'}) {
 2717:                     $forceview = 1;
 2718:                 } else {
 2719:                     $forceedit = 1;
 2720:                 }
 2721:                 $cfile = $resurl;
 2722:             } else {
 2723:                 return;
 2724:             }
 2725:         } else {
 2726:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2727:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2728:                     return;
 2729:                 }
 2730:             } elsif (!$crsedit) {
 2731: #
 2732: # No edit allowed where CC has switched to student role.
 2733: #
 2734:                 return;
 2735:             }
 2736:         }
 2737:     }
 2738: 
 2739:     if ($file ne '') {
 2740:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2741:             if (&is_course_upload($file,$cnum,$cdom)) {
 2742:                 $uploaded = 1;
 2743:                 $incourse = 1;
 2744:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2745:                     $cfile = &hreflocation('',$file);
 2746:                     if ($env{'form.forceedit'}) {
 2747:                         $forceview = 1;
 2748:                     } else {
 2749:                         $forceedit = 1;
 2750:                     }
 2751:                 }
 2752:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2753:                 $incourse = 1;
 2754:                 if ($env{'form.forceedit'}) {
 2755:                     $forceview = 1;
 2756:                 } else {
 2757:                     $forceedit = 1;
 2758:                 }
 2759:                 $cfile = $resurl;
 2760:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2761:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2762:                     $incourse = 1;
 2763:                     if ($env{'form.forceedit'}) {
 2764:                         $forceview = 1;
 2765:                     } else {
 2766:                         $forceedit = 1;
 2767:                     }
 2768:                     $cfile = $resurl;
 2769:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2770:                     $incourse = 1;
 2771:                     $cfile = $resurl.'/smpedit';
 2772:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2773:                     $incourse = 1;
 2774:                     if ($env{'form.forceedit'}) {
 2775:                         $forceview = 1;
 2776:                     } else {
 2777:                         $forceedit = 1;
 2778:                     }
 2779:                     $cfile = $resurl;
 2780:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2781:                     $incourse = 1;
 2782:                     if ($env{'form.forceedit'}) {
 2783:                         $forceview = 1;
 2784:                     } else {
 2785:                         $forceedit = 1;
 2786:                     }
 2787:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2788:                 }
 2789:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2790:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2791:                 if (&is_on_map($template)) { 
 2792:                     $incourse = 1;
 2793:                     $forceview = 1;
 2794:                     $cfile = $template;
 2795:                 }
 2796:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2797:                     $incourse = 1;
 2798:                     if ($env{'form.forceedit'}) {
 2799:                         $forceview = 1;
 2800:                     } else {
 2801:                         $forceedit = 1;
 2802:                     }
 2803:                     $cfile = $resurl;
 2804:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2805:                 $incourse = 1;
 2806:                 $forceview = 1;
 2807:                 if ($symb) {
 2808:                     my ($map,$id,$res)=&decode_symb($symb);
 2809:                     $env{'request.symb'} = $symb;
 2810:                     $cfile = &clutter($res);
 2811:                 } else {
 2812:                     $cfile = $env{'form.suppurl'};
 2813:                     $cfile =~ s{^http://}{};
 2814:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2815:                 }
 2816:             }
 2817:         }
 2818:         if ($uploaded || $incourse) {
 2819:             $home=&homeserver($cnum,$cdom);
 2820:         } elsif ($file !~ m{/$}) {
 2821:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2822:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2823:             # Check that the user has permission to edit this resource
 2824:             my $setpriv = 1;
 2825:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2826:             if (defined($cfudom)) {
 2827:                 $home=&homeserver($cfuname,$cfudom);
 2828:                 $cfile=$file;
 2829:             }
 2830:         }
 2831:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2832:             (($home ne '') && ($home ne 'no_host'))) {
 2833:             my @ids=&current_machine_ids();
 2834:             unless (grep(/^\Q$home\E$/,@ids)) {
 2835:                 $switchserver=1;
 2836:             }
 2837:         }
 2838:     }
 2839:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2840: }
 2841: 
 2842: sub is_course_upload {
 2843:     my ($file,$cnum,$cdom) = @_;
 2844:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2845:     $uploadpath =~ s{^\/}{};
 2846:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2847:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2848:         return 1;
 2849:     }
 2850:     return;
 2851: }
 2852: 
 2853: sub in_course {
 2854:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2855:     if ($hideprivileged) {
 2856:         my $skipuser;
 2857:         if (&privileged($uname,$udom)) {
 2858:             $skipuser = 1;
 2859:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2860:             if ($coursehash{'nothideprivileged'}) {
 2861:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2862:                     my $user;
 2863:                     if ($item =~ /:/) {
 2864:                         $user = $item;
 2865:                     } else {
 2866:                         $user = join(':',split(/[\@]/,$item));
 2867:                     }
 2868:                     if ($user eq $uname.':'.$udom) {
 2869:                         undef($skipuser);
 2870:                         last;
 2871:                     }
 2872:                 }
 2873:             }
 2874:             if ($skipuser) {
 2875:                 return 0;
 2876:             }
 2877:         }
 2878:     }
 2879:     $type ||= 'any';
 2880:     if (!defined($cdom) || !defined($cnum)) {
 2881:         my $cid  = $env{'request.course.id'};
 2882:         $cdom = $env{'course.'.$cid.'.domain'};
 2883:         $cnum = $env{'course.'.$cid.'.num'};
 2884:     }
 2885:     my $typesref;
 2886:     if (($type eq 'any') || ($type eq 'all')) {
 2887:         $typesref = ['active','previous','future'];
 2888:     } elsif ($type eq 'previous' || $type eq 'future') {
 2889:         $typesref = [$type];
 2890:     }
 2891:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2892:                               $typesref,undef,[$cdom]);
 2893:     my ($tmp) = keys(%roles);
 2894:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2895:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2896:     if (@course_roles > 0) {
 2897:         return 1;
 2898:     }
 2899:     return 0;
 2900: }
 2901: 
 2902: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2903: # input: action, courseID, current domain, intended
 2904: #        path to file, source of file, instruction to parse file for objects,
 2905: #        ref to hash for embedded objects,
 2906: #        ref to hash for codebase of java objects.
 2907: #        reference to scalar to accommodate mime type determined
 2908: #          from File::MMagic if $parser = parse.
 2909: #
 2910: # output: url to file (if action was uploaddoc), 
 2911: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2912: #
 2913: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2914: # course.
 2915: #
 2916: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2917: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2918: #          course's home server.
 2919: #
 2920: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2921: #          be copied from $source (current location) to 
 2922: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2923: #         and will then be copied to
 2924: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2925: #         course's home server.
 2926: #
 2927: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2928: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2929: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2930: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2931: #         in course's home server.
 2932: #
 2933: 
 2934: sub process_coursefile {
 2935:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2936:         $mimetype)=@_;
 2937:     my $fetchresult;
 2938:     my $home=&homeserver($docuname,$docudom);
 2939:     if ($action eq 'propagate') {
 2940:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2941: 			     $home);
 2942:     } else {
 2943:         my $fpath = '';
 2944:         my $fname = $file;
 2945:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2946:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2947:         my $filepath = &build_filepath($fpath);
 2948:         if ($action eq 'copy') {
 2949:             if ($source eq '') {
 2950:                 $fetchresult = 'no source file';
 2951:                 return $fetchresult;
 2952:             } else {
 2953:                 my $destination = $filepath.'/'.$fname;
 2954:                 rename($source,$destination);
 2955:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2956:                                  $home);
 2957:             }
 2958:         } elsif ($action eq 'uploaddoc') {
 2959:             open(my $fh,'>'.$filepath.'/'.$fname);
 2960:             print $fh $env{'form.'.$source};
 2961:             close($fh);
 2962:             if ($parser eq 'parse') {
 2963:                 my $mm = new File::MMagic;
 2964:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2965:                 if ($type eq 'text/html') {
 2966:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2967:                     unless ($parse_result eq 'ok') {
 2968:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2969:                     }
 2970:                 }
 2971:                 if (ref($mimetype)) {
 2972:                     $$mimetype = $type;
 2973:                 } 
 2974:             }
 2975:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2976:                                  $home);
 2977:             if ($fetchresult eq 'ok') {
 2978:                 return '/uploaded/'.$fpath.'/'.$fname;
 2979:             } else {
 2980:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2981:                         ' to host '.$home.': '.$fetchresult);
 2982:                 return '/adm/notfound.html';
 2983:             }
 2984:         }
 2985:     }
 2986:     unless ( $fetchresult eq 'ok') {
 2987:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2988:              ' to host '.$home.': '.$fetchresult);
 2989:     }
 2990:     return $fetchresult;
 2991: }
 2992: 
 2993: sub build_filepath {
 2994:     my ($fpath) = @_;
 2995:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2996:     unless ($fpath eq '') {
 2997:         my @parts=split('/',$fpath);
 2998:         foreach my $part (@parts) {
 2999:             $filepath.= '/'.$part;
 3000:             if ((-e $filepath)!=1) {
 3001:                 mkdir($filepath,0777);
 3002:             }
 3003:         }
 3004:     }
 3005:     return $filepath;
 3006: }
 3007: 
 3008: sub store_edited_file {
 3009:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3010:     my $file = $primary_url;
 3011:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3012:     my $fpath = '';
 3013:     my $fname = $file;
 3014:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3015:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3016:     my $filepath = &build_filepath($fpath);
 3017:     open(my $fh,'>'.$filepath.'/'.$fname);
 3018:     print $fh $content;
 3019:     close($fh);
 3020:     my $home=&homeserver($docuname,$docudom);
 3021:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3022: 			  $home);
 3023:     if ($$fetchresult eq 'ok') {
 3024:         return '/uploaded/'.$fpath.'/'.$fname;
 3025:     } else {
 3026:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3027: 		 ' to host '.$home.': '.$$fetchresult);
 3028:         return '/adm/notfound.html';
 3029:     }
 3030: }
 3031: 
 3032: sub clean_filename {
 3033:     my ($fname,$args)=@_;
 3034: # Replace Windows backslashes by forward slashes
 3035:     $fname=~s/\\/\//g;
 3036:     if (!$args->{'keep_path'}) {
 3037:         # Get rid of everything but the actual filename
 3038: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3039:     }
 3040: # Replace spaces by underscores
 3041:     $fname=~s/\s+/\_/g;
 3042: # Replace all other weird characters by nothing
 3043:     $fname=~s{[^/\w\.\-]}{}g;
 3044: # Replace all .\d. sequences with _\d. so they no longer look like version
 3045: # numbers
 3046:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3047:     return $fname;
 3048: }
 3049: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3050: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3051: # image with the same aspect ratio as the original, but with dimensions which do 
 3052: # not exceed $resizewidth and $resizeheight.
 3053:  
 3054: sub resizeImage {
 3055:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3056:     my $ima = Image::Magick->new;
 3057:     my $resized;
 3058:     if (-e $img_path) {
 3059:         $ima->Read($img_path);
 3060:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3061:             my $width = $ima->Get('width');
 3062:             my $height = $ima->Get('height');
 3063:             if ($width > $resizewidth) {
 3064: 	        my $factor = $width/$resizewidth;
 3065:                 my $newheight = $height/$factor;
 3066:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3067:                 $resized = 1;
 3068:             }
 3069:         }
 3070:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3071:             my $width = $ima->Get('width');
 3072:             my $height = $ima->Get('height');
 3073:             if ($height > $resizeheight) {
 3074:                 my $factor = $height/$resizeheight;
 3075:                 my $newwidth = $width/$factor;
 3076:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3077:                 $resized = 1;
 3078:             }
 3079:         }
 3080:         if ($resized) {
 3081:             $ima->Write($img_path);
 3082:         }
 3083:     }
 3084:     return;
 3085: }
 3086: 
 3087: # --------------- Take an uploaded file and put it into the userfiles directory
 3088: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3089: #                    the desired filename is in $env{"form.$formname.filename"}
 3090: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3091: #                                    canceloverwrite, or ''. 
 3092: #                   if 'coursedoc': upload to the current course
 3093: #                   if 'existingfile': write file to tmp/overwrites directory 
 3094: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3095: #                   $context is passed as argument to &finishuserfileupload
 3096: #        $subdir - directory in userfile to store the file into
 3097: #        $parser - instruction to parse file for objects ($parser = parse)    
 3098: #        $allfiles - reference to hash for embedded objects
 3099: #        $codebase - reference to hash for codebase of java objects
 3100: #        $desuname - username for permanent storage of uploaded file
 3101: #        $dsetudom - domain for permanaent storage of uploaded file
 3102: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3103: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3104: #        $resizewidth - width (pixels) to which to resize uploaded image
 3105: #        $resizeheight - height (pixels) to which to resize uploaded image
 3106: #        $mimetype - reference to scalar to accommodate mime type determined
 3107: #                    from File::MMagic.
 3108: # 
 3109: # output: url of file in userspace, or error: <message> 
 3110: #             or /adm/notfound.html if failure to upload occurse
 3111: 
 3112: sub userfileupload {
 3113:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3114:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3115:     if (!defined($subdir)) { $subdir='unknown'; }
 3116:     my $fname=$env{'form.'.$formname.'.filename'};
 3117:     $fname=&clean_filename($fname);
 3118:     # See if there is anything left
 3119:     unless ($fname) { return 'error: no uploaded file'; }
 3120:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3121:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3122:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3123:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3124:         my $now = time;
 3125:         my $filepath;
 3126:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3127:              $filepath = 'tmp/helprequests/'.$now;
 3128:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3129:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3130:                          '_'.$env{'user.domain'}.'/pending';
 3131:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3132:             my ($docuname,$docudom);
 3133:             if ($destudom) {
 3134:                 $docudom = $destudom;
 3135:             } else {
 3136:                 $docudom = $env{'user.domain'};
 3137:             }
 3138:             if ($destuname) {
 3139:                 $docuname = $destuname;
 3140:             } else {
 3141:                 $docuname = $env{'user.name'};
 3142:             }
 3143:             if (exists($env{'form.group'})) {
 3144:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3145:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3146:             }
 3147:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3148:             if ($context eq 'canceloverwrite') {
 3149:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3150:                 if (-e  $tempfile) {
 3151:                     my @info = stat($tempfile);
 3152:                     if ($info[9] eq $env{'form.timestamp'}) {
 3153:                         unlink($tempfile);
 3154:                     }
 3155:                 }
 3156:                 return;
 3157:             }
 3158:         }
 3159:         # Create the directory if not present
 3160:         my @parts=split(/\//,$filepath);
 3161:         my $fullpath = $perlvar{'lonDaemons'};
 3162:         for (my $i=0;$i<@parts;$i++) {
 3163:             $fullpath .= '/'.$parts[$i];
 3164:             if ((-e $fullpath)!=1) {
 3165:                 mkdir($fullpath,0777);
 3166:             }
 3167:         }
 3168:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3169:         print $fh $env{'form.'.$formname};
 3170:         close($fh);
 3171:         if ($context eq 'existingfile') {
 3172:             my @info = stat($fullpath.'/'.$fname);
 3173:             return ($fullpath.'/'.$fname,$info[9]);
 3174:         } else {
 3175:             return $fullpath.'/'.$fname;
 3176:         }
 3177:     }
 3178:     if ($subdir eq 'scantron') {
 3179:         $fname = 'scantron_orig_'.$fname;
 3180:     } else {
 3181:         $fname="$subdir/$fname";
 3182:     }
 3183:     if ($context eq 'coursedoc') {
 3184: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3185: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3186:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3187:             return &finishuserfileupload($docuname,$docudom,
 3188: 					 $formname,$fname,$parser,$allfiles,
 3189: 					 $codebase,$thumbwidth,$thumbheight,
 3190:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3191:         } else {
 3192:             $fname=$env{'form.folder'}.'/'.$fname;
 3193:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3194: 				       $fname,$formname,$parser,
 3195: 				       $allfiles,$codebase,$mimetype);
 3196:         }
 3197:     } elsif (defined($destuname)) {
 3198:         my $docuname=$destuname;
 3199:         my $docudom=$destudom;
 3200: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3201: 				     $parser,$allfiles,$codebase,
 3202:                                      $thumbwidth,$thumbheight,
 3203:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3204:     } else {
 3205:         my $docuname=$env{'user.name'};
 3206:         my $docudom=$env{'user.domain'};
 3207:         if (exists($env{'form.group'})) {
 3208:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3209:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3210:         }
 3211: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3212: 				     $parser,$allfiles,$codebase,
 3213:                                      $thumbwidth,$thumbheight,
 3214:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3215:     }
 3216: }
 3217: 
 3218: sub finishuserfileupload {
 3219:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3220:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3221:     my $path=$docudom.'/'.$docuname.'/';
 3222:     my $filepath=$perlvar{'lonDocRoot'};
 3223:   
 3224:     my ($fnamepath,$file,$fetchthumb);
 3225:     $file=$fname;
 3226:     if ($fname=~m|/|) {
 3227:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3228: 	$path.=$fnamepath.'/';
 3229:     }
 3230:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3231:     my $count;
 3232:     for ($count=4;$count<=$#parts;$count++) {
 3233:         $filepath.="/$parts[$count]";
 3234:         if ((-e $filepath)!=1) {
 3235: 	    mkdir($filepath,0777);
 3236:         }
 3237:     }
 3238: 
 3239: # Save the file
 3240:     {
 3241: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3242: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3243: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3244: 	    return '/adm/notfound.html';
 3245: 	}
 3246:         if ($context eq 'overwrite') {
 3247:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3248:             my $target = $filepath.'/'.$file;
 3249:             if (-e $source) {
 3250:                 my @info = stat($source);
 3251:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3252:                     unless (&File::Copy::move($source,$target)) {
 3253:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3254:                         return "Moving from $source failed";
 3255:                     }
 3256:                 } else {
 3257:                     return "Temporary file: $source had unexpected date/time for last modification";
 3258:                 }
 3259:             } else {
 3260:                 return "Temporary file: $source missing";
 3261:             }
 3262:         } elsif (!print FH ($env{'form.'.$formname})) {
 3263: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3264: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3265: 	    return '/adm/notfound.html';
 3266: 	}
 3267: 	close(FH);
 3268:         if ($resizewidth && $resizeheight) {
 3269:             my $mm = new File::MMagic;
 3270:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3271:             if ($mime_type =~ m{^image/}) {
 3272: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3273:             }  
 3274: 	}
 3275:     }
 3276:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3277:         if (ref($mimetype)) {
 3278:             if ($$mimetype eq '') {
 3279:                 my $mm = new File::MMagic;
 3280:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3281:                 $$mimetype = $type;
 3282:             }
 3283:         }
 3284:     }
 3285:     if ($parser eq 'parse') {
 3286:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3287:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3288:                                                        $allfiles,$codebase);
 3289:             unless ($parse_result eq 'ok') {
 3290:                 &logthis('Failed to parse '.$filepath.$file.
 3291: 	   	         ' for embedded media: '.$parse_result); 
 3292:             }
 3293:         }
 3294:     }
 3295:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3296:         my $input = $filepath.'/'.$file;
 3297:         my $output = $filepath.'/'.'tn-'.$file;
 3298:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3299:         system("convert -sample $thumbsize $input $output");
 3300:         if (-e $filepath.'/'.'tn-'.$file) {
 3301:             $fetchthumb  = 1; 
 3302:         }
 3303:     }
 3304:  
 3305: # Notify homeserver to grep it
 3306: #
 3307:     my $docuhome=&homeserver($docuname,$docudom);	
 3308:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3309:     if ($fetchresult eq 'ok') {
 3310:         if ($fetchthumb) {
 3311:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3312:             if ($thumbresult ne 'ok') {
 3313:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3314:                          $docuhome.': '.$thumbresult);
 3315:             }
 3316:         }
 3317: #
 3318: # Return the URL to it
 3319:         return '/uploaded/'.$path.$file;
 3320:     } else {
 3321:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3322: 		 ': '.$fetchresult);
 3323:         return '/adm/notfound.html';
 3324:     }
 3325: }
 3326: 
 3327: sub extract_embedded_items {
 3328:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3329:     my @state = ();
 3330:     my (%lastids,%related,%shockwave,%flashvars);
 3331:     my %javafiles = (
 3332:                       codebase => '',
 3333:                       code => '',
 3334:                       archive => ''
 3335:                     );
 3336:     my %mediafiles = (
 3337:                       src => '',
 3338:                       movie => '',
 3339:                      );
 3340:     my $p;
 3341:     if ($content) {
 3342:         $p = HTML::LCParser->new($content);
 3343:     } else {
 3344:         $p = HTML::LCParser->new($fullpath);
 3345:     }
 3346:     while (my $t=$p->get_token()) {
 3347: 	if ($t->[0] eq 'S') {
 3348: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3349: 	    push(@state, $tagname);
 3350:             if (lc($tagname) eq 'allow') {
 3351:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3352:             }
 3353: 	    if (lc($tagname) eq 'img') {
 3354: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3355: 	    }
 3356: 	    if (lc($tagname) eq 'a') {
 3357: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3358: 	    }
 3359:             if (lc($tagname) eq 'script') {
 3360:                 my $src;
 3361:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3362:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3363:                 } else {
 3364:                     if ($attr->{'src'} ne '') {
 3365:                         $src = $attr->{'src'};
 3366:                         &add_filetype($allfiles,$src,'src');
 3367:                     }
 3368:                 }
 3369:                 my $text = $p->get_trimmed_text();
 3370:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3371:                     my @swfargs = split(/,/,$1);
 3372:                     foreach my $item (@swfargs) {
 3373:                         $item =~ s/["']//g;
 3374:                         $item =~ s/^\s+//;
 3375:                         $item =~ s/\s+$//;
 3376:                     }
 3377:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3378:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3379:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3380:                         } else {
 3381:                             $related{$swfargs[0]} = [$swfargs[2]];
 3382:                         }
 3383:                     }
 3384:                 }
 3385:             }
 3386:             if (lc($tagname) eq 'link') {
 3387:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3388:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3389:                 }
 3390:             }
 3391: 	    if (lc($tagname) eq 'object' ||
 3392: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3393: 		foreach my $item (keys(%javafiles)) {
 3394: 		    $javafiles{$item} = '';
 3395: 		}
 3396:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3397:                     $lastids{lc($tagname)} = $attr->{'id'};
 3398:                 }
 3399: 	    }
 3400: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3401: 		my $name = lc($attr->{'name'});
 3402: 		foreach my $item (keys(%javafiles)) {
 3403: 		    if ($name eq $item) {
 3404: 			$javafiles{$item} = $attr->{'value'};
 3405: 			last;
 3406: 		    }
 3407: 		}
 3408:                 my $pathfrom;
 3409: 		foreach my $item (keys(%mediafiles)) {
 3410: 		    if ($name eq $item) {
 3411:                         $pathfrom = $attr->{'value'};
 3412:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3413: 			&add_filetype($allfiles,$pathfrom,$name);
 3414: 			last;
 3415: 		    }
 3416: 		}
 3417:                 if ($name eq 'flashvars') {
 3418:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3419:                 }
 3420:                 if ($pathfrom ne '') {
 3421:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3422:                                          $pathfrom);
 3423:                 }
 3424: 	    }
 3425: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3426: 		foreach my $item (keys(%javafiles)) {
 3427: 		    if ($attr->{$item}) {
 3428: 			$javafiles{$item} = $attr->{$item};
 3429: 			last;
 3430: 		    }
 3431: 		}
 3432: 		foreach my $item (keys(%mediafiles)) {
 3433: 		    if ($attr->{$item}) {
 3434: 			&add_filetype($allfiles,$attr->{$item},$item);
 3435: 			last;
 3436: 		    }
 3437: 		}
 3438:                 if (lc($tagname) eq 'embed') {
 3439:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3440:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3441:                                              $attr->{'src'});
 3442:                     }
 3443:                 }
 3444: 	    }
 3445:             if ($t->[4] =~ m{/>$}) {
 3446:                 pop(@state);  
 3447:             }
 3448: 	} elsif ($t->[0] eq 'E') {
 3449: 	    my ($tagname) = ($t->[1]);
 3450: 	    if ($javafiles{'codebase'} ne '') {
 3451: 		$javafiles{'codebase'} .= '/';
 3452: 	    }  
 3453: 	    if (lc($tagname) eq 'applet' ||
 3454: 		lc($tagname) eq 'object' ||
 3455: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3456: 		) {
 3457: 		foreach my $item (keys(%javafiles)) {
 3458: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3459: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3460: 			&add_filetype($allfiles,$file,$item);
 3461: 		    }
 3462: 		}
 3463: 	    } 
 3464: 	    pop @state;
 3465: 	}
 3466:     }
 3467:     foreach my $id (sort(keys(%flashvars))) {
 3468:         if ($shockwave{$id} ne '') {
 3469:             my @pairs = split(/\&/,$flashvars{$id});
 3470:             foreach my $pair (@pairs) {
 3471:                 my ($key,$value) = split(/\=/,$pair);
 3472:                 if ($key eq 'thumb') {
 3473:                     &add_filetype($allfiles,$value,$key);
 3474:                 } elsif ($key eq 'content') {
 3475:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3476:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3477:                     if ($ext ne '') {
 3478:                         &add_filetype($allfiles,$path.$value,$ext);
 3479:                     }
 3480:                 }
 3481:             }
 3482:         }
 3483:     }
 3484:     return 'ok';
 3485: }
 3486: 
 3487: sub add_filetype {
 3488:     my ($allfiles,$file,$type)=@_;
 3489:     if (exists($allfiles->{$file})) {
 3490: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3491: 	    push(@{$allfiles->{$file}}, &escape($type));
 3492: 	}
 3493:     } else {
 3494: 	@{$allfiles->{$file}} = (&escape($type));
 3495:     }
 3496: }
 3497: 
 3498: sub embedded_dependency {
 3499:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3500:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3501:         if (($identifier ne '') &&
 3502:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3503:             ($pathfrom ne '')) {
 3504:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3505:             foreach my $dep (@{$related->{$identifier}}) {
 3506:                 &add_filetype($allfiles,$path.$dep,'object');
 3507:             }
 3508:         }
 3509:     }
 3510:     return;
 3511: }
 3512: 
 3513: sub removeuploadedurl {
 3514:     my ($url)=@_;	
 3515:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3516:     return &removeuserfile($uname,$udom,$fname);
 3517: }
 3518: 
 3519: sub removeuserfile {
 3520:     my ($docuname,$docudom,$fname)=@_;
 3521:     my $home=&homeserver($docuname,$docudom);    
 3522:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3523:     if ($result eq 'ok') {	
 3524:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3525:             my $metafile = $fname.'.meta';
 3526:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3527: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3528:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3529:             my $sqlresult = 
 3530:                 &update_portfolio_table($docuname,$docudom,$file,
 3531:                                         'portfolio_metadata',$group,
 3532:                                         'delete');
 3533:         }
 3534:     }
 3535:     return $result;
 3536: }
 3537: 
 3538: sub mkdiruserfile {
 3539:     my ($docuname,$docudom,$dir)=@_;
 3540:     my $home=&homeserver($docuname,$docudom);
 3541:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3542: }
 3543: 
 3544: sub renameuserfile {
 3545:     my ($docuname,$docudom,$old,$new)=@_;
 3546:     my $home=&homeserver($docuname,$docudom);
 3547:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3548:                         &escape("$old").':'.&escape("$new"),$home);
 3549:     if ($result eq 'ok') {
 3550:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3551:             my $oldmeta = $old.'.meta';
 3552:             my $newmeta = $new.'.meta';
 3553:             my $metaresult = 
 3554:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3555: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3556:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3557:             my $sqlresult = 
 3558:                 &update_portfolio_table($docuname,$docudom,$file,
 3559:                                         'portfolio_metadata',$group,
 3560:                                         'delete');
 3561:         }
 3562:     }
 3563:     return $result;
 3564: }
 3565: 
 3566: # ------------------------------------------------------------------------- Log
 3567: 
 3568: sub log {
 3569:     my ($dom,$nam,$hom,$what)=@_;
 3570:     return critical("log:$dom:$nam:$what",$hom);
 3571: }
 3572: 
 3573: # ------------------------------------------------------------------ Course Log
 3574: #
 3575: # This routine flushes several buffers of non-mission-critical nature
 3576: #
 3577: 
 3578: sub flushcourselogs {
 3579:     &logthis('Flushing log buffers');
 3580: #
 3581: # course logs
 3582: # This is a log of all transactions in a course, which can be used
 3583: # for data mining purposes
 3584: #
 3585: # It also collects the courseid database, which lists last transaction
 3586: # times and course titles for all courseids
 3587: #
 3588:     my %courseidbuffer=();
 3589:     foreach my $crsid (keys(%courselogs)) {
 3590:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3591: 		          &escape($courselogs{$crsid}),
 3592: 		          $coursehombuf{$crsid}) eq 'ok') {
 3593: 	    delete $courselogs{$crsid};
 3594:         } else {
 3595:             &logthis('Failed to flush log buffer for '.$crsid);
 3596:             if (length($courselogs{$crsid})>40000) {
 3597:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3598:                         " exceeded maximum size, deleting.</font>");
 3599:                delete $courselogs{$crsid};
 3600:             }
 3601:         }
 3602:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3603:             'description' => $coursedescrbuf{$crsid},
 3604:             'inst_code'    => $courseinstcodebuf{$crsid},
 3605:             'type'        => $coursetypebuf{$crsid},
 3606:             'owner'       => $courseownerbuf{$crsid},
 3607:         };
 3608:     }
 3609: #
 3610: # Write course id database (reverse lookup) to homeserver of courses 
 3611: # Is used in pickcourse
 3612: #
 3613:     foreach my $crs_home (keys(%courseidbuffer)) {
 3614:         my $response = &courseidput(&host_domain($crs_home),
 3615:                                     $courseidbuffer{$crs_home},
 3616:                                     $crs_home,'timeonly');
 3617:     }
 3618: #
 3619: # File accesses
 3620: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3621: #
 3622:     foreach my $entry (keys(%accesshash)) {
 3623:         if ($entry =~ /___count$/) {
 3624:             my ($dom,$name);
 3625:             ($dom,$name,undef)=
 3626: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3627:             if (! defined($dom) || $dom eq '' || 
 3628:                 ! defined($name) || $name eq '') {
 3629:                 my $cid = $env{'request.course.id'};
 3630:                 $dom  = $env{'request.'.$cid.'.domain'};
 3631:                 $name = $env{'request.'.$cid.'.num'};
 3632:             }
 3633:             my $value = $accesshash{$entry};
 3634:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3635:             my %temphash=($url => $value);
 3636:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3637:             if ($result eq 'ok') {
 3638:                 delete $accesshash{$entry};
 3639:             }
 3640:         } else {
 3641:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3642:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3643:             my %temphash=($entry => $accesshash{$entry});
 3644:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3645:                 delete $accesshash{$entry};
 3646:             }
 3647:         }
 3648:     }
 3649: #
 3650: # Roles
 3651: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3652: #
 3653:     foreach my $entry (keys(%userrolehash)) {
 3654:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3655: 	    split(/\:/,$entry);
 3656:         if (&Apache::lonnet::put('nohist_userroles',
 3657:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3658:                 $rudom,$runame) eq 'ok') {
 3659: 	    delete $userrolehash{$entry};
 3660:         }
 3661:     }
 3662: #
 3663: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3664: #
 3665:     my %domrolebuffer = ();
 3666:     foreach my $entry (keys(%domainrolehash)) {
 3667:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3668:         if ($domrolebuffer{$rudom}) {
 3669:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3670:                       '='.&escape($domainrolehash{$entry});
 3671:         } else {
 3672:             $domrolebuffer{$rudom}.=&escape($entry).
 3673:                       '='.&escape($domainrolehash{$entry});
 3674:         }
 3675:         delete $domainrolehash{$entry};
 3676:     }
 3677:     foreach my $dom (keys(%domrolebuffer)) {
 3678: 	my %servers = &get_servers($dom,'library');
 3679: 	foreach my $tryserver (keys(%servers)) {
 3680: 	    unless (&reply('domroleput:'.$dom.':'.
 3681: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3682: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3683: 	    }
 3684:         }
 3685:     }
 3686:     $dumpcount++;
 3687: }
 3688: 
 3689: sub courselog {
 3690:     my $what=shift;
 3691:     $what=time.':'.$what;
 3692:     unless ($env{'request.course.id'}) { return ''; }
 3693:     $coursedombuf{$env{'request.course.id'}}=
 3694:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3695:     $coursenumbuf{$env{'request.course.id'}}=
 3696:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3697:     $coursehombuf{$env{'request.course.id'}}=
 3698:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3699:     $coursedescrbuf{$env{'request.course.id'}}=
 3700:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3701:     $courseinstcodebuf{$env{'request.course.id'}}=
 3702:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3703:     $courseownerbuf{$env{'request.course.id'}}=
 3704:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3705:     $coursetypebuf{$env{'request.course.id'}}=
 3706:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3707:     if (defined $courselogs{$env{'request.course.id'}}) {
 3708: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3709:     } else {
 3710: 	$courselogs{$env{'request.course.id'}}.=$what;
 3711:     }
 3712:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3713: 	&flushcourselogs();
 3714:     }
 3715: }
 3716: 
 3717: sub courseacclog {
 3718:     my $fnsymb=shift;
 3719:     unless ($env{'request.course.id'}) { return ''; }
 3720:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3721:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3722:         $what.=':POST';
 3723:         # FIXME: Probably ought to escape things....
 3724: 	foreach my $key (keys(%env)) {
 3725:             if ($key=~/^form\.(.*)/) {
 3726:                 my $formitem = $1;
 3727:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3728:                     $what.=':'.$formitem.'='.$env{$key};
 3729:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3730:                     $what.=':'.$formitem.'='.$env{$key};
 3731:                 }
 3732:             }
 3733:         }
 3734:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3735:         # FIXME: We should not be depending on a form parameter that someone
 3736:         # editing lonsearchcat.pm might change in the future.
 3737:         if ($env{'form.phase'} eq 'course_search') {
 3738:             $what.= ':POST';
 3739:             # FIXME: Probably ought to escape things....
 3740:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3741:                                  'crsdiscuss') {
 3742:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3743:             }
 3744:         }
 3745:     }
 3746:     &courselog($what);
 3747: }
 3748: 
 3749: sub countacc {
 3750:     my $url=&declutter(shift);
 3751:     return if (! defined($url) || $url eq '');
 3752:     unless ($env{'request.course.id'}) { return ''; }
 3753: #
 3754: # Mark that this url was used in this course
 3755: #
 3756:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3757: #
 3758: # Increase the access count for this resource in this child process
 3759: #
 3760:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3761:     $accesshash{$key}++;
 3762: }
 3763: 
 3764: sub linklog {
 3765:     my ($from,$to)=@_;
 3766:     $from=&declutter($from);
 3767:     $to=&declutter($to);
 3768:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3769:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3770: }
 3771: 
 3772: sub statslog {
 3773:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3774:     if ($users<2) { return; }
 3775:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3776:             'course'       => $env{'request.course.id'},
 3777:             'sections'     => '"all"',
 3778:             'num_students' => $users,
 3779:             'part'         => $part,
 3780:             'symb'         => $symb,
 3781:             'mean_tries'   => $av_attempts,
 3782:             'deg_of_diff'  => $degdiff});
 3783:     foreach my $key (keys(%dynstore)) {
 3784:         $accesshash{$key}=$dynstore{$key};
 3785:     }
 3786: }
 3787:   
 3788: sub userrolelog {
 3789:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3790:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3791:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3792:        $userrolehash
 3793:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3794:                     =$tend.':'.$tstart;
 3795:     }
 3796:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3797:        $userrolehash
 3798:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3799:                     =$tend.':'.$tstart;
 3800:     }
 3801:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3802:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3803:        $domainrolehash
 3804:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3805:                     = $tend.':'.$tstart;
 3806:     }
 3807: }
 3808: 
 3809: sub courserolelog {
 3810:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3811:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3812:         my $cdom = $1;
 3813:         my $cnum = $2;
 3814:         my $sec = $3;
 3815:         my $namespace = 'rolelog';
 3816:         my %storehash = (
 3817:                            role    => $trole,
 3818:                            start   => $tstart,
 3819:                            end     => $tend,
 3820:                            selfenroll => $selfenroll,
 3821:                            context    => $context,
 3822:                         );
 3823:         if ($trole eq 'gr') {
 3824:             $namespace = 'groupslog';
 3825:             $storehash{'group'} = $sec;
 3826:         } else {
 3827:             $storehash{'section'} = $sec;
 3828:         }
 3829:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3830:                    $domain,$cnum,$cdom);
 3831:         if (($trole ne 'st') || ($sec ne '')) {
 3832:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3833:         }
 3834:     }
 3835:     return;
 3836: }
 3837: 
 3838: sub domainrolelog {
 3839:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3840:     if ($area =~ m{^/($match_domain)/$}) {
 3841:         my $cdom = $1;
 3842:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3843:         my $namespace = 'rolelog';
 3844:         my %storehash = (
 3845:                            role    => $trole,
 3846:                            start   => $tstart,
 3847:                            end     => $tend,
 3848:                            context => $context,
 3849:                         );
 3850:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3851:                    $domain,$domconfiguser,$cdom);
 3852:     }
 3853:     return;
 3854: 
 3855: }
 3856: 
 3857: sub coauthorrolelog {
 3858:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3859:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3860:         my $audom = $1;
 3861:         my $auname = $2;
 3862:         my $namespace = 'rolelog';
 3863:         my %storehash = (
 3864:                            role    => $trole,
 3865:                            start   => $tstart,
 3866:                            end     => $tend,
 3867:                            context => $context,
 3868:                         );
 3869:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3870:                    $domain,$auname,$audom);
 3871:     }
 3872:     return;
 3873: }
 3874: 
 3875: sub get_course_adv_roles {
 3876:     my ($cid,$codes) = @_;
 3877:     $cid=$env{'request.course.id'} unless (defined($cid));
 3878:     my %coursehash=&coursedescription($cid);
 3879:     my $crstype = &Apache::loncommon::course_type($cid);
 3880:     my %nothide=();
 3881:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3882:         if ($user !~ /:/) {
 3883: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3884:         } else {
 3885:             $nothide{$user}=1;
 3886:         }
 3887:     }
 3888:     my %returnhash=();
 3889:     my %dumphash=
 3890:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3891:     my $now=time;
 3892:     my %privileged;
 3893:     foreach my $entry (keys(%dumphash)) {
 3894: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3895:         if (($tstart) && ($tstart<0)) { next; }
 3896:         if (($tend) && ($tend<$now)) { next; }
 3897:         if (($tstart) && ($now<$tstart)) { next; }
 3898:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3899: 	if ($username eq '' || $domain eq '') { next; }
 3900:         unless (ref($privileged{$domain}) eq 'HASH') {
 3901:             my %dompersonnel =
 3902:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3903:             $privileged{$domain} = {};
 3904:             foreach my $server (keys(%dompersonnel)) {
 3905:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3906:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3907:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3908:                         $privileged{$udom}{$uname} = 1;
 3909:                     }
 3910:                 }
 3911:             }
 3912:         }
 3913:         if ((exists($privileged{$domain}{$username})) && 
 3914:             (!$nothide{$username.':'.$domain})) { next; }
 3915: 	if ($role eq 'cr') { next; }
 3916:         if ($codes) {
 3917:             if ($section) { $role .= ':'.$section; }
 3918:             if ($returnhash{$role}) {
 3919:                 $returnhash{$role}.=','.$username.':'.$domain;
 3920:             } else {
 3921:                 $returnhash{$role}=$username.':'.$domain;
 3922:             }
 3923:         } else {
 3924:             my $key=&plaintext($role,$crstype);
 3925:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3926:             if ($returnhash{$key}) {
 3927: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3928:             } else {
 3929:                 $returnhash{$key}=$username.':'.$domain;
 3930:             }
 3931:         }
 3932:     }
 3933:     return %returnhash;
 3934: }
 3935: 
 3936: sub get_my_roles {
 3937:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3938:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3939:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3940:     my (%dumphash,%nothide);
 3941:     if ($context eq 'userroles') {
 3942:         %dumphash = &dump('roles',$udom,$uname);
 3943:     } else {
 3944:         %dumphash=
 3945:             &dump('nohist_userroles',$udom,$uname);
 3946:         if ($hidepriv) {
 3947:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3948:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3949:                 if ($user !~ /:/) {
 3950:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3951:                 } else {
 3952:                     $nothide{$user} = 1;
 3953:                 }
 3954:             }
 3955:         }
 3956:     }
 3957:     my %returnhash=();
 3958:     my $now=time;
 3959:     my %privileged;
 3960:     foreach my $entry (keys(%dumphash)) {
 3961:         my ($role,$tend,$tstart);
 3962:         if ($context eq 'userroles') {
 3963:             next if ($entry =~ /^rolesdef/);
 3964: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3965:         } else {
 3966:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3967:         }
 3968:         if (($tstart) && ($tstart<0)) { next; }
 3969:         my $status = 'active';
 3970:         if (($tend) && ($tend<=$now)) {
 3971:             $status = 'previous';
 3972:         } 
 3973:         if (($tstart) && ($now<$tstart)) {
 3974:             $status = 'future';
 3975:         }
 3976:         if (ref($types) eq 'ARRAY') {
 3977:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3978:                 next;
 3979:             } 
 3980:         } else {
 3981:             if ($status ne 'active') {
 3982:                 next;
 3983:             }
 3984:         }
 3985:         my ($rolecode,$username,$domain,$section,$area);
 3986:         if ($context eq 'userroles') {
 3987:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 3988:             (undef,$domain,$username,$section) = split(/\//,$area);
 3989:         } else {
 3990:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3991:         }
 3992:         if (ref($roledoms) eq 'ARRAY') {
 3993:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3994:                 next;
 3995:             }
 3996:         }
 3997:         if (ref($roles) eq 'ARRAY') {
 3998:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3999:                 if ($role =~ /^cr\//) {
 4000:                     if (!grep(/^cr$/,@{$roles})) {
 4001:                         next;
 4002:                     }
 4003:                 } elsif ($role =~ /^gr\//) {
 4004:                     if (!grep(/^gr$/,@{$roles})) {
 4005:                         next;
 4006:                     }
 4007:                 } else {
 4008:                     next;
 4009:                 }
 4010:             }
 4011:         }
 4012:         if ($hidepriv) {
 4013:             if ($context eq 'userroles') {
 4014:                 if ((&privileged($username,$domain)) &&
 4015:                     (!$nothide{$username.':'.$domain})) {
 4016:                     next;
 4017:                 }
 4018:             } else {
 4019:                 unless (ref($privileged{$domain}) eq 'HASH') {
 4020:                     my %dompersonnel =
 4021:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 4022:                     $privileged{$domain} = {};
 4023:                     if (keys(%dompersonnel)) {
 4024:                         foreach my $server (keys(%dompersonnel)) {
 4025:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 4026:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 4027:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 4028:                                     $privileged{$udom}{$uname} = $trole;
 4029:                                 }
 4030:                             }
 4031:                         }
 4032:                     }
 4033:                 }
 4034:                 if (exists($privileged{$domain}{$username})) {
 4035:                     if (!$nothide{$username.':'.$domain}) {
 4036:                         next;
 4037:                     }
 4038:                 }
 4039:             }
 4040:         }
 4041:         if ($withsec) {
 4042:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4043:                 $tstart.':'.$tend;
 4044:         } else {
 4045:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4046:         }
 4047:     }
 4048:     return %returnhash;
 4049: }
 4050: 
 4051: # ----------------------------------------------------- Frontpage Announcements
 4052: #
 4053: #
 4054: 
 4055: sub postannounce {
 4056:     my ($server,$text)=@_;
 4057:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4058:     unless ($text=~/\w/) { $text=''; }
 4059:     return &reply('setannounce:'.&escape($text),$server);
 4060: }
 4061: 
 4062: sub getannounce {
 4063: 
 4064:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4065: 	my $announcement='';
 4066: 	while (my $line = <$fh>) { $announcement .= $line; }
 4067: 	close($fh);
 4068: 	if ($announcement=~/\w/) { 
 4069: 	    return 
 4070:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4071:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4072: 	} else {
 4073: 	    return '';
 4074: 	}
 4075:     } else {
 4076: 	return '';
 4077:     }
 4078: }
 4079: 
 4080: # ---------------------------------------------------------- Course ID routines
 4081: # Deal with domain's nohist_courseid.db files
 4082: #
 4083: 
 4084: sub courseidput {
 4085:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4086:     return unless (ref($storehash) eq 'HASH');
 4087:     my $outcome;
 4088:     if ($caller eq 'timeonly') {
 4089:         my $cids = '';
 4090:         foreach my $item (keys(%$storehash)) {
 4091:             $cids.=&escape($item).'&';
 4092:         }
 4093:         $cids=~s/\&$//;
 4094:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4095:                           $coursehome);       
 4096:     } else {
 4097:         my $items = '';
 4098:         foreach my $item (keys(%$storehash)) {
 4099:             $items.= &escape($item).'='.
 4100:                      &freeze_escape($$storehash{$item}).'&';
 4101:         }
 4102:         $items=~s/\&$//;
 4103:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4104:                           $coursehome);
 4105:     }
 4106:     if ($outcome eq 'unknown_cmd') {
 4107:         my $what;
 4108:         foreach my $cid (keys(%$storehash)) {
 4109:             $what .= &escape($cid).'=';
 4110:             foreach my $item ('description','inst_code','owner','type') {
 4111:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4112:             }
 4113:             $what =~ s/\:$/&/;
 4114:         }
 4115:         $what =~ s/\&$//;  
 4116:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4117:     } else {
 4118:         return $outcome;
 4119:     }
 4120: }
 4121: 
 4122: sub courseiddump {
 4123:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4124:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4125:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4126:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4127:     my $as_hash = 1;
 4128:     my %returnhash;
 4129:     if (!$domfilter) { $domfilter=''; }
 4130:     my %libserv = &all_library();
 4131:     foreach my $tryserver (keys(%libserv)) {
 4132:         if ( (  $hostidflag == 1 
 4133: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4134: 	     || (!defined($hostidflag)) ) {
 4135: 
 4136: 	    if (($domfilter eq '') ||
 4137: 		(&host_domain($tryserver) eq $domfilter)) {
 4138:                 my $rep;
 4139:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4140:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4141:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4142:                                 &escape($descfilter), &escape($instcodefilter), 
 4143:                                 &escape($ownerfilter), &escape($coursefilter),
 4144:                                 &escape($typefilter), &escape($regexp_ok), 
 4145:                                 $as_hash, &escape($selfenrollonly), 
 4146:                                 &escape($catfilter), $showhidden, $caller, 
 4147:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4148:                                 &escape($createdbefore), &escape($createdafter), 
 4149:                                 &escape($creationcontext), $domcloner)));
 4150:                 } else {
 4151:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4152:                              $sincefilter.':'.&escape($descfilter).':'.
 4153:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4154:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4155:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4156:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4157:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4158:                              &escape($cc_clone).':'.$cloneonly.':'.
 4159:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4160:                              &escape($creationcontext).':'.$domcloner,
 4161:                              $tryserver);
 4162:                 }
 4163:                      
 4164:                 my @pairs=split(/\&/,$rep);
 4165:                 foreach my $item (@pairs) {
 4166:                     my ($key,$value)=split(/\=/,$item,2);
 4167:                     $key = &unescape($key);
 4168:                     next if ($key =~ /^error: 2 /);
 4169:                     my $result = &thaw_unescape($value);
 4170:                     if (ref($result) eq 'HASH') {
 4171:                         $returnhash{$key}=$result;
 4172:                     } else {
 4173:                         my @responses = split(/:/,$value);
 4174:                         my @items = ('description','inst_code','owner','type');
 4175:                         for (my $i=0; $i<@responses; $i++) {
 4176:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4177:                         }
 4178:                     }
 4179:                 }
 4180:             }
 4181:         }
 4182:     }
 4183:     return %returnhash;
 4184: }
 4185: 
 4186: sub courselastaccess {
 4187:     my ($cdom,$cnum,$hostidref) = @_;
 4188:     my %returnhash;
 4189:     if ($cdom && $cnum) {
 4190:         my $chome = &homeserver($cnum,$cdom);
 4191:         if ($chome ne 'no_host') {
 4192:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4193:             &extract_lastaccess(\%returnhash,$rep);
 4194:         }
 4195:     } else {
 4196:         if (!$cdom) { $cdom=''; }
 4197:         my %libserv = &all_library();
 4198:         foreach my $tryserver (keys(%libserv)) {
 4199:             if (ref($hostidref) eq 'ARRAY') {
 4200:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4201:             } 
 4202:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4203:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4204:                 &extract_lastaccess(\%returnhash,$rep);
 4205:             }
 4206:         }
 4207:     }
 4208:     return %returnhash;
 4209: }
 4210: 
 4211: sub extract_lastaccess {
 4212:     my ($returnhash,$rep) = @_;
 4213:     if (ref($returnhash) eq 'HASH') {
 4214:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4215:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4216:                  $rep eq '') {
 4217:             my @pairs=split(/\&/,$rep);
 4218:             foreach my $item (@pairs) {
 4219:                 my ($key,$value)=split(/\=/,$item,2);
 4220:                 $key = &unescape($key);
 4221:                 next if ($key =~ /^error: 2 /);
 4222:                 $returnhash->{$key} = &thaw_unescape($value);
 4223:             }
 4224:         }
 4225:     }
 4226:     return;
 4227: }
 4228: 
 4229: # ---------------------------------------------------------- DC e-mail
 4230: 
 4231: sub dcmailput {
 4232:     my ($domain,$msgid,$message,$server)=@_;
 4233:     my $status = &Apache::lonnet::critical(
 4234:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4235:        &escape($message),$server);
 4236:     return $status;
 4237: }
 4238: 
 4239: sub dcmaildump {
 4240:     my ($dom,$startdate,$enddate,$senders) = @_;
 4241:     my %returnhash=();
 4242: 
 4243:     if (defined(&domain($dom,'primary'))) {
 4244:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4245:                                                          &escape($enddate).':';
 4246: 	my @esc_senders=map { &escape($_)} @$senders;
 4247: 	$cmd.=&escape(join('&',@esc_senders));
 4248: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4249:             my ($key,$value) = split(/\=/,$line,2);
 4250:             if (($key) && ($value)) {
 4251:                 $returnhash{&unescape($key)} = &unescape($value);
 4252:             }
 4253:         }
 4254:     }
 4255:     return %returnhash;
 4256: }
 4257: # ---------------------------------------------------------- Domain roles
 4258: 
 4259: sub get_domain_roles {
 4260:     my ($dom,$roles,$startdate,$enddate)=@_;
 4261:     if ((!defined($startdate)) || ($startdate eq '')) {
 4262:         $startdate = '.';
 4263:     }
 4264:     if ((!defined($enddate)) || ($enddate eq '')) {
 4265:         $enddate = '.';
 4266:     }
 4267:     my $rolelist;
 4268:     if (ref($roles) eq 'ARRAY') {
 4269:         $rolelist = join(':',@{$roles});
 4270:     }
 4271:     my %personnel = ();
 4272: 
 4273:     my %servers = &get_servers($dom,'library');
 4274:     foreach my $tryserver (keys(%servers)) {
 4275: 	%{$personnel{$tryserver}}=();
 4276: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4277: 					    &escape($startdate).':'.
 4278: 					    &escape($enddate).':'.
 4279: 					    &escape($rolelist), $tryserver))) {
 4280: 	    my ($key,$value) = split(/\=/,$line,2);
 4281: 	    if (($key) && ($value)) {
 4282: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4283: 	    }
 4284: 	}
 4285:     }
 4286:     return %personnel;
 4287: }
 4288: 
 4289: # ----------------------------------------------------------- Interval timing 
 4290: 
 4291: {
 4292: # Caches needed for speedup of navmaps
 4293: # We don't want to cache this for very long at all (5 seconds at most)
 4294: # 
 4295: # The user for whom we cache
 4296: my $cachedkey='';
 4297: # The cached times for this user
 4298: my %cachedtimes=();
 4299: # When this was last done
 4300: my $cachedtime=();
 4301: 
 4302: sub load_all_first_access {
 4303:     my ($uname,$udom)=@_;
 4304:     if (($cachedkey eq $uname.':'.$udom) &&
 4305:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4306:         return;
 4307:     }
 4308:     $cachedtime=time;
 4309:     $cachedkey=$uname.':'.$udom;
 4310:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4311: }
 4312: 
 4313: sub get_first_access {
 4314:     my ($type,$argsymb,$argmap)=@_;
 4315:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4316:     if ($argsymb) { $symb=$argsymb; }
 4317:     my ($map,$id,$res)=&decode_symb($symb);
 4318:     if ($argmap) { $map = $argmap; }
 4319:     if ($type eq 'course') {
 4320: 	$res='course';
 4321:     } elsif ($type eq 'map') {
 4322: 	$res=&symbread($map);
 4323:     } else {
 4324: 	$res=$symb;
 4325:     }
 4326:     &load_all_first_access($uname,$udom);
 4327:     return $cachedtimes{"$courseid\0$res"};
 4328: }
 4329: 
 4330: sub set_first_access {
 4331:     my ($type,$interval)=@_;
 4332:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4333:     my ($map,$id,$res)=&decode_symb($symb);
 4334:     if ($type eq 'course') {
 4335: 	$res='course';
 4336:     } elsif ($type eq 'map') {
 4337: 	$res=&symbread($map);
 4338:     } else {
 4339: 	$res=$symb;
 4340:     }
 4341:     $cachedkey='';
 4342:     my $firstaccess=&get_first_access($type,$symb,$map);
 4343:     if (!$firstaccess) {
 4344:         my $start = time;
 4345: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4346:                           $udom,$uname);
 4347:         if ($putres eq 'ok') {
 4348:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4349:                  $udom,$uname); 
 4350:             &appenv(
 4351:                      {
 4352:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4353:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4354:                      }
 4355:                   );
 4356:         }
 4357:         return $putres;
 4358:     }
 4359:     return 'already_set';
 4360: }
 4361: }
 4362: # --------------------------------------------- Set Expire Date for Spreadsheet
 4363: 
 4364: sub expirespread {
 4365:     my ($uname,$udom,$stype,$usymb)=@_;
 4366:     my $cid=$env{'request.course.id'}; 
 4367:     if ($cid) {
 4368:        my $now=time;
 4369:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4370:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4371:                             $env{'course.'.$cid.'.num'}.
 4372: 	        	    ':nohist_expirationdates:'.
 4373:                             &escape($key).'='.$now,
 4374:                             $env{'course.'.$cid.'.home'})
 4375:     }
 4376:     return 'ok';
 4377: }
 4378: 
 4379: # ----------------------------------------------------- Devalidate Spreadsheets
 4380: 
 4381: sub devalidate {
 4382:     my ($symb,$uname,$udom)=@_;
 4383:     my $cid=$env{'request.course.id'}; 
 4384:     if ($cid) {
 4385:         # delete the stored spreadsheets for
 4386:         # - the student level sheet of this user in course's homespace
 4387:         # - the assessment level sheet for this resource 
 4388:         #   for this user in user's homespace
 4389: 	# - current conditional state info
 4390: 	my $key=$uname.':'.$udom.':';
 4391:         my $status=
 4392: 	    &del('nohist_calculatedsheets',
 4393: 		 [$key.'studentcalc:'],
 4394: 		 $env{'course.'.$cid.'.domain'},
 4395: 		 $env{'course.'.$cid.'.num'})
 4396: 		.' '.
 4397: 	    &del('nohist_calculatedsheets_'.$cid,
 4398: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4399:         unless ($status eq 'ok ok') {
 4400:            &logthis('Could not devalidate spreadsheet '.
 4401:                     $uname.' at '.$udom.' for '.
 4402: 		    $symb.': '.$status);
 4403:         }
 4404: 	&delenv('user.state.'.$cid);
 4405:     }
 4406: }
 4407: 
 4408: sub get_scalar {
 4409:     my ($string,$end) = @_;
 4410:     my $value;
 4411:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4412: 	$value = $1;
 4413:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4414: 	$value = $1;
 4415:     }
 4416:     return &unescape($value);
 4417: }
 4418: 
 4419: sub array2str {
 4420:   my (@array) = @_;
 4421:   my $result=&arrayref2str(\@array);
 4422:   $result=~s/^__ARRAY_REF__//;
 4423:   $result=~s/__END_ARRAY_REF__$//;
 4424:   return $result;
 4425: }
 4426: 
 4427: sub arrayref2str {
 4428:   my ($arrayref) = @_;
 4429:   my $result='__ARRAY_REF__';
 4430:   foreach my $elem (@$arrayref) {
 4431:     if(ref($elem) eq 'ARRAY') {
 4432:       $result.=&arrayref2str($elem).'&';
 4433:     } elsif(ref($elem) eq 'HASH') {
 4434:       $result.=&hashref2str($elem).'&';
 4435:     } elsif(ref($elem)) {
 4436:       #print("Got a ref of ".(ref($elem))." skipping.");
 4437:     } else {
 4438:       $result.=&escape($elem).'&';
 4439:     }
 4440:   }
 4441:   $result=~s/\&$//;
 4442:   $result .= '__END_ARRAY_REF__';
 4443:   return $result;
 4444: }
 4445: 
 4446: sub hash2str {
 4447:   my (%hash) = @_;
 4448:   my $result=&hashref2str(\%hash);
 4449:   $result=~s/^__HASH_REF__//;
 4450:   $result=~s/__END_HASH_REF__$//;
 4451:   return $result;
 4452: }
 4453: 
 4454: sub hashref2str {
 4455:   my ($hashref)=@_;
 4456:   my $result='__HASH_REF__';
 4457:   foreach my $key (sort(keys(%$hashref))) {
 4458:     if (ref($key) eq 'ARRAY') {
 4459:       $result.=&arrayref2str($key).'=';
 4460:     } elsif (ref($key) eq 'HASH') {
 4461:       $result.=&hashref2str($key).'=';
 4462:     } elsif (ref($key)) {
 4463:       $result.='=';
 4464:       #print("Got a ref of ".(ref($key))." skipping.");
 4465:     } else {
 4466: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4467:     }
 4468: 
 4469:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4470:       $result.=&arrayref2str($hashref->{$key}).'&';
 4471:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4472:       $result.=&hashref2str($hashref->{$key}).'&';
 4473:     } elsif(ref($hashref->{$key})) {
 4474:        $result.='&';
 4475:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4476:     } else {
 4477:       $result.=&escape($hashref->{$key}).'&';
 4478:     }
 4479:   }
 4480:   $result=~s/\&$//;
 4481:   $result .= '__END_HASH_REF__';
 4482:   return $result;
 4483: }
 4484: 
 4485: sub str2hash {
 4486:     my ($string)=@_;
 4487:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4488:     return %$hash;
 4489: }
 4490: 
 4491: sub str2hashref {
 4492:   my ($string) = @_;
 4493: 
 4494:   my %hash;
 4495: 
 4496:   if($string !~ /^__HASH_REF__/) {
 4497:       if (! ($string eq '' || !defined($string))) {
 4498: 	  $hash{'error'}='Not hash reference';
 4499:       }
 4500:       return (\%hash, $string);
 4501:   }
 4502: 
 4503:   $string =~ s/^__HASH_REF__//;
 4504: 
 4505:   while($string !~ /^__END_HASH_REF__/) {
 4506:       #key
 4507:       my $key='';
 4508:       if($string =~ /^__HASH_REF__/) {
 4509:           ($key, $string)=&str2hashref($string);
 4510:           if(defined($key->{'error'})) {
 4511:               $hash{'error'}='Bad data';
 4512:               return (\%hash, $string);
 4513:           }
 4514:       } elsif($string =~ /^__ARRAY_REF__/) {
 4515:           ($key, $string)=&str2arrayref($string);
 4516:           if($key->[0] eq 'Array reference error') {
 4517:               $hash{'error'}='Bad data';
 4518:               return (\%hash, $string);
 4519:           }
 4520:       } else {
 4521:           $string =~ s/^(.*?)=//;
 4522: 	  $key=&unescape($1);
 4523:       }
 4524:       $string =~ s/^=//;
 4525: 
 4526:       #value
 4527:       my $value='';
 4528:       if($string =~ /^__HASH_REF__/) {
 4529:           ($value, $string)=&str2hashref($string);
 4530:           if(defined($value->{'error'})) {
 4531:               $hash{'error'}='Bad data';
 4532:               return (\%hash, $string);
 4533:           }
 4534:       } elsif($string =~ /^__ARRAY_REF__/) {
 4535:           ($value, $string)=&str2arrayref($string);
 4536:           if($value->[0] eq 'Array reference error') {
 4537:               $hash{'error'}='Bad data';
 4538:               return (\%hash, $string);
 4539:           }
 4540:       } else {
 4541: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4542:       }
 4543:       $string =~ s/^&//;
 4544: 
 4545:       $hash{$key}=$value;
 4546:   }
 4547: 
 4548:   $string =~ s/^__END_HASH_REF__//;
 4549: 
 4550:   return (\%hash, $string);
 4551: }
 4552: 
 4553: sub str2array {
 4554:     my ($string)=@_;
 4555:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4556:     return @$array;
 4557: }
 4558: 
 4559: sub str2arrayref {
 4560:   my ($string) = @_;
 4561:   my @array;
 4562: 
 4563:   if($string !~ /^__ARRAY_REF__/) {
 4564:       if (! ($string eq '' || !defined($string))) {
 4565: 	  $array[0]='Array reference error';
 4566:       }
 4567:       return (\@array, $string);
 4568:   }
 4569: 
 4570:   $string =~ s/^__ARRAY_REF__//;
 4571: 
 4572:   while($string !~ /^__END_ARRAY_REF__/) {
 4573:       my $value='';
 4574:       if($string =~ /^__HASH_REF__/) {
 4575:           ($value, $string)=&str2hashref($string);
 4576:           if(defined($value->{'error'})) {
 4577:               $array[0] ='Array reference error';
 4578:               return (\@array, $string);
 4579:           }
 4580:       } elsif($string =~ /^__ARRAY_REF__/) {
 4581:           ($value, $string)=&str2arrayref($string);
 4582:           if($value->[0] eq 'Array reference error') {
 4583:               $array[0] ='Array reference error';
 4584:               return (\@array, $string);
 4585:           }
 4586:       } else {
 4587: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4588:       }
 4589:       $string =~ s/^&//;
 4590: 
 4591:       push(@array, $value);
 4592:   }
 4593: 
 4594:   $string =~ s/^__END_ARRAY_REF__//;
 4595: 
 4596:   return (\@array, $string);
 4597: }
 4598: 
 4599: # -------------------------------------------------------------------Temp Store
 4600: 
 4601: sub tmpreset {
 4602:   my ($symb,$namespace,$domain,$stuname) = @_;
 4603:   if (!$symb) {
 4604:     $symb=&symbread();
 4605:     if (!$symb) { $symb= $env{'request.url'}; }
 4606:   }
 4607:   $symb=escape($symb);
 4608: 
 4609:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4610:   $namespace=~s/\//\_/g;
 4611:   $namespace=~s/\W//g;
 4612: 
 4613:   if (!$domain) { $domain=$env{'user.domain'}; }
 4614:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4615:   if ($domain eq 'public' && $stuname eq 'public') {
 4616:       $stuname=$ENV{'REMOTE_ADDR'};
 4617:   }
 4618:   my $path=LONCAPA::tempdir();
 4619:   my %hash;
 4620:   if (tie(%hash,'GDBM_File',
 4621: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4622: 	  &GDBM_WRCREAT(),0640)) {
 4623:     foreach my $key (keys(%hash)) {
 4624:       if ($key=~ /:$symb/) {
 4625: 	delete($hash{$key});
 4626:       }
 4627:     }
 4628:   }
 4629: }
 4630: 
 4631: sub tmpstore {
 4632:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4633: 
 4634:   if (!$symb) {
 4635:     $symb=&symbread();
 4636:     if (!$symb) { $symb= $env{'request.url'}; }
 4637:   }
 4638:   $symb=escape($symb);
 4639: 
 4640:   if (!$namespace) {
 4641:     # I don't think we would ever want to store this for a course.
 4642:     # it seems this will only be used if we don't have a course.
 4643:     #$namespace=$env{'request.course.id'};
 4644:     #if (!$namespace) {
 4645:       $namespace=$env{'request.state'};
 4646:     #}
 4647:   }
 4648:   $namespace=~s/\//\_/g;
 4649:   $namespace=~s/\W//g;
 4650:   if (!$domain) { $domain=$env{'user.domain'}; }
 4651:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4652:   if ($domain eq 'public' && $stuname eq 'public') {
 4653:       $stuname=$ENV{'REMOTE_ADDR'};
 4654:   }
 4655:   my $now=time;
 4656:   my %hash;
 4657:   my $path=LONCAPA::tempdir();
 4658:   if (tie(%hash,'GDBM_File',
 4659: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4660: 	  &GDBM_WRCREAT(),0640)) {
 4661:     $hash{"version:$symb"}++;
 4662:     my $version=$hash{"version:$symb"};
 4663:     my $allkeys=''; 
 4664:     foreach my $key (keys(%$storehash)) {
 4665:       $allkeys.=$key.':';
 4666:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4667:     }
 4668:     $hash{"$version:$symb:timestamp"}=$now;
 4669:     $allkeys.='timestamp';
 4670:     $hash{"$version:keys:$symb"}=$allkeys;
 4671:     if (untie(%hash)) {
 4672:       return 'ok';
 4673:     } else {
 4674:       return "error:$!";
 4675:     }
 4676:   } else {
 4677:     return "error:$!";
 4678:   }
 4679: }
 4680: 
 4681: # -----------------------------------------------------------------Temp Restore
 4682: 
 4683: sub tmprestore {
 4684:   my ($symb,$namespace,$domain,$stuname) = @_;
 4685: 
 4686:   if (!$symb) {
 4687:     $symb=&symbread();
 4688:     if (!$symb) { $symb= $env{'request.url'}; }
 4689:   }
 4690:   $symb=escape($symb);
 4691: 
 4692:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4693: 
 4694:   if (!$domain) { $domain=$env{'user.domain'}; }
 4695:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4696:   if ($domain eq 'public' && $stuname eq 'public') {
 4697:       $stuname=$ENV{'REMOTE_ADDR'};
 4698:   }
 4699:   my %returnhash;
 4700:   $namespace=~s/\//\_/g;
 4701:   $namespace=~s/\W//g;
 4702:   my %hash;
 4703:   my $path=LONCAPA::tempdir();
 4704:   if (tie(%hash,'GDBM_File',
 4705: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4706: 	  &GDBM_READER(),0640)) {
 4707:     my $version=$hash{"version:$symb"};
 4708:     $returnhash{'version'}=$version;
 4709:     my $scope;
 4710:     for ($scope=1;$scope<=$version;$scope++) {
 4711:       my $vkeys=$hash{"$scope:keys:$symb"};
 4712:       my @keys=split(/:/,$vkeys);
 4713:       my $key;
 4714:       $returnhash{"$scope:keys"}=$vkeys;
 4715:       foreach $key (@keys) {
 4716: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4717: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4718:       }
 4719:     }
 4720:     if (!(untie(%hash))) {
 4721:       return "error:$!";
 4722:     }
 4723:   } else {
 4724:     return "error:$!";
 4725:   }
 4726:   return %returnhash;
 4727: }
 4728: 
 4729: # ----------------------------------------------------------------------- Store
 4730: 
 4731: sub store {
 4732:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4733:     my $home='';
 4734: 
 4735:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4736: 
 4737:     $symb=&symbclean($symb);
 4738:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4739: 
 4740:     if (!$domain) { $domain=$env{'user.domain'}; }
 4741:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4742: 
 4743:     &devalidate($symb,$stuname,$domain);
 4744: 
 4745:     $symb=escape($symb);
 4746:     if (!$namespace) { 
 4747:        unless ($namespace=$env{'request.course.id'}) { 
 4748:           return ''; 
 4749:        } 
 4750:     }
 4751:     if (!$home) { $home=$env{'user.home'}; }
 4752: 
 4753:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4754:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4755: 
 4756:     my $namevalue='';
 4757:     foreach my $key (keys(%$storehash)) {
 4758:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4759:     }
 4760:     $namevalue=~s/\&$//;
 4761:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4762:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4763: }
 4764: 
 4765: # -------------------------------------------------------------- Critical Store
 4766: 
 4767: sub cstore {
 4768:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4769:     my $home='';
 4770: 
 4771:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4772: 
 4773:     $symb=&symbclean($symb);
 4774:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4775: 
 4776:     if (!$domain) { $domain=$env{'user.domain'}; }
 4777:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4778: 
 4779:     &devalidate($symb,$stuname,$domain);
 4780: 
 4781:     $symb=escape($symb);
 4782:     if (!$namespace) { 
 4783:        unless ($namespace=$env{'request.course.id'}) { 
 4784:           return ''; 
 4785:        } 
 4786:     }
 4787:     if (!$home) { $home=$env{'user.home'}; }
 4788: 
 4789:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4790:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4791: 
 4792:     my $namevalue='';
 4793:     foreach my $key (keys(%$storehash)) {
 4794:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4795:     }
 4796:     $namevalue=~s/\&$//;
 4797:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4798:     return critical
 4799:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4800: }
 4801: 
 4802: # --------------------------------------------------------------------- Restore
 4803: 
 4804: sub restore {
 4805:     my ($symb,$namespace,$domain,$stuname) = @_;
 4806:     my $home='';
 4807: 
 4808:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4809: 
 4810:     if (!$symb) {
 4811:       unless ($symb=escape(&symbread())) { return ''; }
 4812:     } else {
 4813:       $symb=&escape(&symbclean($symb));
 4814:     }
 4815:     if (!$namespace) { 
 4816:        unless ($namespace=$env{'request.course.id'}) { 
 4817:           return ''; 
 4818:        } 
 4819:     }
 4820:     if (!$domain) { $domain=$env{'user.domain'}; }
 4821:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4822:     if (!$home) { $home=$env{'user.home'}; }
 4823:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4824: 
 4825:     my %returnhash=();
 4826:     foreach my $line (split(/\&/,$answer)) {
 4827: 	my ($name,$value)=split(/\=/,$line);
 4828:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4829:     }
 4830:     my $version;
 4831:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4832:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4833:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4834:        }
 4835:     }
 4836:     return %returnhash;
 4837: }
 4838: 
 4839: # ---------------------------------------------------------- Course Description
 4840: #
 4841: #  
 4842: 
 4843: sub coursedescription {
 4844:     my ($courseid,$args)=@_;
 4845:     $courseid=~s/^\///;
 4846:     $courseid=~s/\_/\//g;
 4847:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4848:     my $chome=&homeserver($cnum,$cdomain);
 4849:     my $normalid=$cdomain.'_'.$cnum;
 4850:     # need to always cache even if we get errors otherwise we keep 
 4851:     # trying and trying and trying to get the course description.
 4852:     my %envhash=();
 4853:     my %returnhash=();
 4854:     
 4855:     my $expiretime=600;
 4856:     if ($env{'request.course.id'} eq $normalid) {
 4857: 	$expiretime=120;
 4858:     }
 4859: 
 4860:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4861:     if (!$args->{'freshen_cache'}
 4862: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4863: 	foreach my $key (keys(%env)) {
 4864: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4865: 	    my ($setting) = $1;
 4866: 	    $returnhash{$setting} = $env{$key};
 4867: 	}
 4868: 	return %returnhash;
 4869:     }
 4870: 
 4871:     # get the data again
 4872: 
 4873:     if (!$args->{'one_time'}) {
 4874: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4875:     }
 4876: 
 4877:     if ($chome ne 'no_host') {
 4878:        %returnhash=&dump('environment',$cdomain,$cnum);
 4879:        if (!exists($returnhash{'con_lost'})) {
 4880: 	   my $username = $env{'user.name'}; # Defult username
 4881: 	   if(defined $args->{'user'}) {
 4882: 	       $username = $args->{'user'};
 4883: 	   }
 4884:            $returnhash{'home'}= $chome;
 4885: 	   $returnhash{'domain'} = $cdomain;
 4886: 	   $returnhash{'num'} = $cnum;
 4887:            if (!defined($returnhash{'type'})) {
 4888:                $returnhash{'type'} = 'Course';
 4889:            }
 4890:            while (my ($name,$value) = each %returnhash) {
 4891:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4892:            }
 4893:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4894:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4895: 	       $username.'_'.$cdomain.'_'.$cnum;
 4896:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4897:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4898:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4899:        }
 4900:     }
 4901:     if (!$args->{'one_time'}) {
 4902: 	&appenv(\%envhash);
 4903:     }
 4904:     return %returnhash;
 4905: }
 4906: 
 4907: sub update_released_required {
 4908:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4909:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4910:         $cid = $env{'request.course.id'};
 4911:         $cdom = $env{'course.'.$cid.'.domain'};
 4912:         $cnum = $env{'course.'.$cid.'.num'};
 4913:         $chome = $env{'course.'.$cid.'.home'};
 4914:     }
 4915:     if ($needsrelease) {
 4916:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4917:         my $needsupdate;
 4918:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4919:             $needsupdate = 1;
 4920:         } else {
 4921:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4922:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4923:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4924:                 $needsupdate = 1;
 4925:             }
 4926:         }
 4927:         if ($needsupdate) {
 4928:             my %needshash = (
 4929:                              'internal.releaserequired' => $needsrelease,
 4930:                             );
 4931:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4932:             if ($putresult eq 'ok') {
 4933:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4934:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4935:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4936:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4937:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4938:                 }
 4939:             }
 4940:         }
 4941:     }
 4942:     return;
 4943: }
 4944: 
 4945: # -------------------------------------------------See if a user is privileged
 4946: 
 4947: sub privileged {
 4948:     my ($username,$domain)=@_;
 4949: 
 4950:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4951:     my $now = time;
 4952: 
 4953:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4954:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4955:             if (($trole eq 'dc') || ($trole eq 'su')) {
 4956:                 return 1 unless ($tend && $tend < $now) 
 4957:                     or ($tstart && $tstart > $now);
 4958:             }
 4959: 	}
 4960: 
 4961:     return 0;
 4962: }
 4963: 
 4964: # -------------------------------------------------------- Get user privileges
 4965: 
 4966: sub rolesinit {
 4967:     my ($domain, $username) = @_;
 4968:     my %userroles = ('user.login.time' => time);
 4969:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 4970: 
 4971:     # firstaccess and timerinterval are related to timed maps/resources. 
 4972:     # also, blocking can be triggered by an activating timer
 4973:     # it's saved in the user's %env.
 4974:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 4975:     my %timerinterval = &dump('timerinterval', $domain, $username);
 4976:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 4977:         %timerintchk, %timerintenv);
 4978: 
 4979:     foreach my $key (keys(%firstaccess)) {
 4980:         my ($cid, $rest) = split(/\0/, $key);
 4981:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4982:     }
 4983: 
 4984:     foreach my $key (keys(%timerinterval)) {
 4985:         my ($cid,$rest) = split(/\0/,$key);
 4986:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4987:     }
 4988: 
 4989:     my %allroles=();
 4990:     my %allgroups=();
 4991: 
 4992:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 4993:         my $role = $rolesdump{$area};
 4994:         $area =~ s/\_\w\w$//;
 4995: 
 4996:         my ($trole, $tend, $tstart, $group_privs);
 4997: 
 4998:         if ($role =~ /^cr/) {
 4999:         # Custom role, defined by a user 
 5000:         # e.g., user.role.cr/msu/smith/mynewrole
 5001:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5002:                 $trole = $1;
 5003:                 ($tend, $tstart) = split('_', $2);
 5004:             } else {
 5005:                 $trole = $role;
 5006:             }
 5007:         } elsif ($role =~ m|^gr/|) {
 5008:         # Role of member in a group, defined within a course/community
 5009:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5010:             ($trole, $tend, $tstart) = split(/_/, $role);
 5011:             next if $tstart eq '-1';
 5012:             ($trole, $group_privs) = split(/\//, $trole);
 5013:             $group_privs = &unescape($group_privs);
 5014:         } else {
 5015:         # Just a normal role, defined in roles.tab
 5016:             ($trole, $tend, $tstart) = split(/_/,$role);
 5017:         }
 5018: 
 5019:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5020:                  $username);
 5021:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5022: 
 5023:         # role expired or not available yet?
 5024:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5025:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5026: 
 5027:         next if $area eq '' or $trole eq '';
 5028: 
 5029:         my $spec = "$trole.$area";
 5030:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5031: 
 5032:         if ($trole =~ /^cr\//) {
 5033:         # Custom role, defined by a user
 5034:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5035:         } elsif ($trole eq 'gr') {
 5036:         # Role of a member in a group, defined within a course/community
 5037:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5038:             next;
 5039:         } else {
 5040:         # Normal role, defined in roles.tab
 5041:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5042:         }
 5043: 
 5044:         my $cid = $tdomain.'_'.$trest;
 5045:         unless ($firstaccchk{$cid}) {
 5046:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5047:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5048:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5049:                         $coursetimerstarts{$cid}{$item}; 
 5050:                 }
 5051:             }
 5052:             $firstaccchk{$cid} = 1;
 5053:         }
 5054:         unless ($timerintchk{$cid}) {
 5055:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5056:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5057:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5058:                        $coursetimerintervals{$cid}{$item};
 5059:                 }
 5060:             }
 5061:             $timerintchk{$cid} = 1;
 5062:         }
 5063:     }
 5064: 
 5065:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5066:         \%allroles, \%allgroups);
 5067:     $env{'user.adv'} = $userroles{'user.adv'};
 5068: 
 5069:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5070: }
 5071: 
 5072: sub set_arearole {
 5073:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5074:     unless ($nolog) {
 5075: # log the associated role with the area
 5076:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5077:     }
 5078:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5079: }
 5080: 
 5081: sub custom_roleprivs {
 5082:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5083:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5084:     my $homsvr=homeserver($rauthor,$rdomain);
 5085:     if (&hostname($homsvr) ne '') {
 5086:         my ($rdummy,$roledef)=
 5087:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5088:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5089:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5090:             if (defined($syspriv)) {
 5091:                 if ($trest =~ /^$match_community$/) {
 5092:                     $syspriv =~ s/bre\&S//; 
 5093:                 }
 5094:                 $$allroles{'cm./'}.=':'.$syspriv;
 5095:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5096:             }
 5097:             if ($tdomain ne '') {
 5098:                 if (defined($dompriv)) {
 5099:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5100:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5101:                 }
 5102:                 if (($trest ne '') && (defined($coursepriv))) {
 5103:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5104:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5105:                 }
 5106:             }
 5107:         }
 5108:     }
 5109: }
 5110: 
 5111: sub group_roleprivs {
 5112:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5113:     my $access = 1;
 5114:     my $now = time;
 5115:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5116:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5117:     if ($access) {
 5118:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5119:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5120:     }
 5121: }
 5122: 
 5123: sub standard_roleprivs {
 5124:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5125:     if (defined($pr{$trole.':s'})) {
 5126:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5127:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5128:     }
 5129:     if ($tdomain ne '') {
 5130:         if (defined($pr{$trole.':d'})) {
 5131:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5132:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5133:         }
 5134:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5135:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5136:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5137:         }
 5138:     }
 5139: }
 5140: 
 5141: sub set_userprivs {
 5142:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5143:     my $author=0;
 5144:     my $adv=0;
 5145:     my %grouproles = ();
 5146:     if (keys(%{$allgroups}) > 0) {
 5147:         my @groupkeys; 
 5148:         foreach my $role (keys(%{$allroles})) {
 5149:             push(@groupkeys,$role);
 5150:         }
 5151:         if (ref($groups_roles) eq 'HASH') {
 5152:             foreach my $key (keys(%{$groups_roles})) {
 5153:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5154:                     push(@groupkeys,$key);
 5155:                 }
 5156:             }
 5157:         }
 5158:         if (@groupkeys > 0) {
 5159:             foreach my $role (@groupkeys) {
 5160:                 my ($trole,$area,$sec,$extendedarea);
 5161:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5162:                     $trole = $1;
 5163:                     $area = $2;
 5164:                     $sec = $3;
 5165:                     $extendedarea = $area.$sec;
 5166:                     if (exists($$allgroups{$area})) {
 5167:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5168:                             my $spec = $trole.'.'.$extendedarea;
 5169:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5170:                                                 $$allgroups{$area}{$group};
 5171:                         }
 5172:                     }
 5173:                 }
 5174:             }
 5175:         }
 5176:     }
 5177:     foreach my $group (keys(%grouproles)) {
 5178:         $$allroles{$group} = $grouproles{$group};
 5179:     }
 5180:     foreach my $role (keys(%{$allroles})) {
 5181:         my %thesepriv;
 5182:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5183:         foreach my $item (split(/:/,$$allroles{$role})) {
 5184:             if ($item ne '') {
 5185:                 my ($privilege,$restrictions)=split(/&/,$item);
 5186:                 if ($restrictions eq '') {
 5187:                     $thesepriv{$privilege}='F';
 5188:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5189:                     $thesepriv{$privilege}.=$restrictions;
 5190:                 }
 5191:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5192:             }
 5193:         }
 5194:         my $thesestr='';
 5195:         foreach my $priv (sort(keys(%thesepriv))) {
 5196: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5197: 	}
 5198:         $userroles->{'user.priv.'.$role} = $thesestr;
 5199:     }
 5200:     return ($author,$adv);
 5201: }
 5202: 
 5203: sub role_status {
 5204:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5205:     my @pwhere = ();
 5206:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5207:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5208:         unless (!defined($$role) || $$role eq '') {
 5209:             $$where=join('.',@pwhere);
 5210:             $$trolecode=$$role.'.'.$$where;
 5211:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5212:             $$tstatus='is';
 5213:             if ($$tstart && $$tstart>$update) {
 5214:                 $$tstatus='future';
 5215:                 if ($$tstart<$now) {
 5216:                     if ($$tstart && $$tstart>$refresh) {
 5217:                         if (($$where ne '') && ($$role ne '')) {
 5218:                             my (%allroles,%allgroups,$group_privs,
 5219:                                 %groups_roles,@rolecodes);
 5220:                             my %userroles = (
 5221:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5222:                             );
 5223:                             @rolecodes = ('cm'); 
 5224:                             my $spec=$$role.'.'.$$where;
 5225:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5226:                             if ($$role =~ /^cr\//) {
 5227:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5228:                                 push(@rolecodes,'cr');
 5229:                             } elsif ($$role eq 'gr') {
 5230:                                 push(@rolecodes,$$role);
 5231:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5232:                                                     $env{'user.name'});
 5233:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5234:                                 (undef,my $group_privs) = split(/\//,$trole);
 5235:                                 $group_privs = &unescape($group_privs);
 5236:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5237:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5238:                                 &get_groups_roles($tdomain,$trest,
 5239:                                                   \%course_roles,\@rolecodes,
 5240:                                                   \%groups_roles);
 5241:                             } else {
 5242:                                 push(@rolecodes,$$role);
 5243:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5244:                             }
 5245:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5246:                             &appenv(\%userroles,\@rolecodes);
 5247:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5248:                         }
 5249:                     }
 5250:                     $$tstatus = 'is';
 5251:                 }
 5252:             }
 5253:             if ($$tend) {
 5254:                 if ($$tend<$update) {
 5255:                     $$tstatus='expired';
 5256:                 } elsif ($$tend<$now) {
 5257:                     $$tstatus='will_not';
 5258:                 }
 5259:             }
 5260:         }
 5261:     }
 5262: }
 5263: 
 5264: sub get_groups_roles {
 5265:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5266:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5267:                   (ref($rolecodes) eq 'ARRAY') && 
 5268:                   (ref($groups_roles) eq 'HASH')); 
 5269:     if (keys(%{$cdom_courseroles}) > 0) {
 5270:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5271:         if ($cdom ne '' && $cnum ne '') {
 5272:             foreach my $key (keys(%{$cdom_courseroles})) {
 5273:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5274:                     my $crsrole = $1;
 5275:                     my $crssec = $2;
 5276:                     if ($crsrole =~ /^cr/) {
 5277:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5278:                             push(@{$rolecodes},'cr');
 5279:                         }
 5280:                     } else {
 5281:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5282:                             push(@{$rolecodes},$crsrole);
 5283:                         }
 5284:                     }
 5285:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5286:                     if ($crssec ne '') {
 5287:                         $rolekey .= "/$crssec";
 5288:                     }
 5289:                     $rolekey .= './';
 5290:                     $groups_roles->{$rolekey} = $rolecodes;
 5291:                 }
 5292:             }
 5293:         }
 5294:     }
 5295:     return;
 5296: }
 5297: 
 5298: sub delete_env_groupprivs {
 5299:     my ($where,$courseroles,$possroles) = @_;
 5300:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5301:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5302:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5303:         %{$courseroles->{$udom}} =
 5304:             &get_my_roles('','','userroles',['active'],
 5305:                           $possroles,[$udom],1);
 5306:     }
 5307:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5308:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5309:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5310:             my $area = '/'.$cdom.'/'.$cnum;
 5311:             my $privkey = "user.priv.$crsrole.$area";
 5312:             if ($crssec ne '') {
 5313:                 $privkey .= '/'.$crssec;
 5314:             }
 5315:             $privkey .= ".$area/$group";
 5316:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5317:         }
 5318:     }
 5319:     return;
 5320: }
 5321: 
 5322: sub check_adhoc_privs {
 5323:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5324:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5325:     my $setprivs;
 5326:     if ($env{$cckey}) {
 5327:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5328:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5329:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5330:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5331:             $setprivs = 1;
 5332:         }
 5333:     } else {
 5334:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5335:         $setprivs = 1;
 5336:     }
 5337:     return $setprivs;
 5338: }
 5339: 
 5340: sub set_adhoc_privileges {
 5341: # role can be cc or ca
 5342:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5343:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5344:     my $spec = $role.'.'.$area;
 5345:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5346:                                   $env{'user.name'},1);
 5347:     my %ccrole = ();
 5348:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5349:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5350:     &appenv(\%userroles,[$role,'cm']);
 5351:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5352:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5353:         &appenv( {'request.role'        => $spec,
 5354:                   'request.role.domain' => $dcdom,
 5355:                   'request.course.sec'  => ''
 5356:                  }
 5357:                );
 5358:         my $tadv=0;
 5359:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5360:         &appenv({'request.role.adv'    => $tadv});
 5361:     }
 5362: }
 5363: 
 5364: # --------------------------------------------------------------- get interface
 5365: 
 5366: sub get {
 5367:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5368:    my $items='';
 5369:    foreach my $item (@$storearr) {
 5370:        $items.=&escape($item).'&';
 5371:    }
 5372:    $items=~s/\&$//;
 5373:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5374:    if (!$uname) { $uname=$env{'user.name'}; }
 5375:    my $uhome=&homeserver($uname,$udomain);
 5376: 
 5377:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5378:    my @pairs=split(/\&/,$rep);
 5379:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5380:      return @pairs;
 5381:    }
 5382:    my %returnhash=();
 5383:    my $i=0;
 5384:    foreach my $item (@$storearr) {
 5385:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5386:       $i++;
 5387:    }
 5388:    return %returnhash;
 5389: }
 5390: 
 5391: # --------------------------------------------------------------- del interface
 5392: 
 5393: sub del {
 5394:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5395:    my $items='';
 5396:    foreach my $item (@$storearr) {
 5397:        $items.=&escape($item).'&';
 5398:    }
 5399: 
 5400:    $items=~s/\&$//;
 5401:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5402:    if (!$uname) { $uname=$env{'user.name'}; }
 5403:    my $uhome=&homeserver($uname,$udomain);
 5404:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5405: }
 5406: 
 5407: # -------------------------------------------------------------- dump interface
 5408: 
 5409: sub unserialize {
 5410:     my ($rep, $escapedkeys) = @_;
 5411: 
 5412:     return {} if $rep =~ /^error/;
 5413: 
 5414:     my %returnhash=();
 5415: 	foreach my $item (split /\&/, $rep) {
 5416: 	    my ($key, $value) = split(/=/, $item, 2);
 5417: 	    $key = unescape($key) unless $escapedkeys;
 5418: 	    next if $key =~ /^error: 2 /;
 5419: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5420: 	}
 5421:     #return %returnhash;
 5422:     return \%returnhash;
 5423: }        
 5424: 
 5425: # see Lond::dump_with_regexp
 5426: # if $escapedkeys hash keys won't get unescaped.
 5427: sub dump {
 5428:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5429:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5430:     if (!$uname) { $uname=$env{'user.name'}; }
 5431:     my $uhome=&homeserver($uname,$udomain);
 5432: 
 5433:     my $reply;
 5434:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5435:         # user is hosted on this machine
 5436:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5437:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
 5438:         return %{unserialize($reply, $escapedkeys)};
 5439:     }
 5440:     if ($regexp) {
 5441: 	$regexp=&escape($regexp);
 5442:     } else {
 5443: 	$regexp='.';
 5444:     }
 5445:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5446:     my @pairs=split(/\&/,$rep);
 5447:     my %returnhash=();
 5448:     if (!($rep =~ /^error/ )) {
 5449: 	foreach my $item (@pairs) {
 5450: 	    my ($key,$value)=split(/=/,$item,2);
 5451:         $key = unescape($key) unless $escapedkeys;
 5452:         #$key = &unescape($key);
 5453: 	    next if ($key =~ /^error: 2 /);
 5454: 	    $returnhash{$key}=&thaw_unescape($value);
 5455: 	}
 5456:     }
 5457:     return %returnhash;
 5458: }
 5459: 
 5460: 
 5461: # --------------------------------------------------------- dumpstore interface
 5462: 
 5463: sub dumpstore {
 5464:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5465:    # same as dump but keys must be escaped. They may contain colon separated
 5466:    # lists of values that may themself contain colons (e.g. symbs).
 5467:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5468: }
 5469: 
 5470: # -------------------------------------------------------------- keys interface
 5471: 
 5472: sub getkeys {
 5473:    my ($namespace,$udomain,$uname)=@_;
 5474:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5475:    if (!$uname) { $uname=$env{'user.name'}; }
 5476:    my $uhome=&homeserver($uname,$udomain);
 5477:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5478:    my @keyarray=();
 5479:    foreach my $key (split(/\&/,$rep)) {
 5480:       next if ($key =~ /^error: 2 /);
 5481:       push(@keyarray,&unescape($key));
 5482:    }
 5483:    return @keyarray;
 5484: }
 5485: 
 5486: # --------------------------------------------------------------- currentdump
 5487: sub currentdump {
 5488:    my ($courseid,$sdom,$sname)=@_;
 5489:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5490:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5491:    $sname    = $env{'user.name'}         if (! defined($sname));
 5492:    my $uhome = &homeserver($sname,$sdom);
 5493:    my $rep;
 5494: 
 5495:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5496:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5497:                    $courseid)));
 5498:    } else {
 5499:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5500:    }
 5501: 
 5502:    return if ($rep =~ /^(error:|no_such_host)/);
 5503:    #
 5504:    my %returnhash=();
 5505:    #
 5506:    if ($rep eq "unknown_cmd") { 
 5507:        # an old lond will not know currentdump
 5508:        # Do a dump and make it look like a currentdump
 5509:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5510:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5511:        my %hash = @tmp;
 5512:        @tmp=();
 5513:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5514:    } else {
 5515:        my @pairs=split(/\&/,$rep);
 5516:        foreach my $pair (@pairs) {
 5517:            my ($key,$value)=split(/=/,$pair,2);
 5518:            my ($symb,$param) = split(/:/,$key);
 5519:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5520:                                                         &thaw_unescape($value);
 5521:        }
 5522:    }
 5523:    return %returnhash;
 5524: }
 5525: 
 5526: sub convert_dump_to_currentdump{
 5527:     my %hash = %{shift()};
 5528:     my %returnhash;
 5529:     # Code ripped from lond, essentially.  The only difference
 5530:     # here is the unescaping done by lonnet::dump().  Conceivably
 5531:     # we might run in to problems with parameter names =~ /^v\./
 5532:     while (my ($key,$value) = each(%hash)) {
 5533:         my ($v,$symb,$param) = split(/:/,$key);
 5534: 	$symb  = &unescape($symb);
 5535: 	$param = &unescape($param);
 5536:         next if ($v eq 'version' || $symb eq 'keys');
 5537:         next if (exists($returnhash{$symb}) &&
 5538:                  exists($returnhash{$symb}->{$param}) &&
 5539:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5540:         $returnhash{$symb}->{$param}=$value;
 5541:         $returnhash{$symb}->{'v.'.$param}=$v;
 5542:     }
 5543:     #
 5544:     # Remove all of the keys in the hashes which keep track of
 5545:     # the version of the parameter.
 5546:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5547:         # use a foreach because we are going to delete from the hash.
 5548:         foreach my $key (keys(%$param_hash)) {
 5549:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5550:         }
 5551:     }
 5552:     return \%returnhash;
 5553: }
 5554: 
 5555: # ------------------------------------------------------ critical inc interface
 5556: 
 5557: sub cinc {
 5558:     return &inc(@_,'critical');
 5559: }
 5560: 
 5561: # --------------------------------------------------------------- inc interface
 5562: 
 5563: sub inc {
 5564:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5565:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5566:     if (!$uname) { $uname=$env{'user.name'}; }
 5567:     my $uhome=&homeserver($uname,$udomain);
 5568:     my $items='';
 5569:     if (! ref($store)) {
 5570:         # got a single value, so use that instead
 5571:         $items = &escape($store).'=&';
 5572:     } elsif (ref($store) eq 'SCALAR') {
 5573:         $items = &escape($$store).'=&';        
 5574:     } elsif (ref($store) eq 'ARRAY') {
 5575:         $items = join('=&',map {&escape($_);} @{$store});
 5576:     } elsif (ref($store) eq 'HASH') {
 5577:         while (my($key,$value) = each(%{$store})) {
 5578:             $items.= &escape($key).'='.&escape($value).'&';
 5579:         }
 5580:     }
 5581:     $items=~s/\&$//;
 5582:     if ($critical) {
 5583: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5584:     } else {
 5585: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5586:     }
 5587: }
 5588: 
 5589: # --------------------------------------------------------------- put interface
 5590: 
 5591: sub put {
 5592:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5593:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5594:    if (!$uname) { $uname=$env{'user.name'}; }
 5595:    my $uhome=&homeserver($uname,$udomain);
 5596:    my $items='';
 5597:    foreach my $item (keys(%$storehash)) {
 5598:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5599:    }
 5600:    $items=~s/\&$//;
 5601:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5602: }
 5603: 
 5604: # ------------------------------------------------------------ newput interface
 5605: 
 5606: sub newput {
 5607:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5608:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5609:    if (!$uname) { $uname=$env{'user.name'}; }
 5610:    my $uhome=&homeserver($uname,$udomain);
 5611:    my $items='';
 5612:    foreach my $key (keys(%$storehash)) {
 5613:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5614:    }
 5615:    $items=~s/\&$//;
 5616:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5617: }
 5618: 
 5619: # ---------------------------------------------------------  putstore interface
 5620: 
 5621: sub putstore {
 5622:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5623:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5624:    if (!$uname) { $uname=$env{'user.name'}; }
 5625:    my $uhome=&homeserver($uname,$udomain);
 5626:    my $items='';
 5627:    foreach my $key (keys(%$storehash)) {
 5628:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5629:    }
 5630:    $items=~s/\&$//;
 5631:    my $esc_symb=&escape($symb);
 5632:    my $esc_v=&escape($version);
 5633:    my $reply =
 5634:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5635: 	      $uhome);
 5636:    if ($reply eq 'unknown_cmd') {
 5637:        # gfall back to way things use to be done
 5638:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5639: 			    $uname);
 5640:    }
 5641:    return $reply;
 5642: }
 5643: 
 5644: sub old_putstore {
 5645:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5646:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5647:     if (!$uname) { $uname=$env{'user.name'}; }
 5648:     my $uhome=&homeserver($uname,$udomain);
 5649:     my %newstorehash;
 5650:     foreach my $item (keys(%$storehash)) {
 5651: 	my $key = $version.':'.&escape($symb).':'.$item;
 5652: 	$newstorehash{$key} = $storehash->{$item};
 5653:     }
 5654:     my $items='';
 5655:     my %allitems = ();
 5656:     foreach my $item (keys(%newstorehash)) {
 5657: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5658: 	    my $key = $1.':keys:'.$2;
 5659: 	    $allitems{$key} .= $3.':';
 5660: 	}
 5661: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5662:     }
 5663:     foreach my $item (keys(%allitems)) {
 5664: 	$allitems{$item} =~ s/\:$//;
 5665: 	$items.= $item.'='.$allitems{$item}.'&';
 5666:     }
 5667:     $items=~s/\&$//;
 5668:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5669: }
 5670: 
 5671: # ------------------------------------------------------ critical put interface
 5672: 
 5673: sub cput {
 5674:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5675:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5676:    if (!$uname) { $uname=$env{'user.name'}; }
 5677:    my $uhome=&homeserver($uname,$udomain);
 5678:    my $items='';
 5679:    foreach my $item (keys(%$storehash)) {
 5680:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5681:    }
 5682:    $items=~s/\&$//;
 5683:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5684: }
 5685: 
 5686: # -------------------------------------------------------------- eget interface
 5687: 
 5688: sub eget {
 5689:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5690:    my $items='';
 5691:    foreach my $item (@$storearr) {
 5692:        $items.=&escape($item).'&';
 5693:    }
 5694:    $items=~s/\&$//;
 5695:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5696:    if (!$uname) { $uname=$env{'user.name'}; }
 5697:    my $uhome=&homeserver($uname,$udomain);
 5698:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5699:    my @pairs=split(/\&/,$rep);
 5700:    my %returnhash=();
 5701:    my $i=0;
 5702:    foreach my $item (@$storearr) {
 5703:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5704:       $i++;
 5705:    }
 5706:    return %returnhash;
 5707: }
 5708: 
 5709: # ------------------------------------------------------------ tmpput interface
 5710: sub tmpput {
 5711:     my ($storehash,$server,$context)=@_;
 5712:     my $items='';
 5713:     foreach my $item (keys(%$storehash)) {
 5714: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5715:     }
 5716:     $items=~s/\&$//;
 5717:     if (defined($context)) {
 5718:         $items .= ':'.&escape($context);
 5719:     }
 5720:     return &reply("tmpput:$items",$server);
 5721: }
 5722: 
 5723: # ------------------------------------------------------------ tmpget interface
 5724: sub tmpget {
 5725:     my ($token,$server)=@_;
 5726:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5727:     my $rep=&reply("tmpget:$token",$server);
 5728:     my %returnhash;
 5729:     foreach my $item (split(/\&/,$rep)) {
 5730: 	my ($key,$value)=split(/=/,$item);
 5731:         next if ($key =~ /^error: 2 /);
 5732: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5733:     }
 5734:     return %returnhash;
 5735: }
 5736: 
 5737: # ------------------------------------------------------------ tmpdel interface
 5738: sub tmpdel {
 5739:     my ($token,$server)=@_;
 5740:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5741:     return &reply("tmpdel:$token",$server);
 5742: }
 5743: 
 5744: # ------------------------------------------------------------ get_timebased_id 
 5745: 
 5746: sub get_timebased_id {
 5747:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5748:         $maxtries) = @_;
 5749:     my ($newid,$error,$dellock);
 5750:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5751:         return ('','ok','invalid call to get suffix');
 5752:     }
 5753: 
 5754: # set defaults for any optional args for which values were not supplied
 5755:     if ($who eq '') {
 5756:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5757:     }
 5758:     if (!$locktries) {
 5759:         $locktries = 3;
 5760:     }
 5761:     if (!$maxtries) {
 5762:         $maxtries = 10;
 5763:     }
 5764:     
 5765:     if (($cdom eq '') || ($cnum eq '')) {
 5766:         if ($env{'request.course.id'}) {
 5767:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5768:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5769:         }
 5770:         if (($cdom eq '') || ($cnum eq '')) {
 5771:             return ('','ok','call to get suffix not in course context');
 5772:         }
 5773:     }
 5774: 
 5775: # construct locking item
 5776:     my $lockhash = {
 5777:                       $prefix."\0".'locked_'.$keyid => $who,
 5778:                    };
 5779:     my $tries = 0;
 5780: 
 5781: # attempt to get lock on nohist_$namespace file
 5782:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5783:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5784:         $tries ++;
 5785:         sleep 1;
 5786:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5787:     }
 5788: 
 5789: # attempt to get unique identifier, based on current timestamp
 5790:     if ($gotlock eq 'ok') {
 5791:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5792:         my $id = time;
 5793:         $newid = $id;
 5794:         my $idtries = 0;
 5795:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5796:             if ($idtype eq 'concat') {
 5797:                 $newid = $id.$idtries;
 5798:             } else {
 5799:                 $newid ++;
 5800:             }
 5801:             $idtries ++;
 5802:         }
 5803:         if (!exists($inuse{$prefix."\0".$newid})) {
 5804:             my %new_item =  (
 5805:                               $prefix."\0".$newid => $who,
 5806:                             );
 5807:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5808:                                                  $cdom,$cnum);
 5809:             if ($putresult ne 'ok') {
 5810:                 undef($newid);
 5811:                 $error = 'error saving new item: '.$putresult;
 5812:             }
 5813:         } else {
 5814:              $error = ('error: no unique suffix available for the new item ');
 5815:         }
 5816: #  remove lock
 5817:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5818:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5819:     } else {
 5820:         $error = "error: could not obtain lockfile\n";
 5821:         $dellock = 'ok';
 5822:     }
 5823:     return ($newid,$dellock,$error);
 5824: }
 5825: 
 5826: # -------------------------------------------------- portfolio access checking
 5827: 
 5828: sub portfolio_access {
 5829:     my ($requrl) = @_;
 5830:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5831:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5832:     if ($result) {
 5833:         my %setters;
 5834:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5835:             my ($startblock,$endblock) =
 5836:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5837:             if ($startblock && $endblock) {
 5838:                 return 'B';
 5839:             }
 5840:         } else {
 5841:             my ($startblock,$endblock) =
 5842:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5843:             if ($startblock && $endblock) {
 5844:                 return 'B';
 5845:             }
 5846:         }
 5847:     }
 5848:     if ($result eq 'ok') {
 5849:        return 'F';
 5850:     } elsif ($result =~ /^[^:]+:guest_/) {
 5851:        return 'A';
 5852:     }
 5853:     return '';
 5854: }
 5855: 
 5856: sub get_portfolio_access {
 5857:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5858: 
 5859:     if (!ref($access_hash)) {
 5860: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5861: 	my %access_controls = &get_access_controls($current_perms,$group,
 5862: 						   $file_name);
 5863: 	$access_hash = $access_controls{$file_name};
 5864:     }
 5865: 
 5866:     my ($public,$guest,@domains,@users,@courses,@groups);
 5867:     my $now = time;
 5868:     if (ref($access_hash) eq 'HASH') {
 5869:         foreach my $key (keys(%{$access_hash})) {
 5870:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5871:             if ($start > $now) {
 5872:                 next;
 5873:             }
 5874:             if ($end && $end<$now) {
 5875:                 next;
 5876:             }
 5877:             if ($scope eq 'public') {
 5878:                 $public = $key;
 5879:                 last;
 5880:             } elsif ($scope eq 'guest') {
 5881:                 $guest = $key;
 5882:             } elsif ($scope eq 'domains') {
 5883:                 push(@domains,$key);
 5884:             } elsif ($scope eq 'users') {
 5885:                 push(@users,$key);
 5886:             } elsif ($scope eq 'course') {
 5887:                 push(@courses,$key);
 5888:             } elsif ($scope eq 'group') {
 5889:                 push(@groups,$key);
 5890:             }
 5891:         }
 5892:         if ($public) {
 5893:             return 'ok';
 5894:         }
 5895:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5896:             if ($guest) {
 5897:                 return $guest;
 5898:             }
 5899:         } else {
 5900:             if (@domains > 0) {
 5901:                 foreach my $domkey (@domains) {
 5902:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5903:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5904:                             return 'ok';
 5905:                         }
 5906:                     }
 5907:                 }
 5908:             }
 5909:             if (@users > 0) {
 5910:                 foreach my $userkey (@users) {
 5911:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5912:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5913:                             if (ref($item) eq 'HASH') {
 5914:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5915:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5916:                                     return 'ok';
 5917:                                 }
 5918:                             }
 5919:                         }
 5920:                     } 
 5921:                 }
 5922:             }
 5923:             my %roleshash;
 5924:             my @courses_and_groups = @courses;
 5925:             push(@courses_and_groups,@groups); 
 5926:             if (@courses_and_groups > 0) {
 5927:                 my (%allgroups,%allroles); 
 5928:                 my ($start,$end,$role,$sec,$group);
 5929:                 foreach my $envkey (%env) {
 5930:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5931:                         my $cid = $2.'_'.$3; 
 5932:                         if ($1 eq 'gr') {
 5933:                             $group = $4;
 5934:                             $allgroups{$cid}{$group} = $env{$envkey};
 5935:                         } else {
 5936:                             if ($4 eq '') {
 5937:                                 $sec = 'none';
 5938:                             } else {
 5939:                                 $sec = $4;
 5940:                             }
 5941:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5942:                         }
 5943:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5944:                         my $cid = $2.'_'.$3;
 5945:                         if ($4 eq '') {
 5946:                             $sec = 'none';
 5947:                         } else {
 5948:                             $sec = $4;
 5949:                         }
 5950:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5951:                     }
 5952:                 }
 5953:                 if (keys(%allroles) == 0) {
 5954:                     return;
 5955:                 }
 5956:                 foreach my $key (@courses_and_groups) {
 5957:                     my %content = %{$$access_hash{$key}};
 5958:                     my $cnum = $content{'number'};
 5959:                     my $cdom = $content{'domain'};
 5960:                     my $cid = $cdom.'_'.$cnum;
 5961:                     if (!exists($allroles{$cid})) {
 5962:                         next;
 5963:                     }    
 5964:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5965:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5966:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5967:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5968:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5969:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5970:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5971:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5972:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5973:                                         if (grep/^all$/,@sections) {
 5974:                                             return 'ok';
 5975:                                         } else {
 5976:                                             if (grep/^$sec$/,@sections) {
 5977:                                                 return 'ok';
 5978:                                             }
 5979:                                         }
 5980:                                     }
 5981:                                 }
 5982:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5983:                                     if (grep/^none$/,@groups) {
 5984:                                         return 'ok';
 5985:                                     }
 5986:                                 } else {
 5987:                                     if (grep/^all$/,@groups) {
 5988:                                         return 'ok';
 5989:                                     } 
 5990:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5991:                                         if (grep/^$group$/,@groups) {
 5992:                                             return 'ok';
 5993:                                         }
 5994:                                     }
 5995:                                 } 
 5996:                             }
 5997:                         }
 5998:                     }
 5999:                 }
 6000:             }
 6001:             if ($guest) {
 6002:                 return $guest;
 6003:             }
 6004:         }
 6005:     }
 6006:     return;
 6007: }
 6008: 
 6009: sub course_group_datechecker {
 6010:     my ($dates,$now,$status) = @_;
 6011:     my ($start,$end) = split(/\./,$dates);
 6012:     if (!$start && !$end) {
 6013:         return 'ok';
 6014:     }
 6015:     if (grep/^active$/,@{$status}) {
 6016:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6017:             return 'ok';
 6018:         }
 6019:     }
 6020:     if (grep/^previous$/,@{$status}) {
 6021:         if ($end > $now ) {
 6022:             return 'ok';
 6023:         }
 6024:     }
 6025:     if (grep/^future$/,@{$status}) {
 6026:         if ($start > $now) {
 6027:             return 'ok';
 6028:         }
 6029:     }
 6030:     return; 
 6031: }
 6032: 
 6033: sub parse_portfolio_url {
 6034:     my ($url) = @_;
 6035: 
 6036:     my ($type,$udom,$unum,$group,$file_name);
 6037:     
 6038:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6039: 	$type = 1;
 6040:         $udom = $1;
 6041:         $unum = $2;
 6042:         $file_name = $3;
 6043:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6044: 	$type = 2;
 6045:         $udom = $1;
 6046:         $unum = $2;
 6047:         $group = $3;
 6048:         $file_name = $3.'/'.$4;
 6049:     }
 6050:     if (wantarray) {
 6051: 	return ($type,$udom,$unum,$file_name,$group);
 6052:     }
 6053:     return $type;
 6054: }
 6055: 
 6056: sub is_portfolio_url {
 6057:     my ($url) = @_;
 6058:     return scalar(&parse_portfolio_url($url));
 6059: }
 6060: 
 6061: sub is_portfolio_file {
 6062:     my ($file) = @_;
 6063:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6064:         return 1;
 6065:     }
 6066:     return;
 6067: }
 6068: 
 6069: sub usertools_access {
 6070:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6071:     my ($access,%tools);
 6072:     if ($context eq '') {
 6073:         $context = 'tools';
 6074:     }
 6075:     if ($context eq 'requestcourses') {
 6076:         %tools = (
 6077:                       official   => 1,
 6078:                       unofficial => 1,
 6079:                       community  => 1,
 6080:                  );
 6081:     } elsif ($context eq 'requestauthor') {
 6082:         %tools = (
 6083:                       requestauthor => 1,
 6084:                  );
 6085:     } else {
 6086:         %tools = (
 6087:                       aboutme   => 1,
 6088:                       blog      => 1,
 6089:                       webdav    => 1,
 6090:                       portfolio => 1,
 6091:                  );
 6092:     }
 6093:     return if (!defined($tools{$tool}));
 6094: 
 6095:     if ((!defined($udom)) || (!defined($uname))) {
 6096:         $udom = $env{'user.domain'};
 6097:         $uname = $env{'user.name'};
 6098:     }
 6099: 
 6100:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6101:         if ($action ne 'reload') {
 6102:             if ($context eq 'requestcourses') {
 6103:                 return $env{'environment.canrequest.'.$tool};
 6104:             } elsif ($context eq 'requestauthor') {
 6105:                 return $env{'environment.canrequest.author'};
 6106:             } else {
 6107:                 return $env{'environment.availabletools.'.$tool};
 6108:             }
 6109:         }
 6110:     }
 6111: 
 6112:     my ($toolstatus,$inststatus,$envkey);
 6113:     if ($context eq 'requestauthor') {
 6114:         $envkey = $context; 
 6115:     } else {
 6116:         $envkey = $context.'.'.$tool;
 6117:     }
 6118: 
 6119:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6120:          ($action ne 'reload')) {
 6121:         $toolstatus = $env{'environment.'.$envkey};
 6122:         $inststatus = $env{'environment.inststatus'};
 6123:     } else {
 6124:         if (ref($userenvref) eq 'HASH') {
 6125:             $toolstatus = $userenvref->{$envkey};
 6126:             $inststatus = $userenvref->{'inststatus'};
 6127:         } else {
 6128:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6129:             $toolstatus = $userenv{$envkey};
 6130:             $inststatus = $userenv{'inststatus'};
 6131:         }
 6132:     }
 6133: 
 6134:     if ($toolstatus ne '') {
 6135:         if ($toolstatus) {
 6136:             $access = 1;
 6137:         } else {
 6138:             $access = 0;
 6139:         }
 6140:         return $access;
 6141:     }
 6142: 
 6143:     my ($is_adv,%domdef);
 6144:     if (ref($is_advref) eq 'HASH') {
 6145:         $is_adv = $is_advref->{'is_adv'};
 6146:     } else {
 6147:         $is_adv = &is_advanced_user($udom,$uname);
 6148:     }
 6149:     if (ref($domdefref) eq 'HASH') {
 6150:         %domdef = %{$domdefref};
 6151:     } else {
 6152:         %domdef = &get_domain_defaults($udom);
 6153:     }
 6154:     if (ref($domdef{$tool}) eq 'HASH') {
 6155:         if ($is_adv) {
 6156:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6157:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6158:                     $access = 1;
 6159:                 } else {
 6160:                     $access = 0;
 6161:                 }
 6162:                 return $access;
 6163:             }
 6164:         }
 6165:         if ($inststatus ne '') {
 6166:             my ($hasaccess,$hasnoaccess);
 6167:             foreach my $affiliation (split(/:/,$inststatus)) {
 6168:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6169:                     if ($domdef{$tool}{$affiliation}) {
 6170:                         $hasaccess = 1;
 6171:                     } else {
 6172:                         $hasnoaccess = 1;
 6173:                     }
 6174:                 }
 6175:             }
 6176:             if ($hasaccess || $hasnoaccess) {
 6177:                 if ($hasaccess) {
 6178:                     $access = 1;
 6179:                 } elsif ($hasnoaccess) {
 6180:                     $access = 0; 
 6181:                 }
 6182:                 return $access;
 6183:             }
 6184:         } else {
 6185:             if ($domdef{$tool}{'default'} ne '') {
 6186:                 if ($domdef{$tool}{'default'}) {
 6187:                     $access = 1;
 6188:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6189:                     $access = 0;
 6190:                 }
 6191:                 return $access;
 6192:             }
 6193:         }
 6194:     } else {
 6195:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6196:             $access = 1;
 6197:         } else {
 6198:             $access = 0;
 6199:         }
 6200:         return $access;
 6201:     }
 6202: }
 6203: 
 6204: sub is_course_owner {
 6205:     my ($cdom,$cnum,$udom,$uname) = @_;
 6206:     if (($udom eq '') || ($uname eq '')) {
 6207:         $udom = $env{'user.domain'};
 6208:         $uname = $env{'user.name'};
 6209:     }
 6210:     unless (($udom eq '') || ($uname eq '')) {
 6211:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6212:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6213:                 return 1;
 6214:             } else {
 6215:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6216:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6217:                     return 1;
 6218:                 }
 6219:             }
 6220:         }
 6221:     }
 6222:     return;
 6223: }
 6224: 
 6225: sub is_advanced_user {
 6226:     my ($udom,$uname) = @_;
 6227:     if ($udom ne '' && $uname ne '') {
 6228:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6229:             if (wantarray) {
 6230:                 return ($env{'user.adv'},$env{'user.author'});
 6231:             } else {
 6232:                 return $env{'user.adv'};
 6233:             }
 6234:         }
 6235:     }
 6236:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6237:     my %allroles;
 6238:     my ($is_adv,$is_author);
 6239:     foreach my $role (keys(%roleshash)) {
 6240:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6241:         my $area = '/'.$tdomain.'/'.$trest;
 6242:         if ($sec ne '') {
 6243:             $area .= '/'.$sec;
 6244:         }
 6245:         if (($area ne '') && ($trole ne '')) {
 6246:             my $spec=$trole.'.'.$area;
 6247:             if ($trole =~ /^cr\//) {
 6248:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6249:             } elsif ($trole ne 'gr') {
 6250:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6251:             }
 6252:             if ($trole eq 'au') {
 6253:                 $is_author = 1;
 6254:             }
 6255:         }
 6256:     }
 6257:     foreach my $role (keys(%allroles)) {
 6258:         last if ($is_adv);
 6259:         foreach my $item (split(/:/,$allroles{$role})) {
 6260:             if ($item ne '') {
 6261:                 my ($privilege,$restrictions)=split(/&/,$item);
 6262:                 if ($privilege eq 'adv') {
 6263:                     $is_adv = 1;
 6264:                     last;
 6265:                 }
 6266:             }
 6267:         }
 6268:     }
 6269:     if (wantarray) {
 6270:         return ($is_adv,$is_author);
 6271:     }
 6272:     return $is_adv;
 6273: }
 6274: 
 6275: sub check_can_request {
 6276:     my ($dom,$can_request,$request_domains) = @_;
 6277:     my $canreq = 0;
 6278:     my ($types,$typename) = &Apache::loncommon::course_types();
 6279:     my @options = ('approval','validate','autolimit');
 6280:     my $optregex = join('|',@options);
 6281:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6282:         foreach my $type (@{$types}) {
 6283:             if (&usertools_access($env{'user.name'},
 6284:                                   $env{'user.domain'},
 6285:                                   $type,undef,'requestcourses')) {
 6286:                 $canreq ++;
 6287:                 if (ref($request_domains) eq 'HASH') {
 6288:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6289:                 }
 6290:                 if ($dom eq $env{'user.domain'}) {
 6291:                     $can_request->{$type} = 1;
 6292:                 }
 6293:             }
 6294:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6295:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6296:                 if (@curr > 0) {
 6297:                     foreach my $item (@curr) {
 6298:                         if (ref($request_domains) eq 'HASH') {
 6299:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6300:                             if ($otherdom ne '') {
 6301:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6302:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6303:                                         push(@{$request_domains->{$type}},$otherdom);
 6304:                                     }
 6305:                                 } else {
 6306:                                     push(@{$request_domains->{$type}},$otherdom);
 6307:                                 }
 6308:                             }
 6309:                         }
 6310:                     }
 6311:                     unless($dom eq $env{'user.domain'}) {
 6312:                         $canreq ++;
 6313:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6314:                             $can_request->{$type} = 1;
 6315:                         }
 6316:                     }
 6317:                 }
 6318:             }
 6319:         }
 6320:     }
 6321:     return $canreq;
 6322: }
 6323: 
 6324: # ---------------------------------------------- Custom access rule evaluation
 6325: 
 6326: sub customaccess {
 6327:     my ($priv,$uri)=@_;
 6328:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6329:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6330:     $udom = &LONCAPA::clean_domain($udom);
 6331:     $ucrs = &LONCAPA::clean_username($ucrs);
 6332:     my $access=0;
 6333:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6334: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6335: 	if ($type eq 'user') {
 6336: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6337: 		my ($tdom,$tuname)=split(m{/},$scope);
 6338: 		if ($tdom) {
 6339: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6340: 		}
 6341: 		if ($tuname) {
 6342: 		    if ($tuname ne $env{'user.name'}) { next; }
 6343: 		}
 6344: 		$access=($effect eq 'allow');
 6345: 		last;
 6346: 	    }
 6347: 	} else {
 6348: 	    if ($role) {
 6349: 		if ($role ne $urole) { next; }
 6350: 	    }
 6351: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6352: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6353: 		if ($tdom) {
 6354: 		    if ($tdom ne $udom) { next; }
 6355: 		}
 6356: 		if ($tcrs) {
 6357: 		    if ($tcrs ne $ucrs) { next; }
 6358: 		}
 6359: 		if ($tsec) {
 6360: 		    if ($tsec ne $usec) { next; }
 6361: 		}
 6362: 		$access=($effect eq 'allow');
 6363: 		last;
 6364: 	    }
 6365: 	    if ($realm eq '' && $role eq '') {
 6366: 		$access=($effect eq 'allow');
 6367: 	    }
 6368: 	}
 6369:     }
 6370:     return $access;
 6371: }
 6372: 
 6373: # ------------------------------------------------- Check for a user privilege
 6374: 
 6375: sub allowed {
 6376:     my ($priv,$uri,$symb,$role)=@_;
 6377:     my $ver_orguri=$uri;
 6378:     $uri=&deversion($uri);
 6379:     my $orguri=$uri;
 6380:     $uri=&declutter($uri);
 6381: 
 6382:     if ($priv eq 'evb') {
 6383: # Evade communication block restrictions for specified role in a course
 6384:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6385:             return $1;
 6386:         } else {
 6387:             return;
 6388:         }
 6389:     }
 6390: 
 6391:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6392: # Free bre access to adm and meta resources
 6393:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6394: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6395: 	&& ($priv eq 'bre')) {
 6396: 	return 'F';
 6397:     }
 6398: 
 6399: # Free bre access to user's own portfolio contents
 6400:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6401:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6402: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6403:         my %setters;
 6404:         my ($startblock,$endblock) = 
 6405:             &Apache::loncommon::blockcheck(\%setters,'port');
 6406:         if ($startblock && $endblock) {
 6407:             return 'B';
 6408:         } else {
 6409:             return 'F';
 6410:         }
 6411:     }
 6412: 
 6413: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6414:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6415:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6416:         if (exists($env{'request.course.id'})) {
 6417:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6418:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6419:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6420:                 my $courseprivid=$env{'request.course.id'};
 6421:                 $courseprivid=~s/\_/\//;
 6422:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6423:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6424:                     return $1; 
 6425:                 } else {
 6426:                     if ($env{'request.course.sec'}) {
 6427:                         $courseprivid.='/'.$env{'request.course.sec'};
 6428:                     }
 6429:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6430:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6431:                         return $2;
 6432:                     }
 6433:                 }
 6434:             }
 6435:         }
 6436:     }
 6437: 
 6438: # Free bre to public access
 6439: 
 6440:     if ($priv eq 'bre') {
 6441:         my $copyright=&metadata($uri,'copyright');
 6442: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6443:            return 'F'; 
 6444:         }
 6445:         if ($copyright eq 'priv') {
 6446:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6447: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6448: 		return '';
 6449:             }
 6450:         }
 6451:         if ($copyright eq 'domain') {
 6452:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6453: 	    unless (($env{'user.domain'} eq $1) ||
 6454:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6455: 		return '';
 6456:             }
 6457:         }
 6458:         if ($env{'request.role'}=~ /li\.\//) {
 6459:             # Library role, so allow browsing of resources in this domain.
 6460:             return 'F';
 6461:         }
 6462:         if ($copyright eq 'custom') {
 6463: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6464:         }
 6465:     }
 6466:     # Domain coordinator is trying to create a course
 6467:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6468:         # uri is the requested domain in this case.
 6469:         # comparison to 'request.role.domain' shows if the user has selected
 6470:         # a role of dc for the domain in question.
 6471:         return 'F' if ($uri eq $env{'request.role.domain'});
 6472:     }
 6473: 
 6474:     my $thisallowed='';
 6475:     my $statecond=0;
 6476:     my $courseprivid='';
 6477: 
 6478:     my $ownaccess;
 6479:     # Community Coordinator or Assistant Co-author browsing resource space.
 6480:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6481:         if ($uri eq '') {
 6482:             $ownaccess = 1;
 6483:         } else {
 6484:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6485:                 my $udom = $env{'user.domain'};
 6486:                 my $uname = $env{'user.name'};
 6487:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6488:                     $ownaccess = 1;
 6489:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6490:                     unless ($uri =~ m{\.\./}) {
 6491:                         $ownaccess = 1;
 6492:                     }
 6493:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6494:                     my $now = time;
 6495:                     if ($uri =~ m{^([^/]+)/?$}) {
 6496:                         my $adom = $1;
 6497:                         foreach my $key (keys(%env)) {
 6498:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6499:                                 my ($start,$end) = split('.',$env{$key});
 6500:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6501:                                     $ownaccess = 1;
 6502:                                     last;
 6503:                                 }
 6504:                             }
 6505:                         }
 6506:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6507:                         my $adom = $1;
 6508:                         my $aname = $2;
 6509:                         foreach my $role ('ca','aa') { 
 6510:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6511:                                 my ($start,$end) =
 6512:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6513:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6514:                                     $ownaccess = 1;
 6515:                                     last;
 6516:                                 }
 6517:                             }
 6518:                         }
 6519:                     }
 6520:                 }
 6521:             }
 6522:         }
 6523:     }
 6524: 
 6525: # Course
 6526: 
 6527:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6528:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6529:             $thisallowed.=$1;
 6530:         }
 6531:     }
 6532: 
 6533: # Domain
 6534: 
 6535:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6536:        =~/\Q$priv\E\&([^\:]*)/) {
 6537:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6538:             $thisallowed.=$1;
 6539:         }
 6540:     }
 6541: 
 6542: # User who is not author or co-author might still be able to edit
 6543: # resource of an author in the domain (e.g., if Domain Coordinator).
 6544:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6545:         (&allowed('mdc',$env{'request.course.id'}))) {
 6546:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6547:             $thisallowed.=$1;
 6548:         }
 6549:     }
 6550: 
 6551: # Course: uri itself is a course
 6552:     my $courseuri=$uri;
 6553:     $courseuri=~s/\_(\d)/\/$1/;
 6554:     $courseuri=~s/^([^\/])/\/$1/;
 6555: 
 6556:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6557:        =~/\Q$priv\E\&([^\:]*)/) {
 6558:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6559:             $thisallowed.=$1;
 6560:         }
 6561:     }
 6562: 
 6563: # URI is an uploaded document for this course, default permissions don't matter
 6564: # not allowing 'edit' access (editupload) to uploaded course docs
 6565:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6566: 	$thisallowed='';
 6567:         my ($match)=&is_on_map($uri);
 6568:         if ($match) {
 6569:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6570:                   =~/\Q$priv\E\&([^\:]*)/) {
 6571:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6572:                 if (@blockers > 0) {
 6573:                     $thisallowed = 'B';
 6574:                 } else {
 6575:                     $thisallowed.=$1;
 6576:                 }
 6577:             }
 6578:         } else {
 6579:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6580:             if ($refuri) {
 6581:                 if ($refuri =~ m|^/adm/|) {
 6582:                     $thisallowed='F';
 6583:                 } else {
 6584:                     $refuri=&declutter($refuri);
 6585:                     my ($match) = &is_on_map($refuri);
 6586:                     if ($match) {
 6587:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6588:                         if (@blockers > 0) {
 6589:                             $thisallowed = 'B';
 6590:                         } else {
 6591:                             $thisallowed='F';
 6592:                         }
 6593:                     }
 6594:                 }
 6595:             }
 6596:         }
 6597:     }
 6598: 
 6599:     if ($priv eq 'bre'
 6600: 	&& $thisallowed ne 'F' 
 6601: 	&& $thisallowed ne '2'
 6602: 	&& &is_portfolio_url($uri)) {
 6603: 	$thisallowed = &portfolio_access($uri);
 6604:     }
 6605:     
 6606: # Full access at system, domain or course-wide level? Exit.
 6607:     if ($thisallowed=~/F/) {
 6608: 	return 'F';
 6609:     }
 6610: 
 6611: # If this is generating or modifying users, exit with special codes
 6612: 
 6613:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6614: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6615: 	    my ($audom,$auname)=split('/',$uri);
 6616: # no author name given, so this just checks on the general right to make a co-author in this domain
 6617: 	    unless ($auname) { return $thisallowed; }
 6618: # an author name is given, so we are about to actually make a co-author for a certain account
 6619: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6620: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6621: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6622: 	}
 6623: 	return $thisallowed;
 6624:     }
 6625: #
 6626: # Gathered so far: system, domain and course wide privileges
 6627: #
 6628: # Course: See if uri or referer is an individual resource that is part of 
 6629: # the course
 6630: 
 6631:     if ($env{'request.course.id'}) {
 6632: 
 6633:        $courseprivid=$env{'request.course.id'};
 6634:        if ($env{'request.course.sec'}) {
 6635:           $courseprivid.='/'.$env{'request.course.sec'};
 6636:        }
 6637:        $courseprivid=~s/\_/\//;
 6638:        my $checkreferer=1;
 6639:        my ($match,$cond)=&is_on_map($uri);
 6640:        if ($match) {
 6641:            $statecond=$cond;
 6642:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6643:                =~/\Q$priv\E\&([^\:]*)/) {
 6644:                my $value = $1;
 6645:                if ($priv eq 'bre') {
 6646:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6647:                    if (@blockers > 0) {
 6648:                        $thisallowed = 'B';
 6649:                    } else {
 6650:                        $thisallowed.=$value;
 6651:                    }
 6652:                } else {
 6653:                    $thisallowed.=$value;
 6654:                }
 6655:                $checkreferer=0;
 6656:            }
 6657:        }
 6658:        
 6659:        if ($checkreferer) {
 6660: 	  my $refuri=$env{'httpref.'.$orguri};
 6661:             unless ($refuri) {
 6662:                 foreach my $key (keys(%env)) {
 6663: 		    if ($key=~/^httpref\..*\*/) {
 6664: 			my $pattern=$key;
 6665:                         $pattern=~s/^httpref\.\/res\///;
 6666:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6667:                         $pattern=~s/\//\\\//g;
 6668:                         if ($orguri=~/$pattern/) {
 6669: 			    $refuri=$env{$key};
 6670:                         }
 6671:                     }
 6672:                 }
 6673:             }
 6674: 
 6675:          if ($refuri) { 
 6676: 	  $refuri=&declutter($refuri);
 6677:           my ($match,$cond)=&is_on_map($refuri);
 6678:             if ($match) {
 6679:               my $refstatecond=$cond;
 6680:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6681:                   =~/\Q$priv\E\&([^\:]*)/) {
 6682:                   my $value = $1;
 6683:                   if ($priv eq 'bre') {
 6684:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6685:                       if (@blockers > 0) {
 6686:                           $thisallowed = 'B';
 6687:                       } else {
 6688:                           $thisallowed.=$value;
 6689:                       }
 6690:                   } else {
 6691:                       $thisallowed.=$value;
 6692:                   }
 6693:                   $uri=$refuri;
 6694:                   $statecond=$refstatecond;
 6695:               }
 6696:           }
 6697:         }
 6698:        }
 6699:    }
 6700: 
 6701: #
 6702: # Gathered now: all privileges that could apply, and condition number
 6703: # 
 6704: #
 6705: # Full or no access?
 6706: #
 6707: 
 6708:     if ($thisallowed=~/F/) {
 6709: 	return 'F';
 6710:     }
 6711: 
 6712:     unless ($thisallowed) {
 6713:         return '';
 6714:     }
 6715: 
 6716: # Restrictions exist, deal with them
 6717: #
 6718: #   C:according to course preferences
 6719: #   R:according to resource settings
 6720: #   L:unless locked
 6721: #   X:according to user session state
 6722: #
 6723: 
 6724: # Possibly locked functionality, check all courses
 6725: # Locks might take effect only after 10 minutes cache expiration for other
 6726: # courses, and 2 minutes for current course
 6727: 
 6728:     my $envkey;
 6729:     if ($thisallowed=~/L/) {
 6730:         foreach $envkey (keys(%env)) {
 6731:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6732:                my $courseid=$2;
 6733:                my $roleid=$1.'.'.$2;
 6734:                $courseid=~s/^\///;
 6735:                my $expiretime=600;
 6736:                if ($env{'request.role'} eq $roleid) {
 6737: 		  $expiretime=120;
 6738:                }
 6739: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6740:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6741:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6742: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6743:                }
 6744:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6745:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6746: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6747:                        &log($env{'user.domain'},$env{'user.name'},
 6748:                             $env{'user.home'},
 6749:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6750:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6751:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6752: 		       return '';
 6753:                    }
 6754:                }
 6755:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6756:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6757: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6758:                        &log($env{'user.domain'},$env{'user.name'},
 6759:                             $env{'user.home'},
 6760:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6761:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6762:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6763: 		       return '';
 6764:                    }
 6765:                }
 6766: 	   }
 6767:        }
 6768:     }
 6769:    
 6770: #
 6771: # Rest of the restrictions depend on selected course
 6772: #
 6773: 
 6774:     unless ($env{'request.course.id'}) {
 6775: 	if ($thisallowed eq 'A') {
 6776: 	    return 'A';
 6777:         } elsif ($thisallowed eq 'B') {
 6778:             return 'B';
 6779: 	} else {
 6780: 	    return '1';
 6781: 	}
 6782:     }
 6783: 
 6784: #
 6785: # Now user is definitely in a course
 6786: #
 6787: 
 6788: 
 6789: # Course preferences
 6790: 
 6791:    if ($thisallowed=~/C/) {
 6792:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6793:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6794:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6795: 	   =~/\Q$rolecode\E/) {
 6796: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6797: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6798: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6799: 			$env{'request.course.id'});
 6800: 	   }
 6801:            return '';
 6802:        }
 6803: 
 6804:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6805: 	   =~/\Q$unamedom\E/) {
 6806: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6807: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6808: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6809: 			$env{'request.course.id'});
 6810: 	   }
 6811:            return '';
 6812:        }
 6813:    }
 6814: 
 6815: # Resource preferences
 6816: 
 6817:    if ($thisallowed=~/R/) {
 6818:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6819:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6820: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6821: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6822: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6823: 	   }
 6824: 	   return '';
 6825:        }
 6826:    }
 6827: 
 6828: # Restricted by state or randomout?
 6829: 
 6830:    if ($thisallowed=~/X/) {
 6831:       if ($env{'acc.randomout'}) {
 6832: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6833:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6834:             return ''; 
 6835:          }
 6836:       }
 6837:       if (&condval($statecond)) {
 6838: 	 return '2';
 6839:       } else {
 6840:          return '';
 6841:       }
 6842:    }
 6843: 
 6844:     if ($thisallowed eq 'A') {
 6845: 	return 'A';
 6846:     } elsif ($thisallowed eq 'B') {
 6847:         return 'B';
 6848:     }
 6849:    return 'F';
 6850: }
 6851: 
 6852: # ------------------------------------------- Check construction space access
 6853: 
 6854: sub constructaccess {
 6855:     my ($url,$setpriv)=@_;
 6856: 
 6857: # We do not allow editing of previous versions of files
 6858:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6859: 
 6860: # Get username and domain from URL
 6861:     my ($ownername,$ownerdomain,$ownerhome);
 6862: 
 6863:     ($ownerdomain,$ownername) =
 6864:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6865: 
 6866: # The URL does not really point to any authorspace, forget it
 6867:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6868: 
 6869: # Now we need to see if the user has access to the authorspace of
 6870: # $ownername at $ownerdomain
 6871: 
 6872:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6873: # Real author for this?
 6874:        $ownerhome = $env{'user.home'};
 6875:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6876:           return ($ownername,$ownerdomain,$ownerhome);
 6877:        }
 6878:     } else {
 6879: # Co-author for this?
 6880:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6881:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6882:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6883:             return ($ownername,$ownerdomain,$ownerhome);
 6884:         }
 6885:     }
 6886: 
 6887: # We don't have any access right now. If we are not possibly going to do anything about this,
 6888: # we might as well leave
 6889:    unless ($setpriv) { return ''; }
 6890: 
 6891: # Backdoor access?
 6892:     my $allowed=&allowed('eco',$ownerdomain);
 6893: # Nope
 6894:     unless ($allowed) { return ''; }
 6895: # Looks like we may have access, but could be locked by the owner of the construction space
 6896:     if ($allowed eq 'U') {
 6897:         my %blocked=&get('environment',['domcoord.author'],
 6898:                          $ownerdomain,$ownername);
 6899: # Is blocked by owner
 6900:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 6901:     }
 6902:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 6903: # Grant temporary access
 6904:         my $then=$env{'user.login.time'};
 6905:         my $update=$env{'user.update.time'};
 6906:         if (!$update) { $update = $then; }
 6907:         my $refresh=$env{'user.refresh.time'};
 6908:         if (!$refresh) { $refresh = $update; }
 6909:         my $now = time;
 6910:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 6911:                            $now,'ca','constructaccess');
 6912:         $ownerhome = &homeserver($ownername,$ownerdomain);
 6913:         return($ownername,$ownerdomain,$ownerhome);
 6914:     }
 6915: # No business here
 6916:     return '';
 6917: }
 6918: 
 6919: sub get_comm_blocks {
 6920:     my ($cdom,$cnum) = @_;
 6921:     if ($cdom eq '' || $cnum eq '') {
 6922:         return unless ($env{'request.course.id'});
 6923:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6924:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6925:     }
 6926:     my %commblocks;
 6927:     my $hashid=$cdom.'_'.$cnum;
 6928:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6929:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6930:         %commblocks = %{$blocksref};
 6931:     } else {
 6932:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6933:         my $cachetime = 600;
 6934:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6935:     }
 6936:     return %commblocks;
 6937: }
 6938: 
 6939: sub has_comm_blocking {
 6940:     my ($priv,$symb,$uri,$blocks) = @_;
 6941:     return unless ($env{'request.course.id'});
 6942:     return unless ($priv eq 'bre');
 6943:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6944:     my %commblocks;
 6945:     if (ref($blocks) eq 'HASH') {
 6946:         %commblocks = %{$blocks};
 6947:     } else {
 6948:         %commblocks = &get_comm_blocks();
 6949:     }
 6950:     return unless (keys(%commblocks) > 0);
 6951:     if (!$symb) { $symb=&symbread($uri,1); }
 6952:     my ($map,$resid,undef)=&decode_symb($symb);
 6953:     my %tocheck = (
 6954:                     maps      => $map,
 6955:                     resources => $symb,
 6956:                   );
 6957:     my @blockers;
 6958:     my $now = time;
 6959:     my $navmap = Apache::lonnavmaps::navmap->new();
 6960:     foreach my $block (keys(%commblocks)) {
 6961:         if ($block =~ /^(\d+)____(\d+)$/) {
 6962:             my ($start,$end) = ($1,$2);
 6963:             if ($start <= $now && $end >= $now) {
 6964:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6965:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6966:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6967:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6968:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6969:                                     push(@blockers,$block);
 6970:                                 }
 6971:                             }
 6972:                         }
 6973:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6974:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6975:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6976:                                     push(@blockers,$block);
 6977:                                 }
 6978:                             }
 6979:                         }
 6980:                     }
 6981:                 }
 6982:             }
 6983:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6984:             my $item = $1;
 6985:             my @to_test;
 6986:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6987:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6988:                     my $check_interval;
 6989:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6990:                         my @interval;
 6991:                         my $type = 'map';
 6992:                         if ($item eq 'course') {
 6993:                             $type = 'course';
 6994:                             @interval=&EXT("resource.0.interval");
 6995:                         } else {
 6996:                             if ($item =~ /___\d+___/) {
 6997:                                 $type = 'resource';
 6998:                                 @interval=&EXT("resource.0.interval",$item);
 6999:                                 if (ref($navmap)) {                        
 7000:                                     my $res = $navmap->getBySymb($item); 
 7001:                                     push(@to_test,$res);
 7002:                                 }
 7003:                             } else {
 7004:                                 my $mapsymb = &symbread($item,1);
 7005:                                 if ($mapsymb) {
 7006:                                     if (ref($navmap)) {
 7007:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7008:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7009:                                         foreach my $res (@to_test) {
 7010:                                             my $symb = $res->symb();
 7011:                                             next if ($symb eq $mapsymb);
 7012:                                             if ($symb ne '') {
 7013:                                                 @interval=&EXT("resource.0.interval",$symb);
 7014:                                                 last;
 7015:                                             }
 7016:                                         }
 7017:                                     }
 7018:                                 }
 7019:                             }
 7020:                         }
 7021:                         if ($interval[0] =~ /\d+/) {
 7022:                             my $first_access;
 7023:                             if ($type eq 'resource') {
 7024:                                 $first_access=&get_first_access($interval[1],$item);
 7025:                             } elsif ($type eq 'map') {
 7026:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7027:                             } else {
 7028:                                 $first_access=&get_first_access($interval[1]);
 7029:                             }
 7030:                             if ($first_access) {
 7031:                                 my $timesup = $first_access+$interval[0];
 7032:                                 if ($timesup > $now) {
 7033:                                     foreach my $res (@to_test) {
 7034:                                         if ($res->is_problem()) {
 7035:                                             if ($res->completable()) {
 7036:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7037:                                                     push(@blockers,$block);
 7038:                                                 }
 7039:                                                 last;
 7040:                                             }
 7041:                                         }
 7042:                                     }
 7043:                                 }
 7044:                             }
 7045:                         }
 7046:                     }
 7047:                 }
 7048:             }
 7049:         }
 7050:     }
 7051:     return @blockers;
 7052: }
 7053: 
 7054: sub check_docs_block {
 7055:     my ($docsblock,$tocheck) =@_;
 7056:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7057:         return;
 7058:     }
 7059:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7060:         if ($tocheck->{'maps'}) {
 7061:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7062:                 return 1;
 7063:             }
 7064:         }
 7065:     }
 7066:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7067:         if ($tocheck->{'resources'}) {
 7068:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7069:                 return 1;
 7070:             }
 7071:         }
 7072:     }
 7073:     return;
 7074: }
 7075: 
 7076: #
 7077: #   Removes the versino from a URI and
 7078: #   splits it in to its filename and path to the filename.
 7079: #   Seems like File::Basename could have done this more clearly.
 7080: #   Parameters:
 7081: #      $uri   - input URI
 7082: #   Returns:
 7083: #     Two element list consisting of 
 7084: #     $pathname  - the URI up to and excluding the trailing /
 7085: #     $filename  - The part of the URI following the last /
 7086: #  NOTE:
 7087: #    Another realization of this is simply:
 7088: #    use File::Basename;
 7089: #    ...
 7090: #    $uri = shift;
 7091: #    $filename = basename($uri);
 7092: #    $path     = dirname($uri);
 7093: #    return ($filename, $path);
 7094: #
 7095: #     The implementation below is probably faster however.
 7096: #
 7097: sub split_uri_for_cond {
 7098:     my $uri=&deversion(&declutter(shift));
 7099:     my @uriparts=split(/\//,$uri);
 7100:     my $filename=pop(@uriparts);
 7101:     my $pathname=join('/',@uriparts);
 7102:     return ($pathname,$filename);
 7103: }
 7104: # --------------------------------------------------- Is a resource on the map?
 7105: 
 7106: sub is_on_map {
 7107:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7108:     #Trying to find the conditional for the file
 7109:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7110: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7111:     if ($match) {
 7112: 	return (1,$1);
 7113:     } else {
 7114: 	return (0,0);
 7115:     }
 7116: }
 7117: 
 7118: # --------------------------------------------------------- Get symb from alias
 7119: 
 7120: sub get_symb_from_alias {
 7121:     my $symb=shift;
 7122:     my ($map,$resid,$url)=&decode_symb($symb);
 7123: # Already is a symb
 7124:     if ($url) { return $symb; }
 7125: # Must be an alias
 7126:     my $aliassymb='';
 7127:     my %bighash;
 7128:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7129:                             &GDBM_READER(),0640)) {
 7130:         my $rid=$bighash{'mapalias_'.$symb};
 7131: 	if ($rid) {
 7132: 	    my ($mapid,$resid)=split(/\./,$rid);
 7133: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7134: 				    $resid,$bighash{'src_'.$rid});
 7135: 	}
 7136:         untie %bighash;
 7137:     }
 7138:     return $aliassymb;
 7139: }
 7140: 
 7141: # ----------------------------------------------------------------- Define Role
 7142: 
 7143: sub definerole {
 7144:   if (allowed('mcr','/')) {
 7145:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7146:     foreach my $role (split(':',$sysrole)) {
 7147: 	my ($crole,$cqual)=split(/\&/,$role);
 7148:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7149:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7150: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7151:                return "refused:s:$crole&$cqual"; 
 7152:             }
 7153:         }
 7154:     }
 7155:     foreach my $role (split(':',$domrole)) {
 7156: 	my ($crole,$cqual)=split(/\&/,$role);
 7157:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7158:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7159: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7160:                return "refused:d:$crole&$cqual"; 
 7161:             }
 7162:         }
 7163:     }
 7164:     foreach my $role (split(':',$courole)) {
 7165: 	my ($crole,$cqual)=split(/\&/,$role);
 7166:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7167:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7168: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7169:                return "refused:c:$crole&$cqual"; 
 7170:             }
 7171:         }
 7172:     }
 7173:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7174:                 "$env{'user.domain'}:$env{'user.name'}:".
 7175: 	        "rolesdef_$rolename=".
 7176:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7177:     return reply($command,$env{'user.home'});
 7178:   } else {
 7179:     return 'refused';
 7180:   }
 7181: }
 7182: 
 7183: # ---------------- Make a metadata query against the network of library servers
 7184: 
 7185: sub metadata_query {
 7186:     my ($query,$custom,$customshow,$server_array)=@_;
 7187:     my %rhash;
 7188:     my %libserv = &all_library();
 7189:     my @server_list = (defined($server_array) ? @$server_array
 7190:                                               : keys(%libserv) );
 7191:     for my $server (@server_list) {
 7192: 	unless ($custom or $customshow) {
 7193: 	    my $reply=&reply("querysend:".&escape($query),$server);
 7194: 	    $rhash{$server}=$reply;
 7195: 	}
 7196: 	else {
 7197: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7198: 			     &escape($custom).':'.&escape($customshow),
 7199: 			     $server);
 7200: 	    $rhash{$server}=$reply;
 7201: 	}
 7202:     }
 7203:     return \%rhash;
 7204: }
 7205: 
 7206: # ----------------------------------------- Send log queries and wait for reply
 7207: 
 7208: sub log_query {
 7209:     my ($uname,$udom,$query,%filters)=@_;
 7210:     my $uhome=&homeserver($uname,$udom);
 7211:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7212:     my $uhost=&hostname($uhome);
 7213:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7214:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7215:                        $uhome);
 7216:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7217:     return get_query_reply($queryid);
 7218: }
 7219: 
 7220: # -------------------------- Update MySQL table for portfolio file
 7221: 
 7222: sub update_portfolio_table {
 7223:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7224:     if ($group ne '') {
 7225:         $file_name =~s /^\Q$group\E//;
 7226:     }
 7227:     my $homeserver = &homeserver($uname,$udom);
 7228:     my $queryid=
 7229:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7230:                ':'.&escape($file_name).':'.$action,$homeserver);
 7231:     my $reply = &get_query_reply($queryid);
 7232:     return $reply;
 7233: }
 7234: 
 7235: # -------------------------- Update MySQL allusers table
 7236: 
 7237: sub update_allusers_table {
 7238:     my ($uname,$udom,$names) = @_;
 7239:     my $homeserver = &homeserver($uname,$udom);
 7240:     my $queryid=
 7241:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7242:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7243:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7244:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7245:                'generation='.&escape($names->{'generation'}).'%%'.
 7246:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7247:                'id='.&escape($names->{'id'}),$homeserver);
 7248:     return;
 7249: }
 7250: 
 7251: # ------- Request retrieval of institutional classlists for course(s)
 7252: 
 7253: sub fetch_enrollment_query {
 7254:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7255:     my $homeserver;
 7256:     my $maxtries = 1;
 7257:     if ($context eq 'automated') {
 7258:         $homeserver = $perlvar{'lonHostID'};
 7259:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7260:     } else {
 7261:         $homeserver = &homeserver($cnum,$dom);
 7262:     }
 7263:     my $host=&hostname($homeserver);
 7264:     my $cmd = '';
 7265:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7266:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7267:     }
 7268:     $cmd =~ s/%%$//;
 7269:     $cmd = &escape($cmd);
 7270:     my $query = 'fetchenrollment';
 7271:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7272:     unless ($queryid=~/^\Q$host\E\_/) { 
 7273:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7274:         return 'error: '.$queryid;
 7275:     }
 7276:     my $reply = &get_query_reply($queryid);
 7277:     my $tries = 1;
 7278:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7279:         $reply = &get_query_reply($queryid);
 7280:         $tries ++;
 7281:     }
 7282:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7283:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7284:     } else {
 7285:         my @responses = split(/:/,$reply);
 7286:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7287:             foreach my $line (@responses) {
 7288:                 my ($key,$value) = split(/=/,$line,2);
 7289:                 $$replyref{$key} = $value;
 7290:             }
 7291:         } else {
 7292:             my $pathname = LONCAPA::tempdir();
 7293:             foreach my $line (@responses) {
 7294:                 my ($key,$value) = split(/=/,$line);
 7295:                 $$replyref{$key} = $value;
 7296:                 if ($value > 0) {
 7297:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7298:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7299:                         my $destname = $pathname.'/'.$filename;
 7300:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7301:                         if ($xml_classlist =~ /^error/) {
 7302:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7303:                         } else {
 7304:                             if ( open(FILE,">$destname") ) {
 7305:                                 print FILE &unescape($xml_classlist);
 7306:                                 close(FILE);
 7307:                             } else {
 7308:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7309:                             }
 7310:                         }
 7311:                     }
 7312:                 }
 7313:             }
 7314:         }
 7315:         return 'ok';
 7316:     }
 7317:     return 'error';
 7318: }
 7319: 
 7320: sub get_query_reply {
 7321:     my $queryid=shift;
 7322:     my $replyfile=LONCAPA::tempdir().$queryid;
 7323:     my $reply='';
 7324:     for (1..100) {
 7325: 	sleep 2;
 7326:         if (-e $replyfile.'.end') {
 7327: 	    if (open(my $fh,$replyfile)) {
 7328: 		$reply = join('',<$fh>);
 7329: 		close($fh);
 7330: 	   } else { return 'error: reply_file_error'; }
 7331:            return &unescape($reply);
 7332: 	}
 7333:     }
 7334:     return 'timeout:'.$queryid;
 7335: }
 7336: 
 7337: sub courselog_query {
 7338: #
 7339: # possible filters:
 7340: # url: url or symb
 7341: # username
 7342: # domain
 7343: # action: view, submit, grade
 7344: # start: timestamp
 7345: # end: timestamp
 7346: #
 7347:     my (%filters)=@_;
 7348:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7349:     if ($filters{'url'}) {
 7350: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7351:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7352:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7353:     }
 7354:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7355:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7356:     return &log_query($cname,$cdom,'courselog',%filters);
 7357: }
 7358: 
 7359: sub userlog_query {
 7360: #
 7361: # possible filters:
 7362: # action: log check role
 7363: # start: timestamp
 7364: # end: timestamp
 7365: #
 7366:     my ($uname,$udom,%filters)=@_;
 7367:     return &log_query($uname,$udom,'userlog',%filters);
 7368: }
 7369: 
 7370: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7371: 
 7372: sub auto_run {
 7373:     my ($cnum,$cdom) = @_;
 7374:     my $response = 0;
 7375:     my $settings;
 7376:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7377:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7378:         $settings = $domconfig{'autoenroll'};
 7379:         if ($settings->{'run'} eq '1') {
 7380:             $response = 1;
 7381:         }
 7382:     } else {
 7383:         my $homeserver;
 7384:         if (&is_course($cdom,$cnum)) {
 7385:             $homeserver = &homeserver($cnum,$cdom);
 7386:         } else {
 7387:             $homeserver = &domain($cdom,'primary');
 7388:         }
 7389:         if ($homeserver ne 'no_host') {
 7390:             $response = &reply('autorun:'.$cdom,$homeserver);
 7391:         }
 7392:     }
 7393:     return $response;
 7394: }
 7395: 
 7396: sub auto_get_sections {
 7397:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7398:     my $homeserver;
 7399:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7400:         $homeserver = &homeserver($cnum,$cdom);
 7401:     }
 7402:     if (!defined($homeserver)) { 
 7403:         if ($cdom =~ /^$match_domain$/) {
 7404:             $homeserver = &domain($cdom,'primary');
 7405:         }
 7406:     }
 7407:     my @secs;
 7408:     if (defined($homeserver)) {
 7409:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7410:         unless ($response eq 'refused') {
 7411:             @secs = split(/:/,$response);
 7412:         }
 7413:     }
 7414:     return @secs;
 7415: }
 7416: 
 7417: sub auto_new_course {
 7418:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7419:     my $homeserver = &homeserver($cnum,$cdom);
 7420:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7421:     return $response;
 7422: }
 7423: 
 7424: sub auto_validate_courseID {
 7425:     my ($cnum,$cdom,$inst_course_id) = @_;
 7426:     my $homeserver = &homeserver($cnum,$cdom);
 7427:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7428:     return $response;
 7429: }
 7430: 
 7431: sub auto_validate_instcode {
 7432:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7433:     my ($homeserver,$response);
 7434:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7435:         $homeserver = &homeserver($cnum,$cdom);
 7436:     }
 7437:     if (!defined($homeserver)) {
 7438:         if ($cdom =~ /^$match_domain$/) {
 7439:             $homeserver = &domain($cdom,'primary');
 7440:         }
 7441:     }
 7442:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7443:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7444:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 7445:     return ($outcome,$description);
 7446: }
 7447: 
 7448: sub auto_create_password {
 7449:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7450:     my ($homeserver,$response);
 7451:     my $create_passwd = 0;
 7452:     my $authchk = '';
 7453:     if ($udom =~ /^$match_domain$/) {
 7454:         $homeserver = &domain($udom,'primary');
 7455:     }
 7456:     if ($homeserver eq '') {
 7457:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7458:             $homeserver = &homeserver($cnum,$cdom);
 7459:         }
 7460:     }
 7461:     if ($homeserver eq '') {
 7462:         $authchk = 'nodomain';
 7463:     } else {
 7464:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7465:         if ($response eq 'refused') {
 7466:             $authchk = 'refused';
 7467:         } else {
 7468:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7469:         }
 7470:     }
 7471:     return ($authparam,$create_passwd,$authchk);
 7472: }
 7473: 
 7474: sub auto_photo_permission {
 7475:     my ($cnum,$cdom,$students) = @_;
 7476:     my $homeserver = &homeserver($cnum,$cdom);
 7477:     my ($outcome,$perm_reqd,$conditions) = 
 7478: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7479:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7480: 	return (undef,undef);
 7481:     }
 7482:     return ($outcome,$perm_reqd,$conditions);
 7483: }
 7484: 
 7485: sub auto_checkphotos {
 7486:     my ($uname,$udom,$pid) = @_;
 7487:     my $homeserver = &homeserver($uname,$udom);
 7488:     my ($result,$resulttype);
 7489:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7490: 				   &escape($uname).':'.&escape($pid),
 7491: 				   $homeserver));
 7492:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7493: 	return (undef,undef);
 7494:     }
 7495:     if ($outcome) {
 7496:         ($result,$resulttype) = split(/:/,$outcome);
 7497:     } 
 7498:     return ($result,$resulttype);
 7499: }
 7500: 
 7501: sub auto_photochoice {
 7502:     my ($cnum,$cdom) = @_;
 7503:     my $homeserver = &homeserver($cnum,$cdom);
 7504:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7505: 						       &escape($cdom),
 7506: 						       $homeserver)));
 7507:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7508: 	return (undef,undef);
 7509:     }
 7510:     return ($update,$comment);
 7511: }
 7512: 
 7513: sub auto_photoupdate {
 7514:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7515:     my $homeserver = &homeserver($cnum,$dom);
 7516:     my $host=&hostname($homeserver);
 7517:     my $cmd = '';
 7518:     my $maxtries = 1;
 7519:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7520:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7521:     }
 7522:     $cmd =~ s/%%$//;
 7523:     $cmd = &escape($cmd);
 7524:     my $query = 'institutionalphotos';
 7525:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7526:     unless ($queryid=~/^\Q$host\E\_/) {
 7527:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7528:         return 'error: '.$queryid;
 7529:     }
 7530:     my $reply = &get_query_reply($queryid);
 7531:     my $tries = 1;
 7532:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7533:         $reply = &get_query_reply($queryid);
 7534:         $tries ++;
 7535:     }
 7536:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7537:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7538:     } else {
 7539:         my @responses = split(/:/,$reply);
 7540:         my $outcome = shift(@responses); 
 7541:         foreach my $item (@responses) {
 7542:             my ($key,$value) = split(/=/,$item);
 7543:             $$photo{$key} = $value;
 7544:         }
 7545:         return $outcome;
 7546:     }
 7547:     return 'error';
 7548: }
 7549: 
 7550: sub auto_instcode_format {
 7551:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7552: 	$cat_order) = @_;
 7553:     my $courses = '';
 7554:     my @homeservers;
 7555:     if ($caller eq 'global') {
 7556: 	my %servers = &get_servers($codedom,'library');
 7557: 	foreach my $tryserver (keys(%servers)) {
 7558: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7559: 		push(@homeservers,$tryserver);
 7560: 	    }
 7561:         }
 7562:     } elsif ($caller eq 'requests') {
 7563:         if ($codedom =~ /^$match_domain$/) {
 7564:             my $chome = &domain($codedom,'primary');
 7565:             unless ($chome eq 'no_host') {
 7566:                 push(@homeservers,$chome);
 7567:             }
 7568:         }
 7569:     } else {
 7570:         push(@homeservers,&homeserver($caller,$codedom));
 7571:     }
 7572:     foreach my $code (keys(%{$instcodes})) {
 7573:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7574:     }
 7575:     chop($courses);
 7576:     my $ok_response = 0;
 7577:     my $response;
 7578:     while (@homeservers > 0 && $ok_response == 0) {
 7579:         my $server = shift(@homeservers); 
 7580:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7581:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7582:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7583: 		split(/:/,$response);
 7584:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7585:             push(@{$codetitles},&str2array($codetitles_str));
 7586:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7587:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7588:             $ok_response = 1;
 7589:         }
 7590:     }
 7591:     if ($ok_response) {
 7592:         return 'ok';
 7593:     } else {
 7594:         return $response;
 7595:     }
 7596: }
 7597: 
 7598: sub auto_instcode_defaults {
 7599:     my ($domain,$returnhash,$code_order) = @_;
 7600:     my @homeservers;
 7601: 
 7602:     my %servers = &get_servers($domain,'library');
 7603:     foreach my $tryserver (keys(%servers)) {
 7604: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7605: 	    push(@homeservers,$tryserver);
 7606: 	}
 7607:     }
 7608: 
 7609:     my $response;
 7610:     foreach my $server (@homeservers) {
 7611:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7612:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7613: 	
 7614: 	foreach my $pair (split(/\&/,$response)) {
 7615: 	    my ($name,$value)=split(/\=/,$pair);
 7616: 	    if ($name eq 'code_order') {
 7617: 		@{$code_order} = split(/\&/,&unescape($value));
 7618: 	    } else {
 7619: 		$returnhash->{&unescape($name)}=&unescape($value);
 7620: 	    }
 7621: 	}
 7622: 	return 'ok';
 7623:     }
 7624: 
 7625:     return $response;
 7626: }
 7627: 
 7628: sub auto_possible_instcodes {
 7629:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7630:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7631:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7632:         return;
 7633:     }
 7634:     my (@homeservers,$uhome);
 7635:     if (defined(&domain($domain,'primary'))) {
 7636:         $uhome=&domain($domain,'primary');
 7637:         push(@homeservers,&domain($domain,'primary'));
 7638:     } else {
 7639:         my %servers = &get_servers($domain,'library');
 7640:         foreach my $tryserver (keys(%servers)) {
 7641:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7642:                 push(@homeservers,$tryserver);
 7643:             }
 7644:         }
 7645:     }
 7646:     my $response;
 7647:     foreach my $server (@homeservers) {
 7648:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7649:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7650:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7651:             split(':',$response);
 7652:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7653:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7654:         foreach my $item (split('&',$cat_title)) {   
 7655:             my ($name,$value)=split('=',$item);
 7656:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7657:         }
 7658:         foreach my $item (split('&',$cat_order)) {
 7659:             my ($name,$value)=split('=',$item);
 7660:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7661:         }
 7662:         return 'ok';
 7663:     }
 7664:     return $response;
 7665: }
 7666: 
 7667: sub auto_courserequest_checks {
 7668:     my ($dom) = @_;
 7669:     my ($homeserver,%validations);
 7670:     if ($dom =~ /^$match_domain$/) {
 7671:         $homeserver = &domain($dom,'primary');
 7672:     }
 7673:     unless ($homeserver eq 'no_host') {
 7674:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7675:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7676:             my @items = split(/&/,$response);
 7677:             foreach my $item (@items) {
 7678:                 my ($key,$value) = split('=',$item);
 7679:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7680:             }
 7681:         }
 7682:     }
 7683:     return %validations; 
 7684: }
 7685: 
 7686: sub auto_courserequest_validation {
 7687:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7688:     my ($homeserver,$response);
 7689:     if ($dom =~ /^$match_domain$/) {
 7690:         $homeserver = &domain($dom,'primary');
 7691:     }
 7692:     unless ($homeserver eq 'no_host') {  
 7693:           
 7694:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7695:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7696:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7697:                                     $homeserver));
 7698:     }
 7699:     return $response;
 7700: }
 7701: 
 7702: sub auto_validate_class_sec {
 7703:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7704:     my $homeserver = &homeserver($cnum,$cdom);
 7705:     my $ownerlist;
 7706:     if (ref($owners) eq 'ARRAY') {
 7707:         $ownerlist = join(',',@{$owners});
 7708:     } else {
 7709:         $ownerlist = $owners;
 7710:     }
 7711:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7712:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7713:     return $response;
 7714: }
 7715: 
 7716: # ------------------------------------------------------- Course Group routines
 7717: 
 7718: sub get_coursegroups {
 7719:     my ($cdom,$cnum,$group,$namespace) = @_;
 7720:     return(&dump($namespace,$cdom,$cnum,$group));
 7721: }
 7722: 
 7723: sub modify_coursegroup {
 7724:     my ($cdom,$cnum,$groupsettings) = @_;
 7725:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7726: }
 7727: 
 7728: sub toggle_coursegroup_status {
 7729:     my ($cdom,$cnum,$group,$action) = @_;
 7730:     my ($from_namespace,$to_namespace);
 7731:     if ($action eq 'delete') {
 7732:         $from_namespace = 'coursegroups';
 7733:         $to_namespace = 'deleted_groups';
 7734:     } else {
 7735:         $from_namespace = 'deleted_groups';
 7736:         $to_namespace = 'coursegroups';
 7737:     }
 7738:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7739:     if (my $tmp = &error(%curr_group)) {
 7740:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7741:         return ('read error',$tmp);
 7742:     } else {
 7743:         my %savedsettings = %curr_group; 
 7744:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7745:         my $deloutcome;
 7746:         if ($result eq 'ok') {
 7747:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7748:         } else {
 7749:             return ('write error',$result);
 7750:         }
 7751:         if ($deloutcome eq 'ok') {
 7752:             return 'ok';
 7753:         } else {
 7754:             return ('delete error',$deloutcome);
 7755:         }
 7756:     }
 7757: }
 7758: 
 7759: sub modify_group_roles {
 7760:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7761:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7762:     my $role = 'gr/'.&escape($userprivs);
 7763:     my ($uname,$udom) = split(/:/,$user);
 7764:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7765:     if ($result eq 'ok') {
 7766:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7767:     }
 7768:     return $result;
 7769: }
 7770: 
 7771: sub modify_coursegroup_membership {
 7772:     my ($cdom,$cnum,$membership) = @_;
 7773:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7774:     return $result;
 7775: }
 7776: 
 7777: sub get_active_groups {
 7778:     my ($udom,$uname,$cdom,$cnum) = @_;
 7779:     my $now = time;
 7780:     my %groups = ();
 7781:     foreach my $key (keys(%env)) {
 7782:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7783:             my ($start,$end) = split(/\./,$env{$key});
 7784:             if (($end!=0) && ($end<$now)) { next; }
 7785:             if (($start!=0) && ($start>$now)) { next; }
 7786:             if ($1 eq $cdom && $2 eq $cnum) {
 7787:                 $groups{$3} = $env{$key} ;
 7788:             }
 7789:         }
 7790:     }
 7791:     return %groups;
 7792: }
 7793: 
 7794: sub get_group_membership {
 7795:     my ($cdom,$cnum,$group) = @_;
 7796:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7797: }
 7798: 
 7799: sub get_users_groups {
 7800:     my ($udom,$uname,$courseid) = @_;
 7801:     my @usersgroups;
 7802:     my $cachetime=1800;
 7803: 
 7804:     my $hashid="$udom:$uname:$courseid";
 7805:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7806:     if (defined($cached)) {
 7807:         @usersgroups = split(/:/,$grouplist);
 7808:     } else {  
 7809:         $grouplist = '';
 7810:         my $courseurl = &courseid_to_courseurl($courseid);
 7811:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7812:         my $access_end = $env{'course.'.$courseid.
 7813:                               '.default_enrollment_end_date'};
 7814:         my $now = time;
 7815:         foreach my $key (keys(%roleshash)) {
 7816:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7817:                 my $group = $1;
 7818:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7819:                     my $start = $2;
 7820:                     my $end = $1;
 7821:                     if ($start == -1) { next; } # deleted from group
 7822:                     if (($start!=0) && ($start>$now)) { next; }
 7823:                     if (($end!=0) && ($end<$now)) {
 7824:                         if ($access_end && $access_end < $now) {
 7825:                             if ($access_end - $end < 86400) {
 7826:                                 push(@usersgroups,$group);
 7827:                             }
 7828:                         }
 7829:                         next;
 7830:                     }
 7831:                     push(@usersgroups,$group);
 7832:                 }
 7833:             }
 7834:         }
 7835:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7836:         $grouplist = join(':',@usersgroups);
 7837:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7838:     }
 7839:     return @usersgroups;
 7840: }
 7841: 
 7842: sub devalidate_getgroups_cache {
 7843:     my ($udom,$uname,$cdom,$cnum)=@_;
 7844:     my $courseid = $cdom.'_'.$cnum;
 7845: 
 7846:     my $hashid="$udom:$uname:$courseid";
 7847:     &devalidate_cache_new('getgroups',$hashid);
 7848: }
 7849: 
 7850: # ------------------------------------------------------------------ Plain Text
 7851: 
 7852: sub plaintext {
 7853:     my ($short,$type,$cid,$forcedefault) = @_;
 7854:     if ($short =~ m{^cr/}) {
 7855: 	return (split('/',$short))[-1];
 7856:     }
 7857:     if (!defined($cid)) {
 7858:         $cid = $env{'request.course.id'};
 7859:     }
 7860:     my %rolenames = (
 7861:                       Course    => 'std',
 7862:                       Community => 'alt1',
 7863:                     );
 7864:     if ($cid ne '') {
 7865:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7866:             unless ($forcedefault) {
 7867:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7868:                 &Apache::lonlocal::mt_escape(\$roletext);
 7869:                 return &Apache::lonlocal::mt($roletext);
 7870:             }
 7871:         }
 7872:     }
 7873:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7874:         (defined($rolenames{$type})) && 
 7875:         (defined($prp{$short}{$rolenames{$type}}))) {
 7876:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7877:     } elsif ($cid ne '') {
 7878:         my $crstype = $env{'course.'.$cid.'.type'};
 7879:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7880:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7881:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7882:         }
 7883:     }
 7884:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7885: }
 7886: 
 7887: # ----------------------------------------------------------------- Assign Role
 7888: 
 7889: sub assignrole {
 7890:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7891:         $context)=@_;
 7892:     my $mrole;
 7893:     if ($role =~ /^cr\//) {
 7894:         my $cwosec=$url;
 7895:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7896: 	unless (&allowed('ccr',$cwosec)) {
 7897:            my $refused = 1;
 7898:            if ($context eq 'requestcourses') {
 7899:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7900:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7901:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7902:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7903:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7904:                            if ($crsenv{'internal.courseowner'} eq
 7905:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7906:                                $refused = '';
 7907:                            }
 7908:                        }
 7909:                    }
 7910:                }
 7911:            }
 7912:            if ($refused) {
 7913:                &logthis('Refused custom assignrole: '.
 7914:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7915:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7916:                return 'refused';
 7917:            }
 7918:         }
 7919:         $mrole='cr';
 7920:     } elsif ($role =~ /^gr\//) {
 7921:         my $cwogrp=$url;
 7922:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7923:         unless (&allowed('mdg',$cwogrp)) {
 7924:             &logthis('Refused group assignrole: '.
 7925:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7926:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7927:             return 'refused';
 7928:         }
 7929:         $mrole='gr';
 7930:     } else {
 7931:         my $cwosec=$url;
 7932:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7933:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7934:             my $refused;
 7935:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7936:                 if (!(&allowed('c'.$role,$url))) {
 7937:                     $refused = 1;
 7938:                 }
 7939:             } else {
 7940:                 $refused = 1;
 7941:             }
 7942:             if ($refused) {
 7943:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7944:                 if (!$selfenroll && $context eq 'course') {
 7945:                     my %crsenv;
 7946:                     if ($role eq 'cc' || $role eq 'co') {
 7947:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7948:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7949:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7950:                                 if ($crsenv{'internal.courseowner'} eq 
 7951:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7952:                                     $refused = '';
 7953:                                 }
 7954:                             }
 7955:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7956:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7957:                                 if ($crsenv{'internal.courseowner'} eq 
 7958:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7959:                                     $refused = '';
 7960:                                 }
 7961:                             }
 7962:                         }
 7963:                     }
 7964:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7965:                     $refused = '';
 7966:                 } elsif ($context eq 'requestcourses') {
 7967:                     my @possroles = ('st','ta','ep','in','cc','co');
 7968:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7969:                         my $wrongcc;
 7970:                         if ($cnum =~ /^$match_community$/) {
 7971:                             $wrongcc = 1 if ($role eq 'cc');
 7972:                         } else {
 7973:                             $wrongcc = 1 if ($role eq 'co');
 7974:                         }
 7975:                         unless ($wrongcc) {
 7976:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7977:                             if ($crsenv{'internal.courseowner'} eq 
 7978:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7979:                                 $refused = '';
 7980:                             }
 7981:                         }
 7982:                     }
 7983:                 } elsif ($context eq 'requestauthor') {
 7984:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 7985:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 7986:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 7987:                             $refused = '';
 7988:                         } else {
 7989:                             my %domdefaults = &get_domain_defaults($udom);
 7990:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 7991:                                 my $checkbystatus;
 7992:                                 if ($env{'user.adv'}) { 
 7993:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 7994:                                     if ($disposition eq 'automatic') {
 7995:                                         $refused = '';
 7996:                                     } elsif ($disposition eq '') {
 7997:                                         $checkbystatus = 1;
 7998:                                     } 
 7999:                                 } else {
 8000:                                     $checkbystatus = 1;
 8001:                                 }
 8002:                                 if ($checkbystatus) {
 8003:                                     if ($env{'environment.inststatus'}) {
 8004:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8005:                                         foreach my $type (@inststatuses) {
 8006:                                             if (($type ne '') &&
 8007:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8008:                                                 $refused = '';
 8009:                                             }
 8010:                                         }
 8011:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8012:                                         $refused = '';
 8013:                                     }
 8014:                                 }
 8015:                             }
 8016:                         }
 8017:                     }
 8018:                 }
 8019:                 if ($refused) {
 8020:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8021:                              ' '.$role.' '.$end.' '.$start.' by '.
 8022: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8023:                     return 'refused';
 8024:                 }
 8025:             }
 8026:         } elsif ($role eq 'au') {
 8027:             if ($url ne '/'.$udom.'/') {
 8028:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8029:                          ' to assign author role for '.$uname.':'.$udom.
 8030:                          ' in domain: '.$url.' refused (wrong domain).');
 8031:                 return 'refused';
 8032:             }
 8033:         }
 8034:         $mrole=$role;
 8035:     }
 8036:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8037:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8038:     if ($end) { $command.='_'.$end; }
 8039:     if ($start) {
 8040: 	if ($end) { 
 8041:            $command.='_'.$start; 
 8042:         } else {
 8043:            $command.='_0_'.$start;
 8044:         }
 8045:     }
 8046:     my $origstart = $start;
 8047:     my $origend = $end;
 8048:     my $delflag;
 8049: # actually delete
 8050:     if ($deleteflag) {
 8051: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8052: # modify command to delete the role
 8053:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8054:                 "$udom:$uname:$url".'_'."$mrole";
 8055: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8056: # set start and finish to negative values for userrolelog
 8057:            $start=-1;
 8058:            $end=-1;
 8059:            $delflag = 1;
 8060:         }
 8061:     }
 8062: # send command
 8063:     my $answer=&reply($command,&homeserver($uname,$udom));
 8064: # log new user role if status is ok
 8065:     if ($answer eq 'ok') {
 8066: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8067:         if (($role eq 'cc') || ($role eq 'in') ||
 8068:             ($role eq 'ep') || ($role eq 'ad') ||
 8069:             ($role eq 'ta') || ($role eq 'st') ||
 8070:             ($role=~/^cr/) || ($role eq 'gr') ||
 8071:             ($role eq 'co')) {
 8072: # for course roles, perform group memberships changes triggered by role change.
 8073:             unless ($role =~ /^gr/) {
 8074:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8075:                                                  $origstart,$selfenroll,$context);
 8076:             }
 8077:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8078:                            $selfenroll,$context);
 8079:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8080:                  ($role eq 'au') || ($role eq 'dc')) {
 8081:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8082:                            $context);
 8083:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8084:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8085:                              $context); 
 8086:         }
 8087:         if ($role eq 'cc') {
 8088:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8089:         }
 8090:     }
 8091:     return $answer;
 8092: }
 8093: 
 8094: sub autoupdate_coowners {
 8095:     my ($url,$end,$start,$uname,$udom) = @_;
 8096:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8097:     if (($cdom ne '') && ($cnum ne '')) {
 8098:         my $now = time;
 8099:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8100:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8101:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8102:             my $instcode = $coursehash{'internal.coursecode'};
 8103:             if ($instcode ne '') {
 8104:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8105:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8106:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8107:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8108:                         if ($result eq 'valid') {
 8109:                             if ($coursehash{'internal.co-owners'}) {
 8110:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8111:                                     push(@newcoowners,$coowner);
 8112:                                 }
 8113:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8114:                                     push(@newcoowners,$uname.':'.$udom);
 8115:                                 }
 8116:                                 @newcoowners = sort(@newcoowners);
 8117:                             } else {
 8118:                                 push(@newcoowners,$uname.':'.$udom);
 8119:                             }
 8120:                         } else {
 8121:                             if ($coursehash{'internal.co-owners'}) {
 8122:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8123:                                     unless ($coowner eq $uname.':'.$udom) {
 8124:                                         push(@newcoowners,$coowner);
 8125:                                     }
 8126:                                 }
 8127:                                 unless (@newcoowners > 0) {
 8128:                                     $delcoowners = 1;
 8129:                                     $coowners = '';
 8130:                                 }
 8131:                             }
 8132:                         }
 8133:                         if (@newcoowners || $delcoowners) {
 8134:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8135:                                             $delcoowners,@newcoowners);
 8136:                         }
 8137:                     }
 8138:                 }
 8139:             }
 8140:         }
 8141:     }
 8142: }
 8143: 
 8144: sub store_coowners {
 8145:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8146:     my $cid = $cdom.'_'.$cnum;
 8147:     my ($coowners,$delresult,$putresult);
 8148:     if (@newcoowners) {
 8149:         $coowners = join(',',@newcoowners);
 8150:         my %coownershash = (
 8151:                             'internal.co-owners' => $coowners,
 8152:                            );
 8153:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8154:         if ($putresult eq 'ok') {
 8155:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8156:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8157:             }
 8158:         }
 8159:     }
 8160:     if ($delcoowners) {
 8161:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8162:         if ($delresult eq 'ok') {
 8163:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8164:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8165:             }
 8166:         }
 8167:     }
 8168:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8169:         my %crsinfo =
 8170:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8171:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8172:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8173:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8174:         }
 8175:     }
 8176: }
 8177: 
 8178: # -------------------------------------------------- Modify user authentication
 8179: # Overrides without validation
 8180: 
 8181: sub modifyuserauth {
 8182:     my ($udom,$uname,$umode,$upass)=@_;
 8183:     my $uhome=&homeserver($uname,$udom);
 8184:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8185:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8186:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8187:              ' in domain '.$env{'request.role.domain'});  
 8188:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8189: 		     &escape($upass),$uhome);
 8190:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8191:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8192:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8193:     &log($udom,,$uname,$uhome,
 8194:         'Authentication changed by '.$env{'user.domain'}.', '.
 8195:                                      $env{'user.name'}.', '.$umode.
 8196:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8197:     unless ($reply eq 'ok') {
 8198:         &logthis('Authentication mode error: '.$reply);
 8199: 	return 'error: '.$reply;
 8200:     }   
 8201:     return 'ok';
 8202: }
 8203: 
 8204: # --------------------------------------------------------------- Modify a user
 8205: 
 8206: sub modifyuser {
 8207:     my ($udom,    $uname, $uid,
 8208:         $umode,   $upass, $first,
 8209:         $middle,  $last,  $gene,
 8210:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8211:     $udom= &LONCAPA::clean_domain($udom);
 8212:     $uname=&LONCAPA::clean_username($uname);
 8213:     my $showcandelete = 'none';
 8214:     if (ref($candelete) eq 'ARRAY') {
 8215:         if (@{$candelete} > 0) {
 8216:             $showcandelete = join(', ',@{$candelete});
 8217:         }
 8218:     }
 8219:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8220:              $umode.', '.$first.', '.$middle.', '.
 8221: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8222:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8223:                                      ' desiredhome not specified'). 
 8224:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8225:              ' in domain '.$env{'request.role.domain'});
 8226:     my $uhome=&homeserver($uname,$udom,'true');
 8227:     my $newuser;
 8228:     if ($uhome eq 'no_host') {
 8229:         $newuser = 1;
 8230:     }
 8231: # ----------------------------------------------------------------- Create User
 8232:     if (($uhome eq 'no_host') && 
 8233: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8234:         my $unhome='';
 8235:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8236:             $unhome = $desiredhome;
 8237: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8238: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8239:         } else { # load balancing routine for determining $unhome
 8240:             my $loadm=10000000;
 8241: 	    my %servers = &get_servers($udom,'library');
 8242: 	    foreach my $tryserver (keys(%servers)) {
 8243: 		my $answer=reply('load',$tryserver);
 8244: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8245: 		    $loadm=$answer;
 8246: 		    $unhome=$tryserver;
 8247: 		}
 8248: 	    }
 8249:         }
 8250:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8251: 	    return 'error: unable to find a home server for '.$uname.
 8252:                    ' in domain '.$udom;
 8253:         }
 8254:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8255:                          &escape($upass),$unhome);
 8256: 	unless ($reply eq 'ok') {
 8257:             return 'error: '.$reply;
 8258:         }   
 8259:         $uhome=&homeserver($uname,$udom,'true');
 8260:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8261: 	    return 'error: unable verify users home machine.';
 8262:         }
 8263:     }   # End of creation of new user
 8264: # ---------------------------------------------------------------------- Add ID
 8265:     if ($uid) {
 8266:        $uid=~tr/A-Z/a-z/;
 8267:        my %uidhash=&idrget($udom,$uname);
 8268:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8269:          && (!$forceid)) {
 8270: 	  unless ($uid eq $uidhash{$uname}) {
 8271: 	      return 'error: user id "'.$uid.'" does not match '.
 8272:                   'current user id "'.$uidhash{$uname}.'".';
 8273:           }
 8274:        } else {
 8275: 	  &idput($udom,($uname => $uid));
 8276:        }
 8277:     }
 8278: # -------------------------------------------------------------- Add names, etc
 8279:     my @tmp=&get('environment',
 8280: 		   ['firstname','middlename','lastname','generation','id',
 8281:                     'permanentemail','inststatus'],
 8282: 		   $udom,$uname);
 8283:     my (%names,%oldnames);
 8284:     if ($tmp[0] =~ m/^error:.*/) { 
 8285:         %names=(); 
 8286:     } else {
 8287:         %names = @tmp;
 8288:         %oldnames = %names;
 8289:     }
 8290: #
 8291: # If name, email and/or uid are blank (e.g., because an uploaded file
 8292: # of users did not contain them), do not overwrite existing values
 8293: # unless field is in $candelete array ref.  
 8294: #
 8295: 
 8296:     my @fields = ('firstname','middlename','lastname','generation',
 8297:                   'permanentemail','id');
 8298:     my %newvalues;
 8299:     if (ref($candelete) eq 'ARRAY') {
 8300:         foreach my $field (@fields) {
 8301:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8302:                 if ($field eq 'firstname') {
 8303:                     $names{$field} = $first;
 8304:                 } elsif ($field eq 'middlename') {
 8305:                     $names{$field} = $middle;
 8306:                 } elsif ($field eq 'lastname') {
 8307:                     $names{$field} = $last;
 8308:                 } elsif ($field eq 'generation') { 
 8309:                     $names{$field} = $gene;
 8310:                 } elsif ($field eq 'permanentemail') {
 8311:                     $names{$field} = $email;
 8312:                 } elsif ($field eq 'id') {
 8313:                     $names{$field}  = $uid;
 8314:                 }
 8315:             }
 8316:         }
 8317:     }
 8318:     if ($first)  { $names{'firstname'}  = $first; }
 8319:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8320:     if ($last)   { $names{'lastname'}   = $last; }
 8321:     if (defined($gene))   { $names{'generation'} = $gene; }
 8322:     if ($email) {
 8323:        $email=~s/[^\w\@\.\-\,]//gs;
 8324:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8325:     }
 8326:     if ($uid) { $names{'id'}  = $uid; }
 8327:     if (defined($inststatus)) {
 8328:         $names{'inststatus'} = '';
 8329:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8330:         if (ref($usertypes) eq 'HASH') {
 8331:             my @okstatuses; 
 8332:             foreach my $item (split(/:/,$inststatus)) {
 8333:                 if (defined($usertypes->{$item})) {
 8334:                     push(@okstatuses,$item);  
 8335:                 }
 8336:             }
 8337:             if (@okstatuses) {
 8338:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8339:             }
 8340:         }
 8341:     }
 8342:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8343:                  $umode.', '.$first.', '.$middle.', '.
 8344:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8345:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8346:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8347:     } else {
 8348:         $logmsg .= ' during self creation';
 8349:     }
 8350:     my $changed;
 8351:     if ($newuser) {
 8352:         $changed = 1;
 8353:     } else {
 8354:         foreach my $field (@fields) {
 8355:             if ($names{$field} ne $oldnames{$field}) {
 8356:                 $changed = 1;
 8357:                 last;
 8358:             }
 8359:         }
 8360:     }
 8361:     unless ($changed) {
 8362:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8363:         &logthis($logmsg);
 8364:         return 'ok';
 8365:     }
 8366:     my $reply = &put('environment', \%names, $udom,$uname);
 8367:     if ($reply ne 'ok') { 
 8368:         return 'error: '.$reply;
 8369:     }
 8370:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8371:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8372:     }
 8373:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8374:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8375:     $logmsg = 'Success modifying user '.$logmsg;
 8376:     &logthis($logmsg);
 8377:     return 'ok';
 8378: }
 8379: 
 8380: # -------------------------------------------------------------- Modify student
 8381: 
 8382: sub modifystudent {
 8383:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8384:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8385:         $selfenroll,$context,$inststatus)=@_;
 8386:     if (!$cid) {
 8387: 	unless ($cid=$env{'request.course.id'}) {
 8388: 	    return 'not_in_class';
 8389: 	}
 8390:     }
 8391: # --------------------------------------------------------------- Make the user
 8392:     my $reply=&modifyuser
 8393: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8394:          $desiredhome,$email,$inststatus);
 8395:     unless ($reply eq 'ok') { return $reply; }
 8396:     # This will cause &modify_student_enrollment to get the uid from the
 8397:     # students environment
 8398:     $uid = undef if (!$forceid);
 8399:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8400: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 8401:     return $reply;
 8402: }
 8403: 
 8404: sub modify_student_enrollment {
 8405:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 8406:     my ($cdom,$cnum,$chome);
 8407:     if (!$cid) {
 8408: 	unless ($cid=$env{'request.course.id'}) {
 8409: 	    return 'not_in_class';
 8410: 	}
 8411: 	$cdom=$env{'course.'.$cid.'.domain'};
 8412: 	$cnum=$env{'course.'.$cid.'.num'};
 8413:     } else {
 8414: 	($cdom,$cnum)=split(/_/,$cid);
 8415:     }
 8416:     $chome=$env{'course.'.$cid.'.home'};
 8417:     if (!$chome) {
 8418: 	$chome=&homeserver($cnum,$cdom);
 8419:     }
 8420:     if (!$chome) { return 'unknown_course'; }
 8421:     # Make sure the user exists
 8422:     my $uhome=&homeserver($uname,$udom);
 8423:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8424: 	return 'error: no such user';
 8425:     }
 8426:     # Get student data if we were not given enough information
 8427:     if (!defined($first)  || $first  eq '' || 
 8428:         !defined($last)   || $last   eq '' || 
 8429:         !defined($uid)    || $uid    eq '' || 
 8430:         !defined($middle) || $middle eq '' || 
 8431:         !defined($gene)   || $gene   eq '') {
 8432:         # They did not supply us with enough data to enroll the student, so
 8433:         # we need to pick up more information.
 8434:         my %tmp = &get('environment',
 8435:                        ['firstname','middlename','lastname', 'generation','id']
 8436:                        ,$udom,$uname);
 8437: 
 8438:         #foreach my $key (keys(%tmp)) {
 8439:         #    &logthis("key $key = ".$tmp{$key});
 8440:         #}
 8441:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8442:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8443:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8444:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8445:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8446:     }
 8447:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8448:     my $user = "$uname:$udom";
 8449:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8450:     my $reply=cput('classlist',
 8451: 		   {$user => 
 8452: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 8453: 		   $cdom,$cnum);
 8454:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8455:         &devalidate_getsection_cache($udom,$uname,$cid);
 8456:     } else { 
 8457: 	return 'error: '.$reply;
 8458:     }
 8459:     # Add student role to user
 8460:     my $uurl='/'.$cid;
 8461:     $uurl=~s/\_/\//g;
 8462:     if ($usec) {
 8463: 	$uurl.='/'.$usec;
 8464:     }
 8465:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8466:                              $selfenroll,$context);
 8467:     if ($result ne 'ok') {
 8468:         if ($old_entry{$user} ne '') {
 8469:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8470:         } else {
 8471:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8472:         }
 8473:     }
 8474:     return $result; 
 8475: }
 8476: 
 8477: sub format_name {
 8478:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8479:     my $name;
 8480:     if ($first ne 'lastname') {
 8481: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8482:     } else {
 8483: 	if ($lastname=~/\S/) {
 8484: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8485: 	    $name=~s/\s+,/,/;
 8486: 	} else {
 8487: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8488: 	}
 8489:     }
 8490:     $name=~s/^\s+//;
 8491:     $name=~s/\s+$//;
 8492:     $name=~s/\s+/ /g;
 8493:     return $name;
 8494: }
 8495: 
 8496: # ------------------------------------------------- Write to course preferences
 8497: 
 8498: sub writecoursepref {
 8499:     my ($courseid,%prefs)=@_;
 8500:     $courseid=~s/^\///;
 8501:     $courseid=~s/\_/\//g;
 8502:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8503:     my $chome=homeserver($cnum,$cdomain);
 8504:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8505: 	return 'error: no such course';
 8506:     }
 8507:     my $cstring='';
 8508:     foreach my $pref (keys(%prefs)) {
 8509: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8510:     }
 8511:     $cstring=~s/\&$//;
 8512:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8513: }
 8514: 
 8515: # ---------------------------------------------------------- Make/modify course
 8516: 
 8517: sub createcourse {
 8518:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8519:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8520:     $url=&declutter($url);
 8521:     my $cid='';
 8522:     if ($context eq 'requestcourses') {
 8523:         my $can_create = 0;
 8524:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8525:         if ($udom eq $ownerdom) {
 8526:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8527:                                   $context)) {
 8528:                 $can_create = 1;
 8529:             }
 8530:         } else {
 8531:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8532:                                            $category);
 8533:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8534:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8535:                 if (@curr > 0) {
 8536:                     my @options = qw(approval validate autolimit);
 8537:                     my $optregex = join('|',@options);
 8538:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8539:                         $can_create = 1;
 8540:                     }
 8541:                 }
 8542:             }
 8543:         }
 8544:         if ($can_create) {
 8545:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8546:                 unless (&allowed('ccc',$udom)) {
 8547:                     return 'refused'; 
 8548:                 }
 8549:             }
 8550:         } else {
 8551:             return 'refused';
 8552:         }
 8553:     } elsif (!&allowed('ccc',$udom)) {
 8554:         return 'refused';
 8555:     }
 8556: # --------------------------------------------------------------- Get Unique ID
 8557:     my $uname;
 8558:     if ($cnum =~ /^$match_courseid$/) {
 8559:         my $chome=&homeserver($cnum,$udom,'true');
 8560:         if (($chome eq '') || ($chome eq 'no_host')) {
 8561:             $uname = $cnum;
 8562:         } else {
 8563:             $uname = &generate_coursenum($udom,$crstype);
 8564:         }
 8565:     } else {
 8566:         $uname = &generate_coursenum($udom,$crstype);
 8567:     }
 8568:     return $uname if ($uname =~ /^error/);
 8569: # -------------------------------------------------- Check supplied server name
 8570:     if (!defined($course_server)) {
 8571:         if (defined(&domain($udom,'primary'))) {
 8572:             $course_server = &domain($udom,'primary');
 8573:         } else {
 8574:             $course_server = $env{'user.home'}; 
 8575:         }
 8576:     }
 8577:     my %host_servers =
 8578:         &Apache::lonnet::get_servers($udom,'library');
 8579:     unless ($host_servers{$course_server}) {
 8580:         return 'error: invalid home server for course: '.$course_server;
 8581:     }
 8582: # ------------------------------------------------------------- Make the course
 8583:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8584:                       $course_server);
 8585:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8586:     my $uhome=&homeserver($uname,$udom,'true');
 8587:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8588: 	return 'error: no such course';
 8589:     }
 8590: # ----------------------------------------------------------------- Course made
 8591: # log existence
 8592:     my $now = time;
 8593:     my $newcourse = {
 8594:                     $udom.'_'.$uname => {
 8595:                                      description => $description,
 8596:                                      inst_code   => $inst_code,
 8597:                                      owner       => $course_owner,
 8598:                                      type        => $crstype,
 8599:                                      creator     => $env{'user.name'}.':'.
 8600:                                                     $env{'user.domain'},
 8601:                                      created     => $now,
 8602:                                      context     => $context,
 8603:                                                 },
 8604:                     };
 8605:     &courseidput($udom,$newcourse,$uhome,'notime');
 8606: # set toplevel url
 8607:     my $topurl=$url;
 8608:     unless ($nonstandard) {
 8609: # ------------------------------------------ For standard courses, make top url
 8610:         my $mapurl=&clutter($url);
 8611:         if ($mapurl eq '/res/') { $mapurl=''; }
 8612:         $env{'form.initmap'}=(<<ENDINITMAP);
 8613: <map>
 8614: <resource id="1" type="start"></resource>
 8615: <resource id="2" src="$mapurl"></resource>
 8616: <resource id="3" type="finish"></resource>
 8617: <link index="1" from="1" to="2"></link>
 8618: <link index="2" from="2" to="3"></link>
 8619: </map>
 8620: ENDINITMAP
 8621:         $topurl=&declutter(
 8622:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8623:                           );
 8624:     }
 8625: # ----------------------------------------------------------- Write preferences
 8626:     &writecoursepref($udom.'_'.$uname,
 8627:                      ('description'              => $description,
 8628:                       'url'                      => $topurl,
 8629:                       'internal.creator'         => $env{'user.name'}.':'.
 8630:                                                     $env{'user.domain'},
 8631:                       'internal.created'         => $now,
 8632:                       'internal.creationcontext' => $context)
 8633:                     );
 8634:     return '/'.$udom.'/'.$uname;
 8635: }
 8636: 
 8637: # ------------------------------------------------------------------- Create ID
 8638: sub generate_coursenum {
 8639:     my ($udom,$crstype) = @_;
 8640:     my $domdesc = &domain($udom);
 8641:     return 'error: invalid domain' if ($domdesc eq '');
 8642:     my $first;
 8643:     if ($crstype eq 'Community') {
 8644:         $first = '0';
 8645:     } else {
 8646:         $first = int(1+rand(9)); 
 8647:     } 
 8648:     my $uname=$first.
 8649:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8650:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8651:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8652: # ----------------------------------------------- Make sure that does not exist
 8653:     my $uhome=&homeserver($uname,$udom,'true');
 8654:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8655:         if ($crstype eq 'Community') {
 8656:             $first = '0';
 8657:         } else {
 8658:             $first = int(1+rand(9));
 8659:         }
 8660:         $uname=$first.
 8661:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8662:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8663:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8664:         $uhome=&homeserver($uname,$udom,'true');
 8665:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8666:             return 'error: unable to generate unique course-ID';
 8667:         }
 8668:     }
 8669:     return $uname;
 8670: }
 8671: 
 8672: sub is_course {
 8673:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8674:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8675: 
 8676:     return unless $cdom and $cnum;
 8677: 
 8678:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8679:         '.');
 8680: 
 8681:     return unless exists($courses{$cdom.'_'.$cnum});
 8682:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8683: }
 8684: 
 8685: sub store_userdata {
 8686:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8687:     my $result;
 8688:     if ($datakey ne '') {
 8689:         if (ref($storehash) eq 'HASH') {
 8690:             if ($udom eq '' || $uname eq '') {
 8691:                 $udom = $env{'user.domain'};
 8692:                 $uname = $env{'user.name'};
 8693:             }
 8694:             my $uhome=&homeserver($uname,$udom);
 8695:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8696:                 $result = 'error: no_host';
 8697:             } else {
 8698:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8699:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8700: 
 8701:                 my $namevalue='';
 8702:                 foreach my $key (keys(%{$storehash})) {
 8703:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8704:                 }
 8705:                 $namevalue=~s/\&$//;
 8706:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8707:                                   $namevalue,$uhome);
 8708:             }
 8709:         } else {
 8710:             $result = 'error: data to store was not a hash reference'; 
 8711:         }
 8712:     } else {
 8713:         $result= 'error: invalid requestkey'; 
 8714:     }
 8715:     return $result;
 8716: }
 8717: 
 8718: # ---------------------------------------------------------- Assign Custom Role
 8719: 
 8720: sub assigncustomrole {
 8721:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8722:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8723:                        $end,$start,$deleteflag,$selfenroll,$context);
 8724: }
 8725: 
 8726: # ----------------------------------------------------------------- Revoke Role
 8727: 
 8728: sub revokerole {
 8729:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8730:     my $now=time;
 8731:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8732: }
 8733: 
 8734: # ---------------------------------------------------------- Revoke Custom Role
 8735: 
 8736: sub revokecustomrole {
 8737:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8738:     my $now=time;
 8739:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8740:            $deleteflag,$selfenroll,$context);
 8741: }
 8742: 
 8743: # ------------------------------------------------------------ Disk usage
 8744: sub diskusage {
 8745:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8746:     $directorypath =~ s/\/$//;
 8747:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8748:                        .&escape($getpropath).':'.&escape($uname).':'
 8749:                        .&escape($udom),homeserver($uname,$udom));
 8750:     if ($listing eq 'unknown_cmd') {
 8751:         if ($getpropath) {
 8752:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8753:         }
 8754:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8755:     }
 8756:     return $listing;
 8757: }
 8758: 
 8759: sub is_locked {
 8760:     my ($file_name, $domain, $user, $which) = @_;
 8761:     my @check;
 8762:     my $is_locked;
 8763:     push (@check,$file_name);
 8764:     my %locked = &get('file_permissions',\@check,
 8765: 		      $env{'user.domain'},$env{'user.name'});
 8766:     my ($tmp)=keys(%locked);
 8767:     if ($tmp=~/^error:/) { undef(%locked); }
 8768:     
 8769:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8770:         $is_locked = 'false';
 8771:         foreach my $entry (@{$locked{$file_name}}) {
 8772:            if (ref($entry) eq 'ARRAY') {
 8773:                $is_locked = 'true';
 8774:                if (ref($which) eq 'ARRAY') {
 8775:                    push(@{$which},$entry);
 8776:                } else {
 8777:                    last;
 8778:                }
 8779:            }
 8780:        }
 8781:     } else {
 8782:         $is_locked = 'false';
 8783:     }
 8784:     return $is_locked;
 8785: }
 8786: 
 8787: sub declutter_portfile {
 8788:     my ($file) = @_;
 8789:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8790:     return $file;
 8791: }
 8792: 
 8793: # ------------------------------------------------------------- Mark as Read Only
 8794: 
 8795: sub mark_as_readonly {
 8796:     my ($domain,$user,$files,$what) = @_;
 8797:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8798:     my ($tmp)=keys(%current_permissions);
 8799:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8800:     foreach my $file (@{$files}) {
 8801: 	$file = &declutter_portfile($file);
 8802:         push(@{$current_permissions{$file}},$what);
 8803:     }
 8804:     &put('file_permissions',\%current_permissions,$domain,$user);
 8805:     return;
 8806: }
 8807: 
 8808: # ------------------------------------------------------------Save Selected Files
 8809: 
 8810: sub save_selected_files {
 8811:     my ($user, $path, @files) = @_;
 8812:     my $filename = $user."savedfiles";
 8813:     my @other_files = &files_not_in_path($user, $path);
 8814:     open (OUT, '>'.$tmpdir.$filename);
 8815:     foreach my $file (@files) {
 8816:         print (OUT $env{'form.currentpath'}.$file."\n");
 8817:     }
 8818:     foreach my $file (@other_files) {
 8819:         print (OUT $file."\n");
 8820:     }
 8821:     close (OUT);
 8822:     return 'ok';
 8823: }
 8824: 
 8825: sub clear_selected_files {
 8826:     my ($user) = @_;
 8827:     my $filename = $user."savedfiles";
 8828:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8829:     print (OUT undef);
 8830:     close (OUT);
 8831:     return ("ok");    
 8832: }
 8833: 
 8834: sub files_in_path {
 8835:     my ($user, $path) = @_;
 8836:     my $filename = $user."savedfiles";
 8837:     my %return_files;
 8838:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8839:     while (my $line_in = <IN>) {
 8840:         chomp ($line_in);
 8841:         my @paths_and_file = split (m!/!, $line_in);
 8842:         my $file_part = pop (@paths_and_file);
 8843:         my $path_part = join ('/', @paths_and_file);
 8844:         $path_part.='/';
 8845:         my $path_and_file = $path_part.$file_part;
 8846:         if ($path_part eq $path) {
 8847:             $return_files{$file_part}= 'selected';
 8848:         }
 8849:     }
 8850:     close (IN);
 8851:     return (\%return_files);
 8852: }
 8853: 
 8854: # called in portfolio select mode, to show files selected NOT in current directory
 8855: sub files_not_in_path {
 8856:     my ($user, $path) = @_;
 8857:     my $filename = $user."savedfiles";
 8858:     my @return_files;
 8859:     my $path_part;
 8860:     open(IN, '<'.LONCAPA::.$filename);
 8861:     while (my $line = <IN>) {
 8862:         #ok, I know it's clunky, but I want it to work
 8863:         my @paths_and_file = split(m|/|, $line);
 8864:         my $file_part = pop(@paths_and_file);
 8865:         chomp($file_part);
 8866:         my $path_part = join('/', @paths_and_file);
 8867:         $path_part .= '/';
 8868:         my $path_and_file = $path_part.$file_part;
 8869:         if ($path_part ne $path) {
 8870:             push(@return_files, ($path_and_file));
 8871:         }
 8872:     }
 8873:     close(OUT);
 8874:     return (@return_files);
 8875: }
 8876: 
 8877: #----------------------------------------------Get portfolio file permissions
 8878: 
 8879: sub get_portfile_permissions {
 8880:     my ($domain,$user) = @_;
 8881:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8882:     my ($tmp)=keys(%current_permissions);
 8883:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8884:     return \%current_permissions;
 8885: }
 8886: 
 8887: #---------------------------------------------Get portfolio file access controls
 8888: 
 8889: sub get_access_controls {
 8890:     my ($current_permissions,$group,$file) = @_;
 8891:     my %access;
 8892:     my $real_file = $file;
 8893:     $file =~ s/\.meta$//;
 8894:     if (defined($file)) {
 8895:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8896:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8897:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8898:             }
 8899:         }
 8900:     } else {
 8901:         foreach my $key (keys(%{$current_permissions})) {
 8902:             if ($key =~ /\0accesscontrol$/) {
 8903:                 if (defined($group)) {
 8904:                     if ($key !~ m-^\Q$group\E/-) {
 8905:                         next;
 8906:                     }
 8907:                 }
 8908:                 my ($fullpath) = split(/\0/,$key);
 8909:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8910:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8911:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8912:                     }
 8913:                 }
 8914:             }
 8915:         }
 8916:     }
 8917:     return %access;
 8918: }
 8919: 
 8920: sub modify_access_controls {
 8921:     my ($file_name,$changes,$domain,$user)=@_;
 8922:     my ($outcome,$deloutcome);
 8923:     my %store_permissions;
 8924:     my %new_values;
 8925:     my %new_control;
 8926:     my %translation;
 8927:     my @deletions = ();
 8928:     my $now = time;
 8929:     if (exists($$changes{'activate'})) {
 8930:         if (ref($$changes{'activate'}) eq 'HASH') {
 8931:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8932:             my $numnew = scalar(@newitems);
 8933:             for (my $i=0; $i<$numnew; $i++) {
 8934:                 my $newkey = $newitems[$i];
 8935:                 my $newid = &Apache::loncommon::get_cgi_id();
 8936:                 if ($newkey =~ /^\d+:/) { 
 8937:                     $newkey =~ s/^(\d+)/$newid/;
 8938:                     $translation{$1} = $newid;
 8939:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8940:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8941:                     $translation{$1} = $newid;
 8942:                 }
 8943:                 $new_values{$file_name."\0".$newkey} = 
 8944:                                           $$changes{'activate'}{$newitems[$i]};
 8945:                 $new_control{$newkey} = $now;
 8946:             }
 8947:         }
 8948:     }
 8949:     my %todelete;
 8950:     my %changed_items;
 8951:     foreach my $action ('delete','update') {
 8952:         if (exists($$changes{$action})) {
 8953:             if (ref($$changes{$action}) eq 'HASH') {
 8954:                 foreach my $key (keys(%{$$changes{$action}})) {
 8955:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8956:                     if ($action eq 'delete') { 
 8957:                         $todelete{$itemnum} = 1;
 8958:                     } else {
 8959:                         $changed_items{$itemnum} = $key;
 8960:                     }
 8961:                 }
 8962:             }
 8963:         }
 8964:     }
 8965:     # get lock on access controls for file.
 8966:     my $lockhash = {
 8967:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8968:                                                        ':'.$env{'user.domain'},
 8969:                    }; 
 8970:     my $tries = 0;
 8971:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8972:    
 8973:     while (($gotlock ne 'ok') && $tries <3) {
 8974:         $tries ++;
 8975:         sleep 1;
 8976:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8977:     }
 8978:     if ($gotlock eq 'ok') {
 8979:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8980:         my ($tmp)=keys(%curr_permissions);
 8981:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8982:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8983:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8984:             if (ref($curr_controls) eq 'HASH') {
 8985:                 foreach my $control_item (keys(%{$curr_controls})) {
 8986:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8987:                     if (defined($todelete{$itemnum})) {
 8988:                         push(@deletions,$file_name."\0".$control_item);
 8989:                     } else {
 8990:                         if (defined($changed_items{$itemnum})) {
 8991:                             $new_control{$changed_items{$itemnum}} = $now;
 8992:                             push(@deletions,$file_name."\0".$control_item);
 8993:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8994:                         } else {
 8995:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8996:                         }
 8997:                     }
 8998:                 }
 8999:             }
 9000:         }
 9001:         my ($group);
 9002:         if (&is_course($domain,$user)) {
 9003:             ($group,my $file) = split(/\//,$file_name,2);
 9004:         }
 9005:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9006:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9007:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9008:         #  remove lock
 9009:         my @del_lock = ($file_name."\0".'locked_access_records');
 9010:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9011:         my $sqlresult =
 9012:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9013:                                     $group);
 9014:     } else {
 9015:         $outcome = "error: could not obtain lockfile\n";  
 9016:     }
 9017:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9018: }
 9019: 
 9020: sub make_public_indefinitely {
 9021:     my ($requrl) = @_;
 9022:     my $now = time;
 9023:     my $action = 'activate';
 9024:     my $aclnum = 0;
 9025:     if (&is_portfolio_url($requrl)) {
 9026:         my (undef,$udom,$unum,$file_name,$group) =
 9027:             &parse_portfolio_url($requrl);
 9028:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9029:         my %access_controls = &get_access_controls($current_perms,
 9030:                                                    $group,$file_name);
 9031:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9032:             my ($num,$scope,$end,$start) = 
 9033:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9034:             if ($scope eq 'public') {
 9035:                 if ($start <= $now && $end == 0) {
 9036:                     $action = 'none';
 9037:                 } else {
 9038:                     $action = 'update';
 9039:                     $aclnum = $num;
 9040:                 }
 9041:                 last;
 9042:             }
 9043:         }
 9044:         if ($action eq 'none') {
 9045:              return 'ok';
 9046:         } else {
 9047:             my %changes;
 9048:             my $newend = 0;
 9049:             my $newstart = $now;
 9050:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9051:             $changes{$action}{$newkey} = {
 9052:                 type => 'public',
 9053:                 time => {
 9054:                     start => $newstart,
 9055:                     end   => $newend,
 9056:                 },
 9057:             };
 9058:             my ($outcome,$deloutcome,$new_values,$translation) =
 9059:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9060:             return $outcome;
 9061:         }
 9062:     } else {
 9063:         return 'invalid';
 9064:     }
 9065: }
 9066: 
 9067: #------------------------------------------------------Get Marked as Read Only
 9068: 
 9069: sub get_marked_as_readonly {
 9070:     my ($domain,$user,$what,$group) = @_;
 9071:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9072:     my @readonly_files;
 9073:     my $cmp1=$what;
 9074:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9075:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9076:         if (defined($group)) {
 9077:             if ($file_name !~ m-^\Q$group\E/-) {
 9078:                 next;
 9079:             }
 9080:         }
 9081:         if (ref($value) eq "ARRAY"){
 9082:             foreach my $stored_what (@{$value}) {
 9083:                 my $cmp2=$stored_what;
 9084:                 if (ref($stored_what) eq 'ARRAY') {
 9085:                     $cmp2=join('',@{$stored_what});
 9086:                 }
 9087:                 if ($cmp1 eq $cmp2) {
 9088:                     push(@readonly_files, $file_name);
 9089:                     last;
 9090:                 } elsif (!defined($what)) {
 9091:                     push(@readonly_files, $file_name);
 9092:                     last;
 9093:                 }
 9094:             }
 9095:         }
 9096:     }
 9097:     return @readonly_files;
 9098: }
 9099: #-----------------------------------------------------------Get Marked as Read Only Hash
 9100: 
 9101: sub get_marked_as_readonly_hash {
 9102:     my ($current_permissions,$group,$what) = @_;
 9103:     my %readonly_files;
 9104:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9105:         if (defined($group)) {
 9106:             if ($file_name !~ m-^\Q$group\E/-) {
 9107:                 next;
 9108:             }
 9109:         }
 9110:         if (ref($value) eq "ARRAY"){
 9111:             foreach my $stored_what (@{$value}) {
 9112:                 if (ref($stored_what) eq 'ARRAY') {
 9113:                     foreach my $lock_descriptor(@{$stored_what}) {
 9114:                         if ($lock_descriptor eq 'graded') {
 9115:                             $readonly_files{$file_name} = 'graded';
 9116:                         } elsif ($lock_descriptor eq 'handback') {
 9117:                             $readonly_files{$file_name} = 'handback';
 9118:                         } else {
 9119:                             if (!exists($readonly_files{$file_name})) {
 9120:                                 $readonly_files{$file_name} = 'locked';
 9121:                             }
 9122:                         }
 9123:                     }
 9124:                 } 
 9125:             }
 9126:         } 
 9127:     }
 9128:     return %readonly_files;
 9129: }
 9130: # ------------------------------------------------------------ Unmark as Read Only
 9131: 
 9132: sub unmark_as_readonly {
 9133:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9134:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9135:     my ($domain,$user,$what,$file_name,$group) = @_;
 9136:     $file_name = &declutter_portfile($file_name);
 9137:     my $symb_crs = $what;
 9138:     if (ref($what)) { $symb_crs=join('',@$what); }
 9139:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9140:     my ($tmp)=keys(%current_permissions);
 9141:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9142:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9143:     foreach my $file (@readonly_files) {
 9144: 	my $clean_file = &declutter_portfile($file);
 9145: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9146: 	my $current_locks = $current_permissions{$file};
 9147:         my @new_locks;
 9148:         my @del_keys;
 9149:         if (ref($current_locks) eq "ARRAY"){
 9150:             foreach my $locker (@{$current_locks}) {
 9151:                 my $compare=$locker;
 9152:                 if (ref($locker) eq 'ARRAY') {
 9153:                     $compare=join('',@{$locker});
 9154:                     if ($compare ne $symb_crs) {
 9155:                         push(@new_locks, $locker);
 9156:                     }
 9157:                 }
 9158:             }
 9159:             if (scalar(@new_locks) > 0) {
 9160:                 $current_permissions{$file} = \@new_locks;
 9161:             } else {
 9162:                 push(@del_keys, $file);
 9163:                 &del('file_permissions',\@del_keys, $domain, $user);
 9164:                 delete($current_permissions{$file});
 9165:             }
 9166:         }
 9167:     }
 9168:     &put('file_permissions',\%current_permissions,$domain,$user);
 9169:     return;
 9170: }
 9171: 
 9172: # ------------------------------------------------------------ Directory lister
 9173: 
 9174: sub dirlist {
 9175:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9176:     $uri=~s/^\///;
 9177:     $uri=~s/\/$//;
 9178:     my ($udom, $uname);
 9179:     if ($getuserdir) {
 9180:         $udom = $userdomain;
 9181:         $uname = $username;
 9182:     } else {
 9183:         (undef,$udom,$uname)=split(/\//,$uri);
 9184:         if(defined($userdomain)) {
 9185:             $udom = $userdomain;
 9186:         }
 9187:         if(defined($username)) {
 9188:             $uname = $username;
 9189:         }
 9190:     }
 9191:     my ($dirRoot,$listing,@listing_results);
 9192: 
 9193:     $dirRoot = $perlvar{'lonDocRoot'};
 9194:     if (defined($getpropath)) {
 9195:         $dirRoot = &propath($udom,$uname);
 9196:         $dirRoot =~ s/\/$//;
 9197:     } elsif (defined($getuserdir)) {
 9198:         my $subdir=$uname.'__';
 9199:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9200:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9201:                    ."/$udom/$subdir/$uname";
 9202:     } elsif (defined($alternateRoot)) {
 9203:         $dirRoot = $alternateRoot;
 9204:     }
 9205: 
 9206:     if($udom) {
 9207:         if($uname) {
 9208:             my $uhome = &homeserver($uname,$udom);
 9209:             if ($uhome eq 'no_host') {
 9210:                 return ([],'no_host');
 9211:             }
 9212:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9213:                               .$getuserdir.':'.&escape($dirRoot)
 9214:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9215:             if ($listing eq 'unknown_cmd') {
 9216:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9217:             } else {
 9218:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9219:             }
 9220:             if ($listing eq 'unknown_cmd') {
 9221:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9222:                 @listing_results = split(/:/,$listing);
 9223:             } else {
 9224:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9225:             }
 9226:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9227:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9228:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9229:                 return ([],$listing);
 9230:             } else {
 9231:                 return (\@listing_results);
 9232:             }
 9233:         } elsif(!$alternateRoot) {
 9234:             my (%allusers,%listerror);
 9235: 	    my %servers = &get_servers($udom,'library');
 9236:  	    foreach my $tryserver (keys(%servers)) {
 9237:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9238:                                   &escape($udom),$tryserver);
 9239:                 if ($listing eq 'unknown_cmd') {
 9240: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9241: 				      $udom, $tryserver);
 9242:                 } else {
 9243:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9244:                 }
 9245: 		if ($listing eq 'unknown_cmd') {
 9246: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9247: 				      $udom, $tryserver);
 9248: 		    @listing_results = split(/:/,$listing);
 9249: 		} else {
 9250: 		    @listing_results =
 9251: 			map { &unescape($_); } split(/:/,$listing);
 9252: 		}
 9253:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9254:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9255:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9256:                     $listerror{$tryserver} = $listing;
 9257:                 } else {
 9258: 		    foreach my $line (@listing_results) {
 9259: 			my ($entry) = split(/&/,$line,2);
 9260: 			$allusers{$entry} = 1;
 9261: 		    }
 9262: 		}
 9263:             }
 9264:             my @alluserslist=();
 9265:             foreach my $user (sort(keys(%allusers))) {
 9266:                 push(@alluserslist,$user.'&user');
 9267:             }
 9268:             return (\@alluserslist);
 9269:         } else {
 9270:             return ([],'missing username');
 9271:         }
 9272:     } elsif(!defined($getpropath)) {
 9273:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9274:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9275:         return (\@all_domains);
 9276:     } else {
 9277:         return ([],'missing domain');
 9278:     }
 9279: }
 9280: 
 9281: # --------------------------------------------- GetFileTimestamp
 9282: # This function utilizes dirlist and returns the date stamp for
 9283: # when it was last modified.  It will also return an error of -1
 9284: # if an error occurs
 9285: 
 9286: sub GetFileTimestamp {
 9287:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9288:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9289:     $studentName   = &LONCAPA::clean_username($studentName);
 9290:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9291:                                     undef,$getuserdir);
 9292:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9293:         return -1;
 9294:     }
 9295:     if (ref($fileref) eq 'ARRAY') {
 9296:         my @stats = split('&',$fileref->[0]);
 9297:         # @stats contains first the filename, then the stat output
 9298:         return $stats[10]; # so this is 10 instead of 9.
 9299:     } else {
 9300:         return -1;
 9301:     }
 9302: }
 9303: 
 9304: sub stat_file {
 9305:     my ($uri) = @_;
 9306:     $uri = &clutter_with_no_wrapper($uri);
 9307: 
 9308:     my ($udom,$uname,$file);
 9309:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9310: 	($udom,$uname,$file) =
 9311: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9312: 	$file = 'userfiles/'.$file;
 9313:     }
 9314:     if ($uri =~ m-^/res/-) {
 9315: 	($udom,$uname) = 
 9316: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9317: 	$file = $uri;
 9318:     }
 9319: 
 9320:     if (!$udom || !$uname || !$file) {
 9321: 	# unable to handle the uri
 9322: 	return ();
 9323:     }
 9324:     my $getpropath;
 9325:     if ($file =~ /^userfiles\//) {
 9326:         $getpropath = 1;
 9327:     }
 9328:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9329:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9330:         return ();
 9331:     } else {
 9332:         if (ref($listref) eq 'ARRAY') {
 9333:             my @stats = split('&',$listref->[0]);
 9334: 	    shift(@stats); #filename is first
 9335: 	    return @stats;
 9336:         }
 9337:     }
 9338:     return ();
 9339: }
 9340: 
 9341: # -------------------------------------------------------- Value of a Condition
 9342: 
 9343: # gets the value of a specific preevaluated condition
 9344: #    stored in the string  $env{user.state.<cid>}
 9345: # or looks up a condition reference in the bighash and if if hasn't
 9346: # already been evaluated recurses into docondval to get the value of
 9347: # the condition, then memoizing it to 
 9348: #   $env{user.state.<cid>.<condition>}
 9349: sub directcondval {
 9350:     my $number=shift;
 9351:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9352: 	&Apache::lonuserstate::evalstate();
 9353:     }
 9354:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9355: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9356:     } elsif ($number =~ /^_/) {
 9357: 	my $sub_condition;
 9358: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9359: 		&GDBM_READER(),0640)) {
 9360: 	    $sub_condition=$bighash{'conditions'.$number};
 9361: 	    untie(%bighash);
 9362: 	}
 9363: 	my $value = &docondval($sub_condition);
 9364: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9365: 	return $value;
 9366:     }
 9367:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9368:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9369:     } else {
 9370:        return 2;
 9371:     }
 9372: }
 9373: 
 9374: # get the collection of conditions for this resource
 9375: sub condval {
 9376:     my $condidx=shift;
 9377:     my $allpathcond='';
 9378:     foreach my $cond (split(/\|/,$condidx)) {
 9379: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9380: 	    $allpathcond.=
 9381: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9382: 	}
 9383:     }
 9384:     $allpathcond=~s/\|$//;
 9385:     return &docondval($allpathcond);
 9386: }
 9387: 
 9388: #evaluates an expression of conditions
 9389: sub docondval {
 9390:     my ($allpathcond) = @_;
 9391:     my $result=0;
 9392:     if ($env{'request.course.id'}
 9393: 	&& defined($allpathcond)) {
 9394: 	my $operand='|';
 9395: 	my @stack;
 9396: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9397: 	    if ($chunk eq '(') {
 9398: 		push @stack,($operand,$result);
 9399: 	    } elsif ($chunk eq ')') {
 9400: 		my $before=pop @stack;
 9401: 		if (pop @stack eq '&') {
 9402: 		    $result=$result>$before?$before:$result;
 9403: 		} else {
 9404: 		    $result=$result>$before?$result:$before;
 9405: 		}
 9406: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9407: 		$operand=$chunk;
 9408: 	    } else {
 9409: 		my $new=directcondval($chunk);
 9410: 		if ($operand eq '&') {
 9411: 		    $result=$result>$new?$new:$result;
 9412: 		} else {
 9413: 		    $result=$result>$new?$result:$new;
 9414: 		}
 9415: 	    }
 9416: 	}
 9417:     }
 9418:     return $result;
 9419: }
 9420: 
 9421: # ---------------------------------------------------- Devalidate courseresdata
 9422: 
 9423: sub devalidatecourseresdata {
 9424:     my ($coursenum,$coursedomain)=@_;
 9425:     my $hashid=$coursenum.':'.$coursedomain;
 9426:     &devalidate_cache_new('courseres',$hashid);
 9427: }
 9428: 
 9429: 
 9430: # --------------------------------------------------- Course Resourcedata Query
 9431: #
 9432: #  Parameters:
 9433: #      $coursenum    - Number of the course.
 9434: #      $coursedomain - Domain at which the course was created.
 9435: #  Returns:
 9436: #     A hash of the course parameters along (I think) with timestamps
 9437: #     and version info.
 9438: 
 9439: sub get_courseresdata {
 9440:     my ($coursenum,$coursedomain)=@_;
 9441:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9442:     my $hashid=$coursenum.':'.$coursedomain;
 9443:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9444:     my %dumpreply;
 9445:     unless (defined($cached)) {
 9446: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9447: 	$result=\%dumpreply;
 9448: 	my ($tmp) = keys(%dumpreply);
 9449: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9450: 	    &do_cache_new('courseres',$hashid,$result,600);
 9451: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9452: 	    return $tmp;
 9453: 	} elsif ($tmp =~ /^(error)/) {
 9454: 	    $result=undef;
 9455: 	    &do_cache_new('courseres',$hashid,$result,600);
 9456: 	}
 9457:     }
 9458:     return $result;
 9459: }
 9460: 
 9461: sub devalidateuserresdata {
 9462:     my ($uname,$udom)=@_;
 9463:     my $hashid="$udom:$uname";
 9464:     &devalidate_cache_new('userres',$hashid);
 9465: }
 9466: 
 9467: sub get_userresdata {
 9468:     my ($uname,$udom)=@_;
 9469:     #most student don\'t have any data set, check if there is some data
 9470:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9471: 
 9472:     my $hashid="$udom:$uname";
 9473:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9474:     if (!defined($cached)) {
 9475: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9476: 	$result=\%resourcedata;
 9477: 	&do_cache_new('userres',$hashid,$result,600);
 9478:     }
 9479:     my ($tmp)=keys(%$result);
 9480:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9481: 	return $result;
 9482:     }
 9483:     #error 2 occurs when the .db doesn't exist
 9484:     if ($tmp!~/error: 2 /) {
 9485: 	&logthis("<font color=\"blue\">WARNING:".
 9486: 		 " Trying to get resource data for ".
 9487: 		 $uname." at ".$udom.": ".
 9488: 		 $tmp."</font>");
 9489:     } elsif ($tmp=~/error: 2 /) {
 9490: 	#&EXT_cache_set($udom,$uname);
 9491: 	&do_cache_new('userres',$hashid,undef,600);
 9492: 	undef($tmp); # not really an error so don't send it back
 9493:     }
 9494:     return $tmp;
 9495: }
 9496: #----------------------------------------------- resdata - return resource data
 9497: #  Purpose:
 9498: #    Return resource data for either users or for a course.
 9499: #  Parameters:
 9500: #     $name      - Course/user name.
 9501: #     $domain    - Name of the domain the user/course is registered on.
 9502: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9503: #     @which     - Array of names of resources desired.
 9504: #  Returns:
 9505: #     The value of the first reasource in @which that is found in the
 9506: #     resource hash.
 9507: #  Exceptional Conditions:
 9508: #     If the $type passed in is not valid (not the string 'course' or 
 9509: #     'user', an undefined  reference is returned.
 9510: #     If none of the resources are found, an undef is returned
 9511: sub resdata {
 9512:     my ($name,$domain,$type,@which)=@_;
 9513:     my $result;
 9514:     if ($type eq 'course') {
 9515: 	$result=&get_courseresdata($name,$domain);
 9516:     } elsif ($type eq 'user') {
 9517: 	$result=&get_userresdata($name,$domain);
 9518:     }
 9519:     if (!ref($result)) { return $result; }    
 9520:     foreach my $item (@which) {
 9521: 	if (defined($result->{$item->[0]})) {
 9522: 	    return [$result->{$item->[0]},$item->[1]];
 9523: 	}
 9524:     }
 9525:     return undef;
 9526: }
 9527: 
 9528: #
 9529: # EXT resource caching routines
 9530: #
 9531: 
 9532: sub clear_EXT_cache_status {
 9533:     &delenv('cache.EXT.');
 9534: }
 9535: 
 9536: sub EXT_cache_status {
 9537:     my ($target_domain,$target_user) = @_;
 9538:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9539:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9540:         # We know already the user has no data
 9541:         return 1;
 9542:     } else {
 9543:         return 0;
 9544:     }
 9545: }
 9546: 
 9547: sub EXT_cache_set {
 9548:     my ($target_domain,$target_user) = @_;
 9549:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9550:     #&appenv({$cachename => time});
 9551: }
 9552: 
 9553: # --------------------------------------------------------- Value of a Variable
 9554: sub EXT {
 9555: 
 9556:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 9557:     unless ($varname) { return ''; }
 9558:     #get real user name/domain, courseid and symb
 9559:     my $courseid;
 9560:     my $publicuser;
 9561:     if ($symbparm) {
 9562: 	$symbparm=&get_symb_from_alias($symbparm);
 9563:     }
 9564:     if (!($uname && $udom)) {
 9565:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9566:       if (!$symbparm) {	$symbparm=$cursymb; }
 9567:     } else {
 9568: 	$courseid=$env{'request.course.id'};
 9569:     }
 9570:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9571:     my $rest;
 9572:     if (defined($therest[0])) {
 9573:        $rest=join('.',@therest);
 9574:     } else {
 9575:        $rest='';
 9576:     }
 9577: 
 9578:     my $qualifierrest=$qualifier;
 9579:     if ($rest) { $qualifierrest.='.'.$rest; }
 9580:     my $spacequalifierrest=$space;
 9581:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9582:     if ($realm eq 'user') {
 9583: # --------------------------------------------------------------- user.resource
 9584: 	if ($space eq 'resource') {
 9585: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9586: 		  || defined($Apache::lonhomework::parsing_a_task))
 9587: 		 &&
 9588: 		 ($symbparm eq &symbread()) ) {	
 9589: 		# if we are in the middle of processing the resource the
 9590: 		# get the value we are planning on committing
 9591:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9592:                     return $Apache::lonhomework::results{$qualifierrest};
 9593:                 } else {
 9594:                     return $Apache::lonhomework::history{$qualifierrest};
 9595:                 }
 9596: 	    } else {
 9597: 		my %restored;
 9598: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9599: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9600: 		} else {
 9601: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9602: 		}
 9603: 		return $restored{$qualifierrest};
 9604: 	    }
 9605: # ----------------------------------------------------------------- user.access
 9606:         } elsif ($space eq 'access') {
 9607: 	    # FIXME - not supporting calls for a specific user
 9608:             return &allowed($qualifier,$rest);
 9609: # ------------------------------------------ user.preferences, user.environment
 9610:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9611: 	    if (($uname eq $env{'user.name'}) &&
 9612: 		($udom eq $env{'user.domain'})) {
 9613: 		return $env{join('.',('environment',$qualifierrest))};
 9614: 	    } else {
 9615: 		my %returnhash;
 9616: 		if (!$publicuser) {
 9617: 		    %returnhash=&userenvironment($udom,$uname,
 9618: 						 $qualifierrest);
 9619: 		}
 9620: 		return $returnhash{$qualifierrest};
 9621: 	    }
 9622: # ----------------------------------------------------------------- user.course
 9623:         } elsif ($space eq 'course') {
 9624: 	    # FIXME - not supporting calls for a specific user
 9625:             return $env{join('.',('request.course',$qualifier))};
 9626: # ------------------------------------------------------------------- user.role
 9627:         } elsif ($space eq 'role') {
 9628: 	    # FIXME - not supporting calls for a specific user
 9629:             my ($role,$where)=split(/\./,$env{'request.role'});
 9630:             if ($qualifier eq 'value') {
 9631: 		return $role;
 9632:             } elsif ($qualifier eq 'extent') {
 9633:                 return $where;
 9634:             }
 9635: # ----------------------------------------------------------------- user.domain
 9636:         } elsif ($space eq 'domain') {
 9637:             return $udom;
 9638: # ------------------------------------------------------------------- user.name
 9639:         } elsif ($space eq 'name') {
 9640:             return $uname;
 9641: # ---------------------------------------------------- Any other user namespace
 9642:         } else {
 9643: 	    my %reply;
 9644: 	    if (!$publicuser) {
 9645: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9646: 	    }
 9647: 	    return $reply{$qualifierrest};
 9648:         }
 9649:     } elsif ($realm eq 'query') {
 9650: # ---------------------------------------------- pull stuff out of query string
 9651:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9652: 						[$spacequalifierrest]);
 9653: 	return $env{'form.'.$spacequalifierrest}; 
 9654:    } elsif ($realm eq 'request') {
 9655: # ------------------------------------------------------------- request.browser
 9656:         if ($space eq 'browser') {
 9657:             return $env{'browser.'.$qualifier};
 9658: # ------------------------------------------------------------ request.filename
 9659:         } else {
 9660:             return $env{'request.'.$spacequalifierrest};
 9661:         }
 9662:     } elsif ($realm eq 'course') {
 9663: # ---------------------------------------------------------- course.description
 9664:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9665:     } elsif ($realm eq 'resource') {
 9666: 
 9667: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9668: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9669: 	}
 9670: 
 9671: 	if ($space eq 'title') {
 9672: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9673: 	    return &gettitle($symbparm);
 9674: 	}
 9675: 	
 9676: 	if ($space eq 'map') {
 9677: 	    my ($map) = &decode_symb($symbparm);
 9678: 	    return &symbread($map);
 9679: 	}
 9680: 	if ($space eq 'filename') {
 9681: 	    if ($symbparm) {
 9682: 		return &clutter((&decode_symb($symbparm))[2]);
 9683: 	    }
 9684: 	    return &hreflocation('',$env{'request.filename'});
 9685: 	}
 9686: 
 9687: 	my ($section, $group, @groups);
 9688: 	my ($courselevelm,$courselevel);
 9689: 	if ($symbparm && defined($courseid) && 
 9690: 	    $courseid eq $env{'request.course.id'}) {
 9691: 
 9692: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9693: 
 9694: # ----------------------------------------------------- Cascading lookup scheme
 9695: 	    my $symbp=$symbparm;
 9696: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9697: 
 9698: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9699: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9700: 
 9701: 	    if (($env{'user.name'} eq $uname) &&
 9702: 		($env{'user.domain'} eq $udom)) {
 9703: 		$section=$env{'request.course.sec'};
 9704:                 @groups = split(/:/,$env{'request.course.groups'});  
 9705:                 @groups=&sort_course_groups($courseid,@groups); 
 9706: 	    } else {
 9707: 		if (! defined($usection)) {
 9708: 		    $section=&getsection($udom,$uname,$courseid);
 9709: 		} else {
 9710: 		    $section = $usection;
 9711: 		}
 9712:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9713: 	    }
 9714: 
 9715: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9716: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9717: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9718: 
 9719: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9720: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9721: 	    $courselevelm=$courseid.'.'.$mapparm;
 9722: 
 9723: # ----------------------------------------------------------- first, check user
 9724: 
 9725: 	    my $userreply=&resdata($uname,$udom,'user',
 9726: 				       ([$courselevelr,'resource'],
 9727: 					[$courselevelm,'map'     ],
 9728: 					[$courselevel, 'course'  ]));
 9729: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9730: 
 9731: # ------------------------------------------------ second, check some of course
 9732:             my $coursereply;
 9733:             if (@groups > 0) {
 9734:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9735:                                        $mapparm,$spacequalifierrest);
 9736:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9737:             }
 9738: 
 9739: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9740: 				  $env{'course.'.$courseid.'.domain'},
 9741: 				  'course',
 9742: 				  ([$seclevelr,   'resource'],
 9743: 				   [$seclevelm,   'map'     ],
 9744: 				   [$seclevel,    'course'  ],
 9745: 				   [$courselevelr,'resource']));
 9746: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9747: 
 9748: # ------------------------------------------------------ third, check map parms
 9749: 	    my %parmhash=();
 9750: 	    my $thisparm='';
 9751: 	    if (tie(%parmhash,'GDBM_File',
 9752: 		    $env{'request.course.fn'}.'_parms.db',
 9753: 		    &GDBM_READER(),0640)) {
 9754: 		$thisparm=$parmhash{$symbparm};
 9755: 		untie(%parmhash);
 9756: 	    }
 9757: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9758: 	}
 9759: # ------------------------------------------ fourth, look in resource metadata
 9760: 
 9761: 	$spacequalifierrest=~s/\./\_/;
 9762: 	my $filename;
 9763: 	if (!$symbparm) { $symbparm=&symbread(); }
 9764: 	if ($symbparm) {
 9765: 	    $filename=(&decode_symb($symbparm))[2];
 9766: 	} else {
 9767: 	    $filename=$env{'request.filename'};
 9768: 	}
 9769: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9770: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9771: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9772: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9773: 
 9774: # ---------------------------------------------- fourth, look in rest of course
 9775: 	if ($symbparm && defined($courseid) && 
 9776: 	    $courseid eq $env{'request.course.id'}) {
 9777: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9778: 				     $env{'course.'.$courseid.'.domain'},
 9779: 				     'course',
 9780: 				     ([$courselevelm,'map'   ],
 9781: 				      [$courselevel, 'course']));
 9782: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9783: 	}
 9784: # ------------------------------------------------------------------ Cascade up
 9785: 	unless ($space eq '0') {
 9786: 	    my @parts=split(/_/,$space);
 9787: 	    my $id=pop(@parts);
 9788: 	    my $part=join('_',@parts);
 9789: 	    if ($part eq '') { $part='0'; }
 9790: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9791: 				 $symbparm,$udom,$uname,$section,1);
 9792: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9793: 	}
 9794: 	if ($recurse) { return undef; }
 9795: 	my $pack_def=&packages_tab_default($filename,$varname);
 9796: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9797: # ---------------------------------------------------- Any other user namespace
 9798:     } elsif ($realm eq 'environment') {
 9799: # ----------------------------------------------------------------- environment
 9800: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9801: 	    return $env{'environment.'.$spacequalifierrest};
 9802: 	} else {
 9803: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9804: 		return '';
 9805: 	    }
 9806: 	    my %returnhash=&userenvironment($udom,$uname,
 9807: 					    $spacequalifierrest);
 9808: 	    return $returnhash{$spacequalifierrest};
 9809: 	}
 9810:     } elsif ($realm eq 'system') {
 9811: # ----------------------------------------------------------------- system.time
 9812: 	if ($space eq 'time') {
 9813: 	    return time;
 9814:         }
 9815:     } elsif ($realm eq 'server') {
 9816: # ----------------------------------------------------------------- system.time
 9817: 	if ($space eq 'name') {
 9818: 	    return $ENV{'SERVER_NAME'};
 9819:         }
 9820:     }
 9821:     return '';
 9822: }
 9823: 
 9824: sub get_reply {
 9825:     my ($reply_value) = @_;
 9826:     if (ref($reply_value) eq 'ARRAY') {
 9827:         if (wantarray) {
 9828: 	    return @$reply_value;
 9829:         }
 9830:         return $reply_value->[0];
 9831:     } else {
 9832:         return $reply_value;
 9833:     }
 9834: }
 9835: 
 9836: sub check_group_parms {
 9837:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9838:     my @groupitems = ();
 9839:     my $resultitem;
 9840:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9841:     foreach my $group (@{$groups}) {
 9842:         foreach my $level (@levels) {
 9843:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9844:              push(@groupitems,[$item,$level->[1]]);
 9845:         }
 9846:     }
 9847:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9848:                             $env{'course.'.$courseid.'.domain'},
 9849:                                      'course',@groupitems);
 9850:     return $coursereply;
 9851: }
 9852: 
 9853: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9854:     my ($courseid,@groups) = @_;
 9855:     @groups = sort(@groups);
 9856:     return @groups;
 9857: }
 9858: 
 9859: sub packages_tab_default {
 9860:     my ($uri,$varname)=@_;
 9861:     my (undef,$part,$name)=split(/\./,$varname);
 9862: 
 9863:     my (@extension,@specifics,$do_default);
 9864:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9865: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9866: 	if ($pack_type eq 'default') {
 9867: 	    $do_default=1;
 9868: 	} elsif ($pack_type eq 'extension') {
 9869: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9870: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9871: 	    # only look at packages defaults for packages that this id is
 9872: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9873: 	}
 9874:     }
 9875:     # first look for a package that matches the requested part id
 9876:     foreach my $package (@specifics) {
 9877: 	my (undef,$pack_type,$pack_part)=@{$package};
 9878: 	next if ($pack_part ne $part);
 9879: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9880: 	    return $packagetab{"$pack_type&$name&default"};
 9881: 	}
 9882:     }
 9883:     # look for any possible matching non extension_ package
 9884:     foreach my $package (@specifics) {
 9885: 	my (undef,$pack_type,$pack_part)=@{$package};
 9886: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9887: 	    return $packagetab{"$pack_type&$name&default"};
 9888: 	}
 9889: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9890: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9891: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9892: 	}
 9893:     }
 9894:     # look for any posible extension_ match
 9895:     foreach my $package (@extension) {
 9896: 	my ($package,$pack_type)=@{$package};
 9897: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9898: 	    return $packagetab{"$pack_type&$name&default"};
 9899: 	}
 9900: 	if (defined($packagetab{$package."&$name&default"})) {
 9901: 	    return $packagetab{$package."&$name&default"};
 9902: 	}
 9903:     }
 9904:     # look for a global default setting
 9905:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9906: 	return $packagetab{"default&$name&default"};
 9907:     }
 9908:     return undef;
 9909: }
 9910: 
 9911: sub add_prefix_and_part {
 9912:     my ($prefix,$part)=@_;
 9913:     my $keyroot;
 9914:     if (defined($prefix) && $prefix !~ /^__/) {
 9915: 	# prefix that has a part already
 9916: 	$keyroot=$prefix;
 9917:     } elsif (defined($prefix)) {
 9918: 	# prefix that is missing a part
 9919: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9920:     } else {
 9921: 	# no prefix at all
 9922: 	if (defined($part)) { $keyroot='_'.$part; }
 9923:     }
 9924:     return $keyroot;
 9925: }
 9926: 
 9927: # ---------------------------------------------------------------- Get metadata
 9928: 
 9929: my %metaentry;
 9930: my %importedpartids;
 9931: sub metadata {
 9932:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9933:     $uri=&declutter($uri);
 9934:     # if it is a non metadata possible uri return quickly
 9935:     if (($uri eq '') || 
 9936: 	(($uri =~ m|^/*adm/|) && 
 9937: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9938:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9939: 	return undef;
 9940:     }
 9941:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9942: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9943: 	return undef;
 9944:     }
 9945:     my $filename=$uri;
 9946:     $uri=~s/\.meta$//;
 9947: #
 9948: # Is the metadata already cached?
 9949: # Look at timestamp of caching
 9950: # Everything is cached by the main uri, libraries are never directly cached
 9951: #
 9952:     if (!defined($liburi)) {
 9953: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9954: 	if (defined($cached)) { return $result->{':'.$what}; }
 9955:     }
 9956:     {
 9957: # Imported parts would go here
 9958:         my %importedids=();
 9959:         my @origfileimportpartids=();
 9960:         my $importedparts=0;
 9961: #
 9962: # Is this a recursive call for a library?
 9963: #
 9964: #	if (! exists($metacache{$uri})) {
 9965: #	    $metacache{$uri}={};
 9966: #	}
 9967: 	my $cachetime = 60*60;
 9968:         if ($liburi) {
 9969: 	    $liburi=&declutter($liburi);
 9970:             $filename=$liburi;
 9971:         } else {
 9972: 	    &devalidate_cache_new('meta',$uri);
 9973: 	    undef(%metaentry);
 9974: 	}
 9975:         my %metathesekeys=();
 9976:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9977: 	my $metastring;
 9978: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9979: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9980: 	    $metastring = 
 9981: 		&Apache::lonnet::ssi_body($which,
 9982: 					  ('grade_target' => 'meta'));
 9983: 	    $cachetime = 1; # only want this cached in the child not long term
 9984: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9985:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9986: 	    my $file=&filelocation('',&clutter($filename));
 9987: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9988: 	    $metastring=&getfile($file);
 9989: 	}
 9990:         my $parser=HTML::LCParser->new(\$metastring);
 9991:         my $token;
 9992:         undef %metathesekeys;
 9993:         while ($token=$parser->get_token) {
 9994: 	    if ($token->[0] eq 'S') {
 9995: 		if (defined($token->[2]->{'package'})) {
 9996: #
 9997: # This is a package - get package info
 9998: #
 9999: 		    my $package=$token->[2]->{'package'};
10000: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10001: 		    if (defined($token->[2]->{'id'})) { 
10002: 			$keyroot.='_'.$token->[2]->{'id'}; 
10003: 		    }
10004: 		    if ($metaentry{':packages'}) {
10005: 			$metaentry{':packages'}.=','.$package.$keyroot;
10006: 		    } else {
10007: 			$metaentry{':packages'}=$package.$keyroot;
10008: 		    }
10009: 		    foreach my $pack_entry (keys(%packagetab)) {
10010: 			my $part=$keyroot;
10011: 			$part=~s/^\_//;
10012: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10013: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10014: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10015: 			    # ignore package.tab specified default values
10016:                             # here &package_tab_default() will fetch those
10017: 			    if ($subp eq 'default') { next; }
10018: 			    my $value=$packagetab{$pack_entry};
10019: 			    my $unikey;
10020: 			    if ($pack =~ /_0$/) {
10021: 				$unikey='parameter_0_'.$name;
10022: 				$part=0;
10023: 			    } else {
10024: 				$unikey='parameter'.$keyroot.'_'.$name;
10025: 			    }
10026: 			    if ($subp eq 'display') {
10027: 				$value.=' [Part: '.$part.']';
10028: 			    }
10029: 			    $metaentry{':'.$unikey.'.part'}=$part;
10030: 			    $metathesekeys{$unikey}=1;
10031: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10032: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10033: 			    }
10034: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10035: 				$metaentry{':'.$unikey}=
10036: 				    $metaentry{':'.$unikey.'.default'};
10037: 			    }
10038: 			}
10039: 		    }
10040: 		} else {
10041: #
10042: # This is not a package - some other kind of start tag
10043: #
10044: 		    my $entry=$token->[1];
10045: 		    my $unikey='';
10046: 
10047: 		    if ($entry eq 'import') {
10048: #
10049: # Importing a library here
10050: #
10051:                         my $location=$parser->get_text('/import');
10052:                         my $dir=$filename;
10053:                         $dir=~s|[^/]*$||;
10054:                         $location=&filelocation($dir,$location);
10055:                        
10056:                         my $importmode=$token->[2]->{'importmode'};
10057:                         if ($importmode eq 'problem') {
10058: # Import as problem/response
10059:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10060:                         } elsif ($importmode eq 'part') {
10061: # Import as part(s)
10062:                            $importedparts=1;
10063: # We need to get the original file and the imported file to get the part order correct
10064: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10065: # Load and inspect original file
10066:                            if ($#origfileimportpartids<0) {
10067:                               undef(%importedpartids);
10068:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10069:                               my $origfile=&getfile($origfilelocation);
10070:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10071:                            }
10072: 
10073: # Load and inspect imported file
10074:                            my $impfile=&getfile($location);
10075:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10076:                            if ($#impfilepartids>=0) {
10077: # This problem had parts
10078:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10079:                            } else {
10080: # Importing by turning a single problem into a problem part
10081: # It gets the import-tags ID as part-ID
10082:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10083:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10084:                            }
10085:                         } else {
10086: # Normal import
10087:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10088:                            if (defined($token->[2]->{'id'})) {
10089:                               $unikey.='_'.$token->[2]->{'id'};
10090:                            }
10091:                         }
10092: 
10093: 			if ($depthcount<20) {
10094: 			    my $metadata = 
10095: 				&metadata($uri,'keys', $location,$unikey,
10096: 					  $depthcount+1);
10097: 			    foreach my $meta (split(',',$metadata)) {
10098: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10099: 				$metathesekeys{$meta}=1;
10100: 			    }
10101: 			
10102:                         }
10103: 		    } else {
10104: #
10105: # Not importing, some other kind of non-package, non-library start tag
10106: # 
10107:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10108:                         if (defined($token->[2]->{'id'})) {
10109:                             $unikey.='_'.$token->[2]->{'id'};
10110:                         }
10111: 			if (defined($token->[2]->{'name'})) { 
10112: 			    $unikey.='_'.$token->[2]->{'name'}; 
10113: 			}
10114: 			$metathesekeys{$unikey}=1;
10115: 			foreach my $param (@{$token->[3]}) {
10116: 			    $metaentry{':'.$unikey.'.'.$param} =
10117: 				$token->[2]->{$param};
10118: 			}
10119: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10120: 			my $default=$metaentry{':'.$unikey.'.default'};
10121: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10122: 		 # only ws inside the tag, and not in default, so use default
10123: 		 # as value
10124: 			    $metaentry{':'.$unikey}=$default;
10125: 			} elsif ( $internaltext =~ /\S/ ) {
10126: 		  # something interesting inside the tag
10127: 			    $metaentry{':'.$unikey}=$internaltext;
10128: 			} else {
10129: 		  # no interesting values, don't set a default
10130: 			}
10131: # end of not-a-package not-a-library import
10132: 		    }
10133: # end of not-a-package start tag
10134: 		}
10135: # the next is the end of "start tag"
10136: 	    }
10137: 	}
10138: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10139: 	$extension = lc($extension);
10140: 	if ($extension eq 'htm') { $extension='html'; }
10141: 
10142: 	foreach my $key (keys(%packagetab)) {
10143: 	    #no specific packages #how's our extension
10144: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10145: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10146: 					 \%metathesekeys);
10147: 	}
10148: 
10149: 	if (!exists($metaentry{':packages'})
10150: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10151: 	    foreach my $key (keys(%packagetab)) {
10152: 		#no specific packages well let's get default then
10153: 		if ($key!~/^default&/) { next; }
10154: 		&metadata_create_package_def($uri,$key,'default',
10155: 					     \%metathesekeys);
10156: 	    }
10157: 	}
10158: # are there custom rights to evaluate
10159: 	if ($metaentry{':copyright'} eq 'custom') {
10160: 
10161:     #
10162:     # Importing a rights file here
10163:     #
10164: 	    unless ($depthcount) {
10165: 		my $location=$metaentry{':customdistributionfile'};
10166: 		my $dir=$filename;
10167: 		$dir=~s|[^/]*$||;
10168: 		$location=&filelocation($dir,$location);
10169: 		my $rights_metadata =
10170: 		    &metadata($uri,'keys',$location,'_rights',
10171: 			      $depthcount+1);
10172: 		foreach my $rights (split(',',$rights_metadata)) {
10173: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10174: 		    $metathesekeys{$rights}=1;
10175: 		}
10176: 	    }
10177: 	}
10178: 	# uniqifiy package listing
10179: 	my %seen;
10180: 	my @uniq_packages =
10181: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10182: 	$metaentry{':packages'} = join(',',@uniq_packages);
10183: 
10184:         if ($importedparts) {
10185: # We had imported parts and need to rebuild partorder
10186:            $metaentry{':partorder'}='';
10187:            $metathesekeys{'partorder'}=1;
10188:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10189:                if ($origfileimportpartids[$index] eq 'part') {
10190: # original part, part of the problem
10191:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10192:                } else {
10193: # we have imported parts at this position
10194:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10195:                }
10196:            }
10197:            $metaentry{':partorder'}=~s/^\,//;
10198:         }
10199: 
10200: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10201: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10202: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10203: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10204: # this is the end of "was not already recently cached
10205:     }
10206:     return $metaentry{':'.$what};
10207: }
10208: 
10209: sub metadata_create_package_def {
10210:     my ($uri,$key,$package,$metathesekeys)=@_;
10211:     my ($pack,$name,$subp)=split(/\&/,$key);
10212:     if ($subp eq 'default') { next; }
10213:     
10214:     if (defined($metaentry{':packages'})) {
10215: 	$metaentry{':packages'}.=','.$package;
10216:     } else {
10217: 	$metaentry{':packages'}=$package;
10218:     }
10219:     my $value=$packagetab{$key};
10220:     my $unikey;
10221:     $unikey='parameter_0_'.$name;
10222:     $metaentry{':'.$unikey.'.part'}=0;
10223:     $$metathesekeys{$unikey}=1;
10224:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10225: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10226:     }
10227:     if (defined($metaentry{':'.$unikey.'.default'})) {
10228: 	$metaentry{':'.$unikey}=
10229: 	    $metaentry{':'.$unikey.'.default'};
10230:     }
10231: }
10232: 
10233: sub metadata_generate_part0 {
10234:     my ($metadata,$metacache,$uri) = @_;
10235:     my %allnames;
10236:     foreach my $metakey (keys(%$metadata)) {
10237: 	if ($metakey=~/^parameter\_(.*)/) {
10238: 	  my $part=$$metacache{':'.$metakey.'.part'};
10239: 	  my $name=$$metacache{':'.$metakey.'.name'};
10240: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10241: 	    $allnames{$name}=$part;
10242: 	  }
10243: 	}
10244:     }
10245:     foreach my $name (keys(%allnames)) {
10246:       $$metadata{"parameter_0_$name"}=1;
10247:       my $key=":parameter_0_$name";
10248:       $$metacache{"$key.part"}='0';
10249:       $$metacache{"$key.name"}=$name;
10250:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10251: 					   $allnames{$name}.'_'.$name.
10252: 					   '.type'};
10253:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10254: 			     '.display'};
10255:       my $expr='[Part: '.$allnames{$name}.']';
10256:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10257:       $$metacache{"$key.display"}=$olddis;
10258:     }
10259: }
10260: 
10261: # ------------------------------------------------------ Devalidate title cache
10262: 
10263: sub devalidate_title_cache {
10264:     my ($url)=@_;
10265:     if (!$env{'request.course.id'}) { return; }
10266:     my $symb=&symbread($url);
10267:     if (!$symb) { return; }
10268:     my $key=$env{'request.course.id'}."\0".$symb;
10269:     &devalidate_cache_new('title',$key);
10270: }
10271: 
10272: # ------------------------------------------------- Get the title of a course
10273: 
10274: sub current_course_title {
10275:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10276: }
10277: # ------------------------------------------------- Get the title of a resource
10278: 
10279: sub gettitle {
10280:     my $urlsymb=shift;
10281:     my $symb=&symbread($urlsymb);
10282:     if ($symb) {
10283: 	my $key=$env{'request.course.id'}."\0".$symb;
10284: 	my ($result,$cached)=&is_cached_new('title',$key);
10285: 	if (defined($cached)) { 
10286: 	    return $result;
10287: 	}
10288: 	my ($map,$resid,$url)=&decode_symb($symb);
10289: 	my $title='';
10290: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10291: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10292: 	} else {
10293: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10294: 		    &GDBM_READER(),0640)) {
10295: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10296: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10297: 		untie(%bighash);
10298: 	    }
10299: 	}
10300: 	$title=~s/\&colon\;/\:/gs;
10301: 	if ($title) {
10302: # Remember both $symb and $title for dynamic metadata
10303:             $accesshash{$symb.'___crstitle'}=$title;
10304:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10305: # Cache this title and then return it
10306: 	    return &do_cache_new('title',$key,$title,600);
10307: 	}
10308: 	$urlsymb=$url;
10309:     }
10310:     my $title=&metadata($urlsymb,'title');
10311:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10312:     return $title;
10313: }
10314: 
10315: sub getdocspath {
10316:     my ($symb) = @_;
10317:     my $path;
10318:     if ($symb) {
10319:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
10320:         if ($resurl=~/\.(sequence|page)$/) {
10321:             $mapurl=$resurl;
10322:         } elsif ($resurl eq 'adm/navmaps') {
10323:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
10324:         }
10325:         my $mapresobj;
10326:         my $navmap = Apache::lonnavmaps::navmap->new();
10327:         if (ref($navmap)) {
10328:             $mapresobj = $navmap->getResourceByUrl($mapurl);
10329:         }
10330:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
10331:         my $type=$2;
10332:         if (ref($mapresobj)) {
10333:             my $pcslist = $mapresobj->map_hierarchy();
10334:             if ($pcslist ne '') {
10335:                 foreach my $pc (split(/,/,$pcslist)) {
10336:                     next if ($pc <= 1);
10337:                     my $res = $navmap->getByMapPc($pc);
10338:                     if (ref($res)) {
10339:                         my $thisurl = $res->src();
10340:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
10341:                         my $thistitle = $res->title();
10342:                         $path .= '&'.
10343:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
10344:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
10345:                                  ':'.$res->randompick().
10346:                                  ':'.$res->randomout().
10347:                                  ':'.$res->encrypted().
10348:                                  ':'.$res->randomorder().
10349:                                  ':'.$res->is_page();
10350:                     }
10351:                 }
10352:             }
10353:             $path =~ s/^\&//;
10354:             my $maptitle = $mapresobj->title();
10355:             if ($mapurl eq 'default') {
10356:                 $maptitle = 'Main Course Documents';
10357:             }
10358:             $path .= ($path ne '')? '&' : ''.
10359:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10360:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
10361:                     ':'.$mapresobj->randompick().
10362:                     ':'.$mapresobj->randomout().
10363:                     ':'.$mapresobj->encrypted().
10364:                     ':'.$mapresobj->randomorder().
10365:                     ':'.$mapresobj->is_page();
10366:         } else {
10367:             my $maptitle = &gettitle($mapurl);
10368:             my $ispage;
10369:             if ($mapurl =~ /\.page$/) {
10370:                 $ispage = 1;
10371:             }
10372:             if ($mapurl eq 'default') {
10373:                 $maptitle = 'Main Course Documents';
10374:             }
10375:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10376:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
10377:         }
10378:         unless ($mapurl eq 'default') {
10379:             $path = 'default&'.
10380:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
10381:                     ':::::&'.$path;
10382:         }
10383:     }
10384:     return $path;
10385: }
10386: 
10387: sub get_slot {
10388:     my ($which,$cnum,$cdom)=@_;
10389:     if (!$cnum || !$cdom) {
10390: 	(undef,my $courseid)=&whichuser();
10391: 	$cdom=$env{'course.'.$courseid.'.domain'};
10392: 	$cnum=$env{'course.'.$courseid.'.num'};
10393:     }
10394:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10395:     my %slotinfo;
10396:     if (exists($remembered{$key})) {
10397: 	$slotinfo{$which} = $remembered{$key};
10398:     } else {
10399: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10400: 	&Apache::lonhomework::showhash(%slotinfo);
10401: 	my ($tmp)=keys(%slotinfo);
10402: 	if ($tmp=~/^error:/) { return (); }
10403: 	$remembered{$key} = $slotinfo{$which};
10404:     }
10405:     if (ref($slotinfo{$which}) eq 'HASH') {
10406: 	return %{$slotinfo{$which}};
10407:     }
10408:     return $slotinfo{$which};
10409: }
10410: 
10411: sub get_reservable_slots {
10412:     my ($cnum,$cdom,$uname,$udom) = @_;
10413:     my $now = time;
10414:     my $reservable_info;
10415:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10416:     if (exists($remembered{$key})) {
10417:         $reservable_info = $remembered{$key};
10418:     } else {
10419:         my %resv;
10420:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10421:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10422:         $reservable_info = \%resv;
10423:         $remembered{$key} = $reservable_info;
10424:     }
10425:     return $reservable_info;
10426: }
10427: 
10428: sub get_course_slots {
10429:     my ($cnum,$cdom) = @_;
10430:     my $hashid=$cnum.':'.$cdom;
10431:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10432:     if (defined($cached)) {
10433:         if (ref($result) eq 'HASH') {
10434:             return %{$result};
10435:         }
10436:     } else {
10437:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10438:         my ($tmp) = keys(%slots);
10439:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10440:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
10441:             return %slots;
10442:         }
10443:     }
10444:     return;
10445: }
10446: 
10447: sub devalidate_slots_cache {
10448:     my ($cnum,$cdom)=@_;
10449:     my $hashid=$cnum.':'.$cdom;
10450:     &devalidate_cache_new('allslots',$hashid);
10451: }
10452: 
10453: sub get_coursechange {
10454:     my ($cdom,$cnum) = @_;
10455:     if ($cdom eq '' || $cnum eq '') {
10456:         return unless ($env{'request.course.id'});
10457:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10458:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10459:     }
10460:     my $hashid=$cdom.'_'.$cnum;
10461:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10462:     if ((defined($cached)) && ($change ne '')) {
10463:         return $change;
10464:     } else {
10465:         my %crshash;
10466:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10467:         if ($crshash{'internal.contentchange'} eq '') {
10468:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10469:             if ($change eq '') {
10470:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10471:                 $change = $crshash{'internal.created'};
10472:             }
10473:         } else {
10474:             $change = $crshash{'internal.contentchange'};
10475:         }
10476:         my $cachetime = 600;
10477:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10478:     }
10479:     return $change;
10480: }
10481: 
10482: sub devalidate_coursechange_cache {
10483:     my ($cnum,$cdom)=@_;
10484:     my $hashid=$cnum.':'.$cdom;
10485:     &devalidate_cache_new('crschange',$hashid);
10486: }
10487: 
10488: # ------------------------------------------------- Update symbolic store links
10489: 
10490: sub symblist {
10491:     my ($mapname,%newhash)=@_;
10492:     $mapname=&deversion(&declutter($mapname));
10493:     my %hash;
10494:     if (($env{'request.course.fn'}) && (%newhash)) {
10495:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10496:                       &GDBM_WRCREAT(),0640)) {
10497: 	    foreach my $url (keys(%newhash)) {
10498: 		next if ($url eq 'last_known'
10499: 			 && $env{'form.no_update_last_known'});
10500: 		$hash{declutter($url)}=&encode_symb($mapname,
10501: 						    $newhash{$url}->[1],
10502: 						    $newhash{$url}->[0]);
10503:             }
10504:             if (untie(%hash)) {
10505: 		return 'ok';
10506:             }
10507:         }
10508:     }
10509:     return 'error';
10510: }
10511: 
10512: # --------------------------------------------------------------- Verify a symb
10513: 
10514: sub symbverify {
10515:     my ($symb,$thisurl,$encstate)=@_;
10516:     my $thisfn=$thisurl;
10517:     $thisfn=&declutter($thisfn);
10518: # direct jump to resource in page or to a sequence - will construct own symbs
10519:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10520: # check URL part
10521:     my ($map,$resid,$url)=&decode_symb($symb);
10522: 
10523:     unless ($url eq $thisfn) { return 0; }
10524: 
10525:     $symb=&symbclean($symb);
10526:     $thisurl=&deversion($thisurl);
10527:     $thisfn=&deversion($thisfn);
10528: 
10529:     my %bighash;
10530:     my $okay=0;
10531: 
10532:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10533:                             &GDBM_READER(),0640)) {
10534:         my $noclutter;
10535:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10536:             $thisurl =~ s/\?.+$//;
10537:             if ($map =~ m{^uploaded/.+\.page$}) {
10538:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10539:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10540:                 $noclutter = 1;
10541:             }
10542:         }
10543:         my $ids;
10544:         if ($noclutter) {
10545:             $ids=$bighash{'ids_'.$thisurl};
10546:         } else {
10547:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10548:         }
10549:         unless ($ids) {
10550:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10551:             $ids=$bighash{$idkey};
10552:         }
10553:         if ($ids) {
10554: # ------------------------------------------------------------------- Has ID(s)
10555:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10556:                 $symb =~ s/\?.+$//;
10557:             }
10558: 	    foreach my $id (split(/\,/,$ids)) {
10559: 	       my ($mapid,$resid)=split(/\./,$id);
10560:                if (
10561:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10562:    eq $symb) {
10563:                    if (ref($encstate)) {
10564:                        $$encstate = $bighash{'encrypted_'.$id};
10565:                    }
10566: 		   if (($env{'request.role.adv'}) ||
10567: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10568:                        ($thisurl eq '/adm/navmaps')) {
10569: 		       $okay=1;
10570:                        last;
10571: 		   }
10572: 	       }
10573: 	   }
10574:         }
10575: 	untie(%bighash);
10576:     }
10577:     return $okay;
10578: }
10579: 
10580: # --------------------------------------------------------------- Clean-up symb
10581: 
10582: sub symbclean {
10583:     my $symb=shift;
10584:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10585: # remove version from map
10586:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10587: 
10588: # remove version from URL
10589:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10590: 
10591: # remove wrapper
10592: 
10593:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10594:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10595:     return $symb;
10596: }
10597: 
10598: # ---------------------------------------------- Split symb to find map and url
10599: 
10600: sub encode_symb {
10601:     my ($map,$resid,$url)=@_;
10602:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10603: }
10604: 
10605: sub decode_symb {
10606:     my $symb=shift;
10607:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10608:     my ($map,$resid,$url)=split(/___/,$symb);
10609:     return (&fixversion($map),$resid,&fixversion($url));
10610: }
10611: 
10612: sub fixversion {
10613:     my $fn=shift;
10614:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10615:     my %bighash;
10616:     my $uri=&clutter($fn);
10617:     my $key=$env{'request.course.id'}.'_'.$uri;
10618: # is this cached?
10619:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10620:     if (defined($cached)) { return $result; }
10621: # unfortunately not cached, or expired
10622:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10623: 	    &GDBM_READER(),0640)) {
10624:  	if ($bighash{'version_'.$uri}) {
10625:  	    my $version=$bighash{'version_'.$uri};
10626:  	    unless (($version eq 'mostrecent') || 
10627: 		    ($version==&getversion($uri))) {
10628:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10629:  	    }
10630:  	}
10631:  	untie %bighash;
10632:     }
10633:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10634: }
10635: 
10636: sub deversion {
10637:     my $url=shift;
10638:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10639:     return $url;
10640: }
10641: 
10642: # ------------------------------------------------------ Return symb list entry
10643: 
10644: sub symbread {
10645:     my ($thisfn,$donotrecurse)=@_;
10646:     my $cache_str;
10647:     if ($thisfn ne '') {
10648:         $cache_str='request.symbread.cached.'.$thisfn;
10649:         if ($env{$cache_str} ne '') {
10650:             return $env{$cache_str};
10651:         }
10652:     } else {
10653: # no filename provided? try from environment
10654:         if ($env{'request.symb'}) {
10655: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10656: 	}
10657: 	$thisfn=$env{'request.filename'};
10658:     }
10659:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10660: # is that filename actually a symb? Verify, clean, and return
10661:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10662: 	if (&symbverify($thisfn,$1)) {
10663: 	    return $env{$cache_str}=&symbclean($thisfn);
10664: 	}
10665:     }
10666:     $thisfn=declutter($thisfn);
10667:     my %hash;
10668:     my %bighash;
10669:     my $syval='';
10670:     if (($env{'request.course.fn'}) && ($thisfn)) {
10671:         my $targetfn = $thisfn;
10672:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10673:             $targetfn = 'adm/wrapper/'.$thisfn;
10674:         }
10675: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10676: 	    $targetfn=$1;
10677: 	}
10678:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10679:                       &GDBM_READER(),0640)) {
10680: 	    $syval=$hash{$targetfn};
10681:             untie(%hash);
10682:         }
10683: # ---------------------------------------------------------- There was an entry
10684:         if ($syval) {
10685: 	    #unless ($syval=~/\_\d+$/) {
10686: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10687: 		    #&appenv({'request.ambiguous' => $thisfn});
10688: 		    #return $env{$cache_str}='';
10689: 		#}    
10690: 		#$syval.=$1;
10691: 	    #}
10692:         } else {
10693: # ------------------------------------------------------- Was not in symb table
10694:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10695:                             &GDBM_READER(),0640)) {
10696: # ---------------------------------------------- Get ID(s) for current resource
10697:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10698:               unless ($ids) { 
10699:                  $ids=$bighash{'ids_/'.$thisfn};
10700:               }
10701:               unless ($ids) {
10702: # alias?
10703: 		  $ids=$bighash{'mapalias_'.$thisfn};
10704:               }
10705:               if ($ids) {
10706: # ------------------------------------------------------------------- Has ID(s)
10707:                  my @possibilities=split(/\,/,$ids);
10708:                  if ($#possibilities==0) {
10709: # ----------------------------------------------- There is only one possibility
10710: 		     my ($mapid,$resid)=split(/\./,$ids);
10711: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10712: 						    $resid,$thisfn);
10713:                  } elsif (!$donotrecurse) {
10714: # ------------------------------------------ There is more than one possibility
10715:                      my $realpossible=0;
10716:                      foreach my $id (@possibilities) {
10717: 			 my $file=$bighash{'src_'.$id};
10718:                          if (&allowed('bre',$file)) {
10719:          		    my ($mapid,$resid)=split(/\./,$id);
10720:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10721: 				$realpossible++;
10722:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10723: 						    $resid,$thisfn);
10724:                             }
10725: 			 }
10726:                      }
10727: 		     if ($realpossible!=1) { $syval=''; }
10728:                  } else {
10729:                      $syval='';
10730:                  }
10731: 	      }
10732:               untie(%bighash)
10733:            }
10734:         }
10735:         if ($syval) {
10736: 	    return $env{$cache_str}=$syval;
10737:         }
10738:     }
10739:     &appenv({'request.ambiguous' => $thisfn});
10740:     return $env{$cache_str}='';
10741: }
10742: 
10743: # ---------------------------------------------------------- Return random seed
10744: 
10745: sub numval {
10746:     my $txt=shift;
10747:     $txt=~tr/A-J/0-9/;
10748:     $txt=~tr/a-j/0-9/;
10749:     $txt=~tr/K-T/0-9/;
10750:     $txt=~tr/k-t/0-9/;
10751:     $txt=~tr/U-Z/0-5/;
10752:     $txt=~tr/u-z/0-5/;
10753:     $txt=~s/\D//g;
10754:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10755:     return int($txt);
10756: }
10757: 
10758: sub numval2 {
10759:     my $txt=shift;
10760:     $txt=~tr/A-J/0-9/;
10761:     $txt=~tr/a-j/0-9/;
10762:     $txt=~tr/K-T/0-9/;
10763:     $txt=~tr/k-t/0-9/;
10764:     $txt=~tr/U-Z/0-5/;
10765:     $txt=~tr/u-z/0-5/;
10766:     $txt=~s/\D//g;
10767:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10768:     my $total;
10769:     foreach my $val (@txts) { $total+=$val; }
10770:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10771:     return int($total);
10772: }
10773: 
10774: sub numval3 {
10775:     use integer;
10776:     my $txt=shift;
10777:     $txt=~tr/A-J/0-9/;
10778:     $txt=~tr/a-j/0-9/;
10779:     $txt=~tr/K-T/0-9/;
10780:     $txt=~tr/k-t/0-9/;
10781:     $txt=~tr/U-Z/0-5/;
10782:     $txt=~tr/u-z/0-5/;
10783:     $txt=~s/\D//g;
10784:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10785:     my $total;
10786:     foreach my $val (@txts) { $total+=$val; }
10787:     if ($_64bit) { $total=(($total<<32)>>32); }
10788:     return $total;
10789: }
10790: 
10791: sub digest {
10792:     my ($data)=@_;
10793:     my $digest=&Digest::MD5::md5($data);
10794:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10795:     my ($e,$f);
10796:     {
10797:         use integer;
10798:         $e=($a+$b);
10799:         $f=($c+$d);
10800:         if ($_64bit) {
10801:             $e=(($e<<32)>>32);
10802:             $f=(($f<<32)>>32);
10803:         }
10804:     }
10805:     if (wantarray) {
10806: 	return ($e,$f);
10807:     } else {
10808: 	my $g;
10809: 	{
10810: 	    use integer;
10811: 	    $g=($e+$f);
10812: 	    if ($_64bit) {
10813: 		$g=(($g<<32)>>32);
10814: 	    }
10815: 	}
10816: 	return $g;
10817:     }
10818: }
10819: 
10820: sub latest_rnd_algorithm_id {
10821:     return '64bit5';
10822: }
10823: 
10824: sub get_rand_alg {
10825:     my ($courseid)=@_;
10826:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10827:     if ($courseid) {
10828: 	return $env{"course.$courseid.rndseed"};
10829:     }
10830:     return &latest_rnd_algorithm_id();
10831: }
10832: 
10833: sub validCODE {
10834:     my ($CODE)=@_;
10835:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10836:     return 0;
10837: }
10838: 
10839: sub getCODE {
10840:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10841:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10842: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10843: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10844: 	return $Apache::lonhomework::history{'resource.CODE'};
10845:     }
10846:     return undef;
10847: }
10848: #
10849: #  Determines the random seed for a specific context:
10850: #
10851: # parameters:
10852: #   symb      - in course context the symb for the seed.
10853: #   course_id - The course id of the form domain_coursenum.
10854: #   domain    - Domain for the user.
10855: #   course    - Course for the user.
10856: #   cenv      - environment of the course.
10857: #
10858: # NOTE:
10859: #   All parameters are picked out of the environment if missing
10860: #   or not defined.
10861: #   If a symb cannot be determined the current time is used instead.
10862: #
10863: #  For a given well defined symb, courside, domain, username,
10864: #  and course environment, the seed is reproducible.
10865: #
10866: sub rndseed {
10867:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10868:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10869:     if (!defined($symb)) {
10870: 	unless ($symb=$wsymb) { return time; }
10871:     }
10872:     if (!defined $courseid) { 
10873: 	$courseid=$wcourseid; 
10874:     }
10875:     if (!defined $domain) { $domain=$wdomain; }
10876:     if (!defined $username) { $username=$wusername }
10877: 
10878:     my $which;
10879:     if (defined($cenv->{'rndseed'})) {
10880: 	$which = $cenv->{'rndseed'};
10881:     } else {
10882: 	$which =&get_rand_alg($courseid);
10883:     }
10884:     if (defined(&getCODE())) {
10885: 
10886: 	if ($which eq '64bit5') {
10887: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10888: 	} elsif ($which eq '64bit4') {
10889: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10890: 	} else {
10891: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10892: 	}
10893:     } elsif ($which eq '64bit5') {
10894: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10895:     } elsif ($which eq '64bit4') {
10896: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10897:     } elsif ($which eq '64bit3') {
10898: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10899:     } elsif ($which eq '64bit2') {
10900: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10901:     } elsif ($which eq '64bit') {
10902: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10903:     }
10904:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10905: }
10906: 
10907: sub rndseed_32bit {
10908:     my ($symb,$courseid,$domain,$username)=@_;
10909:     {
10910: 	use integer;
10911: 	my $symbchck=unpack("%32C*",$symb) << 27;
10912: 	my $symbseed=numval($symb) << 22;
10913: 	my $namechck=unpack("%32C*",$username) << 17;
10914: 	my $nameseed=numval($username) << 12;
10915: 	my $domainseed=unpack("%32C*",$domain) << 7;
10916: 	my $courseseed=unpack("%32C*",$courseid);
10917: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10918: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10919: 	#&logthis("rndseed :$num:$symb");
10920: 	if ($_64bit) { $num=(($num<<32)>>32); }
10921: 	return $num;
10922:     }
10923: }
10924: 
10925: sub rndseed_64bit {
10926:     my ($symb,$courseid,$domain,$username)=@_;
10927:     {
10928: 	use integer;
10929: 	my $symbchck=unpack("%32S*",$symb) << 21;
10930: 	my $symbseed=numval($symb) << 10;
10931: 	my $namechck=unpack("%32S*",$username);
10932: 	
10933: 	my $nameseed=numval($username) << 21;
10934: 	my $domainseed=unpack("%32S*",$domain) << 10;
10935: 	my $courseseed=unpack("%32S*",$courseid);
10936: 	
10937: 	my $num1=$symbchck+$symbseed+$namechck;
10938: 	my $num2=$nameseed+$domainseed+$courseseed;
10939: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10940: 	#&logthis("rndseed :$num:$symb");
10941: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10942: 	return "$num1,$num2";
10943:     }
10944: }
10945: 
10946: sub rndseed_64bit2 {
10947:     my ($symb,$courseid,$domain,$username)=@_;
10948:     {
10949: 	use integer;
10950: 	# strings need to be an even # of cahracters long, it it is odd the
10951:         # last characters gets thrown away
10952: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10953: 	my $symbseed=numval($symb) << 10;
10954: 	my $namechck=unpack("%32S*",$username.' ');
10955: 	
10956: 	my $nameseed=numval($username) << 21;
10957: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10958: 	my $courseseed=unpack("%32S*",$courseid.' ');
10959: 	
10960: 	my $num1=$symbchck+$symbseed+$namechck;
10961: 	my $num2=$nameseed+$domainseed+$courseseed;
10962: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10963: 	#&logthis("rndseed :$num:$symb");
10964: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10965: 	return "$num1,$num2";
10966:     }
10967: }
10968: 
10969: sub rndseed_64bit3 {
10970:     my ($symb,$courseid,$domain,$username)=@_;
10971:     {
10972: 	use integer;
10973: 	# strings need to be an even # of cahracters long, it it is odd the
10974:         # last characters gets thrown away
10975: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10976: 	my $symbseed=numval2($symb) << 10;
10977: 	my $namechck=unpack("%32S*",$username.' ');
10978: 	
10979: 	my $nameseed=numval2($username) << 21;
10980: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10981: 	my $courseseed=unpack("%32S*",$courseid.' ');
10982: 	
10983: 	my $num1=$symbchck+$symbseed+$namechck;
10984: 	my $num2=$nameseed+$domainseed+$courseseed;
10985: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10986: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10987: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10988: 	
10989: 	return "$num1:$num2";
10990:     }
10991: }
10992: 
10993: sub rndseed_64bit4 {
10994:     my ($symb,$courseid,$domain,$username)=@_;
10995:     {
10996: 	use integer;
10997: 	# strings need to be an even # of cahracters long, it it is odd the
10998:         # last characters gets thrown away
10999: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11000: 	my $symbseed=numval3($symb) << 10;
11001: 	my $namechck=unpack("%32S*",$username.' ');
11002: 	
11003: 	my $nameseed=numval3($username) << 21;
11004: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11005: 	my $courseseed=unpack("%32S*",$courseid.' ');
11006: 	
11007: 	my $num1=$symbchck+$symbseed+$namechck;
11008: 	my $num2=$nameseed+$domainseed+$courseseed;
11009: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11010: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11011: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11012: 	
11013: 	return "$num1:$num2";
11014:     }
11015: }
11016: 
11017: sub rndseed_64bit5 {
11018:     my ($symb,$courseid,$domain,$username)=@_;
11019:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11020:     return "$num1:$num2";
11021: }
11022: 
11023: sub rndseed_CODE_64bit {
11024:     my ($symb,$courseid,$domain,$username)=@_;
11025:     {
11026: 	use integer;
11027: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11028: 	my $symbseed=numval2($symb);
11029: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11030: 	my $CODEseed=numval(&getCODE());
11031: 	my $courseseed=unpack("%32S*",$courseid.' ');
11032: 	my $num1=$symbseed+$CODEchck;
11033: 	my $num2=$CODEseed+$courseseed+$symbchck;
11034: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11035: 	#&logthis("rndseed :$num1:$num2:$symb");
11036: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11037: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11038: 	return "$num1:$num2";
11039:     }
11040: }
11041: 
11042: sub rndseed_CODE_64bit4 {
11043:     my ($symb,$courseid,$domain,$username)=@_;
11044:     {
11045: 	use integer;
11046: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11047: 	my $symbseed=numval3($symb);
11048: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11049: 	my $CODEseed=numval3(&getCODE());
11050: 	my $courseseed=unpack("%32S*",$courseid.' ');
11051: 	my $num1=$symbseed+$CODEchck;
11052: 	my $num2=$CODEseed+$courseseed+$symbchck;
11053: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11054: 	#&logthis("rndseed :$num1:$num2:$symb");
11055: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11056: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11057: 	return "$num1:$num2";
11058:     }
11059: }
11060: 
11061: sub rndseed_CODE_64bit5 {
11062:     my ($symb,$courseid,$domain,$username)=@_;
11063:     my $code = &getCODE();
11064:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11065:     return "$num1:$num2";
11066: }
11067: 
11068: sub setup_random_from_rndseed {
11069:     my ($rndseed)=@_;
11070:     if ($rndseed =~/([,:])/) {
11071: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11072: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11073:     } else {
11074: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11075:     }
11076: }
11077: 
11078: sub latest_receipt_algorithm_id {
11079:     return 'receipt3';
11080: }
11081: 
11082: sub recunique {
11083:     my $fucourseid=shift;
11084:     my $unique;
11085:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11086: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11087: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11088:     } else {
11089: 	$unique=$perlvar{'lonReceipt'};
11090:     }
11091:     return unpack("%32C*",$unique);
11092: }
11093: 
11094: sub recprefix {
11095:     my $fucourseid=shift;
11096:     my $prefix;
11097:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11098: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11099: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11100:     } else {
11101: 	$prefix=$perlvar{'lonHostID'};
11102:     }
11103:     return unpack("%32C*",$prefix);
11104: }
11105: 
11106: sub ireceipt {
11107:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11108: 
11109:     my $return =&recprefix($fucourseid).'-';
11110: 
11111:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11112: 	$env{'request.state'} eq 'construct') {
11113: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11114: 	return $return;
11115:     }
11116: 
11117:     my $cuname=unpack("%32C*",$funame);
11118:     my $cudom=unpack("%32C*",$fudom);
11119:     my $cucourseid=unpack("%32C*",$fucourseid);
11120:     my $cusymb=unpack("%32C*",$fusymb);
11121:     my $cunique=&recunique($fucourseid);
11122:     my $cpart=unpack("%32S*",$part);
11123:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11124: 
11125: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11126: 			       
11127: 	$return.= ($cunique%$cuname+
11128: 		   $cunique%$cudom+
11129: 		   $cusymb%$cuname+
11130: 		   $cusymb%$cudom+
11131: 		   $cucourseid%$cuname+
11132: 		   $cucourseid%$cudom+
11133: 		   $cpart%$cuname+
11134: 		   $cpart%$cudom);
11135:     } else {
11136: 	$return.= ($cunique%$cuname+
11137: 		   $cunique%$cudom+
11138: 		   $cusymb%$cuname+
11139: 		   $cusymb%$cudom+
11140: 		   $cucourseid%$cuname+
11141: 		   $cucourseid%$cudom);
11142:     }
11143:     return $return;
11144: }
11145: 
11146: sub receipt {
11147:     my ($part)=@_;
11148:     my ($symb,$courseid,$domain,$name) = &whichuser();
11149:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11150: }
11151: 
11152: sub whichuser {
11153:     my ($passedsymb)=@_;
11154:     my ($symb,$courseid,$domain,$name,$publicuser);
11155:     if (defined($env{'form.grade_symb'})) {
11156: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11157: 	my $allowed=&allowed('vgr',$tmp_courseid);
11158: 	if (!$allowed &&
11159: 	    exists($env{'request.course.sec'}) &&
11160: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11161: 	    $allowed=&allowed('vgr',$tmp_courseid.
11162: 			      '/'.$env{'request.course.sec'});
11163: 	}
11164: 	if ($allowed) {
11165: 	    ($symb)=&get_env_multiple('form.grade_symb');
11166: 	    $courseid=$tmp_courseid;
11167: 	    ($domain)=&get_env_multiple('form.grade_domain');
11168: 	    ($name)=&get_env_multiple('form.grade_username');
11169: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11170: 	}
11171:     }
11172:     if (!$passedsymb) {
11173: 	$symb=&symbread();
11174:     } else {
11175: 	$symb=$passedsymb;
11176:     }
11177:     $courseid=$env{'request.course.id'};
11178:     $domain=$env{'user.domain'};
11179:     $name=$env{'user.name'};
11180:     if ($name eq 'public' && $domain eq 'public') {
11181: 	if (!defined($env{'form.username'})) {
11182: 	    $env{'form.username'}.=time.rand(10000000);
11183: 	}
11184: 	$name.=$env{'form.username'};
11185:     }
11186:     return ($symb,$courseid,$domain,$name,$publicuser);
11187: 
11188: }
11189: 
11190: # ------------------------------------------------------------ Serves up a file
11191: # returns either the contents of the file or 
11192: # -1 if the file doesn't exist
11193: #
11194: # if the target is a file that was uploaded via DOCS, 
11195: # a check will be made to see if a current copy exists on the local server,
11196: # if it does this will be served, otherwise a copy will be retrieved from
11197: # the home server for the course and stored in /home/httpd/html/userfiles on
11198: # the local server.   
11199: 
11200: sub getfile {
11201:     my ($file) = @_;
11202:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11203:     &repcopy($file);
11204:     return &readfile($file);
11205: }
11206: 
11207: sub repcopy_userfile {
11208:     my ($file)=@_;
11209:     my $londocroot = $perlvar{'lonDocRoot'};
11210:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11211:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11212:     my ($cdom,$cnum,$filename) = 
11213: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11214:     my $uri="/uploaded/$cdom/$cnum/$filename";
11215:     if (-e "$file") {
11216: # we already have a local copy, check it out
11217: 	my @fileinfo = stat($file);
11218: 	my $rtncode;
11219: 	my $info;
11220: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11221: 	if ($lwpresp ne 'ok') {
11222: # there is no such file anymore, even though we had a local copy
11223: 	    if ($rtncode eq '404') {
11224: 		unlink($file);
11225: 	    }
11226: 	    return -1;
11227: 	}
11228: 	if ($info < $fileinfo[9]) {
11229: # nice, the file we have is up-to-date, just say okay
11230: 	    return 'ok';
11231: 	} else {
11232: # the file is outdated, get rid of it
11233: 	    unlink($file);
11234: 	}
11235:     }
11236: # one way or the other, at this point, we don't have the file
11237: # construct the correct path for the file
11238:     my @parts = ($cdom,$cnum); 
11239:     if ($filename =~ m|^(.+)/[^/]+$|) {
11240: 	push @parts, split(/\//,$1);
11241:     }
11242:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11243:     foreach my $part (@parts) {
11244: 	$path .= '/'.$part;
11245: 	if (!-e $path) {
11246: 	    mkdir($path,0770);
11247: 	}
11248:     }
11249: # now the path exists for sure
11250: # get a user agent
11251:     my $ua=new LWP::UserAgent;
11252:     my $transferfile=$file.'.in.transfer';
11253: # FIXME: this should flock
11254:     if (-e $transferfile) { return 'ok'; }
11255:     my $request;
11256:     $uri=~s/^\///;
11257:     my $homeserver = &homeserver($cnum,$cdom);
11258:     my $protocol = $protocol{$homeserver};
11259:     $protocol = 'http' if ($protocol ne 'https');
11260:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11261:     my $response=$ua->request($request,$transferfile);
11262: # did it work?
11263:     if ($response->is_error()) {
11264: 	unlink($transferfile);
11265: 	&logthis("Userfile repcopy failed for $uri");
11266: 	return -1;
11267:     }
11268: # worked, rename the transfer file
11269:     rename($transferfile,$file);
11270:     return 'ok';
11271: }
11272: 
11273: sub tokenwrapper {
11274:     my $uri=shift;
11275:     $uri=~s|^https?\://([^/]+)||;
11276:     $uri=~s|^/||;
11277:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11278:     my $token=$1;
11279:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11280:     if ($udom && $uname && $file) {
11281: 	$file=~s|(\?\.*)*$||;
11282:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11283:         my $homeserver = &homeserver($uname,$udom);
11284:         my $protocol = $protocol{$homeserver};
11285:         $protocol = 'http' if ($protocol ne 'https');
11286:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11287:                (($uri=~/\?/)?'&':'?').'token='.$token.
11288:                                '&tokenissued='.$perlvar{'lonHostID'};
11289:     } else {
11290:         return '/adm/notfound.html';
11291:     }
11292: }
11293: 
11294: # call with reqtype HEAD: get last modification time
11295: # call with reqtype GET: get the file contents
11296: # Do not call this with reqtype GET for large files! It loads everything into memory
11297: #
11298: sub getuploaded {
11299:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11300:     $uri=~s/^\///;
11301:     my $homeserver = &homeserver($cnum,$cdom);
11302:     my $protocol = $protocol{$homeserver};
11303:     $protocol = 'http' if ($protocol ne 'https');
11304:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11305:     my $ua=new LWP::UserAgent;
11306:     my $request=new HTTP::Request($reqtype,$uri);
11307:     my $response=$ua->request($request);
11308:     $$rtncode = $response->code;
11309:     if (! $response->is_success()) {
11310: 	return 'failed';
11311:     }      
11312:     if ($reqtype eq 'HEAD') {
11313: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11314:     } elsif ($reqtype eq 'GET') {
11315: 	$$info = $response->content;
11316:     }
11317:     return 'ok';
11318: }
11319: 
11320: sub readfile {
11321:     my $file = shift;
11322:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11323:     my $fh;
11324:     open($fh,"<$file");
11325:     my $a='';
11326:     while (my $line = <$fh>) { $a .= $line; }
11327:     return $a;
11328: }
11329: 
11330: sub filelocation {
11331:     my ($dir,$file) = @_;
11332:     my $location;
11333:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11334: 
11335:     if ($file =~ m-^/adm/-) {
11336: 	$file=~s-^/adm/wrapper/-/-;
11337: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11338:     }
11339: 
11340:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11341:         $location = $file;
11342:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11343:         my ($udom,$uname,$filename)=
11344:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11345:         my $home=&homeserver($uname,$udom);
11346:         my $is_me=0;
11347:         my @ids=&current_machine_ids();
11348:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11349:         if ($is_me) {
11350:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11351:         } else {
11352:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11353:   	      $udom.'/'.$uname.'/'.$filename;
11354:         }
11355:     } elsif ($file =~ m-^/adm/-) {
11356: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11357:     } else {
11358:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11359:         $file=~s:^/(res|priv)/:/:;
11360:         my $space=$1;
11361:         if ( !( $file =~ m:^/:) ) {
11362:             $location = $dir. '/'.$file;
11363:         } else {
11364:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11365:         }
11366:     }
11367:     $location=~s://+:/:g; # remove duplicate /
11368:     while ($location=~m{/\.\./}) {
11369: 	if ($location =~ m{/[^/]+/\.\./}) {
11370: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11371: 	} else {
11372: 	    $location=~ s{/\.\./}{/}g;
11373: 	}
11374:     } #remove dir/..
11375:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11376:     return $location;
11377: }
11378: 
11379: sub hreflocation {
11380:     my ($dir,$file)=@_;
11381:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11382: 	$file=filelocation($dir,$file);
11383:     } elsif ($file=~m-^/adm/-) {
11384: 	$file=~s-^/adm/wrapper/-/-;
11385: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11386:     }
11387:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11388: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11389:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11390: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11391: 	        {/uploaded/$1/$2/}x;
11392:     }
11393:     if ($file=~ m{^/userfiles/}) {
11394: 	$file =~ s{^/userfiles/}{/uploaded/};
11395:     }
11396:     return $file;
11397: }
11398: 
11399: 
11400: 
11401: 
11402: 
11403: sub current_machine_domains {
11404:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11405: }
11406: 
11407: sub machine_domains {
11408:     my ($hostname) = @_;
11409:     my @domains;
11410:     my %hostname = &all_hostnames();
11411:     while( my($id, $name) = each(%hostname)) {
11412: #	&logthis("-$id-$name-$hostname-");
11413: 	if ($hostname eq $name) {
11414: 	    push(@domains,&host_domain($id));
11415: 	}
11416:     }
11417:     return @domains;
11418: }
11419: 
11420: sub current_machine_ids {
11421:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11422: }
11423: 
11424: sub machine_ids {
11425:     my ($hostname) = @_;
11426:     $hostname ||= &hostname($perlvar{'lonHostID'});
11427:     my @ids;
11428:     my %name_to_host = &all_names();
11429:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11430: 	return @{ $name_to_host{$hostname} };
11431:     }
11432:     return;
11433: }
11434: 
11435: sub additional_machine_domains {
11436:     my @domains;
11437:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11438:     while( my $line = <$fh>) {
11439:         $line =~ s/\s//g;
11440:         push(@domains,$line);
11441:     }
11442:     return @domains;
11443: }
11444: 
11445: sub default_login_domain {
11446:     my $domain = $perlvar{'lonDefDomain'};
11447:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11448:     foreach my $posdom (&current_machine_domains(),
11449:                         &additional_machine_domains()) {
11450:         if (lc($posdom) eq lc($testdomain)) {
11451:             $domain=$posdom;
11452:             last;
11453:         }
11454:     }
11455:     return $domain;
11456: }
11457: 
11458: # ------------------------------------------------------------- Declutters URLs
11459: 
11460: sub declutter {
11461:     my $thisfn=shift;
11462:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11463:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11464:     $thisfn=~s/^\///;
11465:     $thisfn=~s|^adm/wrapper/||;
11466:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11467:     $thisfn=~s/^res\///;
11468:     $thisfn=~s/^priv\///;
11469:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11470:         $thisfn=~s/\?.+$//;
11471:     }
11472:     return $thisfn;
11473: }
11474: 
11475: # ------------------------------------------------------------- Clutter up URLs
11476: 
11477: sub clutter {
11478:     my $thisfn='/'.&declutter(shift);
11479:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11480: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11481:        $thisfn='/res'.$thisfn; 
11482:     }
11483:     if ($thisfn !~m|^/adm|) {
11484: 	if ($thisfn =~ m|^/ext/|) {
11485: 	    $thisfn='/adm/wrapper'.$thisfn;
11486: 	} else {
11487: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11488: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11489: 	    if ($embstyle eq 'ssi'
11490: 		|| ($embstyle eq 'hdn')
11491: 		|| ($embstyle eq 'rat')
11492: 		|| ($embstyle eq 'prv')
11493: 		|| ($embstyle eq 'ign')) {
11494: 		#do nothing with these
11495: 	    } elsif (($embstyle eq 'img') 
11496: 		|| ($embstyle eq 'emb')
11497: 		|| ($embstyle eq 'wrp')) {
11498: 		$thisfn='/adm/wrapper'.$thisfn;
11499: 	    } elsif ($embstyle eq 'unk'
11500: 		     && $thisfn!~/\.(sequence|page)$/) {
11501: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11502: 	    } else {
11503: #		&logthis("Got a blank emb style");
11504: 	    }
11505: 	}
11506:     }
11507:     return $thisfn;
11508: }
11509: 
11510: sub clutter_with_no_wrapper {
11511:     my $uri = &clutter(shift);
11512:     if ($uri =~ m-^/adm/-) {
11513: 	$uri =~ s-^/adm/wrapper/-/-;
11514: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11515:     }
11516:     return $uri;
11517: }
11518: 
11519: sub freeze_escape {
11520:     my ($value)=@_;
11521:     if (ref($value)) {
11522: 	$value=&nfreeze($value);
11523: 	return '__FROZEN__'.&escape($value);
11524:     }
11525:     return &escape($value);
11526: }
11527: 
11528: 
11529: sub thaw_unescape {
11530:     my ($value)=@_;
11531:     if ($value =~ /^__FROZEN__/) {
11532: 	substr($value,0,10,undef);
11533: 	$value=&unescape($value);
11534: 	return &thaw($value);
11535:     }
11536:     return &unescape($value);
11537: }
11538: 
11539: sub correct_line_ends {
11540:     my ($result)=@_;
11541:     $$result =~s/\r\n/\n/mg;
11542:     $$result =~s/\r/\n/mg;
11543: }
11544: # ================================================================ Main Program
11545: 
11546: sub goodbye {
11547:    &logthis("Starting Shut down");
11548: #not converted to using infrastruture and probably shouldn't be
11549:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11550: #converted
11551: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11552:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11553: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11554: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11555: #1.1 only
11556: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11557: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11558: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11559: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11560:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11561:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11562:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11563:    &flushcourselogs();
11564:    &logthis("Shutting down");
11565: }
11566: 
11567: sub get_dns {
11568:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11569:     if (!$ignore_cache) {
11570: 	my ($content,$cached)=
11571: 	    &Apache::lonnet::is_cached_new('dns',$url);
11572: 	if ($cached) {
11573: 	    &$func($content,$hashref);
11574: 	    return;
11575: 	}
11576:     }
11577: 
11578:     my %alldns;
11579:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11580:     foreach my $dns (<$config>) {
11581: 	next if ($dns !~ /^\^(\S*)/x);
11582:         my $line = $1;
11583:         my ($host,$protocol) = split(/:/,$line);
11584:         if ($protocol ne 'https') {
11585:             $protocol = 'http';
11586:         }
11587: 	$alldns{$host} = $protocol;
11588:     }
11589:     while (%alldns) {
11590: 	my ($dns) = keys(%alldns);
11591: 	my $ua=new LWP::UserAgent;
11592:         $ua->timeout(30);
11593: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11594: 	my $response=$ua->request($request);
11595:         delete($alldns{$dns});
11596: 	next if ($response->is_error());
11597: 	my @content = split("\n",$response->content);
11598: 	unless ($nocache) {
11599: 	    &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
11600: 	}
11601: 	&$func(\@content,$hashref);
11602: 	return;
11603:     }
11604:     close($config);
11605:     my $which = (split('/',$url))[3];
11606:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11607:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11608:     my @content = <$config>;
11609:     &$func(\@content,$hashref);
11610:     return;
11611: }
11612: 
11613: # ------------------------------------------------------Get DNS checksums file
11614: sub parse_dns_checksums_tab {
11615:     my ($lines,$hashref) = @_;
11616:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11617:     my $loncaparev = &get_server_loncaparev($machine_dom);
11618:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11619:     my (%chksum,%revnum);
11620:     if (ref($lines) eq 'ARRAY') {
11621:         chomp(@{$lines});
11622:         my $versions = shift(@{$lines});
11623:         my %supported;
11624:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
11625:             my $releaseslist = $1;
11626:             if ($releaseslist =~ /,/) {
11627:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
11628:             } elsif ($releaseslist) {
11629:                 $supported{$releaseslist} = 1;
11630:             }
11631:         }
11632:         if ($supported{$release}) {  
11633:             my $matchthis = 0;
11634:             foreach my $line (@{$lines}) {
11635:                 if ($line =~ /^(\d[\w\.]+)$/) {
11636:                     if ($matchthis) {
11637:                         last;
11638:                     } elsif ($1 eq $release) {
11639:                         $matchthis = 1;
11640:                     }
11641:                 } elsif ($matchthis) {
11642:                     my ($file,$version,$shasum) = split(/,/,$line);
11643:                     $chksum{$file} = $shasum;
11644:                     $revnum{$file} = $version;
11645:                 }
11646:             }
11647:             if (ref($hashref) eq 'HASH') {
11648:                 %{$hashref} = (
11649:                                 sums     => \%chksum,
11650:                                 versions => \%revnum,
11651:                               );
11652:             }
11653:         }
11654:     }
11655:     return;
11656: }
11657: 
11658: sub fetch_dns_checksums {
11659:     my %checksums; 
11660:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
11661:              \%checksums);
11662:     return \%checksums;
11663: }
11664: 
11665: # ------------------------------------------------------------ Read domain file
11666: {
11667:     my $loaded;
11668:     my %domain;
11669: 
11670:     sub parse_domain_tab {
11671: 	my ($lines) = @_;
11672: 	foreach my $line (@$lines) {
11673: 	    next if ($line =~ /^(\#|\s*$ )/x);
11674: 
11675: 	    chomp($line);
11676: 	    my ($name,@elements) = split(/:/,$line,9);
11677: 	    my %this_domain;
11678: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11679: 			       'lang_def', 'city', 'longi', 'lati',
11680: 			       'primary') {
11681: 		$this_domain{$field} = shift(@elements);
11682: 	    }
11683: 	    $domain{$name} = \%this_domain;
11684: 	}
11685:     }
11686: 
11687:     sub reset_domain_info {
11688: 	undef($loaded);
11689: 	undef(%domain);
11690:     }
11691: 
11692:     sub load_domain_tab {
11693: 	my ($ignore_cache) = @_;
11694: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11695: 	my $fh;
11696: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11697: 	    my @lines = <$fh>;
11698: 	    &parse_domain_tab(\@lines);
11699: 	}
11700: 	close($fh);
11701: 	$loaded = 1;
11702:     }
11703: 
11704:     sub domain {
11705: 	&load_domain_tab() if (!$loaded);
11706: 
11707: 	my ($name,$what) = @_;
11708: 	return if ( !exists($domain{$name}) );
11709: 
11710: 	if (!$what) {
11711: 	    return $domain{$name}{'description'};
11712: 	}
11713: 	return $domain{$name}{$what};
11714:     }
11715: 
11716:     sub domain_info {
11717:         &load_domain_tab() if (!$loaded);
11718:         return %domain;
11719:     }
11720: 
11721: }
11722: 
11723: 
11724: # ------------------------------------------------------------- Read hosts file
11725: {
11726:     my %hostname;
11727:     my %hostdom;
11728:     my %libserv;
11729:     my $loaded;
11730:     my %name_to_host;
11731:     my %internetdom;
11732:     my %LC_dns_serv;
11733: 
11734:     sub parse_hosts_tab {
11735: 	my ($file) = @_;
11736: 	foreach my $configline (@$file) {
11737: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11738:             chomp($configline);
11739: 	    if ($configline =~ /^\^/) {
11740:                 if ($configline =~ /^\^([\w.\-]+)/) {
11741:                     $LC_dns_serv{$1} = 1;
11742:                 }
11743:                 next;
11744:             }
11745: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11746: 	    $name=~s/\s//g;
11747: 	    if ($id && $domain && $role && $name) {
11748: 		$hostname{$id}=$name;
11749: 		push(@{$name_to_host{$name}}, $id);
11750: 		$hostdom{$id}=$domain;
11751: 		if ($role eq 'library') { $libserv{$id}=$name; }
11752:                 if (defined($protocol)) {
11753:                     if ($protocol eq 'https') {
11754:                         $protocol{$id} = $protocol;
11755:                     } else {
11756:                         $protocol{$id} = 'http'; 
11757:                     }
11758:                 } else {
11759:                     $protocol{$id} = 'http';
11760:                 }
11761:                 if (defined($intdom)) {
11762:                     $internetdom{$id} = $intdom;
11763:                 }
11764: 	    }
11765: 	}
11766:     }
11767:     
11768:     sub reset_hosts_info {
11769: 	&purge_remembered();
11770: 	&reset_domain_info();
11771: 	&reset_hosts_ip_info();
11772: 	undef(%name_to_host);
11773: 	undef(%hostname);
11774: 	undef(%hostdom);
11775: 	undef(%libserv);
11776: 	undef($loaded);
11777:     }
11778: 
11779:     sub load_hosts_tab {
11780: 	my ($ignore_cache) = @_;
11781: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11782: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11783: 	my @config = <$config>;
11784: 	&parse_hosts_tab(\@config);
11785: 	close($config);
11786: 	$loaded=1;
11787:     }
11788: 
11789:     sub hostname {
11790: 	&load_hosts_tab() if (!$loaded);
11791: 
11792: 	my ($lonid) = @_;
11793: 	return $hostname{$lonid};
11794:     }
11795: 
11796:     sub all_hostnames {
11797: 	&load_hosts_tab() if (!$loaded);
11798: 
11799: 	return %hostname;
11800:     }
11801: 
11802:     sub all_names {
11803: 	&load_hosts_tab() if (!$loaded);
11804: 
11805: 	return %name_to_host;
11806:     }
11807: 
11808:     sub all_host_domain {
11809:         &load_hosts_tab() if (!$loaded);
11810:         return %hostdom;
11811:     }
11812: 
11813:     sub is_library {
11814: 	&load_hosts_tab() if (!$loaded);
11815: 
11816: 	return exists($libserv{$_[0]});
11817:     }
11818: 
11819:     sub all_library {
11820: 	&load_hosts_tab() if (!$loaded);
11821: 
11822: 	return %libserv;
11823:     }
11824: 
11825:     sub unique_library {
11826: 	#2x reverse removes all hostnames that appear more than once
11827:         my %unique = reverse &all_library();
11828:         return reverse %unique;
11829:     }
11830: 
11831:     sub get_servers {
11832: 	&load_hosts_tab() if (!$loaded);
11833: 
11834: 	my ($domain,$type) = @_;
11835: 	my %possible_hosts = ($type eq 'library') ? %libserv
11836: 	                                          : %hostname;
11837: 	my %result;
11838: 	if (ref($domain) eq 'ARRAY') {
11839: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11840: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11841: 		    $result{$host} = $hostname;
11842: 		}
11843: 	    }
11844: 	} else {
11845: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11846: 		if ($hostdom{$host} eq $domain) {
11847: 		    $result{$host} = $hostname;
11848: 		}
11849: 	    }
11850: 	}
11851: 	return %result;
11852:     }
11853: 
11854:     sub get_unique_servers {
11855:         my %unique = reverse &get_servers(@_);
11856: 	return reverse %unique;
11857:     }
11858: 
11859:     sub host_domain {
11860: 	&load_hosts_tab() if (!$loaded);
11861: 
11862: 	my ($lonid) = @_;
11863: 	return $hostdom{$lonid};
11864:     }
11865: 
11866:     sub all_domains {
11867: 	&load_hosts_tab() if (!$loaded);
11868: 
11869: 	my %seen;
11870: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11871: 	return @uniq;
11872:     }
11873: 
11874:     sub internet_dom {
11875:         &load_hosts_tab() if (!$loaded);
11876: 
11877:         my ($lonid) = @_;
11878:         return $internetdom{$lonid};
11879:     }
11880: 
11881:     sub is_LC_dns {
11882:         &load_hosts_tab() if (!$loaded);
11883: 
11884:         my ($hostname) = @_;
11885:         return exists($LC_dns_serv{$hostname});
11886:     }
11887: 
11888: }
11889: 
11890: { 
11891:     my %iphost;
11892:     my %name_to_ip;
11893:     my %lonid_to_ip;
11894: 
11895:     sub get_hosts_from_ip {
11896: 	my ($ip) = @_;
11897: 	my %iphosts = &get_iphost();
11898: 	if (ref($iphosts{$ip})) {
11899: 	    return @{$iphosts{$ip}};
11900: 	}
11901: 	return;
11902:     }
11903:     
11904:     sub reset_hosts_ip_info {
11905: 	undef(%iphost);
11906: 	undef(%name_to_ip);
11907: 	undef(%lonid_to_ip);
11908:     }
11909: 
11910:     sub get_host_ip {
11911: 	my ($lonid) = @_;
11912: 	if (exists($lonid_to_ip{$lonid})) {
11913: 	    return $lonid_to_ip{$lonid};
11914: 	}
11915: 	my $name=&hostname($lonid);
11916:    	my $ip = gethostbyname($name);
11917: 	return if (!$ip || length($ip) ne 4);
11918: 	$ip=inet_ntoa($ip);
11919: 	$name_to_ip{$name}   = $ip;
11920: 	$lonid_to_ip{$lonid} = $ip;
11921: 	return $ip;
11922:     }
11923:     
11924:     sub get_iphost {
11925: 	my ($ignore_cache) = @_;
11926: 
11927: 	if (!$ignore_cache) {
11928: 	    if (%iphost) {
11929: 		return %iphost;
11930: 	    }
11931: 	    my ($ip_info,$cached)=
11932: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11933: 	    if ($cached) {
11934: 		%iphost      = %{$ip_info->[0]};
11935: 		%name_to_ip  = %{$ip_info->[1]};
11936: 		%lonid_to_ip = %{$ip_info->[2]};
11937: 		return %iphost;
11938: 	    }
11939: 	}
11940: 
11941: 	# get yesterday's info for fallback
11942: 	my %old_name_to_ip;
11943: 	my ($ip_info,$cached)=
11944: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11945: 	if ($cached) {
11946: 	    %old_name_to_ip = %{$ip_info->[1]};
11947: 	}
11948: 
11949: 	my %name_to_host = &all_names();
11950: 	foreach my $name (keys(%name_to_host)) {
11951: 	    my $ip;
11952: 	    if (!exists($name_to_ip{$name})) {
11953: 		$ip = gethostbyname($name);
11954: 		if (!$ip || length($ip) ne 4) {
11955: 		    if (defined($old_name_to_ip{$name})) {
11956: 			$ip = $old_name_to_ip{$name};
11957: 			&logthis("Can't find $name defaulting to old $ip");
11958: 		    } else {
11959: 			&logthis("Name $name no IP found");
11960: 			next;
11961: 		    }
11962: 		} else {
11963: 		    $ip=inet_ntoa($ip);
11964: 		}
11965: 		$name_to_ip{$name} = $ip;
11966: 	    } else {
11967: 		$ip = $name_to_ip{$name};
11968: 	    }
11969: 	    foreach my $id (@{ $name_to_host{$name} }) {
11970: 		$lonid_to_ip{$id} = $ip;
11971: 	    }
11972: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11973: 	}
11974: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11975: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11976: 				      48*60*60);
11977: 
11978: 	return %iphost;
11979:     }
11980: 
11981:     #
11982:     #  Given a DNS returns the loncapa host name for that DNS 
11983:     # 
11984:     sub host_from_dns {
11985:         my ($dns) = @_;
11986:         my @hosts;
11987:         my $ip;
11988: 
11989:         if (exists($name_to_ip{$dns})) {
11990:             $ip = $name_to_ip{$dns};
11991:         }
11992:         if (!$ip) {
11993:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11994:             if (length($ip) == 4) { 
11995: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11996:             }
11997:         }
11998:         if ($ip) {
11999: 	    @hosts = get_hosts_from_ip($ip);
12000: 	    return $hosts[0];
12001:         }
12002:         return undef;
12003:     }
12004: 
12005:     sub get_internet_names {
12006:         my ($lonid) = @_;
12007:         return if ($lonid eq '');
12008:         my ($idnref,$cached)=
12009:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12010:         if ($cached) {
12011:             return $idnref;
12012:         }
12013:         my $ip = &get_host_ip($lonid);
12014:         my @hosts = &get_hosts_from_ip($ip);
12015:         my %iphost = &get_iphost();
12016:         my (@idns,%seen);
12017:         foreach my $id (@hosts) {
12018:             my $dom = &host_domain($id);
12019:             my $prim_id = &domain($dom,'primary');
12020:             my $prim_ip = &get_host_ip($prim_id);
12021:             next if ($seen{$prim_ip});
12022:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12023:                 foreach my $id (@{$iphost{$prim_ip}}) {
12024:                     my $intdom = &internet_dom($id);
12025:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12026:                         push(@idns,$intdom);
12027:                     }
12028:                 }
12029:             }
12030:             $seen{$prim_ip} = 1;
12031:         }
12032:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12033:     }
12034: 
12035: }
12036: 
12037: sub all_loncaparevs {
12038:     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);
12039: }
12040: 
12041: BEGIN {
12042: 
12043: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12044:     unless ($readit) {
12045: {
12046:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12047:     %perlvar = (%perlvar,%{$configvars});
12048: }
12049: 
12050: 
12051: # ------------------------------------------------------ Read spare server file
12052: {
12053:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12054: 
12055:     while (my $configline=<$config>) {
12056:        chomp($configline);
12057:        if ($configline) {
12058: 	   my ($host,$type) = split(':',$configline,2);
12059: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12060: 	   push(@{ $spareid{$type} }, $host);
12061:        }
12062:     }
12063:     close($config);
12064: }
12065: # ------------------------------------------------------------ Read permissions
12066: {
12067:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12068: 
12069:     while (my $configline=<$config>) {
12070: 	chomp($configline);
12071: 	if ($configline) {
12072: 	    my ($role,$perm)=split(/ /,$configline);
12073: 	    if ($perm ne '') { $pr{$role}=$perm; }
12074: 	}
12075:     }
12076:     close($config);
12077: }
12078: 
12079: # -------------------------------------------- Read plain texts for permissions
12080: {
12081:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12082: 
12083:     while (my $configline=<$config>) {
12084: 	chomp($configline);
12085: 	if ($configline) {
12086: 	    my ($short,@plain)=split(/:/,$configline);
12087:             %{$prp{$short}} = ();
12088: 	    if (@plain > 0) {
12089:                 $prp{$short}{'std'} = $plain[0];
12090:                 for (my $i=1; $i<@plain; $i++) {
12091:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12092:                 }
12093:             }
12094: 	}
12095:     }
12096:     close($config);
12097: }
12098: 
12099: # ---------------------------------------------------------- Read package table
12100: {
12101:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12102: 
12103:     while (my $configline=<$config>) {
12104: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12105: 	chomp($configline);
12106: 	my ($short,$plain)=split(/:/,$configline);
12107: 	my ($pack,$name)=split(/\&/,$short);
12108: 	if ($plain ne '') {
12109: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12110: 	    $packagetab{$short}=$plain; 
12111: 	}
12112:     }
12113:     close($config);
12114: }
12115: 
12116: # ---------------------------------------------------------- Read loncaparev table
12117: {
12118:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12119:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12120:             while (my $configline=<$config>) {
12121:                 chomp($configline);
12122:                 my ($hostid,$loncaparev)=split(/:/,$configline);
12123:                 $loncaparevs{$hostid}=$loncaparev;
12124:             }
12125:             close($config);
12126:         }
12127:     }
12128: }
12129: 
12130: # ---------------------------------------------------------- Read serverhostID table
12131: {
12132:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12133:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12134:             while (my $configline=<$config>) {
12135:                 chomp($configline);
12136:                 my ($name,$id)=split(/:/,$configline);
12137:                 $serverhomeIDs{$name}=$id;
12138:             }
12139:             close($config);
12140:         }
12141:     }
12142: }
12143: 
12144: {
12145:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12146:     if (-e $file) {
12147:         my $parser = HTML::LCParser->new($file);
12148:         while (my $token = $parser->get_token()) {
12149:             if ($token->[0] eq 'S') {
12150:                 my $item = $token->[1];
12151:                 my $name = $token->[2]{'name'};
12152:                 my $value = $token->[2]{'value'};
12153:                 if ($item ne '' && $name ne '' && $value ne '') {
12154:                     my $release = $parser->get_text();
12155:                     $release =~ s/(^\s*|\s*$ )//gx;
12156:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12157:                 }
12158:             }
12159:         }
12160:     }
12161: }
12162: 
12163: # ---------------------------------------------------------- Read managers table
12164: {
12165:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12166:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12167:             while (my $configline=<$config>) {
12168:                 chomp($configline);
12169:                 next if ($configline =~ /^\#/);
12170:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12171:                     $managerstab{$configline} = 1;
12172:                 }
12173:             }
12174:             close($config);
12175:         }
12176:     }
12177: }
12178: 
12179: # ------------- set up temporary directory
12180: {
12181:     $tmpdir = LONCAPA::tempdir();
12182: 
12183: }
12184: 
12185: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12186: 				'compress_threshold'=> 20_000,
12187:  			        });
12188: 
12189: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12190: $dumpcount=0;
12191: $locknum=0;
12192: 
12193: &logtouch();
12194: &logthis('<font color="yellow">INFO: Read configuration</font>');
12195: $readit=1;
12196:     {
12197: 	use integer;
12198: 	my $test=(2**32)+1;
12199: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12200: 	&logthis(" Detected 64bit platform ($_64bit)");
12201:     }
12202: 
12203:     {
12204:         eval {
12205:             ($apache) =
12206:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12207:         };
12208:         if ($@) {
12209:            $apache = 1.3;
12210:         }
12211:     }
12212: 
12213: }
12214: }
12215: 
12216: 1;
12217: __END__
12218: 
12219: =pod
12220: 
12221: =head1 NAME
12222: 
12223: Apache::lonnet - Subroutines to ask questions about things in the network.
12224: 
12225: =head1 SYNOPSIS
12226: 
12227: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12228: 
12229:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12230: 
12231: Common parameters:
12232: 
12233: =over 4
12234: 
12235: =item *
12236: 
12237: $uname : an internal username (if $cname expecting a course Id specifically)
12238: 
12239: =item *
12240: 
12241: $udom : a domain (if $cdom expecting a course's domain specifically)
12242: 
12243: =item *
12244: 
12245: $symb : a resource instance identifier
12246: 
12247: =item *
12248: 
12249: $namespace : the name of a .db file that contains the data needed or
12250: being set.
12251: 
12252: =back
12253: 
12254: =head1 OVERVIEW
12255: 
12256: lonnet provides subroutines which interact with the
12257: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12258: about classes, users, and resources.
12259: 
12260: For many of these objects you can also use this to store data about
12261: them or modify them in various ways.
12262: 
12263: =head2 Symbs
12264: 
12265: To identify a specific instance of a resource, LON-CAPA uses symbols
12266: or "symbs"X<symb>. These identifiers are built from the URL of the
12267: map, the resource number of the resource in the map, and the URL of
12268: the resource itself. The latter is somewhat redundant, but might help
12269: if maps change.
12270: 
12271: An example is
12272: 
12273:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12274: 
12275: The respective map entry is
12276: 
12277:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12278:   title="Problem 2">
12279:  </resource>
12280: 
12281: Symbs are used by the random number generator, as well as to store and
12282: restore data specific to a certain instance of for example a problem.
12283: 
12284: =head2 Storing And Retrieving Data
12285: 
12286: X<store()>X<cstore()>X<restore()>Three of the most important functions
12287: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12288: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12289: is is the non-critical message twin of cstore. These functions are for
12290: handlers to store a perl hash to a user's permanent data space in an
12291: easy manner, and to retrieve it again on another call. It is expected
12292: that a handler would use this once at the beginning to retrieve data,
12293: and then again once at the end to send only the new data back.
12294: 
12295: The data is stored in the user's data directory on the user's
12296: homeserver under the ID of the course.
12297: 
12298: The hash that is returned by restore will have all of the previous
12299: value for all of the elements of the hash.
12300: 
12301: Example:
12302: 
12303:  #creating a hash
12304:  my %hash;
12305:  $hash{'foo'}='bar';
12306: 
12307:  #storing it
12308:  &Apache::lonnet::cstore(\%hash);
12309: 
12310:  #changing a value
12311:  $hash{'foo'}='notbar';
12312: 
12313:  #adding a new value
12314:  $hash{'bar'}='foo';
12315:  &Apache::lonnet::cstore(\%hash);
12316: 
12317:  #retrieving the hash
12318:  my %history=&Apache::lonnet::restore();
12319: 
12320:  #print the hash
12321:  foreach my $key (sort(keys(%history))) {
12322:    print("\%history{$key} = $history{$key}");
12323:  }
12324: 
12325: Will print out:
12326: 
12327:  %history{1:foo} = bar
12328:  %history{1:keys} = foo:timestamp
12329:  %history{1:timestamp} = 990455579
12330:  %history{2:bar} = foo
12331:  %history{2:foo} = notbar
12332:  %history{2:keys} = foo:bar:timestamp
12333:  %history{2:timestamp} = 990455580
12334:  %history{bar} = foo
12335:  %history{foo} = notbar
12336:  %history{timestamp} = 990455580
12337:  %history{version} = 2
12338: 
12339: Note that the special hash entries C<keys>, C<version> and
12340: C<timestamp> were added to the hash. C<version> will be equal to the
12341: total number of versions of the data that have been stored. The
12342: C<timestamp> attribute will be the UNIX time the hash was
12343: stored. C<keys> is available in every historical section to list which
12344: keys were added or changed at a specific historical revision of a
12345: hash.
12346: 
12347: B<Warning>: do not store the hash that restore returns directly. This
12348: will cause a mess since it will restore the historical keys as if the
12349: were new keys. I.E. 1:foo will become 1:1:foo etc.
12350: 
12351: Calling convention:
12352: 
12353:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
12354:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
12355: 
12356: For more detailed information, see lonnet specific documentation.
12357: 
12358: =head1 RETURN MESSAGES
12359: 
12360: =over 4
12361: 
12362: =item * B<con_lost>: unable to contact remote host
12363: 
12364: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12365: when the connection is brought back up
12366: 
12367: =item * B<con_failed>: unable to contact remote host and unable to save message
12368: for later delivery
12369: 
12370: =item * B<error:>: an error a occurred, a description of the error follows the :
12371: 
12372: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12373: that was requested
12374: 
12375: =back
12376: 
12377: =head1 PUBLIC SUBROUTINES
12378: 
12379: =head2 Session Environment Functions
12380: 
12381: =over 4
12382: 
12383: =item * 
12384: X<appenv()>
12385: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12386: the user envirnoment file, and will be restored for each access this
12387: user makes during this session, also modifies the %env for the current
12388: process. Optional rolesarrayref - if defined contains a reference to an array
12389: of roles which are exempt from the restriction on modifying user.role entries 
12390: in the user's environment.db and in %env.    
12391: 
12392: =item *
12393: X<delenv()>
12394: B<delenv($delthis,$regexp)>: removes all items from the session
12395: environment file that begin with $delthis. If the 
12396: optional second arg - $regexp - is true, $delthis is treated as a 
12397: regular expression, otherwise \Q$delthis\E is used. 
12398: The values are also deleted from the current processes %env.
12399: 
12400: =item * get_env_multiple($name) 
12401: 
12402: gets $name from the %env hash, it seemlessly handles the cases where multiple
12403: values may be defined and end up as an array ref.
12404: 
12405: returns an array of values
12406: 
12407: =back
12408: 
12409: =head2 User Information
12410: 
12411: =over 4
12412: 
12413: =item *
12414: X<queryauthenticate()>
12415: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12416: authentication scheme
12417: 
12418: =item *
12419: X<authenticate()>
12420: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12421: authenticate user from domain's lib servers (first use the current
12422: one). C<$upass> should be the users password.
12423: $checkdefauth is optional (value is 1 if a check should be made to
12424:    authenticate user using default authentication method, and allow
12425:    account creation if username does not have account in the domain).
12426: $clientcancheckhost is optional (value is 1 if checking whether the
12427:    server can host will occur on the client side in lonauth.pm).   
12428: 
12429: =item *
12430: X<homeserver()>
12431: B<homeserver($uname,$udom)>: find the server which has
12432: the user's directory and files (there must be only one), this caches
12433: the answer, and also caches if there is a borken connection.
12434: 
12435: =item *
12436: X<idget()>
12437: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12438: (IDs are a unique resource in a domain, there must be only 1 ID per
12439: username, and only 1 username per ID in a specific domain) (returns
12440: hash: id=>name,id=>name)
12441: 
12442: =item *
12443: X<idrget()>
12444: B<idrget($udom,@unames)>: find the IDs behind a list of
12445: usernames (returns hash: name=>id,name=>id)
12446: 
12447: =item *
12448: X<idput()>
12449: B<idput($udom,%ids)>: store away a list of names and associated IDs
12450: 
12451: =item *
12452: X<rolesinit()>
12453: B<rolesinit($udom,$username)>: get user privileges.
12454: returns user role, first access and timer interval hashes
12455: 
12456: =item *
12457: X<privileged()>
12458: B<privileged($username,$domain)>: returns a true if user has a
12459: privileged and active role (i.e. su or dc), false otherwise.
12460: 
12461: =item *
12462: X<getsection()>
12463: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12464: course $cname, return section name/number or '' for "not in course"
12465: and '-1' for "no section"
12466: 
12467: =item *
12468: X<userenvironment()>
12469: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12470: passed in @what from the requested user's environment, returns a hash
12471: 
12472: =item * 
12473: X<userlog_query()>
12474: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12475: activity.log file. %filters defines filters applied when parsing the
12476: log file. These can be start or end timestamps, or the type of action
12477: - log to look for Login or Logout events, check for Checkin or
12478: Checkout, role for role selection. The response is in the form
12479: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12480: escaped strings of the action recorded in the activity.log file.
12481: 
12482: =back
12483: 
12484: =head2 User Roles
12485: 
12486: =over 4
12487: 
12488: =item *
12489: 
12490: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12491:  F: full access
12492:  U,I,K: authentication modes (cxx only)
12493:  '': forbidden
12494:  1: user needs to choose course
12495:  2: browse allowed
12496:  A: passphrase authentication needed
12497: 
12498: =item *
12499: 
12500: constructaccess($url,$setpriv) : check for access to construction space URL
12501: 
12502: See if the owner domain and name in the URL match those in the
12503: expected environment.  If so, return three element list
12504: ($ownername,$ownerdomain,$ownerhome).
12505: 
12506: Otherwise return the null string.
12507: 
12508: If second argument 'setpriv' is true, it assigns the privileges,
12509: and returns the same three element list, unless the owner has
12510: blocked "ad hoc" Domain Coordinator access to the Author Space,
12511: in which case the null string is returned.
12512: 
12513: =item *
12514: 
12515: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12516: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12517: and course level
12518: 
12519: =item *
12520: 
12521: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12522: (rolesplain.tab); plain text explanation of a user role term.
12523: $type is Course (default) or Community.
12524: If $forcedefault evaluates to true, text returned will be default 
12525: text for $type. Otherwise, if this is a course, the text returned 
12526: will be a custom name for the role (if defined in the course's 
12527: environment).  If no custom name is defined the default is returned.
12528:    
12529: =item *
12530: 
12531: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
12532: All arguments are optional. Returns a hash of a roles, either for
12533: co-author/assistant author roles for a user's Construction Space
12534: (default), or if $context is 'userroles', roles for the user himself,
12535: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12536: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12537: For each key, value is set to colon-separated start and end times for
12538: the role.  If no username and domain are specified, will default to
12539: current user/domain. Types, roles, and roledoms are references to arrays
12540: of role statuses (active, future or previous), roles 
12541: (e.g., cc,in, st etc.) and domains of the roles which can be used
12542: to restrict the list of roles reported. If no array ref is 
12543: provided for types, will default to return only active roles.
12544: 
12545: =item *
12546: 
12547: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12548: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12549: 
12550: Additional optional arguments are: $type (if role checking is to be restricted 
12551: to certain user status types -- previous (expired roles), active (currently
12552: available roles) or future (roles available in the future), and
12553: $hideprivileged -- if true will not report course roles for users who
12554: have active Domain Coordinator or Super User roles.
12555: 
12556: =back
12557: 
12558: =head2 User Modification
12559: 
12560: =over 4
12561: 
12562: =item *
12563: 
12564: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12565: user for the level given by URL.  Optional start and end dates (leave empty
12566: string or zero for "no date")
12567: 
12568: =item *
12569: 
12570: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12571: change a users, password, possible return values are: ok,
12572: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12573: refused
12574: 
12575: =item *
12576: 
12577: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12578: 
12579: =item *
12580: 
12581: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12582:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12583: 
12584: will update user information (firstname,middlename,lastname,generation,
12585: permanentemail), and if forceid is true, student/employee ID also.
12586: A user's institutional affiliation(s) can also be updated.
12587: User information fields will not be overwritten with empty entries 
12588: unless the field is included in the $candelete array reference.
12589: This array is included when a single user is modified via "Manage Users",
12590: or when Autoupdate.pl is run by cron in a domain.
12591: 
12592: =item *
12593: 
12594: modifystudent
12595: 
12596: modify a student's enrollment and identification information.
12597: The course id is resolved based on the current users environment.  
12598: This means the envoking user must be a course coordinator or otherwise
12599: associated with a course.
12600: 
12601: This call is essentially a wrapper for lonnet::modifyuser and
12602: lonnet::modify_student_enrollment
12603: 
12604: Inputs: 
12605: 
12606: =over 4
12607: 
12608: =item B<$udom> Student's loncapa domain
12609: 
12610: =item B<$uname> Student's loncapa login name
12611: 
12612: =item B<$uid> Student/Employee ID
12613: 
12614: =item B<$umode> Student's authentication mode
12615: 
12616: =item B<$upass> Student's password
12617: 
12618: =item B<$first> Student's first name
12619: 
12620: =item B<$middle> Student's middle name
12621: 
12622: =item B<$last> Student's last name
12623: 
12624: =item B<$gene> Student's generation
12625: 
12626: =item B<$usec> Student's section in course
12627: 
12628: =item B<$end> Unix time of the roles expiration
12629: 
12630: =item B<$start> Unix time of the roles start date
12631: 
12632: =item B<$forceid> If defined, allow $uid to be changed
12633: 
12634: =item B<$desiredhome> server to use as home server for student
12635: 
12636: =item B<$email> Student's permanent e-mail address
12637: 
12638: =item B<$type> Type of enrollment (auto or manual)
12639: 
12640: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12641: 
12642: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12643: 
12644: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12645: 
12646: =item B<$context> role change context (shown in User Management Logs display in a course)
12647: 
12648: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
12649: 
12650: =back
12651: 
12652: =item *
12653: 
12654: modify_student_enrollment
12655: 
12656: Change a students enrollment status in a class.  The environment variable
12657: 'role.request.course' must be defined for this function to proceed.
12658: 
12659: Inputs:
12660: 
12661: =over 4
12662: 
12663: =item $udom, students domain
12664: 
12665: =item $uname, students name
12666: 
12667: =item $uid, students user id
12668: 
12669: =item $first, students first name
12670: 
12671: =item $middle
12672: 
12673: =item $last
12674: 
12675: =item $gene
12676: 
12677: =item $usec
12678: 
12679: =item $end
12680: 
12681: =item $start
12682: 
12683: =item $type
12684: 
12685: =item $locktype
12686: 
12687: =item $cid
12688: 
12689: =item $selfenroll
12690: 
12691: =item $context
12692: 
12693: =back
12694: 
12695: 
12696: =item *
12697: 
12698: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12699: custom role; give a custom role to a user for the level given by URL.  Specify
12700: name and domain of role author, and role name
12701: 
12702: =item *
12703: 
12704: revokerole($udom,$uname,$url,$role) : revoke a role for url
12705: 
12706: =item *
12707: 
12708: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12709: 
12710: =back
12711: 
12712: =head2 Course Infomation
12713: 
12714: =over 4
12715: 
12716: =item *
12717: 
12718: coursedescription($courseid,$options) : returns a hash of information about the
12719: specified course id, including all environment settings for the
12720: course, the description of the course will be in the hash under the
12721: key 'description'
12722: 
12723: $options is an optional parameter that if supplied is a hash reference that controls
12724: what how this function works.  It has the following key/values:
12725: 
12726: =over 4
12727: 
12728: =item freshen_cache
12729: 
12730: If defined, and the environment cache for the course is valid, it is 
12731: returned in the returned hash.
12732: 
12733: =item one_time
12734: 
12735: If defined, the last cache time is set to _now_
12736: 
12737: =item user
12738: 
12739: If defined, the supplied username is used instead of the current user.
12740: 
12741: 
12742: =back
12743: 
12744: =item *
12745: 
12746: resdata($name,$domain,$type,@which) : request for current parameter
12747: setting for a specific $type, where $type is either 'course' or 'user',
12748: @what should be a list of parameters to ask about. This routine caches
12749: answers for 5 minutes.
12750: 
12751: =item *
12752: 
12753: get_courseresdata($courseid, $domain) : dump the entire course resource
12754: data base, returning a hash that is keyed by the resource name and has
12755: values that are the resource value.  I believe that the timestamps and
12756: versions are also returned.
12757: 
12758: =back
12759: 
12760: =head2 Course Modification
12761: 
12762: =over 4
12763: 
12764: =item *
12765: 
12766: writecoursepref($courseid,%prefs) : write preferences (environment
12767: database) for a course
12768: 
12769: =item *
12770: 
12771: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12772: 
12773: =item *
12774: 
12775: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12776: 
12777: =item *
12778: 
12779: is_course($courseid), is_course($cdom, $cnum)
12780: 
12781: Accepts either a combined $courseid (in the form of domain_courseid) or the
12782: two component version $cdom, $cnum. It checks if the specified course exists.
12783: 
12784: Returns:
12785:     undef if the course doesn't exist, otherwise
12786:     in scalar context the combined courseid.
12787:     in list context the two components of the course identifier, domain and 
12788:     courseid.    
12789: 
12790: =back
12791: 
12792: =head2 Resource Subroutines
12793: 
12794: =over 4
12795: 
12796: =item *
12797: 
12798: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12799: 
12800: =item *
12801: 
12802: repcopy($filename) : subscribes to the requested file, and attempts to
12803: replicate from the owning library server, Might return
12804: 'unavailable', 'not_found', 'forbidden', 'ok', or
12805: 'bad_request', also attempts to grab the metadata for the
12806: resource. Expects the local filesystem pathname
12807: (/home/httpd/html/res/....)
12808: 
12809: =back
12810: 
12811: =head2 Resource Information
12812: 
12813: =over 4
12814: 
12815: =item *
12816: 
12817: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12818: a vairety of different possible values, $varname should be a request
12819: string, and the other parameters can be used to specify who and what
12820: one is asking about.
12821: 
12822: Possible values for $varname are environment.lastname (or other item
12823: from the envirnment hash), user.name (or someother aspect about the
12824: user), resource.0.maxtries (or some other part and parameter of a
12825: resource)
12826: 
12827: =item *
12828: 
12829: directcondval($number) : get current value of a condition; reads from a state
12830: string
12831: 
12832: =item *
12833: 
12834: condval($condidx) : value of condition index based on state
12835: 
12836: =item *
12837: 
12838: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12839: resource's metadata, $what should be either a specific key, or either
12840: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12841: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12842: 
12843: this function automatically caches all requests
12844: 
12845: =item *
12846: 
12847: metadata_query($query,$custom,$customshow) : make a metadata query against the
12848: network of library servers; returns file handle of where SQL and regex results
12849: will be stored for query
12850: 
12851: =item *
12852: 
12853: symbread($filename) : return symbolic list entry (filename argument optional);
12854: returns the data handle
12855: 
12856: =item *
12857: 
12858: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12859: and is a possible symb for the URL in $thisfn, and if is an encrypted
12860: resource that the user accessed using /enc/ returns a 1 on success, 0
12861: on failure, user must be in a course, as it assumes the existence of
12862: the course initial hash, and uses $env('request.course.id'}.  The third
12863: arg is an optional reference to a scalar.  If this arg is passed in the 
12864: call to symbverify, it will be set to 1 if the symb has been set to be 
12865: encrypted; otherwise it will be null.  
12866: 
12867: =item *
12868: 
12869: symbclean($symb) : removes versions numbers from a symb, returns the
12870: cleaned symb
12871: 
12872: =item *
12873: 
12874: is_on_map($uri) : checks if the $uri is somewhere on the current
12875: course map, user must be in a course for it to work.
12876: 
12877: =item *
12878: 
12879: numval($salt) : return random seed value (addend for rndseed)
12880: 
12881: =item *
12882: 
12883: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12884: a random seed, all arguments are optional, if they aren't sent it uses the
12885: environment to derive them. Note: if symb isn't sent and it can't get one
12886: from &symbread it will use the current time as its return value
12887: 
12888: =item *
12889: 
12890: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12891: unfakeable, receipt
12892: 
12893: =item *
12894: 
12895: receipt() : API to ireceipt working off of env values; given out to users
12896: 
12897: =item *
12898: 
12899: countacc($url) : count the number of accesses to a given URL
12900: 
12901: =item *
12902: 
12903: 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
12904: 
12905: =item *
12906: 
12907: 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)
12908: 
12909: =item *
12910: 
12911: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12912: 
12913: =item *
12914: 
12915: devalidate($symb) : devalidate temporary spreadsheet calculations,
12916: forcing spreadsheet to reevaluate the resource scores next time.
12917: 
12918: =item * 
12919: 
12920: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
12921: when viewing in course context.
12922: 
12923:  input: six args -- filename (decluttered), course number, course domain,
12924:                     url, symb (if registered) and group (if this is a 
12925:                     group item -- e.g., bulletin board, group page etc.).
12926: 
12927:  output: array of five scalars --
12928:          $cfile -- url for file editing if editable on current server
12929:          $home -- homeserver of resource (i.e., for author if published,
12930:                                           or course if uploaded.).
12931:          $switchserver --  1 if server switch will be needed.
12932:          $forceedit -- 1 if icon/link should be to go to edit mode 
12933:          $forceview -- 1 if icon/link should be to go to view mode
12934: 
12935: =item *
12936: 
12937: is_course_upload($file,$cnum,$cdom)
12938: 
12939: Used in course context to determine if current file was uploaded to 
12940: the course (i.e., would be found in /userfiles/docs on the course's 
12941: homeserver.
12942: 
12943:   input: 3 args -- filename (decluttered), course number and course domain.
12944:   output: boolean -- 1 if file was uploaded.
12945: 
12946: =back
12947: 
12948: =head2 Storing/Retreiving Data
12949: 
12950: =over 4
12951: 
12952: =item *
12953: 
12954: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12955: for this url; hashref needs to be given and should be a \%hashname; the
12956: remaining args aren't required and if they aren't passed or are '' they will
12957: be derived from the env
12958: 
12959: =item *
12960: 
12961: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12962: uses critical subroutine
12963: 
12964: =item *
12965: 
12966: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12967: all args are optional
12968: 
12969: =item *
12970: 
12971: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12972: dumps the complete (or key matching regexp) namespace into a hash
12973: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12974: normally &store()ed into
12975: 
12976: $range should be either an integer '100' (give me the first 100
12977:                                            matching records)
12978:               or be  two integers sperated by a - with no spaces
12979:                  '30-50' (give me the 30th through the 50th matching
12980:                           records)
12981: 
12982: 
12983: =item *
12984: 
12985: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12986: replaces a &store() version of data with a replacement set of data
12987: for a particular resource in a namespace passed in the $storehash hash 
12988: reference
12989: 
12990: =item *
12991: 
12992: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12993: works very similar to store/cstore, but all data is stored in a
12994: temporary location and can be reset using tmpreset, $storehash should
12995: be a hash reference, returns nothing on success
12996: 
12997: =item *
12998: 
12999: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13000: similar to restore, but all data is stored in a temporary location and
13001: can be reset using tmpreset. Returns a hash of values on success,
13002: error string otherwise.
13003: 
13004: =item *
13005: 
13006: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13007: deltes all keys for $symb form the temporary storage hash.
13008: 
13009: =item *
13010: 
13011: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13012: reference filled in from namesp ($udom and $uname are optional)
13013: 
13014: =item *
13015: 
13016: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13017: namesp ($udom and $uname are optional)
13018: 
13019: =item *
13020: 
13021: dump($namespace,$udom,$uname,$regexp,$range) : 
13022: dumps the complete (or key matching regexp) namespace into a hash
13023: ($udom, $uname, $regexp, $range are optional)
13024: 
13025: $range should be either an integer '100' (give me the first 100
13026:                                            matching records)
13027:               or be  two integers sperated by a - with no spaces
13028:                  '30-50' (give me the 30th through the 50th matching
13029:                           records)
13030: =item *
13031: 
13032: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13033: $store can be a scalar, an array reference, or if the amount to be 
13034: incremented is > 1, a hash reference.
13035: 
13036: ($udom and $uname are optional)
13037: 
13038: =item *
13039: 
13040: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13041: ($udom and $uname are optional)
13042: 
13043: =item *
13044: 
13045: cput($namespace,$storehash,$udom,$uname) : critical put
13046: ($udom and $uname are optional)
13047: 
13048: =item *
13049: 
13050: newput($namespace,$storehash,$udom,$uname) :
13051: 
13052: Attempts to store the items in the $storehash, but only if they don't
13053: currently exist, if this succeeds you can be certain that you have 
13054: successfully created a new key value pair in the $namespace db.
13055: 
13056: 
13057: Args:
13058:  $namespace: name of database to store values to
13059:  $storehash: hashref to store to the db
13060:  $udom: (optional) domain of user containing the db
13061:  $uname: (optional) name of user caontaining the db
13062: 
13063: Returns:
13064:  'ok' -> succeeded in storing all keys of $storehash
13065:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13066:                         least <key> already existed in the db (other
13067:                         requested keys may also already exist)
13068:  'error: <msg>' -> unable to tie the DB or other error occurred
13069:  'con_lost' -> unable to contact request server
13070:  'refused' -> action was not allowed by remote machine
13071: 
13072: 
13073: =item *
13074: 
13075: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13076: reference filled in from namesp (encrypts the return communication)
13077: ($udom and $uname are optional)
13078: 
13079: =item *
13080: 
13081: log($udom,$name,$home,$message) : write to permanent log for user; use
13082: critical subroutine
13083: 
13084: =item *
13085: 
13086: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13087: array reference filled in from namespace found in domain level on either
13088: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13089: 
13090: =item *
13091: 
13092: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13093: domain level either on specified domain server ($uhome) or primary domain 
13094: server ($udom and $uhome are optional)
13095: 
13096: =item * 
13097: 
13098: get_domain_defaults($target_domain) : returns hash with defaults for
13099: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
13100: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
13101: or localauth), initial password or a kerberos realm, language (e.g., en-us).
13102: Values are retrieved from cache (if current), or from domain's configuration.db
13103: (if available), or lastly from values in lonTabs/dns_domain,tab, 
13104: or lonTabs/domain.tab. 
13105: 
13106: %domdefaults = &get_auth_defaults($target_domain);
13107: 
13108: =back
13109: 
13110: =head2 Network Status Functions
13111: 
13112: =over 4
13113: 
13114: =item *
13115: 
13116: dirlist() : return directory list based on URI (first arg).
13117: 
13118: Inputs: 1 required, 5 optional.
13119: 
13120: =over
13121: 
13122: =item 
13123: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13124: 
13125: =item
13126: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13127: 
13128: =item
13129: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13130: 
13131: =item
13132: $getpropath - boolean: 1 if prepend path using &propath(). 
13133: 
13134: =item
13135: $getuserdir - boolean: 1 if prepend path for "userfiles".
13136: 
13137: =item 
13138: $alternateRoot - path to prepend in place of path from $uri.
13139: 
13140: =back
13141: 
13142: Returns: Array of up to two items.
13143: 
13144: =over
13145: 
13146: a reference to an array of files/subdirectories
13147: 
13148: =over
13149: 
13150: Each element in the array of files/subdirectories is a & separated list of
13151: item name and the result of running stat on the item.  If dirlist was requested
13152: for a file instead of a directory, the item name will be ''. For a directory 
13153: listing, if the item is a metadata file, the element will end &N&M 
13154: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13155: default copyright set (1).  
13156: 
13157: =back
13158: 
13159: a scalar containing error condition (if encountered).
13160: 
13161: =over
13162: 
13163: =item 
13164: no_host (no homeserver identified for $username:$domain).
13165: 
13166: =item 
13167: no_such_host (server contacted for listing not identified as valid host).
13168: 
13169: =item 
13170: con_lost (connection to remote server failed).
13171: 
13172: =item 
13173: refused (invalid $username:$domain received on lond side).
13174: 
13175: =item 
13176: no_such_dir (directory at specified path on lond side does not exist). 
13177: 
13178: =item 
13179: empty (directory at specified path on lond side is empty).
13180: 
13181: =over
13182: 
13183: This is currently not encountered because the &ls3, &ls2, 
13184: &ls (_handler) routines on the lond side do not filter out
13185: . and .. from a directory listing. 
13186: 
13187: =back
13188: 
13189: =back
13190: 
13191: =back
13192: 
13193: =item *
13194: 
13195: spareserver() : find server with least workload from spare.tab
13196: 
13197: 
13198: =item *
13199: 
13200: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13201: if there is no corresponding loncapa host.
13202: 
13203: =back
13204: 
13205: 
13206: =head2 Apache Request
13207: 
13208: =over 4
13209: 
13210: =item *
13211: 
13212: ssi($url,%hash) : server side include, does a complete request cycle on url to
13213: localhost, posts hash
13214: 
13215: =back
13216: 
13217: =head2 Data to String to Data
13218: 
13219: =over 4
13220: 
13221: =item *
13222: 
13223: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13224: and '&' separators, supports elements that are arrayrefs and hashrefs
13225: 
13226: =item *
13227: 
13228: hashref2str($hashref) : convert a hashref into a string complete with
13229: escaping and '=' and '&' separators, supports elements that are
13230: arrayrefs and hashrefs
13231: 
13232: =item *
13233: 
13234: arrayref2str($arrayref) : convert an arrayref into a string complete
13235: with escaping and '&' separators, supports elements that are arrayrefs
13236: and hashrefs
13237: 
13238: =item *
13239: 
13240: str2hash($string) : convert string to hash using unescaping and
13241: splitting on '=' and '&', supports elements that are arrayrefs and
13242: hashrefs
13243: 
13244: =item *
13245: 
13246: str2array($string) : convert string to hash using unescaping and
13247: splitting on '&', supports elements that are arrayrefs and hashrefs
13248: 
13249: =back
13250: 
13251: =head2 Logging Routines
13252: 
13253: 
13254: These routines allow one to make log messages in the lonnet.log and
13255: lonnet.perm logfiles.
13256: 
13257: =over 4
13258: 
13259: =item *
13260: 
13261: logtouch() : make sure the logfile, lonnet.log, exists
13262: 
13263: =item *
13264: 
13265: logthis() : append message to the normal lonnet.log file, it gets
13266: preiodically rolled over and deleted.
13267: 
13268: =item *
13269: 
13270: logperm() : append a permanent message to lonnet.perm.log, this log
13271: file never gets deleted by any automated portion of the system, only
13272: messages of critical importance should go in here.
13273: 
13274: 
13275: =back
13276: 
13277: =head2 General File Helper Routines
13278: 
13279: =over 4
13280: 
13281: =item *
13282: 
13283: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13284: (a) files in /uploaded
13285:   (i) If a local copy of the file exists - 
13286:       compares modification date of local copy with last-modified date for 
13287:       definitive version stored on home server for course. If local copy is 
13288:       stale, requests a new version from the home server and stores it. 
13289:       If the original has been removed from the home server, then local copy 
13290:       is unlinked.
13291:   (ii) If local copy does not exist -
13292:       requests the file from the home server and stores it. 
13293:   
13294:   If $caller is 'uploadrep':  
13295:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13296:     for request for files originally uploaded via DOCS. 
13297:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13298:   
13299:   Otherwise:
13300:      This indicates a call from the content generation phase of the request.
13301:      -  returns the entire contents of the file or -1.
13302:      
13303: (b) files in /res
13304:    - returns the entire contents of a file or -1; 
13305:    it properly subscribes to and replicates the file if neccessary.
13306: 
13307: 
13308: =item *
13309: 
13310: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13311:                   reference
13312: 
13313: returns either a stat() list of data about the file or an empty list
13314: if the file doesn't exist or couldn't find out about it (connection
13315: problems or user unknown)
13316: 
13317: =item *
13318: 
13319: filelocation($dir,$file) : returns file system location of a file
13320: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13321: directory that relative $file lookups are to looked in ($dir of /a/dir
13322: and a file of ../bob will become /a/bob)
13323: 
13324: =item *
13325: 
13326: hreflocation($dir,$file) : returns file system location or a URL; same as
13327: filelocation except for hrefs
13328: 
13329: =item *
13330: 
13331: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13332: 
13333: =back
13334: 
13335: =head2 Usererfile file routines (/uploaded*)
13336: 
13337: =over 4
13338: 
13339: =item *
13340: 
13341: userfileupload(): main rotine for putting a file in a user or course's
13342:                   filespace, arguments are,
13343: 
13344:  formname - required - this is the name of the element in $env where the
13345:            filename, and the contents of the file to create/modifed exist
13346:            the filename is in $env{'form.'.$formname.'.filename'} and the
13347:            contents of the file is located in $env{'form.'.$formname}
13348:  context - if coursedoc, store the file in the course of the active role
13349:              of the current user; 
13350:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13351:            if 'canceloverwrite': delete file in tmp/overwrites directory
13352:  subdir - required - subdirectory to put the file in under ../userfiles/
13353:          if undefined, it will be placed in "unknown"
13354: 
13355:  (This routine calls clean_filename() to remove any dangerous
13356:  characters from the filename, and then calls finuserfileupload() to
13357:  complete the transaction)
13358: 
13359:  returns either the url of the uploaded file (/uploaded/....) if successful
13360:  and /adm/notfound.html if unsuccessful
13361: 
13362: =item *
13363: 
13364: clean_filename(): routine for cleaing a filename up for storage in
13365:                  userfile space, argument is:
13366: 
13367:  filename - proposed filename
13368: 
13369: returns: the new clean filename
13370: 
13371: =item *
13372: 
13373: finishuserfileupload(): routine that creates and sends the file to
13374: userspace, probably shouldn't be called directly
13375: 
13376:   docuname: username or courseid of destination for the file
13377:   docudom: domain of user/course of destination for the file
13378:   formname: same as for userfileupload()
13379:   fname: filename (including subdirectories) for the file
13380:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13381:   allfiles: reference to hash used to store objects found by parser
13382:   codebase: reference to hash used for codebases of java objects found by parser
13383:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13384:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13385:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13386:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13387:   context: if 'overwrite', will move the uploaded file from its temporary location to
13388:             userfiles to facilitate overwriting a previously uploaded file with same name.
13389:   mimetype: reference to scalar to accommodate mime type determined
13390:             from File::MMagic if $parser = parse.
13391: 
13392:  returns either the url of the uploaded file (/uploaded/....) if successful
13393:  and /adm/notfound.html if unsuccessful (or an error message if context 
13394:  was 'overwrite').
13395:  
13396: 
13397: =item *
13398: 
13399: renameuserfile(): renames an existing userfile to a new name
13400: 
13401:   Args:
13402:    docuname: username or courseid of destination for the file
13403:    docudom: domain of user/course of destination for the file
13404:    old: current file name (including any subdirs under userfiles)
13405:    new: desired file name (including any subdirs under userfiles)
13406: 
13407: =item *
13408: 
13409: mkdiruserfile(): creates a directory is a userfiles dir
13410: 
13411:   Args:
13412:    docuname: username or courseid of destination for the file
13413:    docudom: domain of user/course of destination for the file
13414:    dir: dir to create (including any subdirs under userfiles)
13415: 
13416: =item *
13417: 
13418: removeuserfile(): removes a file that exists in userfiles
13419: 
13420:   Args:
13421:    docuname: username or courseid of destination for the file
13422:    docudom: domain of user/course of destination for the file
13423:    fname: filname to delete (including any subdirs under userfiles)
13424: 
13425: =item *
13426: 
13427: removeuploadedurl(): convience function for removeuserfile()
13428: 
13429:   Args:
13430:    url:  a full /uploaded/... url to delete
13431: 
13432: =item * 
13433: 
13434: get_portfile_permissions():
13435:   Args:
13436:     domain: domain of user or course contain the portfolio files
13437:     user: name of user or num of course contain the portfolio files
13438:   Returns:
13439:     hashref of a dump of the proper file_permissions.db
13440:    
13441: 
13442: =item * 
13443: 
13444: get_access_controls():
13445: 
13446: Args:
13447:   current_permissions: the hash ref returned from get_portfile_permissions()
13448:   group: (optional) the group you want the files associated with
13449:   file: (optional) the file you want access info on
13450: 
13451: Returns:
13452:     a hash (keys are file names) of hashes containing
13453:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13454:         values are XML containing access control settings (see below) 
13455: 
13456: Internal notes:
13457: 
13458:  access controls are stored in file_permissions.db as key=value pairs.
13459:     key -> path to file/file_name\0uniqueID:scope_end_start
13460:         where scope -> public,guest,course,group,domains or users.
13461:               end -> UNIX time for end of access (0 -> no end date)
13462:               start -> UNIX time for start of access
13463: 
13464:     value -> XML description of access control
13465:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13466:             <start></start>
13467:             <end></end>
13468: 
13469:             <password></password>  for scope type = guest
13470: 
13471:             <domain></domain>     for scope type = course or group
13472:             <number></number>
13473:             <roles id="">
13474:              <role></role>
13475:              <access></access>
13476:              <section></section>
13477:              <group></group>
13478:             </roles>
13479: 
13480:             <dom></dom>         for scope type = domains
13481: 
13482:             <users>             for scope type = users
13483:              <user>
13484:               <uname></uname>
13485:               <udom></udom>
13486:              </user>
13487:             </users>
13488:            </scope> 
13489:               
13490:  Access data is also aggregated for each file in an additional key=value pair:
13491:  key -> path to file/file_name\0accesscontrol 
13492:  value -> reference to hash
13493:           hash contains key = value pairs
13494:           where key = uniqueID:scope_end_start
13495:                 value = UNIX time record was last updated
13496: 
13497:           Used to improve speed of look-ups of access controls for each file.  
13498:  
13499:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13500: 
13501: =item *
13502: 
13503: modify_access_controls():
13504: 
13505: Modifies access controls for a portfolio file
13506: Args
13507: 1. file name
13508: 2. reference to hash of required changes,
13509: 3. domain
13510: 4. username
13511:   where domain,username are the domain of the portfolio owner 
13512:   (either a user or a course) 
13513: 
13514: Returns:
13515: 1. result of additions or updates ('ok' or 'error', with error message). 
13516: 2. result of deletions ('ok' or 'error', with error message).
13517: 3. reference to hash of any new or updated access controls.
13518: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13519:    key = integer (inbound ID)
13520:    value = uniqueID
13521: 
13522: =item *
13523: 
13524: get_timebased_id():
13525: 
13526: Attempts to get a unique timestamp-based suffix for use with items added to a 
13527: course via the Course Editor (e.g., folders, composite pages, 
13528: group bulletin boards).
13529: 
13530: Args: (first three required; six others optional)
13531: 
13532: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13533:    docssequence, or name of group
13534: 
13535: 2. keyid (alphanumeric): name of temporary locking key in hash,
13536:    e.g., num, boardids
13537: 
13538: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13539:    file will be named nohist_namespace.db
13540: 
13541: 4. cdom: domain of course; default is current course domain from %env
13542: 
13543: 5. cnum: course number; default is current course number from %env
13544: 
13545: 6. idtype: set to concat if an additional digit is to be appended to the 
13546:    unix timestamp to form the suffix, if the plain timestamp is already
13547:    in use.  Default is to not do this, but simply increment the unix 
13548:    timestamp by 1 until a unique key is obtained.
13549: 
13550: 7. who: holder of locking key; defaults to user:domain for user.
13551: 
13552: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13553:    retrying); default is 3.
13554: 
13555: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13556: 
13557: Returns:
13558: 
13559: 1. suffix obtained (numeric)
13560: 
13561: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13562: 
13563: 3. error: contains (localized) error message if an error occurred.
13564: 
13565: 
13566: =back
13567: 
13568: =head2 HTTP Helper Routines
13569: 
13570: =over 4
13571: 
13572: =item *
13573: 
13574: escape() : unpack non-word characters into CGI-compatible hex codes
13575: 
13576: =item *
13577: 
13578: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13579: 
13580: =back
13581: 
13582: =head1 PRIVATE SUBROUTINES
13583: 
13584: =head2 Underlying communication routines (Shouldn't call)
13585: 
13586: =over 4
13587: 
13588: =item *
13589: 
13590: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13591: 
13592: =item *
13593: 
13594: reply() : uses subreply to send a message to remote machine, logs all failures
13595: 
13596: =item *
13597: 
13598: critical() : passes a critical message to another server; if cannot
13599: get through then place message in connection buffer directory and
13600: returns con_delayed, if incapable of saving message, returns
13601: con_failed
13602: 
13603: =item *
13604: 
13605: reconlonc() : tries to reconnect lonc client processes.
13606: 
13607: =back
13608: 
13609: =head2 Resource Access Logging
13610: 
13611: =over 4
13612: 
13613: =item *
13614: 
13615: flushcourselogs() : flush (save) buffer logs and access logs
13616: 
13617: =item *
13618: 
13619: courselog($what) : save message for course in hash
13620: 
13621: =item *
13622: 
13623: courseacclog($what) : save message for course using &courselog().  Perform
13624: special processing for specific resource types (problems, exams, quizzes, etc).
13625: 
13626: =item *
13627: 
13628: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13629: as a PerlChildExitHandler
13630: 
13631: =back
13632: 
13633: =head2 Other
13634: 
13635: =over 4
13636: 
13637: =item *
13638: 
13639: symblist($mapname,%newhash) : update symbolic storage links
13640: 
13641: =back
13642: 
13643: =cut
13644: 

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