File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1239: download - view: text, annotated - select for diffs
Sun Sep 29 14:15:08 2013 UTC (10 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Can reuse variables defined in scope of current subroutine.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1239 2013/09/29 14:15:08 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:         ($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: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1582: 
 1583: sub iddel {
 1584:     my ($udom,$idshashref,$uhome)=@_;
 1585:     my %result=();
 1586:     unless (ref($idshashref) eq 'HASH') {
 1587:         return %result;
 1588:     }
 1589:     my %servers=();
 1590:     while (my ($id,$uname) = each(%{$idshashref})) {
 1591:         my $uhom;
 1592:         if ($uhome) {
 1593:             $uhom = $uhome;
 1594:         } else {
 1595:             $uhom=&homeserver($uname,$udom);
 1596:         }
 1597:         if ($uhom ne 'no_host') {
 1598:             if ($servers{$uhom}) {
 1599:                 $servers{$uhom}.='&'.&escape($id);
 1600:             } else {
 1601:                 $servers{$uhom}=&escape($id);
 1602:             }
 1603:         }
 1604:     }
 1605:     foreach my $server (keys(%servers)) {
 1606:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1607:     }
 1608:     return %result;
 1609: }
 1610: 
 1611: # ------------------------------dump from db file owned by domainconfig user
 1612: sub dump_dom {
 1613:     my ($namespace, $udom, $regexp) = @_;
 1614: 
 1615:     $udom ||= $env{'user.domain'};
 1616: 
 1617:     return () unless $udom;
 1618: 
 1619:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1620: }
 1621: 
 1622: # ------------------------------------------ get items from domain db files   
 1623: 
 1624: sub get_dom {
 1625:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1626:     my $items='';
 1627:     foreach my $item (@$storearr) {
 1628:         $items.=&escape($item).'&';
 1629:     }
 1630:     $items=~s/\&$//;
 1631:     if (!$udom) {
 1632:         $udom=$env{'user.domain'};
 1633:         if (defined(&domain($udom,'primary'))) {
 1634:             $uhome=&domain($udom,'primary');
 1635:         } else {
 1636:             undef($uhome);
 1637:         }
 1638:     } else {
 1639:         if (!$uhome) {
 1640:             if (defined(&domain($udom,'primary'))) {
 1641:                 $uhome=&domain($udom,'primary');
 1642:             }
 1643:         }
 1644:     }
 1645:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1646:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1647:         my %returnhash;
 1648:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1649:             return %returnhash;
 1650:         }
 1651:         my @pairs=split(/\&/,$rep);
 1652:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1653:             return @pairs;
 1654:         }
 1655:         my $i=0;
 1656:         foreach my $item (@$storearr) {
 1657:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1658:             $i++;
 1659:         }
 1660:         return %returnhash;
 1661:     } else {
 1662:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1663:     }
 1664: }
 1665: 
 1666: # -------------------------------------------- put items in domain db files 
 1667: 
 1668: sub put_dom {
 1669:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1670:     if (!$udom) {
 1671:         $udom=$env{'user.domain'};
 1672:         if (defined(&domain($udom,'primary'))) {
 1673:             $uhome=&domain($udom,'primary');
 1674:         } else {
 1675:             undef($uhome);
 1676:         }
 1677:     } else {
 1678:         if (!$uhome) {
 1679:             if (defined(&domain($udom,'primary'))) {
 1680:                 $uhome=&domain($udom,'primary');
 1681:             }
 1682:         }
 1683:     } 
 1684:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1685:         my $items='';
 1686:         foreach my $item (keys(%$storehash)) {
 1687:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1688:         }
 1689:         $items=~s/\&$//;
 1690:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1691:     } else {
 1692:         &logthis("put_dom failed - no homeserver and/or domain");
 1693:     }
 1694: }
 1695: 
 1696: # --------------------- newput for items in db file owned by domainconfig user
 1697: sub newput_dom {
 1698:     my ($namespace,$storehash,$udom) = @_;
 1699:     my $result;
 1700:     if (!$udom) {
 1701:         $udom=$env{'user.domain'};
 1702:     }
 1703:     if ($udom) {
 1704:         my $uname = &get_domainconfiguser($udom);
 1705:         $result = &newput($namespace,$storehash,$udom,$uname);
 1706:     }
 1707:     return $result;
 1708: }
 1709: 
 1710: # --------------------- delete for items in db file owned by domainconfig user
 1711: sub del_dom {
 1712:     my ($namespace,$storearr,$udom)=@_;
 1713:     if (ref($storearr) eq 'ARRAY') {
 1714:         if (!$udom) {
 1715:             $udom=$env{'user.domain'};
 1716:         }
 1717:         if ($udom) {
 1718:             my $uname = &get_domainconfiguser($udom); 
 1719:             return &del($namespace,$storearr,$udom,$uname);
 1720:         }
 1721:     }
 1722: }
 1723: 
 1724: # ----------------------------------construct domainconfig user for a domain 
 1725: sub get_domainconfiguser {
 1726:     my ($udom) = @_;
 1727:     return $udom.'-domainconfig';
 1728: }
 1729: 
 1730: sub retrieve_inst_usertypes {
 1731:     my ($udom) = @_;
 1732:     my (%returnhash,@order);
 1733:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1734:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1735:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1736:         %returnhash = %{$domdefs{'inststatustypes'}};
 1737:         @order = @{$domdefs{'inststatusorder'}};
 1738:     } else {
 1739:         if (defined(&domain($udom,'primary'))) {
 1740:             my $uhome=&domain($udom,'primary');
 1741:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1742:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1743:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1744:                 return (\%returnhash,\@order);
 1745:             }
 1746:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1747:             my @pairs=split(/\&/,$hashitems);
 1748:             foreach my $item (@pairs) {
 1749:                 my ($key,$value)=split(/=/,$item,2);
 1750:                 $key = &unescape($key);
 1751:                 next if ($key =~ /^error: 2 /);
 1752:                 $returnhash{$key}=&thaw_unescape($value);
 1753:             }
 1754:             my @esc_order = split(/\&/,$orderitems);
 1755:             foreach my $item (@esc_order) {
 1756:                 push(@order,&unescape($item));
 1757:             }
 1758:         } else {
 1759:             &logthis("get_dom failed - no primary domain server for $udom");
 1760:         }
 1761:     }
 1762:     return (\%returnhash,\@order);
 1763: }
 1764: 
 1765: sub is_domainimage {
 1766:     my ($url) = @_;
 1767:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1768:         if (&domain($1) ne '') {
 1769:             return '1';
 1770:         }
 1771:     }
 1772:     return;
 1773: }
 1774: 
 1775: sub inst_directory_query {
 1776:     my ($srch) = @_;
 1777:     my $udom = $srch->{'srchdomain'};
 1778:     my %results;
 1779:     my $homeserver = &domain($udom,'primary');
 1780:     my $outcome;
 1781:     if ($homeserver ne '') {
 1782: 	my $queryid=&reply("querysend:instdirsearch:".
 1783: 			   &escape($srch->{'srchby'}).':'.
 1784: 			   &escape($srch->{'srchterm'}).':'.
 1785: 			   &escape($srch->{'srchtype'}),$homeserver);
 1786: 	my $host=&hostname($homeserver);
 1787: 	if ($queryid !~/^\Q$host\E\_/) {
 1788: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1789: 	    return;
 1790: 	}
 1791: 	my $response = &get_query_reply($queryid);
 1792: 	my $maxtries = 5;
 1793: 	my $tries = 1;
 1794: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1795: 	    $response = &get_query_reply($queryid);
 1796: 	    $tries ++;
 1797: 	}
 1798: 
 1799:         if (!&error($response) && $response ne 'refused') {
 1800:             if ($response eq 'unavailable') {
 1801:                 $outcome = $response;
 1802:             } else {
 1803:                 $outcome = 'ok';
 1804:                 my @matches = split(/\n/,$response);
 1805:                 foreach my $match (@matches) {
 1806:                     my ($key,$value) = split(/=/,$match);
 1807:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1808:                 }
 1809:             }
 1810:         }
 1811:     }
 1812:     return ($outcome,%results);
 1813: }
 1814: 
 1815: sub usersearch {
 1816:     my ($srch) = @_;
 1817:     my $dom = $srch->{'srchdomain'};
 1818:     my %results;
 1819:     my %libserv = &all_library();
 1820:     my $query = 'usersearch';
 1821:     foreach my $tryserver (keys(%libserv)) {
 1822:         if (&host_domain($tryserver) eq $dom) {
 1823:             my $host=&hostname($tryserver);
 1824:             my $queryid=
 1825:                 &reply("querysend:".&escape($query).':'.
 1826:                        &escape($srch->{'srchby'}).':'.
 1827:                        &escape($srch->{'srchtype'}).':'.
 1828:                        &escape($srch->{'srchterm'}),$tryserver);
 1829:             if ($queryid !~/^\Q$host\E\_/) {
 1830:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1831:                 next;
 1832:             }
 1833:             my $reply = &get_query_reply($queryid);
 1834:             my $maxtries = 1;
 1835:             my $tries = 1;
 1836:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1837:                 $reply = &get_query_reply($queryid);
 1838:                 $tries ++;
 1839:             }
 1840:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1841:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1842:             } else {
 1843:                 my @matches;
 1844:                 if ($reply =~ /\n/) {
 1845:                     @matches = split(/\n/,$reply);
 1846:                 } else {
 1847:                     @matches = split(/\&/,$reply);
 1848:                 }
 1849:                 foreach my $match (@matches) {
 1850:                     my ($uname,$udom,%userhash);
 1851:                     foreach my $entry (split(/:/,$match)) {
 1852:                         my ($key,$value) =
 1853:                             map {&unescape($_);} split(/=/,$entry);
 1854:                         $userhash{$key} = $value;
 1855:                         if ($key eq 'username') {
 1856:                             $uname = $value;
 1857:                         } elsif ($key eq 'domain') {
 1858:                             $udom = $value;
 1859:                         }
 1860:                     }
 1861:                     $results{$uname.':'.$udom} = \%userhash;
 1862:                 }
 1863:             }
 1864:         }
 1865:     }
 1866:     return %results;
 1867: }
 1868: 
 1869: sub get_instuser {
 1870:     my ($udom,$uname,$id) = @_;
 1871:     my $homeserver = &domain($udom,'primary');
 1872:     my ($outcome,%results);
 1873:     if ($homeserver ne '') {
 1874:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1875:                            &escape($id).':'.&escape($udom),$homeserver);
 1876:         my $host=&hostname($homeserver);
 1877:         if ($queryid !~/^\Q$host\E\_/) {
 1878:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1879:             return;
 1880:         }
 1881:         my $response = &get_query_reply($queryid);
 1882:         my $maxtries = 5;
 1883:         my $tries = 1;
 1884:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1885:             $response = &get_query_reply($queryid);
 1886:             $tries ++;
 1887:         }
 1888:         if (!&error($response) && $response ne 'refused') {
 1889:             if ($response eq 'unavailable') {
 1890:                 $outcome = $response;
 1891:             } else {
 1892:                 $outcome = 'ok';
 1893:                 my @matches = split(/\n/,$response);
 1894:                 foreach my $match (@matches) {
 1895:                     my ($key,$value) = split(/=/,$match);
 1896:                     $results{&unescape($key)} = &thaw_unescape($value);
 1897:                 }
 1898:             }
 1899:         }
 1900:     }
 1901:     my %userinfo;
 1902:     if (ref($results{$uname}) eq 'HASH') {
 1903:         %userinfo = %{$results{$uname}};
 1904:     } 
 1905:     return ($outcome,%userinfo);
 1906: }
 1907: 
 1908: sub inst_rulecheck {
 1909:     my ($udom,$uname,$id,$item,$rules) = @_;
 1910:     my %returnhash;
 1911:     if ($udom ne '') {
 1912:         if (ref($rules) eq 'ARRAY') {
 1913:             @{$rules} = map {&escape($_);} (@{$rules});
 1914:             my $rulestr = join(':',@{$rules});
 1915:             my $homeserver=&domain($udom,'primary');
 1916:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1917:                 my $response;
 1918:                 if ($item eq 'username') {                
 1919:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1920:                                               ':'.&escape($uname).':'.$rulestr,
 1921:                                               $homeserver));
 1922:                 } elsif ($item eq 'id') {
 1923:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1924:                                               ':'.&escape($id).':'.$rulestr,
 1925:                                               $homeserver));
 1926:                 } elsif ($item eq 'selfcreate') {
 1927:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1928:                                                &escape($udom).':'.&escape($uname).
 1929:                                               ':'.$rulestr,$homeserver));
 1930:                 }
 1931:                 if ($response ne 'refused') {
 1932:                     my @pairs=split(/\&/,$response);
 1933:                     foreach my $item (@pairs) {
 1934:                         my ($key,$value)=split(/=/,$item,2);
 1935:                         $key = &unescape($key);
 1936:                         next if ($key =~ /^error: 2 /);
 1937:                         $returnhash{$key}=&thaw_unescape($value);
 1938:                     }
 1939:                 }
 1940:             }
 1941:         }
 1942:     }
 1943:     return %returnhash;
 1944: }
 1945: 
 1946: sub inst_userrules {
 1947:     my ($udom,$check) = @_;
 1948:     my (%ruleshash,@ruleorder);
 1949:     if ($udom ne '') {
 1950:         my $homeserver=&domain($udom,'primary');
 1951:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1952:             my $response;
 1953:             if ($check eq 'id') {
 1954:                 $response=&reply('instidrules:'.&escape($udom),
 1955:                                  $homeserver);
 1956:             } elsif ($check eq 'email') {
 1957:                 $response=&reply('instemailrules:'.&escape($udom),
 1958:                                  $homeserver);
 1959:             } else {
 1960:                 $response=&reply('instuserrules:'.&escape($udom),
 1961:                                  $homeserver);
 1962:             }
 1963:             if (($response ne 'refused') && ($response ne 'error') && 
 1964:                 ($response ne 'unknown_cmd') && 
 1965:                 ($response ne 'no_such_host')) {
 1966:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1967:                 my @pairs=split(/\&/,$hashitems);
 1968:                 foreach my $item (@pairs) {
 1969:                     my ($key,$value)=split(/=/,$item,2);
 1970:                     $key = &unescape($key);
 1971:                     next if ($key =~ /^error: 2 /);
 1972:                     $ruleshash{$key}=&thaw_unescape($value);
 1973:                 }
 1974:                 my @esc_order = split(/\&/,$orderitems);
 1975:                 foreach my $item (@esc_order) {
 1976:                     push(@ruleorder,&unescape($item));
 1977:                 }
 1978:             }
 1979:         }
 1980:     }
 1981:     return (\%ruleshash,\@ruleorder);
 1982: }
 1983: 
 1984: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1985: 
 1986: sub get_domain_defaults {
 1987:     my ($domain) = @_;
 1988:     my $cachetime = 60*60*24;
 1989:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1990:     if (defined($cached)) {
 1991:         if (ref($result) eq 'HASH') {
 1992:             return %{$result};
 1993:         }
 1994:     }
 1995:     my %domdefaults;
 1996:     my %domconfig =
 1997:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1998:                                   'requestcourses','inststatus',
 1999:                                   'coursedefaults','usersessions',
 2000:                                   'requestauthor'],$domain);
 2001:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2002:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2003:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2004:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2005:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2006:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2007:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2008:     } else {
 2009:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2010:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2011:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2012:     }
 2013:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2014:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2015:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2016:         } else {
 2017:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2018:         }
 2019:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2020:         foreach my $item (@usertools) {
 2021:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2022:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2023:             }
 2024:         }
 2025:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2026:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2027:         }
 2028:     }
 2029:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2030:         foreach my $item ('official','unofficial','community') {
 2031:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2032:         }
 2033:     }
 2034:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2035:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2036:     }
 2037:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2038:         foreach my $item ('inststatustypes','inststatusorder') {
 2039:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2040:         }
 2041:     }
 2042:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2043:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2044:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2045:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
 2046:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
 2047:         }
 2048:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2049:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
 2050:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
 2051:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};           
 2052:         }
 2053:     }
 2054:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2055:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2056:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2057:         }
 2058:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2059:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2060:         }
 2061:     }
 2062:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2063:     return %domdefaults;
 2064: }
 2065: 
 2066: # --------------------------------------------------- Assign a key to a student
 2067: 
 2068: sub assign_access_key {
 2069: #
 2070: # a valid key looks like uname:udom#comments
 2071: # comments are being appended
 2072: #
 2073:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2074:     $kdom=
 2075:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2076:     $knum=
 2077:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2078:     $cdom=
 2079:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2080:     $cnum=
 2081:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2082:     $udom=$env{'user.name'} unless (defined($udom));
 2083:     $uname=$env{'user.domain'} unless (defined($uname));
 2084:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2085:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2086:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2087:                                                   # assigned to this person
 2088:                                                   # - this should not happen,
 2089:                                                   # unless something went wrong
 2090:                                                   # the first time around
 2091: # ready to assign
 2092:         $logentry=$1.'; '.$logentry;
 2093:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2094:                                                  $kdom,$knum) eq 'ok') {
 2095: # key now belongs to user
 2096: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2097:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2098:                 &appenv({'environment.'.$envkey => $ckey});
 2099:                 return 'ok';
 2100:             } else {
 2101:                 return 
 2102:   'error: Count not permanently assign key, will need to be re-entered later.';
 2103: 	    }
 2104:         } else {
 2105:             return 'error: Could not assign key, try again later.';
 2106:         }
 2107:     } elsif (!$existing{$ckey}) {
 2108: # the key does not exist
 2109: 	return 'error: The key does not exist';
 2110:     } else {
 2111: # the key is somebody else's
 2112: 	return 'error: The key is already in use';
 2113:     }
 2114: }
 2115: 
 2116: # ------------------------------------------ put an additional comment on a key
 2117: 
 2118: sub comment_access_key {
 2119: #
 2120: # a valid key looks like uname:udom#comments
 2121: # comments are being appended
 2122: #
 2123:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2124:     $cdom=
 2125:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2126:     $cnum=
 2127:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2128:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2129:     if ($existing{$ckey}) {
 2130:         $existing{$ckey}.='; '.$logentry;
 2131: # ready to assign
 2132:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2133:                                                  $cdom,$cnum) eq 'ok') {
 2134: 	    return 'ok';
 2135:         } else {
 2136: 	    return 'error: Count not store comment.';
 2137:         }
 2138:     } else {
 2139: # the key does not exist
 2140: 	return 'error: The key does not exist';
 2141:     }
 2142: }
 2143: 
 2144: # ------------------------------------------------------ Generate a set of keys
 2145: 
 2146: sub generate_access_keys {
 2147:     my ($number,$cdom,$cnum,$logentry)=@_;
 2148:     $cdom=
 2149:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2150:     $cnum=
 2151:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2152:     unless (&allowed('mky',$cdom)) { return 0; }
 2153:     unless (($cdom) && ($cnum)) { return 0; }
 2154:     if ($number>10000) { return 0; }
 2155:     sleep(2); # make sure don't get same seed twice
 2156:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2157:     my $total=0;
 2158:     for (my $i=1;$i<=$number;$i++) {
 2159:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2160:                   sprintf("%lx",int(100000*rand)).'-'.
 2161:                   sprintf("%lx",int(100000*rand));
 2162:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2163:        $newkey=~s/0/h/g; # and also 0 and O
 2164:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2165:        if ($existing{$newkey}) {
 2166:            $i--;
 2167:        } else {
 2168: 	  if (&put('accesskeys',
 2169:               { $newkey => '# generated '.localtime().
 2170:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2171:                            '; '.$logentry },
 2172: 		   $cdom,$cnum) eq 'ok') {
 2173:               $total++;
 2174: 	  }
 2175:        }
 2176:     }
 2177:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2178:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2179:     return $total;
 2180: }
 2181: 
 2182: # ------------------------------------------------------- Validate an accesskey
 2183: 
 2184: sub validate_access_key {
 2185:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2186:     $cdom=
 2187:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2188:     $cnum=
 2189:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2190:     $udom=$env{'user.domain'} unless (defined($udom));
 2191:     $uname=$env{'user.name'} unless (defined($uname));
 2192:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2193:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2194: }
 2195: 
 2196: # ------------------------------------- Find the section of student in a course
 2197: sub devalidate_getsection_cache {
 2198:     my ($udom,$unam,$courseid)=@_;
 2199:     my $hashid="$udom:$unam:$courseid";
 2200:     &devalidate_cache_new('getsection',$hashid);
 2201: }
 2202: 
 2203: sub courseid_to_courseurl {
 2204:     my ($courseid) = @_;
 2205:     #already url style courseid
 2206:     return $courseid if ($courseid =~ m{^/});
 2207: 
 2208:     if (exists($env{'course.'.$courseid.'.num'})) {
 2209: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2210: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2211: 	return "/$cdom/$cnum";
 2212:     }
 2213: 
 2214:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2215:     if (exists($courseinfo{'num'})) {
 2216: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2217:     }
 2218: 
 2219:     return undef;
 2220: }
 2221: 
 2222: sub getsection {
 2223:     my ($udom,$unam,$courseid)=@_;
 2224:     my $cachetime=1800;
 2225: 
 2226:     my $hashid="$udom:$unam:$courseid";
 2227:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2228:     if (defined($cached)) { return $result; }
 2229: 
 2230:     my %Pending; 
 2231:     my %Expired;
 2232:     #
 2233:     # Each role can either have not started yet (pending), be active, 
 2234:     #    or have expired.
 2235:     #
 2236:     # If there is an active role, we are done.
 2237:     #
 2238:     # If there is more than one role which has not started yet, 
 2239:     #     choose the one which will start sooner
 2240:     # If there is one role which has not started yet, return it.
 2241:     #
 2242:     # If there is more than one expired role, choose the one which ended last.
 2243:     # If there is a role which has expired, return it.
 2244:     #
 2245:     $courseid = &courseid_to_courseurl($courseid);
 2246:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2247:     foreach my $key (keys(%roleshash)) {
 2248:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2249:         my $section=$1;
 2250:         if ($key eq $courseid.'_st') { $section=''; }
 2251:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2252:         my $now=time;
 2253:         if (defined($end) && $end && ($now > $end)) {
 2254:             $Expired{$end}=$section;
 2255:             next;
 2256:         }
 2257:         if (defined($start) && $start && ($now < $start)) {
 2258:             $Pending{$start}=$section;
 2259:             next;
 2260:         }
 2261:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2262:     }
 2263:     #
 2264:     # Presumedly there will be few matching roles from the above
 2265:     # loop and the sorting time will be negligible.
 2266:     if (scalar(keys(%Pending))) {
 2267:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2268:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2269:     } 
 2270:     if (scalar(keys(%Expired))) {
 2271:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2272:         my $time = pop(@sorted);
 2273:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2274:     }
 2275:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2276: }
 2277: 
 2278: sub save_cache {
 2279:     &purge_remembered();
 2280:     #&Apache::loncommon::validate_page();
 2281:     undef(%env);
 2282:     undef($env_loaded);
 2283: }
 2284: 
 2285: my $to_remember=-1;
 2286: my %remembered;
 2287: my %accessed;
 2288: my $kicks=0;
 2289: my $hits=0;
 2290: sub make_key {
 2291:     my ($name,$id) = @_;
 2292:     if (length($id) > 65 
 2293: 	&& length(&escape($id)) > 200) {
 2294: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2295:     }
 2296:     return &escape($name.':'.$id);
 2297: }
 2298: 
 2299: sub devalidate_cache_new {
 2300:     my ($name,$id,$debug) = @_;
 2301:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2302:     $id=&make_key($name,$id);
 2303:     $memcache->delete($id);
 2304:     delete($remembered{$id});
 2305:     delete($accessed{$id});
 2306: }
 2307: 
 2308: sub is_cached_new {
 2309:     my ($name,$id,$debug) = @_;
 2310:     $id=&make_key($name,$id);
 2311:     if (exists($remembered{$id})) {
 2312: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2313: 	$accessed{$id}=[&gettimeofday()];
 2314: 	$hits++;
 2315: 	return ($remembered{$id},1);
 2316:     }
 2317:     my $value = $memcache->get($id);
 2318:     if (!(defined($value))) {
 2319: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2320: 	return (undef,undef);
 2321:     }
 2322:     if ($value eq '__undef__') {
 2323: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2324: 	$value=undef;
 2325:     }
 2326:     &make_room($id,$value,$debug);
 2327:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2328:     return ($value,1);
 2329: }
 2330: 
 2331: sub do_cache_new {
 2332:     my ($name,$id,$value,$time,$debug) = @_;
 2333:     $id=&make_key($name,$id);
 2334:     my $setvalue=$value;
 2335:     if (!defined($setvalue)) {
 2336: 	$setvalue='__undef__';
 2337:     }
 2338:     if (!defined($time) ) {
 2339: 	$time=600;
 2340:     }
 2341:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2342:     my $result = $memcache->set($id,$setvalue,$time);
 2343:     if (! $result) {
 2344: 	&logthis("caching of id -> $id  failed");
 2345: 	$memcache->disconnect_all();
 2346:     }
 2347:     # need to make a copy of $value
 2348:     &make_room($id,$value,$debug);
 2349:     return $value;
 2350: }
 2351: 
 2352: sub make_room {
 2353:     my ($id,$value,$debug)=@_;
 2354: 
 2355:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2356:                                     : $value;
 2357:     if ($to_remember<0) { return; }
 2358:     $accessed{$id}=[&gettimeofday()];
 2359:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2360:     my $to_kick;
 2361:     my $max_time=0;
 2362:     foreach my $other (keys(%accessed)) {
 2363: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2364: 	    $to_kick=$other;
 2365: 	    $max_time=&tv_interval($accessed{$other});
 2366: 	}
 2367:     }
 2368:     delete($remembered{$to_kick});
 2369:     delete($accessed{$to_kick});
 2370:     $kicks++;
 2371:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2372:     return;
 2373: }
 2374: 
 2375: sub purge_remembered {
 2376:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2377:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2378:     undef(%remembered);
 2379:     undef(%accessed);
 2380: }
 2381: # ------------------------------------- Read an entry from a user's environment
 2382: 
 2383: sub userenvironment {
 2384:     my ($udom,$unam,@what)=@_;
 2385:     my $items;
 2386:     foreach my $item (@what) {
 2387:         $items.=&escape($item).'&';
 2388:     }
 2389:     $items=~s/\&$//;
 2390:     my %returnhash=();
 2391:     my $uhome = &homeserver($unam,$udom);
 2392:     unless ($uhome eq 'no_host') {
 2393:         my @answer=split(/\&/, 
 2394:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2395:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2396:             return %returnhash;
 2397:         }
 2398:         my $i;
 2399:         for ($i=0;$i<=$#what;$i++) {
 2400: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2401:         }
 2402:     }
 2403:     return %returnhash;
 2404: }
 2405: 
 2406: # ---------------------------------------------------------- Get a studentphoto
 2407: sub studentphoto {
 2408:     my ($udom,$unam,$ext) = @_;
 2409:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2410:     if (defined($env{'request.course.id'})) {
 2411:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2412:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2413:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2414:             } else {
 2415:                 my ($result,$perm_reqd)=
 2416: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2417:                 if ($result eq 'ok') {
 2418:                     if (!($perm_reqd eq 'yes')) {
 2419:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2420:                     }
 2421:                 }
 2422:             }
 2423:         }
 2424:     } else {
 2425:         my ($result,$perm_reqd) = 
 2426: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2427:         if ($result eq 'ok') {
 2428:             if (!($perm_reqd eq 'yes')) {
 2429:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2430:             }
 2431:         }
 2432:     }
 2433:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2434: }
 2435: 
 2436: sub retrievestudentphoto {
 2437:     my ($udom,$unam,$ext,$type) = @_;
 2438:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2439:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2440:     if ($ret eq 'ok') {
 2441:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2442:         if ($type eq 'thumbnail') {
 2443:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2444:         }
 2445:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2446:         return $tokenurl;
 2447:     } else {
 2448:         if ($type eq 'thumbnail') {
 2449:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2450:         } else { 
 2451:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2452:         }
 2453:     }
 2454: }
 2455: 
 2456: # -------------------------------------------------------------------- New chat
 2457: 
 2458: sub chatsend {
 2459:     my ($newentry,$anon,$group)=@_;
 2460:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2461:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2462:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2463:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2464: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2465: 		   &escape($newentry)).':'.$group,$chome);
 2466: }
 2467: 
 2468: # ------------------------------------------ Find current version of a resource
 2469: 
 2470: sub getversion {
 2471:     my $fname=&clutter(shift);
 2472:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2473:     return &currentversion(&filelocation('',$fname));
 2474: }
 2475: 
 2476: sub currentversion {
 2477:     my $fname=shift;
 2478:     my $author=$fname;
 2479:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2480:     my ($udom,$uname)=split(/\//,$author);
 2481:     my $home=&homeserver($uname,$udom);
 2482:     if ($home eq 'no_host') { 
 2483:         return -1; 
 2484:     }
 2485:     my $answer=&reply("currentversion:$fname",$home);
 2486:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2487: 	return -1;
 2488:     }
 2489:     return $answer;
 2490: }
 2491: 
 2492: #
 2493: # Return special version number of resource if set by override, empty otherwise
 2494: #
 2495: sub usedversion {
 2496:     my $fname=shift;
 2497:     unless ($fname) { $fname=$env{'request.uri'}; }
 2498:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2499:     if ($urlversion) { return $urlversion; }
 2500:     return '';
 2501: }
 2502: 
 2503: # ----------------------------- Subscribe to a resource, return URL if possible
 2504: 
 2505: sub subscribe {
 2506:     my $fname=shift;
 2507:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2508:     $fname=~s/[\n\r]//g;
 2509:     my $author=$fname;
 2510:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2511:     my ($udom,$uname)=split(/\//,$author);
 2512:     my $home=homeserver($uname,$udom);
 2513:     if ($home eq 'no_host') {
 2514:         return 'not_found';
 2515:     }
 2516:     my $answer=reply("sub:$fname",$home);
 2517:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2518: 	$answer.=' by '.$home;
 2519:     }
 2520:     return $answer;
 2521: }
 2522:     
 2523: # -------------------------------------------------------------- Replicate file
 2524: 
 2525: sub repcopy {
 2526:     my $filename=shift;
 2527:     $filename=~s/\/+/\//g;
 2528:     my $londocroot = $perlvar{'lonDocRoot'};
 2529:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2530:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2531:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2532: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2533: 	return &repcopy_userfile($filename);
 2534:     }
 2535:     $filename=~s/[\n\r]//g;
 2536:     my $transname="$filename.in.transfer";
 2537: # FIXME: this should flock
 2538:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2539:     my $remoteurl=subscribe($filename);
 2540:     if ($remoteurl =~ /^con_lost by/) {
 2541: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2542:            return 'unavailable';
 2543:     } elsif ($remoteurl eq 'not_found') {
 2544: 	   #&logthis("Subscribe returned not_found: $filename");
 2545: 	   return 'not_found';
 2546:     } elsif ($remoteurl =~ /^rejected by/) {
 2547: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2548:            return 'forbidden';
 2549:     } elsif ($remoteurl eq 'directory') {
 2550:            return 'ok';
 2551:     } else {
 2552:         my $author=$filename;
 2553:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2554:         my ($udom,$uname)=split(/\//,$author);
 2555:         my $home=homeserver($uname,$udom);
 2556:         unless ($home eq $perlvar{'lonHostID'}) {
 2557:            my @parts=split(/\//,$filename);
 2558:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2559:            if ($path ne "$londocroot/res") {
 2560:                &logthis("Malconfiguration for replication: $filename");
 2561: 	       return 'bad_request';
 2562:            }
 2563:            my $count;
 2564:            for ($count=5;$count<$#parts;$count++) {
 2565:                $path.="/$parts[$count]";
 2566:                if ((-e $path)!=1) {
 2567: 		   mkdir($path,0777);
 2568:                }
 2569:            }
 2570:            my $ua=new LWP::UserAgent;
 2571:            my $request=new HTTP::Request('GET',"$remoteurl");
 2572:            my $response=$ua->request($request,$transname);
 2573:            if ($response->is_error()) {
 2574: 	       unlink($transname);
 2575:                my $message=$response->status_line;
 2576:                &logthis("<font color=\"blue\">WARNING:"
 2577:                        ." LWP get: $message: $filename</font>");
 2578:                return 'unavailable';
 2579:            } else {
 2580: 	       if ($remoteurl!~/\.meta$/) {
 2581:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2582:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2583:                   if ($mresponse->is_error()) {
 2584: 		      unlink($filename.'.meta');
 2585:                       &logthis(
 2586:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2587:                   }
 2588: 	       }
 2589:                rename($transname,$filename);
 2590:                return 'ok';
 2591:            }
 2592:        }
 2593:     }
 2594: }
 2595: 
 2596: # ------------------------------------------------ Get server side include body
 2597: sub ssi_body {
 2598:     my ($filelink,%form)=@_;
 2599:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2600:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2601:     }
 2602:     my $output='';
 2603:     my $response;
 2604:     if ($filelink=~/^https?\:/) {
 2605:        ($output,$response)=&externalssi($filelink);
 2606:     } else {
 2607:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2608:        $filelink .= 'inhibitmenu=yes';
 2609:        ($output,$response)=&ssi($filelink,%form);
 2610:     }
 2611:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2612:     $output=~s/^.*?\<body[^\>]*\>//si;
 2613:     $output=~s/\<\/body\s*\>.*?$//si;
 2614:     if (wantarray) {
 2615:         return ($output, $response);
 2616:     } else {
 2617:         return $output;
 2618:     }
 2619: }
 2620: 
 2621: # --------------------------------------------------------- Server Side Include
 2622: 
 2623: sub absolute_url {
 2624:     my ($host_name) = @_;
 2625:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2626:     if ($host_name eq '') {
 2627: 	$host_name = $ENV{'SERVER_NAME'};
 2628:     }
 2629:     return $protocol.$host_name;
 2630: }
 2631: 
 2632: #
 2633: #   Server side include.
 2634: # Parameters:
 2635: #  fn     Possibly encrypted resource name/id.
 2636: #  form   Hash that describes how the rendering should be done
 2637: #         and other things.
 2638: # Returns:
 2639: #   Scalar context: The content of the response.
 2640: #   Array context:  2 element list of the content and the full response object.
 2641: #     
 2642: sub ssi {
 2643: 
 2644:     my ($fn,%form)=@_;
 2645:     my $ua=new LWP::UserAgent;
 2646:     my $request;
 2647: 
 2648:     $form{'no_update_last_known'}=1;
 2649:     &Apache::lonenc::check_encrypt(\$fn);
 2650:     if (%form) {
 2651:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2652:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2653:     } else {
 2654:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2655:     }
 2656: 
 2657:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2658:     my $response= $ua->request($request);
 2659:     my $content = $response->content;
 2660: 
 2661: 
 2662:     if (wantarray) {
 2663: 	return ($content, $response);
 2664:     } else {
 2665: 	return $content;
 2666:     }
 2667: }
 2668: 
 2669: sub externalssi {
 2670:     my ($url)=@_;
 2671:     my $ua=new LWP::UserAgent;
 2672:     my $request=new HTTP::Request('GET',$url);
 2673:     my $response=$ua->request($request);
 2674:     if (wantarray) {
 2675:         return ($response->content, $response);
 2676:     } else {
 2677:         return $response->content;
 2678:     }
 2679: }
 2680: 
 2681: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2682: 
 2683: sub allowuploaded {
 2684:     my ($srcurl,$url)=@_;
 2685:     $url=&clutter(&declutter($url));
 2686:     my $dir=$url;
 2687:     $dir=~s/\/[^\/]+$//;
 2688:     my %httpref=();
 2689:     my $httpurl=&hreflocation('',$url);
 2690:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2691:     &Apache::lonnet::appenv(\%httpref);
 2692: }
 2693: 
 2694: #
 2695: # Determine if the current user should be able to edit a particular resource,
 2696: # when viewing in course context.
 2697: # (a) When viewing resource used to determine if "Edit" item is included in 
 2698: #     Functions.
 2699: # (b) When displaying folder contents in course editor, used to determine if
 2700: #     "Edit" link will be displayed alongside resource.
 2701: #
 2702: #  input: six args -- filename (decluttered), course number, course domain,
 2703: #                   url, symb (if registered) and group (if this is a group
 2704: #                   item -- e.g., bulletin board, group page etc.).
 2705: #  output: array of five scalars -- 
 2706: #          $cfile -- url for file editing if editable on current server
 2707: #          $home -- homeserver of resource (i.e., for author if published,
 2708: #                                           or course if uploaded.).
 2709: #          $switchserver --  1 if server switch will be needed.
 2710: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2711: #          $forceview -- 1 if icon/link should be to go to view mode
 2712: #
 2713: 
 2714: sub can_edit_resource {
 2715:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2716:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2717: #
 2718: # For aboutme pages user can only edit his/her own.
 2719: #
 2720:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2721:         my ($sdom,$sname) = ($1,$2);
 2722:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2723:             $home = $env{'user.home'};
 2724:             $cfile = $resurl;
 2725:             if ($env{'form.forceedit'}) {
 2726:                 $forceview = 1;
 2727:             } else {
 2728:                 $forceedit = 1;
 2729:             }
 2730:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2731:         } else {
 2732:             return;
 2733:         }
 2734:     }
 2735: 
 2736:     if ($env{'request.course.id'}) {
 2737:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2738:         if ($group ne '') {
 2739: # if this is a group homepage or group bulletin board, check group privs
 2740:             my $allowed = 0;
 2741:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2742:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2743:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2744:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2745:                     $allowed = 1;
 2746:                 }
 2747:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2748:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2749:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2750:                     $allowed = 1;
 2751:                 }
 2752:             }
 2753:             if ($allowed) {
 2754:                 $home=&homeserver($cnum,$cdom);
 2755:                 if ($env{'form.forceedit'}) {
 2756:                     $forceview = 1;
 2757:                 } else {
 2758:                     $forceedit = 1;
 2759:                 }
 2760:                 $cfile = $resurl;
 2761:             } else {
 2762:                 return;
 2763:             }
 2764:         } else {
 2765:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2766:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2767:                     return;
 2768:                 }
 2769:             } elsif (!$crsedit) {
 2770: #
 2771: # No edit allowed where CC has switched to student role.
 2772: #
 2773:                 return;
 2774:             }
 2775:         }
 2776:     }
 2777: 
 2778:     if ($file ne '') {
 2779:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2780:             if (&is_course_upload($file,$cnum,$cdom)) {
 2781:                 $uploaded = 1;
 2782:                 $incourse = 1;
 2783:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2784:                     $cfile = &hreflocation('',$file);
 2785:                     if ($env{'form.forceedit'}) {
 2786:                         $forceview = 1;
 2787:                     } else {
 2788:                         $forceedit = 1;
 2789:                     }
 2790:                 }
 2791:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2792:                 $incourse = 1;
 2793:                 if ($env{'form.forceedit'}) {
 2794:                     $forceview = 1;
 2795:                 } else {
 2796:                     $forceedit = 1;
 2797:                 }
 2798:                 $cfile = $resurl;
 2799:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2800:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2801:                     $incourse = 1;
 2802:                     if ($env{'form.forceedit'}) {
 2803:                         $forceview = 1;
 2804:                     } else {
 2805:                         $forceedit = 1;
 2806:                     }
 2807:                     $cfile = $resurl;
 2808:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2809:                     $incourse = 1;
 2810:                     $cfile = $resurl.'/smpedit';
 2811:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2812:                     $incourse = 1;
 2813:                     if ($env{'form.forceedit'}) {
 2814:                         $forceview = 1;
 2815:                     } else {
 2816:                         $forceedit = 1;
 2817:                     }
 2818:                     $cfile = $resurl;
 2819:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2820:                     $incourse = 1;
 2821:                     if ($env{'form.forceedit'}) {
 2822:                         $forceview = 1;
 2823:                     } else {
 2824:                         $forceedit = 1;
 2825:                     }
 2826:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2827:                 }
 2828:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2829:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2830:                 if (&is_on_map($template)) { 
 2831:                     $incourse = 1;
 2832:                     $forceview = 1;
 2833:                     $cfile = $template;
 2834:                 }
 2835:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2836:                     $incourse = 1;
 2837:                     if ($env{'form.forceedit'}) {
 2838:                         $forceview = 1;
 2839:                     } else {
 2840:                         $forceedit = 1;
 2841:                     }
 2842:                     $cfile = $resurl;
 2843:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2844:                 $incourse = 1;
 2845:                 $forceview = 1;
 2846:                 if ($symb) {
 2847:                     my ($map,$id,$res)=&decode_symb($symb);
 2848:                     $env{'request.symb'} = $symb;
 2849:                     $cfile = &clutter($res);
 2850:                 } else {
 2851:                     $cfile = $env{'form.suppurl'};
 2852:                     $cfile =~ s{^http://}{};
 2853:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2854:                 }
 2855:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2856:                 if ($env{'form.forceedit'}) {
 2857:                     $forceview = 1;
 2858:                 } else {
 2859:                     $forceedit = 1;
 2860:                 }
 2861:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2862:             }
 2863:         }
 2864:         if ($uploaded || $incourse) {
 2865:             $home=&homeserver($cnum,$cdom);
 2866:         } elsif ($file !~ m{/$}) {
 2867:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2868:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2869:             # Check that the user has permission to edit this resource
 2870:             my $setpriv = 1;
 2871:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2872:             if (defined($cfudom)) {
 2873:                 $home=&homeserver($cfuname,$cfudom);
 2874:                 $cfile=$file;
 2875:             }
 2876:         }
 2877:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2878:             (($home ne '') && ($home ne 'no_host'))) {
 2879:             my @ids=&current_machine_ids();
 2880:             unless (grep(/^\Q$home\E$/,@ids)) {
 2881:                 $switchserver=1;
 2882:             }
 2883:         }
 2884:     }
 2885:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2886: }
 2887: 
 2888: sub is_course_upload {
 2889:     my ($file,$cnum,$cdom) = @_;
 2890:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2891:     $uploadpath =~ s{^\/}{};
 2892:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2893:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2894:         return 1;
 2895:     }
 2896:     return;
 2897: }
 2898: 
 2899: sub in_course {
 2900:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2901:     if ($hideprivileged) {
 2902:         my $skipuser;
 2903:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2904:         my @possdoms = ($cdom);  
 2905:         if ($coursehash{'checkforpriv'}) { 
 2906:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2907:         }
 2908:         if (&privileged($uname,$udom,\@possdoms)) {
 2909:             $skipuser = 1;
 2910:             if ($coursehash{'nothideprivileged'}) {
 2911:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2912:                     my $user;
 2913:                     if ($item =~ /:/) {
 2914:                         $user = $item;
 2915:                     } else {
 2916:                         $user = join(':',split(/[\@]/,$item));
 2917:                     }
 2918:                     if ($user eq $uname.':'.$udom) {
 2919:                         undef($skipuser);
 2920:                         last;
 2921:                     }
 2922:                 }
 2923:             }
 2924:             if ($skipuser) {
 2925:                 return 0;
 2926:             }
 2927:         }
 2928:     }
 2929:     $type ||= 'any';
 2930:     if (!defined($cdom) || !defined($cnum)) {
 2931:         my $cid  = $env{'request.course.id'};
 2932:         $cdom = $env{'course.'.$cid.'.domain'};
 2933:         $cnum = $env{'course.'.$cid.'.num'};
 2934:     }
 2935:     my $typesref;
 2936:     if (($type eq 'any') || ($type eq 'all')) {
 2937:         $typesref = ['active','previous','future'];
 2938:     } elsif ($type eq 'previous' || $type eq 'future') {
 2939:         $typesref = [$type];
 2940:     }
 2941:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2942:                               $typesref,undef,[$cdom]);
 2943:     my ($tmp) = keys(%roles);
 2944:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2945:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2946:     if (@course_roles > 0) {
 2947:         return 1;
 2948:     }
 2949:     return 0;
 2950: }
 2951: 
 2952: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2953: # input: action, courseID, current domain, intended
 2954: #        path to file, source of file, instruction to parse file for objects,
 2955: #        ref to hash for embedded objects,
 2956: #        ref to hash for codebase of java objects.
 2957: #        reference to scalar to accommodate mime type determined
 2958: #          from File::MMagic if $parser = parse.
 2959: #
 2960: # output: url to file (if action was uploaddoc), 
 2961: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2962: #
 2963: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2964: # course.
 2965: #
 2966: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2967: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2968: #          course's home server.
 2969: #
 2970: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2971: #          be copied from $source (current location) to 
 2972: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2973: #         and will then be copied to
 2974: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2975: #         course's home server.
 2976: #
 2977: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2978: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2979: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2980: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2981: #         in course's home server.
 2982: #
 2983: 
 2984: sub process_coursefile {
 2985:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2986:         $mimetype)=@_;
 2987:     my $fetchresult;
 2988:     my $home=&homeserver($docuname,$docudom);
 2989:     if ($action eq 'propagate') {
 2990:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2991: 			     $home);
 2992:     } else {
 2993:         my $fpath = '';
 2994:         my $fname = $file;
 2995:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2996:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2997:         my $filepath = &build_filepath($fpath);
 2998:         if ($action eq 'copy') {
 2999:             if ($source eq '') {
 3000:                 $fetchresult = 'no source file';
 3001:                 return $fetchresult;
 3002:             } else {
 3003:                 my $destination = $filepath.'/'.$fname;
 3004:                 rename($source,$destination);
 3005:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3006:                                  $home);
 3007:             }
 3008:         } elsif ($action eq 'uploaddoc') {
 3009:             open(my $fh,'>'.$filepath.'/'.$fname);
 3010:             print $fh $env{'form.'.$source};
 3011:             close($fh);
 3012:             if ($parser eq 'parse') {
 3013:                 my $mm = new File::MMagic;
 3014:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3015:                 if ($type eq 'text/html') {
 3016:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3017:                     unless ($parse_result eq 'ok') {
 3018:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3019:                     }
 3020:                 }
 3021:                 if (ref($mimetype)) {
 3022:                     $$mimetype = $type;
 3023:                 } 
 3024:             }
 3025:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3026:                                  $home);
 3027:             if ($fetchresult eq 'ok') {
 3028:                 return '/uploaded/'.$fpath.'/'.$fname;
 3029:             } else {
 3030:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3031:                         ' to host '.$home.': '.$fetchresult);
 3032:                 return '/adm/notfound.html';
 3033:             }
 3034:         }
 3035:     }
 3036:     unless ( $fetchresult eq 'ok') {
 3037:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3038:              ' to host '.$home.': '.$fetchresult);
 3039:     }
 3040:     return $fetchresult;
 3041: }
 3042: 
 3043: sub build_filepath {
 3044:     my ($fpath) = @_;
 3045:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3046:     unless ($fpath eq '') {
 3047:         my @parts=split('/',$fpath);
 3048:         foreach my $part (@parts) {
 3049:             $filepath.= '/'.$part;
 3050:             if ((-e $filepath)!=1) {
 3051:                 mkdir($filepath,0777);
 3052:             }
 3053:         }
 3054:     }
 3055:     return $filepath;
 3056: }
 3057: 
 3058: sub store_edited_file {
 3059:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3060:     my $file = $primary_url;
 3061:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3062:     my $fpath = '';
 3063:     my $fname = $file;
 3064:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3065:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3066:     my $filepath = &build_filepath($fpath);
 3067:     open(my $fh,'>'.$filepath.'/'.$fname);
 3068:     print $fh $content;
 3069:     close($fh);
 3070:     my $home=&homeserver($docuname,$docudom);
 3071:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3072: 			  $home);
 3073:     if ($$fetchresult eq 'ok') {
 3074:         return '/uploaded/'.$fpath.'/'.$fname;
 3075:     } else {
 3076:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3077: 		 ' to host '.$home.': '.$$fetchresult);
 3078:         return '/adm/notfound.html';
 3079:     }
 3080: }
 3081: 
 3082: sub clean_filename {
 3083:     my ($fname,$args)=@_;
 3084: # Replace Windows backslashes by forward slashes
 3085:     $fname=~s/\\/\//g;
 3086:     if (!$args->{'keep_path'}) {
 3087:         # Get rid of everything but the actual filename
 3088: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3089:     }
 3090: # Replace spaces by underscores
 3091:     $fname=~s/\s+/\_/g;
 3092: # Replace all other weird characters by nothing
 3093:     $fname=~s{[^/\w\.\-]}{}g;
 3094: # Replace all .\d. sequences with _\d. so they no longer look like version
 3095: # numbers
 3096:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3097:     return $fname;
 3098: }
 3099: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3100: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3101: # image with the same aspect ratio as the original, but with dimensions which do 
 3102: # not exceed $resizewidth and $resizeheight.
 3103:  
 3104: sub resizeImage {
 3105:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3106:     my $ima = Image::Magick->new;
 3107:     my $resized;
 3108:     if (-e $img_path) {
 3109:         $ima->Read($img_path);
 3110:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3111:             my $width = $ima->Get('width');
 3112:             my $height = $ima->Get('height');
 3113:             if ($width > $resizewidth) {
 3114: 	        my $factor = $width/$resizewidth;
 3115:                 my $newheight = $height/$factor;
 3116:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3117:                 $resized = 1;
 3118:             }
 3119:         }
 3120:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3121:             my $width = $ima->Get('width');
 3122:             my $height = $ima->Get('height');
 3123:             if ($height > $resizeheight) {
 3124:                 my $factor = $height/$resizeheight;
 3125:                 my $newwidth = $width/$factor;
 3126:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3127:                 $resized = 1;
 3128:             }
 3129:         }
 3130:         if ($resized) {
 3131:             $ima->Write($img_path);
 3132:         }
 3133:     }
 3134:     return;
 3135: }
 3136: 
 3137: # --------------- Take an uploaded file and put it into the userfiles directory
 3138: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3139: #                    the desired filename is in $env{"form.$formname.filename"}
 3140: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3141: #                                    canceloverwrite, or ''. 
 3142: #                   if 'coursedoc': upload to the current course
 3143: #                   if 'existingfile': write file to tmp/overwrites directory 
 3144: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3145: #                   $context is passed as argument to &finishuserfileupload
 3146: #        $subdir - directory in userfile to store the file into
 3147: #        $parser - instruction to parse file for objects ($parser = parse)    
 3148: #        $allfiles - reference to hash for embedded objects
 3149: #        $codebase - reference to hash for codebase of java objects
 3150: #        $desuname - username for permanent storage of uploaded file
 3151: #        $dsetudom - domain for permanaent storage of uploaded file
 3152: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3153: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3154: #        $resizewidth - width (pixels) to which to resize uploaded image
 3155: #        $resizeheight - height (pixels) to which to resize uploaded image
 3156: #        $mimetype - reference to scalar to accommodate mime type determined
 3157: #                    from File::MMagic.
 3158: # 
 3159: # output: url of file in userspace, or error: <message> 
 3160: #             or /adm/notfound.html if failure to upload occurse
 3161: 
 3162: sub userfileupload {
 3163:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3164:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3165:     if (!defined($subdir)) { $subdir='unknown'; }
 3166:     my $fname=$env{'form.'.$formname.'.filename'};
 3167:     $fname=&clean_filename($fname);
 3168:     # See if there is anything left
 3169:     unless ($fname) { return 'error: no uploaded file'; }
 3170:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3171:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3172:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3173:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3174:         my $now = time;
 3175:         my $filepath;
 3176:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3177:              $filepath = 'tmp/helprequests/'.$now;
 3178:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3179:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3180:                          '_'.$env{'user.domain'}.'/pending';
 3181:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3182:             my ($docuname,$docudom);
 3183:             if ($destudom) {
 3184:                 $docudom = $destudom;
 3185:             } else {
 3186:                 $docudom = $env{'user.domain'};
 3187:             }
 3188:             if ($destuname) {
 3189:                 $docuname = $destuname;
 3190:             } else {
 3191:                 $docuname = $env{'user.name'};
 3192:             }
 3193:             if (exists($env{'form.group'})) {
 3194:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3195:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3196:             }
 3197:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3198:             if ($context eq 'canceloverwrite') {
 3199:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3200:                 if (-e  $tempfile) {
 3201:                     my @info = stat($tempfile);
 3202:                     if ($info[9] eq $env{'form.timestamp'}) {
 3203:                         unlink($tempfile);
 3204:                     }
 3205:                 }
 3206:                 return;
 3207:             }
 3208:         }
 3209:         # Create the directory if not present
 3210:         my @parts=split(/\//,$filepath);
 3211:         my $fullpath = $perlvar{'lonDaemons'};
 3212:         for (my $i=0;$i<@parts;$i++) {
 3213:             $fullpath .= '/'.$parts[$i];
 3214:             if ((-e $fullpath)!=1) {
 3215:                 mkdir($fullpath,0777);
 3216:             }
 3217:         }
 3218:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3219:         print $fh $env{'form.'.$formname};
 3220:         close($fh);
 3221:         if ($context eq 'existingfile') {
 3222:             my @info = stat($fullpath.'/'.$fname);
 3223:             return ($fullpath.'/'.$fname,$info[9]);
 3224:         } else {
 3225:             return $fullpath.'/'.$fname;
 3226:         }
 3227:     }
 3228:     if ($subdir eq 'scantron') {
 3229:         $fname = 'scantron_orig_'.$fname;
 3230:     } else {
 3231:         $fname="$subdir/$fname";
 3232:     }
 3233:     if ($context eq 'coursedoc') {
 3234: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3235: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3236:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3237:             return &finishuserfileupload($docuname,$docudom,
 3238: 					 $formname,$fname,$parser,$allfiles,
 3239: 					 $codebase,$thumbwidth,$thumbheight,
 3240:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3241:         } else {
 3242:             if ($env{'form.folder'}) {
 3243:                 $fname=$env{'form.folder'}.'/'.$fname;
 3244:             }
 3245:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3246: 				       $fname,$formname,$parser,
 3247: 				       $allfiles,$codebase,$mimetype);
 3248:         }
 3249:     } elsif (defined($destuname)) {
 3250:         my $docuname=$destuname;
 3251:         my $docudom=$destudom;
 3252: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3253: 				     $parser,$allfiles,$codebase,
 3254:                                      $thumbwidth,$thumbheight,
 3255:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3256:     } else {
 3257:         my $docuname=$env{'user.name'};
 3258:         my $docudom=$env{'user.domain'};
 3259:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3260:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3261:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3262:         }
 3263: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3264: 				     $parser,$allfiles,$codebase,
 3265:                                      $thumbwidth,$thumbheight,
 3266:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3267:     }
 3268: }
 3269: 
 3270: sub finishuserfileupload {
 3271:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3272:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3273:     my $path=$docudom.'/'.$docuname.'/';
 3274:     my $filepath=$perlvar{'lonDocRoot'};
 3275:   
 3276:     my ($fnamepath,$file,$fetchthumb);
 3277:     $file=$fname;
 3278:     if ($fname=~m|/|) {
 3279:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3280: 	$path.=$fnamepath.'/';
 3281:     }
 3282:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3283:     my $count;
 3284:     for ($count=4;$count<=$#parts;$count++) {
 3285:         $filepath.="/$parts[$count]";
 3286:         if ((-e $filepath)!=1) {
 3287: 	    mkdir($filepath,0777);
 3288:         }
 3289:     }
 3290: 
 3291: # Save the file
 3292:     {
 3293: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3294: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3295: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3296: 	    return '/adm/notfound.html';
 3297: 	}
 3298:         if ($context eq 'overwrite') {
 3299:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3300:             my $target = $filepath.'/'.$file;
 3301:             if (-e $source) {
 3302:                 my @info = stat($source);
 3303:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3304:                     unless (&File::Copy::move($source,$target)) {
 3305:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3306:                         return "Moving from $source failed";
 3307:                     }
 3308:                 } else {
 3309:                     return "Temporary file: $source had unexpected date/time for last modification";
 3310:                 }
 3311:             } else {
 3312:                 return "Temporary file: $source missing";
 3313:             }
 3314:         } elsif (!print FH ($env{'form.'.$formname})) {
 3315: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3316: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3317: 	    return '/adm/notfound.html';
 3318: 	}
 3319: 	close(FH);
 3320:         if ($resizewidth && $resizeheight) {
 3321:             my $mm = new File::MMagic;
 3322:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3323:             if ($mime_type =~ m{^image/}) {
 3324: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3325:             }  
 3326: 	}
 3327:     }
 3328:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3329:         if (ref($mimetype)) {
 3330:             if ($$mimetype eq '') {
 3331:                 my $mm = new File::MMagic;
 3332:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3333:                 $$mimetype = $type;
 3334:             }
 3335:         }
 3336:     }
 3337:     if ($parser eq 'parse') {
 3338:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3339:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3340:                                                        $allfiles,$codebase);
 3341:             unless ($parse_result eq 'ok') {
 3342:                 &logthis('Failed to parse '.$filepath.$file.
 3343: 	   	         ' for embedded media: '.$parse_result); 
 3344:             }
 3345:         }
 3346:     }
 3347:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3348:         my $input = $filepath.'/'.$file;
 3349:         my $output = $filepath.'/'.'tn-'.$file;
 3350:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3351:         system("convert -sample $thumbsize $input $output");
 3352:         if (-e $filepath.'/'.'tn-'.$file) {
 3353:             $fetchthumb  = 1; 
 3354:         }
 3355:     }
 3356:  
 3357: # Notify homeserver to grep it
 3358: #
 3359:     my $docuhome=&homeserver($docuname,$docudom);	
 3360:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3361:     if ($fetchresult eq 'ok') {
 3362:         if ($fetchthumb) {
 3363:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3364:             if ($thumbresult ne 'ok') {
 3365:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3366:                          $docuhome.': '.$thumbresult);
 3367:             }
 3368:         }
 3369: #
 3370: # Return the URL to it
 3371:         return '/uploaded/'.$path.$file;
 3372:     } else {
 3373:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3374: 		 ': '.$fetchresult);
 3375:         return '/adm/notfound.html';
 3376:     }
 3377: }
 3378: 
 3379: sub extract_embedded_items {
 3380:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3381:     my @state = ();
 3382:     my (%lastids,%related,%shockwave,%flashvars);
 3383:     my %javafiles = (
 3384:                       codebase => '',
 3385:                       code => '',
 3386:                       archive => ''
 3387:                     );
 3388:     my %mediafiles = (
 3389:                       src => '',
 3390:                       movie => '',
 3391:                      );
 3392:     my $p;
 3393:     if ($content) {
 3394:         $p = HTML::LCParser->new($content);
 3395:     } else {
 3396:         $p = HTML::LCParser->new($fullpath);
 3397:     }
 3398:     while (my $t=$p->get_token()) {
 3399: 	if ($t->[0] eq 'S') {
 3400: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3401: 	    push(@state, $tagname);
 3402:             if (lc($tagname) eq 'allow') {
 3403:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3404:             }
 3405: 	    if (lc($tagname) eq 'img') {
 3406: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3407: 	    }
 3408: 	    if (lc($tagname) eq 'a') {
 3409:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3410:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3411:                 }
 3412: 	    }
 3413:             if (lc($tagname) eq 'script') {
 3414:                 my $src;
 3415:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3416:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3417:                 } else {
 3418:                     if ($attr->{'src'} ne '') {
 3419:                         $src = $attr->{'src'};
 3420:                         &add_filetype($allfiles,$src,'src');
 3421:                     }
 3422:                 }
 3423:                 my $text = $p->get_trimmed_text();
 3424:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3425:                     my @swfargs = split(/,/,$1);
 3426:                     foreach my $item (@swfargs) {
 3427:                         $item =~ s/["']//g;
 3428:                         $item =~ s/^\s+//;
 3429:                         $item =~ s/\s+$//;
 3430:                     }
 3431:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3432:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3433:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3434:                         } else {
 3435:                             $related{$swfargs[0]} = [$swfargs[2]];
 3436:                         }
 3437:                     }
 3438:                 }
 3439:             }
 3440:             if (lc($tagname) eq 'link') {
 3441:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3442:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3443:                 }
 3444:             }
 3445: 	    if (lc($tagname) eq 'object' ||
 3446: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3447: 		foreach my $item (keys(%javafiles)) {
 3448: 		    $javafiles{$item} = '';
 3449: 		}
 3450:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3451:                     $lastids{lc($tagname)} = $attr->{'id'};
 3452:                 }
 3453: 	    }
 3454: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3455: 		my $name = lc($attr->{'name'});
 3456: 		foreach my $item (keys(%javafiles)) {
 3457: 		    if ($name eq $item) {
 3458: 			$javafiles{$item} = $attr->{'value'};
 3459: 			last;
 3460: 		    }
 3461: 		}
 3462:                 my $pathfrom;
 3463: 		foreach my $item (keys(%mediafiles)) {
 3464: 		    if ($name eq $item) {
 3465:                         $pathfrom = $attr->{'value'};
 3466:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3467: 			&add_filetype($allfiles,$pathfrom,$name);
 3468: 			last;
 3469: 		    }
 3470: 		}
 3471:                 if ($name eq 'flashvars') {
 3472:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3473:                 }
 3474:                 if ($pathfrom ne '') {
 3475:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3476:                                          $pathfrom);
 3477:                 }
 3478: 	    }
 3479: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3480: 		foreach my $item (keys(%javafiles)) {
 3481: 		    if ($attr->{$item}) {
 3482: 			$javafiles{$item} = $attr->{$item};
 3483: 			last;
 3484: 		    }
 3485: 		}
 3486: 		foreach my $item (keys(%mediafiles)) {
 3487: 		    if ($attr->{$item}) {
 3488: 			&add_filetype($allfiles,$attr->{$item},$item);
 3489: 			last;
 3490: 		    }
 3491: 		}
 3492:                 if (lc($tagname) eq 'embed') {
 3493:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3494:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3495:                                              $attr->{'src'});
 3496:                     }
 3497:                 }
 3498: 	    }
 3499:             if ($t->[4] =~ m{/>$}) {
 3500:                 pop(@state);  
 3501:             }
 3502: 	} elsif ($t->[0] eq 'E') {
 3503: 	    my ($tagname) = ($t->[1]);
 3504: 	    if ($javafiles{'codebase'} ne '') {
 3505: 		$javafiles{'codebase'} .= '/';
 3506: 	    }  
 3507: 	    if (lc($tagname) eq 'applet' ||
 3508: 		lc($tagname) eq 'object' ||
 3509: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3510: 		) {
 3511: 		foreach my $item (keys(%javafiles)) {
 3512: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3513: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3514: 			&add_filetype($allfiles,$file,$item);
 3515: 		    }
 3516: 		}
 3517: 	    } 
 3518: 	    pop @state;
 3519: 	}
 3520:     }
 3521:     foreach my $id (sort(keys(%flashvars))) {
 3522:         if ($shockwave{$id} ne '') {
 3523:             my @pairs = split(/\&/,$flashvars{$id});
 3524:             foreach my $pair (@pairs) {
 3525:                 my ($key,$value) = split(/\=/,$pair);
 3526:                 if ($key eq 'thumb') {
 3527:                     &add_filetype($allfiles,$value,$key);
 3528:                 } elsif ($key eq 'content') {
 3529:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3530:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3531:                     if ($ext ne '') {
 3532:                         &add_filetype($allfiles,$path.$value,$ext);
 3533:                     }
 3534:                 }
 3535:             }
 3536:         }
 3537:     }
 3538:     return 'ok';
 3539: }
 3540: 
 3541: sub add_filetype {
 3542:     my ($allfiles,$file,$type)=@_;
 3543:     if (exists($allfiles->{$file})) {
 3544: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3545: 	    push(@{$allfiles->{$file}}, &escape($type));
 3546: 	}
 3547:     } else {
 3548: 	@{$allfiles->{$file}} = (&escape($type));
 3549:     }
 3550: }
 3551: 
 3552: sub embedded_dependency {
 3553:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3554:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3555:         if (($identifier ne '') &&
 3556:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3557:             ($pathfrom ne '')) {
 3558:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3559:             foreach my $dep (@{$related->{$identifier}}) {
 3560:                 &add_filetype($allfiles,$path.$dep,'object');
 3561:             }
 3562:         }
 3563:     }
 3564:     return;
 3565: }
 3566: 
 3567: sub removeuploadedurl {
 3568:     my ($url)=@_;	
 3569:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3570:     return &removeuserfile($uname,$udom,$fname);
 3571: }
 3572: 
 3573: sub removeuserfile {
 3574:     my ($docuname,$docudom,$fname)=@_;
 3575:     my $home=&homeserver($docuname,$docudom);    
 3576:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3577:     if ($result eq 'ok') {	
 3578:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3579:             my $metafile = $fname.'.meta';
 3580:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3581: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3582:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3583:             my $sqlresult = 
 3584:                 &update_portfolio_table($docuname,$docudom,$file,
 3585:                                         'portfolio_metadata',$group,
 3586:                                         'delete');
 3587:         }
 3588:     }
 3589:     return $result;
 3590: }
 3591: 
 3592: sub mkdiruserfile {
 3593:     my ($docuname,$docudom,$dir)=@_;
 3594:     my $home=&homeserver($docuname,$docudom);
 3595:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3596: }
 3597: 
 3598: sub renameuserfile {
 3599:     my ($docuname,$docudom,$old,$new)=@_;
 3600:     my $home=&homeserver($docuname,$docudom);
 3601:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3602:                         &escape("$old").':'.&escape("$new"),$home);
 3603:     if ($result eq 'ok') {
 3604:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3605:             my $oldmeta = $old.'.meta';
 3606:             my $newmeta = $new.'.meta';
 3607:             my $metaresult = 
 3608:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3609: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3610:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3611:             my $sqlresult = 
 3612:                 &update_portfolio_table($docuname,$docudom,$file,
 3613:                                         'portfolio_metadata',$group,
 3614:                                         'delete');
 3615:         }
 3616:     }
 3617:     return $result;
 3618: }
 3619: 
 3620: # ------------------------------------------------------------------------- Log
 3621: 
 3622: sub log {
 3623:     my ($dom,$nam,$hom,$what)=@_;
 3624:     return critical("log:$dom:$nam:$what",$hom);
 3625: }
 3626: 
 3627: # ------------------------------------------------------------------ Course Log
 3628: #
 3629: # This routine flushes several buffers of non-mission-critical nature
 3630: #
 3631: 
 3632: sub flushcourselogs {
 3633:     &logthis('Flushing log buffers');
 3634: #
 3635: # course logs
 3636: # This is a log of all transactions in a course, which can be used
 3637: # for data mining purposes
 3638: #
 3639: # It also collects the courseid database, which lists last transaction
 3640: # times and course titles for all courseids
 3641: #
 3642:     my %courseidbuffer=();
 3643:     foreach my $crsid (keys(%courselogs)) {
 3644:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3645: 		          &escape($courselogs{$crsid}),
 3646: 		          $coursehombuf{$crsid}) eq 'ok') {
 3647: 	    delete $courselogs{$crsid};
 3648:         } else {
 3649:             &logthis('Failed to flush log buffer for '.$crsid);
 3650:             if (length($courselogs{$crsid})>40000) {
 3651:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3652:                         " exceeded maximum size, deleting.</font>");
 3653:                delete $courselogs{$crsid};
 3654:             }
 3655:         }
 3656:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3657:             'description' => $coursedescrbuf{$crsid},
 3658:             'inst_code'    => $courseinstcodebuf{$crsid},
 3659:             'type'        => $coursetypebuf{$crsid},
 3660:             'owner'       => $courseownerbuf{$crsid},
 3661:         };
 3662:     }
 3663: #
 3664: # Write course id database (reverse lookup) to homeserver of courses 
 3665: # Is used in pickcourse
 3666: #
 3667:     foreach my $crs_home (keys(%courseidbuffer)) {
 3668:         my $response = &courseidput(&host_domain($crs_home),
 3669:                                     $courseidbuffer{$crs_home},
 3670:                                     $crs_home,'timeonly');
 3671:     }
 3672: #
 3673: # File accesses
 3674: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3675: #
 3676:     foreach my $entry (keys(%accesshash)) {
 3677:         if ($entry =~ /___count$/) {
 3678:             my ($dom,$name);
 3679:             ($dom,$name,undef)=
 3680: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3681:             if (! defined($dom) || $dom eq '' || 
 3682:                 ! defined($name) || $name eq '') {
 3683:                 my $cid = $env{'request.course.id'};
 3684:                 $dom  = $env{'request.'.$cid.'.domain'};
 3685:                 $name = $env{'request.'.$cid.'.num'};
 3686:             }
 3687:             my $value = $accesshash{$entry};
 3688:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3689:             my %temphash=($url => $value);
 3690:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3691:             if ($result eq 'ok') {
 3692:                 delete $accesshash{$entry};
 3693:             }
 3694:         } else {
 3695:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3696:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3697:             my %temphash=($entry => $accesshash{$entry});
 3698:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3699:                 delete $accesshash{$entry};
 3700:             }
 3701:         }
 3702:     }
 3703: #
 3704: # Roles
 3705: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3706: #
 3707:     foreach my $entry (keys(%userrolehash)) {
 3708:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3709: 	    split(/\:/,$entry);
 3710:         if (&Apache::lonnet::put('nohist_userroles',
 3711:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3712:                 $rudom,$runame) eq 'ok') {
 3713: 	    delete $userrolehash{$entry};
 3714:         }
 3715:     }
 3716: #
 3717: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3718: #
 3719:     my %domrolebuffer = ();
 3720:     foreach my $entry (keys(%domainrolehash)) {
 3721:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3722:         if ($domrolebuffer{$rudom}) {
 3723:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3724:                       '='.&escape($domainrolehash{$entry});
 3725:         } else {
 3726:             $domrolebuffer{$rudom}.=&escape($entry).
 3727:                       '='.&escape($domainrolehash{$entry});
 3728:         }
 3729:         delete $domainrolehash{$entry};
 3730:     }
 3731:     foreach my $dom (keys(%domrolebuffer)) {
 3732: 	my %servers = &get_servers($dom,'library');
 3733: 	foreach my $tryserver (keys(%servers)) {
 3734: 	    unless (&reply('domroleput:'.$dom.':'.
 3735: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3736: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3737: 	    }
 3738:         }
 3739:     }
 3740:     $dumpcount++;
 3741: }
 3742: 
 3743: sub courselog {
 3744:     my $what=shift;
 3745:     $what=time.':'.$what;
 3746:     unless ($env{'request.course.id'}) { return ''; }
 3747:     $coursedombuf{$env{'request.course.id'}}=
 3748:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3749:     $coursenumbuf{$env{'request.course.id'}}=
 3750:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3751:     $coursehombuf{$env{'request.course.id'}}=
 3752:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3753:     $coursedescrbuf{$env{'request.course.id'}}=
 3754:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3755:     $courseinstcodebuf{$env{'request.course.id'}}=
 3756:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3757:     $courseownerbuf{$env{'request.course.id'}}=
 3758:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3759:     $coursetypebuf{$env{'request.course.id'}}=
 3760:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3761:     if (defined $courselogs{$env{'request.course.id'}}) {
 3762: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3763:     } else {
 3764: 	$courselogs{$env{'request.course.id'}}.=$what;
 3765:     }
 3766:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3767: 	&flushcourselogs();
 3768:     }
 3769: }
 3770: 
 3771: sub courseacclog {
 3772:     my $fnsymb=shift;
 3773:     unless ($env{'request.course.id'}) { return ''; }
 3774:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3775:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3776:         $what.=':POST';
 3777:         # FIXME: Probably ought to escape things....
 3778: 	foreach my $key (keys(%env)) {
 3779:             if ($key=~/^form\.(.*)/) {
 3780:                 my $formitem = $1;
 3781:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3782:                     $what.=':'.$formitem.'='.$env{$key};
 3783:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3784:                     $what.=':'.$formitem.'='.$env{$key};
 3785:                 }
 3786:             }
 3787:         }
 3788:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3789:         # FIXME: We should not be depending on a form parameter that someone
 3790:         # editing lonsearchcat.pm might change in the future.
 3791:         if ($env{'form.phase'} eq 'course_search') {
 3792:             $what.= ':POST';
 3793:             # FIXME: Probably ought to escape things....
 3794:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3795:                                  'crsdiscuss') {
 3796:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3797:             }
 3798:         }
 3799:     }
 3800:     &courselog($what);
 3801: }
 3802: 
 3803: sub countacc {
 3804:     my $url=&declutter(shift);
 3805:     return if (! defined($url) || $url eq '');
 3806:     unless ($env{'request.course.id'}) { return ''; }
 3807: #
 3808: # Mark that this url was used in this course
 3809: #
 3810:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3811: #
 3812: # Increase the access count for this resource in this child process
 3813: #
 3814:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3815:     $accesshash{$key}++;
 3816: }
 3817: 
 3818: sub linklog {
 3819:     my ($from,$to)=@_;
 3820:     $from=&declutter($from);
 3821:     $to=&declutter($to);
 3822:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3823:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3824: }
 3825: 
 3826: sub statslog {
 3827:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3828:     if ($users<2) { return; }
 3829:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3830:             'course'       => $env{'request.course.id'},
 3831:             'sections'     => '"all"',
 3832:             'num_students' => $users,
 3833:             'part'         => $part,
 3834:             'symb'         => $symb,
 3835:             'mean_tries'   => $av_attempts,
 3836:             'deg_of_diff'  => $degdiff});
 3837:     foreach my $key (keys(%dynstore)) {
 3838:         $accesshash{$key}=$dynstore{$key};
 3839:     }
 3840: }
 3841:   
 3842: sub userrolelog {
 3843:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3844:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3845:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3846:        $userrolehash
 3847:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3848:                     =$tend.':'.$tstart;
 3849:     }
 3850:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3851:        $userrolehash
 3852:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3853:                     =$tend.':'.$tstart;
 3854:     }
 3855:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3856:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3857:        $domainrolehash
 3858:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3859:                     = $tend.':'.$tstart;
 3860:     }
 3861: }
 3862: 
 3863: sub courserolelog {
 3864:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3865:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3866:         my $cdom = $1;
 3867:         my $cnum = $2;
 3868:         my $sec = $3;
 3869:         my $namespace = 'rolelog';
 3870:         my %storehash = (
 3871:                            role    => $trole,
 3872:                            start   => $tstart,
 3873:                            end     => $tend,
 3874:                            selfenroll => $selfenroll,
 3875:                            context    => $context,
 3876:                         );
 3877:         if ($trole eq 'gr') {
 3878:             $namespace = 'groupslog';
 3879:             $storehash{'group'} = $sec;
 3880:         } else {
 3881:             $storehash{'section'} = $sec;
 3882:         }
 3883:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3884:                    $domain,$cnum,$cdom);
 3885:         if (($trole ne 'st') || ($sec ne '')) {
 3886:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3887:         }
 3888:     }
 3889:     return;
 3890: }
 3891: 
 3892: sub domainrolelog {
 3893:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3894:     if ($area =~ m{^/($match_domain)/$}) {
 3895:         my $cdom = $1;
 3896:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3897:         my $namespace = 'rolelog';
 3898:         my %storehash = (
 3899:                            role    => $trole,
 3900:                            start   => $tstart,
 3901:                            end     => $tend,
 3902:                            context => $context,
 3903:                         );
 3904:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3905:                    $domain,$domconfiguser,$cdom);
 3906:     }
 3907:     return;
 3908: 
 3909: }
 3910: 
 3911: sub coauthorrolelog {
 3912:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3913:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3914:         my $audom = $1;
 3915:         my $auname = $2;
 3916:         my $namespace = 'rolelog';
 3917:         my %storehash = (
 3918:                            role    => $trole,
 3919:                            start   => $tstart,
 3920:                            end     => $tend,
 3921:                            context => $context,
 3922:                         );
 3923:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3924:                    $domain,$auname,$audom);
 3925:     }
 3926:     return;
 3927: }
 3928: 
 3929: sub get_course_adv_roles {
 3930:     my ($cid,$codes) = @_;
 3931:     $cid=$env{'request.course.id'} unless (defined($cid));
 3932:     my %coursehash=&coursedescription($cid);
 3933:     my $crstype = &Apache::loncommon::course_type($cid);
 3934:     my %nothide=();
 3935:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3936:         if ($user !~ /:/) {
 3937: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3938:         } else {
 3939:             $nothide{$user}=1;
 3940:         }
 3941:     }
 3942:     my @possdoms = ($coursehash{'domain'});
 3943:     if ($coursehash{'checkforpriv'}) {
 3944:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3945:     }
 3946:     my %returnhash=();
 3947:     my %dumphash=
 3948:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3949:     my $now=time;
 3950:     my %privileged;
 3951:     foreach my $entry (keys(%dumphash)) {
 3952: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3953:         if (($tstart) && ($tstart<0)) { next; }
 3954:         if (($tend) && ($tend<$now)) { next; }
 3955:         if (($tstart) && ($now<$tstart)) { next; }
 3956:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3957: 	if ($username eq '' || $domain eq '') { next; }
 3958:         if ((&privileged($username,$domain,\@possdoms)) &&
 3959:             (!$nothide{$username.':'.$domain})) { next; }
 3960: 	if ($role eq 'cr') { next; }
 3961:         if ($codes) {
 3962:             if ($section) { $role .= ':'.$section; }
 3963:             if ($returnhash{$role}) {
 3964:                 $returnhash{$role}.=','.$username.':'.$domain;
 3965:             } else {
 3966:                 $returnhash{$role}=$username.':'.$domain;
 3967:             }
 3968:         } else {
 3969:             my $key=&plaintext($role,$crstype);
 3970:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3971:             if ($returnhash{$key}) {
 3972: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3973:             } else {
 3974:                 $returnhash{$key}=$username.':'.$domain;
 3975:             }
 3976:         }
 3977:     }
 3978:     return %returnhash;
 3979: }
 3980: 
 3981: sub get_my_roles {
 3982:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3983:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3984:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3985:     my (%dumphash,%nothide);
 3986:     if ($context eq 'userroles') {
 3987:         %dumphash = &dump('roles',$udom,$uname);
 3988:     } else {
 3989:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 3990:         if ($hidepriv) {
 3991:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3992:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3993:                 if ($user !~ /:/) {
 3994:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3995:                 } else {
 3996:                     $nothide{$user} = 1;
 3997:                 }
 3998:             }
 3999:         }
 4000:     }
 4001:     my %returnhash=();
 4002:     my $now=time;
 4003:     my %privileged;
 4004:     foreach my $entry (keys(%dumphash)) {
 4005:         my ($role,$tend,$tstart);
 4006:         if ($context eq 'userroles') {
 4007:             next if ($entry =~ /^rolesdef/);
 4008: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4009:         } else {
 4010:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4011:         }
 4012:         if (($tstart) && ($tstart<0)) { next; }
 4013:         my $status = 'active';
 4014:         if (($tend) && ($tend<=$now)) {
 4015:             $status = 'previous';
 4016:         } 
 4017:         if (($tstart) && ($now<$tstart)) {
 4018:             $status = 'future';
 4019:         }
 4020:         if (ref($types) eq 'ARRAY') {
 4021:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4022:                 next;
 4023:             } 
 4024:         } else {
 4025:             if ($status ne 'active') {
 4026:                 next;
 4027:             }
 4028:         }
 4029:         my ($rolecode,$username,$domain,$section,$area);
 4030:         if ($context eq 'userroles') {
 4031:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4032:             (undef,$domain,$username,$section) = split(/\//,$area);
 4033:         } else {
 4034:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4035:         }
 4036:         if (ref($roledoms) eq 'ARRAY') {
 4037:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4038:                 next;
 4039:             }
 4040:         }
 4041:         if (ref($roles) eq 'ARRAY') {
 4042:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4043:                 if ($role =~ /^cr\//) {
 4044:                     if (!grep(/^cr$/,@{$roles})) {
 4045:                         next;
 4046:                     }
 4047:                 } elsif ($role =~ /^gr\//) {
 4048:                     if (!grep(/^gr$/,@{$roles})) {
 4049:                         next;
 4050:                     }
 4051:                 } else {
 4052:                     next;
 4053:                 }
 4054:             }
 4055:         }
 4056:         if ($hidepriv) {
 4057:             my @privroles = ('dc','su');
 4058:             if ($context eq 'userroles') {
 4059:                 next if (grep(/^\Q$role\E$/,@privroles));
 4060:             } else {
 4061:                 my $possdoms = [$domain];
 4062:                 if (ref($roledoms) eq 'ARRAY') {
 4063:                    push(@{$possdoms},@{$roledoms}); 
 4064:                 }
 4065:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4066:                     if (!$nothide{$username.':'.$domain}) {
 4067:                         next;
 4068:                     }
 4069:                 }
 4070:             }
 4071:         }
 4072:         if ($withsec) {
 4073:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4074:                 $tstart.':'.$tend;
 4075:         } else {
 4076:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4077:         }
 4078:     }
 4079:     return %returnhash;
 4080: }
 4081: 
 4082: # ----------------------------------------------------- Frontpage Announcements
 4083: #
 4084: #
 4085: 
 4086: sub postannounce {
 4087:     my ($server,$text)=@_;
 4088:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4089:     unless ($text=~/\w/) { $text=''; }
 4090:     return &reply('setannounce:'.&escape($text),$server);
 4091: }
 4092: 
 4093: sub getannounce {
 4094: 
 4095:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4096: 	my $announcement='';
 4097: 	while (my $line = <$fh>) { $announcement .= $line; }
 4098: 	close($fh);
 4099: 	if ($announcement=~/\w/) { 
 4100: 	    return 
 4101:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4102:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4103: 	} else {
 4104: 	    return '';
 4105: 	}
 4106:     } else {
 4107: 	return '';
 4108:     }
 4109: }
 4110: 
 4111: # ---------------------------------------------------------- Course ID routines
 4112: # Deal with domain's nohist_courseid.db files
 4113: #
 4114: 
 4115: sub courseidput {
 4116:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4117:     return unless (ref($storehash) eq 'HASH');
 4118:     my $outcome;
 4119:     if ($caller eq 'timeonly') {
 4120:         my $cids = '';
 4121:         foreach my $item (keys(%$storehash)) {
 4122:             $cids.=&escape($item).'&';
 4123:         }
 4124:         $cids=~s/\&$//;
 4125:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4126:                           $coursehome);       
 4127:     } else {
 4128:         my $items = '';
 4129:         foreach my $item (keys(%$storehash)) {
 4130:             $items.= &escape($item).'='.
 4131:                      &freeze_escape($$storehash{$item}).'&';
 4132:         }
 4133:         $items=~s/\&$//;
 4134:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4135:                           $coursehome);
 4136:     }
 4137:     if ($outcome eq 'unknown_cmd') {
 4138:         my $what;
 4139:         foreach my $cid (keys(%$storehash)) {
 4140:             $what .= &escape($cid).'=';
 4141:             foreach my $item ('description','inst_code','owner','type') {
 4142:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4143:             }
 4144:             $what =~ s/\:$/&/;
 4145:         }
 4146:         $what =~ s/\&$//;  
 4147:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4148:     } else {
 4149:         return $outcome;
 4150:     }
 4151: }
 4152: 
 4153: sub courseiddump {
 4154:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4155:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4156:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4157:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4158:     my $as_hash = 1;
 4159:     my %returnhash;
 4160:     if (!$domfilter) { $domfilter=''; }
 4161:     my %libserv = &all_library();
 4162:     foreach my $tryserver (keys(%libserv)) {
 4163:         if ( (  $hostidflag == 1 
 4164: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4165: 	     || (!defined($hostidflag)) ) {
 4166: 
 4167: 	    if (($domfilter eq '') ||
 4168: 		(&host_domain($tryserver) eq $domfilter)) {
 4169:                 my $rep;
 4170:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4171:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4172:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4173:                                 &escape($descfilter), &escape($instcodefilter), 
 4174:                                 &escape($ownerfilter), &escape($coursefilter),
 4175:                                 &escape($typefilter), &escape($regexp_ok), 
 4176:                                 $as_hash, &escape($selfenrollonly), 
 4177:                                 &escape($catfilter), $showhidden, $caller, 
 4178:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4179:                                 &escape($createdbefore), &escape($createdafter), 
 4180:                                 &escape($creationcontext), $domcloner)));
 4181:                 } else {
 4182:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4183:                              $sincefilter.':'.&escape($descfilter).':'.
 4184:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4185:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4186:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4187:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4188:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4189:                              &escape($cc_clone).':'.$cloneonly.':'.
 4190:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4191:                              &escape($creationcontext).':'.$domcloner,
 4192:                              $tryserver);
 4193:                 }
 4194:                      
 4195:                 my @pairs=split(/\&/,$rep);
 4196:                 foreach my $item (@pairs) {
 4197:                     my ($key,$value)=split(/\=/,$item,2);
 4198:                     $key = &unescape($key);
 4199:                     next if ($key =~ /^error: 2 /);
 4200:                     my $result = &thaw_unescape($value);
 4201:                     if (ref($result) eq 'HASH') {
 4202:                         $returnhash{$key}=$result;
 4203:                     } else {
 4204:                         my @responses = split(/:/,$value);
 4205:                         my @items = ('description','inst_code','owner','type');
 4206:                         for (my $i=0; $i<@responses; $i++) {
 4207:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4208:                         }
 4209:                     }
 4210:                 }
 4211:             }
 4212:         }
 4213:     }
 4214:     return %returnhash;
 4215: }
 4216: 
 4217: sub courselastaccess {
 4218:     my ($cdom,$cnum,$hostidref) = @_;
 4219:     my %returnhash;
 4220:     if ($cdom && $cnum) {
 4221:         my $chome = &homeserver($cnum,$cdom);
 4222:         if ($chome ne 'no_host') {
 4223:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4224:             &extract_lastaccess(\%returnhash,$rep);
 4225:         }
 4226:     } else {
 4227:         if (!$cdom) { $cdom=''; }
 4228:         my %libserv = &all_library();
 4229:         foreach my $tryserver (keys(%libserv)) {
 4230:             if (ref($hostidref) eq 'ARRAY') {
 4231:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4232:             } 
 4233:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4234:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4235:                 &extract_lastaccess(\%returnhash,$rep);
 4236:             }
 4237:         }
 4238:     }
 4239:     return %returnhash;
 4240: }
 4241: 
 4242: sub extract_lastaccess {
 4243:     my ($returnhash,$rep) = @_;
 4244:     if (ref($returnhash) eq 'HASH') {
 4245:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4246:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4247:                  $rep eq '') {
 4248:             my @pairs=split(/\&/,$rep);
 4249:             foreach my $item (@pairs) {
 4250:                 my ($key,$value)=split(/\=/,$item,2);
 4251:                 $key = &unescape($key);
 4252:                 next if ($key =~ /^error: 2 /);
 4253:                 $returnhash->{$key} = &thaw_unescape($value);
 4254:             }
 4255:         }
 4256:     }
 4257:     return;
 4258: }
 4259: 
 4260: # ---------------------------------------------------------- DC e-mail
 4261: 
 4262: sub dcmailput {
 4263:     my ($domain,$msgid,$message,$server)=@_;
 4264:     my $status = &Apache::lonnet::critical(
 4265:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4266:        &escape($message),$server);
 4267:     return $status;
 4268: }
 4269: 
 4270: sub dcmaildump {
 4271:     my ($dom,$startdate,$enddate,$senders) = @_;
 4272:     my %returnhash=();
 4273: 
 4274:     if (defined(&domain($dom,'primary'))) {
 4275:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4276:                                                          &escape($enddate).':';
 4277: 	my @esc_senders=map { &escape($_)} @$senders;
 4278: 	$cmd.=&escape(join('&',@esc_senders));
 4279: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4280:             my ($key,$value) = split(/\=/,$line,2);
 4281:             if (($key) && ($value)) {
 4282:                 $returnhash{&unescape($key)} = &unescape($value);
 4283:             }
 4284:         }
 4285:     }
 4286:     return %returnhash;
 4287: }
 4288: # ---------------------------------------------------------- Domain roles
 4289: 
 4290: sub get_domain_roles {
 4291:     my ($dom,$roles,$startdate,$enddate)=@_;
 4292:     if ((!defined($startdate)) || ($startdate eq '')) {
 4293:         $startdate = '.';
 4294:     }
 4295:     if ((!defined($enddate)) || ($enddate eq '')) {
 4296:         $enddate = '.';
 4297:     }
 4298:     my $rolelist;
 4299:     if (ref($roles) eq 'ARRAY') {
 4300:         $rolelist = join('&',@{$roles});
 4301:     }
 4302:     my %personnel = ();
 4303: 
 4304:     my %servers = &get_servers($dom,'library');
 4305:     foreach my $tryserver (keys(%servers)) {
 4306: 	%{$personnel{$tryserver}}=();
 4307: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4308: 					    &escape($startdate).':'.
 4309: 					    &escape($enddate).':'.
 4310: 					    &escape($rolelist), $tryserver))) {
 4311: 	    my ($key,$value) = split(/\=/,$line,2);
 4312: 	    if (($key) && ($value)) {
 4313: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4314: 	    }
 4315: 	}
 4316:     }
 4317:     return %personnel;
 4318: }
 4319: 
 4320: # ----------------------------------------------------------- Interval timing 
 4321: 
 4322: {
 4323: # Caches needed for speedup of navmaps
 4324: # We don't want to cache this for very long at all (5 seconds at most)
 4325: # 
 4326: # The user for whom we cache
 4327: my $cachedkey='';
 4328: # The cached times for this user
 4329: my %cachedtimes=();
 4330: # When this was last done
 4331: my $cachedtime=();
 4332: 
 4333: sub load_all_first_access {
 4334:     my ($uname,$udom)=@_;
 4335:     if (($cachedkey eq $uname.':'.$udom) &&
 4336:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4337:         return;
 4338:     }
 4339:     $cachedtime=time;
 4340:     $cachedkey=$uname.':'.$udom;
 4341:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4342: }
 4343: 
 4344: sub get_first_access {
 4345:     my ($type,$argsymb,$argmap)=@_;
 4346:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4347:     if ($argsymb) { $symb=$argsymb; }
 4348:     my ($map,$id,$res)=&decode_symb($symb);
 4349:     if ($argmap) { $map = $argmap; }
 4350:     if ($type eq 'course') {
 4351: 	$res='course';
 4352:     } elsif ($type eq 'map') {
 4353: 	$res=&symbread($map);
 4354:     } else {
 4355: 	$res=$symb;
 4356:     }
 4357:     &load_all_first_access($uname,$udom);
 4358:     return $cachedtimes{"$courseid\0$res"};
 4359: }
 4360: 
 4361: sub set_first_access {
 4362:     my ($type,$interval)=@_;
 4363:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4364:     my ($map,$id,$res)=&decode_symb($symb);
 4365:     if ($type eq 'course') {
 4366: 	$res='course';
 4367:     } elsif ($type eq 'map') {
 4368: 	$res=&symbread($map);
 4369:     } else {
 4370: 	$res=$symb;
 4371:     }
 4372:     $cachedkey='';
 4373:     my $firstaccess=&get_first_access($type,$symb,$map);
 4374:     if (!$firstaccess) {
 4375:         my $start = time;
 4376: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4377:                           $udom,$uname);
 4378:         if ($putres eq 'ok') {
 4379:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4380:                  $udom,$uname); 
 4381:             &appenv(
 4382:                      {
 4383:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4384:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4385:                      }
 4386:                   );
 4387:         }
 4388:         return $putres;
 4389:     }
 4390:     return 'already_set';
 4391: }
 4392: }
 4393: # --------------------------------------------- Set Expire Date for Spreadsheet
 4394: 
 4395: sub expirespread {
 4396:     my ($uname,$udom,$stype,$usymb)=@_;
 4397:     my $cid=$env{'request.course.id'}; 
 4398:     if ($cid) {
 4399:        my $now=time;
 4400:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4401:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4402:                             $env{'course.'.$cid.'.num'}.
 4403: 	        	    ':nohist_expirationdates:'.
 4404:                             &escape($key).'='.$now,
 4405:                             $env{'course.'.$cid.'.home'})
 4406:     }
 4407:     return 'ok';
 4408: }
 4409: 
 4410: # ----------------------------------------------------- Devalidate Spreadsheets
 4411: 
 4412: sub devalidate {
 4413:     my ($symb,$uname,$udom)=@_;
 4414:     my $cid=$env{'request.course.id'}; 
 4415:     if ($cid) {
 4416:         # delete the stored spreadsheets for
 4417:         # - the student level sheet of this user in course's homespace
 4418:         # - the assessment level sheet for this resource 
 4419:         #   for this user in user's homespace
 4420: 	# - current conditional state info
 4421: 	my $key=$uname.':'.$udom.':';
 4422:         my $status=
 4423: 	    &del('nohist_calculatedsheets',
 4424: 		 [$key.'studentcalc:'],
 4425: 		 $env{'course.'.$cid.'.domain'},
 4426: 		 $env{'course.'.$cid.'.num'})
 4427: 		.' '.
 4428: 	    &del('nohist_calculatedsheets_'.$cid,
 4429: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4430:         unless ($status eq 'ok ok') {
 4431:            &logthis('Could not devalidate spreadsheet '.
 4432:                     $uname.' at '.$udom.' for '.
 4433: 		    $symb.': '.$status);
 4434:         }
 4435: 	&delenv('user.state.'.$cid);
 4436:     }
 4437: }
 4438: 
 4439: sub get_scalar {
 4440:     my ($string,$end) = @_;
 4441:     my $value;
 4442:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4443: 	$value = $1;
 4444:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4445: 	$value = $1;
 4446:     }
 4447:     return &unescape($value);
 4448: }
 4449: 
 4450: sub array2str {
 4451:   my (@array) = @_;
 4452:   my $result=&arrayref2str(\@array);
 4453:   $result=~s/^__ARRAY_REF__//;
 4454:   $result=~s/__END_ARRAY_REF__$//;
 4455:   return $result;
 4456: }
 4457: 
 4458: sub arrayref2str {
 4459:   my ($arrayref) = @_;
 4460:   my $result='__ARRAY_REF__';
 4461:   foreach my $elem (@$arrayref) {
 4462:     if(ref($elem) eq 'ARRAY') {
 4463:       $result.=&arrayref2str($elem).'&';
 4464:     } elsif(ref($elem) eq 'HASH') {
 4465:       $result.=&hashref2str($elem).'&';
 4466:     } elsif(ref($elem)) {
 4467:       #print("Got a ref of ".(ref($elem))." skipping.");
 4468:     } else {
 4469:       $result.=&escape($elem).'&';
 4470:     }
 4471:   }
 4472:   $result=~s/\&$//;
 4473:   $result .= '__END_ARRAY_REF__';
 4474:   return $result;
 4475: }
 4476: 
 4477: sub hash2str {
 4478:   my (%hash) = @_;
 4479:   my $result=&hashref2str(\%hash);
 4480:   $result=~s/^__HASH_REF__//;
 4481:   $result=~s/__END_HASH_REF__$//;
 4482:   return $result;
 4483: }
 4484: 
 4485: sub hashref2str {
 4486:   my ($hashref)=@_;
 4487:   my $result='__HASH_REF__';
 4488:   foreach my $key (sort(keys(%$hashref))) {
 4489:     if (ref($key) eq 'ARRAY') {
 4490:       $result.=&arrayref2str($key).'=';
 4491:     } elsif (ref($key) eq 'HASH') {
 4492:       $result.=&hashref2str($key).'=';
 4493:     } elsif (ref($key)) {
 4494:       $result.='=';
 4495:       #print("Got a ref of ".(ref($key))." skipping.");
 4496:     } else {
 4497: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4498:     }
 4499: 
 4500:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4501:       $result.=&arrayref2str($hashref->{$key}).'&';
 4502:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4503:       $result.=&hashref2str($hashref->{$key}).'&';
 4504:     } elsif(ref($hashref->{$key})) {
 4505:        $result.='&';
 4506:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4507:     } else {
 4508:       $result.=&escape($hashref->{$key}).'&';
 4509:     }
 4510:   }
 4511:   $result=~s/\&$//;
 4512:   $result .= '__END_HASH_REF__';
 4513:   return $result;
 4514: }
 4515: 
 4516: sub str2hash {
 4517:     my ($string)=@_;
 4518:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4519:     return %$hash;
 4520: }
 4521: 
 4522: sub str2hashref {
 4523:   my ($string) = @_;
 4524: 
 4525:   my %hash;
 4526: 
 4527:   if($string !~ /^__HASH_REF__/) {
 4528:       if (! ($string eq '' || !defined($string))) {
 4529: 	  $hash{'error'}='Not hash reference';
 4530:       }
 4531:       return (\%hash, $string);
 4532:   }
 4533: 
 4534:   $string =~ s/^__HASH_REF__//;
 4535: 
 4536:   while($string !~ /^__END_HASH_REF__/) {
 4537:       #key
 4538:       my $key='';
 4539:       if($string =~ /^__HASH_REF__/) {
 4540:           ($key, $string)=&str2hashref($string);
 4541:           if(defined($key->{'error'})) {
 4542:               $hash{'error'}='Bad data';
 4543:               return (\%hash, $string);
 4544:           }
 4545:       } elsif($string =~ /^__ARRAY_REF__/) {
 4546:           ($key, $string)=&str2arrayref($string);
 4547:           if($key->[0] eq 'Array reference error') {
 4548:               $hash{'error'}='Bad data';
 4549:               return (\%hash, $string);
 4550:           }
 4551:       } else {
 4552:           $string =~ s/^(.*?)=//;
 4553: 	  $key=&unescape($1);
 4554:       }
 4555:       $string =~ s/^=//;
 4556: 
 4557:       #value
 4558:       my $value='';
 4559:       if($string =~ /^__HASH_REF__/) {
 4560:           ($value, $string)=&str2hashref($string);
 4561:           if(defined($value->{'error'})) {
 4562:               $hash{'error'}='Bad data';
 4563:               return (\%hash, $string);
 4564:           }
 4565:       } elsif($string =~ /^__ARRAY_REF__/) {
 4566:           ($value, $string)=&str2arrayref($string);
 4567:           if($value->[0] eq 'Array reference error') {
 4568:               $hash{'error'}='Bad data';
 4569:               return (\%hash, $string);
 4570:           }
 4571:       } else {
 4572: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4573:       }
 4574:       $string =~ s/^&//;
 4575: 
 4576:       $hash{$key}=$value;
 4577:   }
 4578: 
 4579:   $string =~ s/^__END_HASH_REF__//;
 4580: 
 4581:   return (\%hash, $string);
 4582: }
 4583: 
 4584: sub str2array {
 4585:     my ($string)=@_;
 4586:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4587:     return @$array;
 4588: }
 4589: 
 4590: sub str2arrayref {
 4591:   my ($string) = @_;
 4592:   my @array;
 4593: 
 4594:   if($string !~ /^__ARRAY_REF__/) {
 4595:       if (! ($string eq '' || !defined($string))) {
 4596: 	  $array[0]='Array reference error';
 4597:       }
 4598:       return (\@array, $string);
 4599:   }
 4600: 
 4601:   $string =~ s/^__ARRAY_REF__//;
 4602: 
 4603:   while($string !~ /^__END_ARRAY_REF__/) {
 4604:       my $value='';
 4605:       if($string =~ /^__HASH_REF__/) {
 4606:           ($value, $string)=&str2hashref($string);
 4607:           if(defined($value->{'error'})) {
 4608:               $array[0] ='Array reference error';
 4609:               return (\@array, $string);
 4610:           }
 4611:       } elsif($string =~ /^__ARRAY_REF__/) {
 4612:           ($value, $string)=&str2arrayref($string);
 4613:           if($value->[0] eq 'Array reference error') {
 4614:               $array[0] ='Array reference error';
 4615:               return (\@array, $string);
 4616:           }
 4617:       } else {
 4618: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4619:       }
 4620:       $string =~ s/^&//;
 4621: 
 4622:       push(@array, $value);
 4623:   }
 4624: 
 4625:   $string =~ s/^__END_ARRAY_REF__//;
 4626: 
 4627:   return (\@array, $string);
 4628: }
 4629: 
 4630: # -------------------------------------------------------------------Temp Store
 4631: 
 4632: sub tmpreset {
 4633:   my ($symb,$namespace,$domain,$stuname) = @_;
 4634:   if (!$symb) {
 4635:     $symb=&symbread();
 4636:     if (!$symb) { $symb= $env{'request.url'}; }
 4637:   }
 4638:   $symb=escape($symb);
 4639: 
 4640:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4641:   $namespace=~s/\//\_/g;
 4642:   $namespace=~s/\W//g;
 4643: 
 4644:   if (!$domain) { $domain=$env{'user.domain'}; }
 4645:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4646:   if ($domain eq 'public' && $stuname eq 'public') {
 4647:       $stuname=$ENV{'REMOTE_ADDR'};
 4648:   }
 4649:   my $path=LONCAPA::tempdir();
 4650:   my %hash;
 4651:   if (tie(%hash,'GDBM_File',
 4652: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4653: 	  &GDBM_WRCREAT(),0640)) {
 4654:     foreach my $key (keys(%hash)) {
 4655:       if ($key=~ /:$symb/) {
 4656: 	delete($hash{$key});
 4657:       }
 4658:     }
 4659:   }
 4660: }
 4661: 
 4662: sub tmpstore {
 4663:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4664: 
 4665:   if (!$symb) {
 4666:     $symb=&symbread();
 4667:     if (!$symb) { $symb= $env{'request.url'}; }
 4668:   }
 4669:   $symb=escape($symb);
 4670: 
 4671:   if (!$namespace) {
 4672:     # I don't think we would ever want to store this for a course.
 4673:     # it seems this will only be used if we don't have a course.
 4674:     #$namespace=$env{'request.course.id'};
 4675:     #if (!$namespace) {
 4676:       $namespace=$env{'request.state'};
 4677:     #}
 4678:   }
 4679:   $namespace=~s/\//\_/g;
 4680:   $namespace=~s/\W//g;
 4681:   if (!$domain) { $domain=$env{'user.domain'}; }
 4682:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4683:   if ($domain eq 'public' && $stuname eq 'public') {
 4684:       $stuname=$ENV{'REMOTE_ADDR'};
 4685:   }
 4686:   my $now=time;
 4687:   my %hash;
 4688:   my $path=LONCAPA::tempdir();
 4689:   if (tie(%hash,'GDBM_File',
 4690: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4691: 	  &GDBM_WRCREAT(),0640)) {
 4692:     $hash{"version:$symb"}++;
 4693:     my $version=$hash{"version:$symb"};
 4694:     my $allkeys=''; 
 4695:     foreach my $key (keys(%$storehash)) {
 4696:       $allkeys.=$key.':';
 4697:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4698:     }
 4699:     $hash{"$version:$symb:timestamp"}=$now;
 4700:     $allkeys.='timestamp';
 4701:     $hash{"$version:keys:$symb"}=$allkeys;
 4702:     if (untie(%hash)) {
 4703:       return 'ok';
 4704:     } else {
 4705:       return "error:$!";
 4706:     }
 4707:   } else {
 4708:     return "error:$!";
 4709:   }
 4710: }
 4711: 
 4712: # -----------------------------------------------------------------Temp Restore
 4713: 
 4714: sub tmprestore {
 4715:   my ($symb,$namespace,$domain,$stuname) = @_;
 4716: 
 4717:   if (!$symb) {
 4718:     $symb=&symbread();
 4719:     if (!$symb) { $symb= $env{'request.url'}; }
 4720:   }
 4721:   $symb=escape($symb);
 4722: 
 4723:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4724: 
 4725:   if (!$domain) { $domain=$env{'user.domain'}; }
 4726:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4727:   if ($domain eq 'public' && $stuname eq 'public') {
 4728:       $stuname=$ENV{'REMOTE_ADDR'};
 4729:   }
 4730:   my %returnhash;
 4731:   $namespace=~s/\//\_/g;
 4732:   $namespace=~s/\W//g;
 4733:   my %hash;
 4734:   my $path=LONCAPA::tempdir();
 4735:   if (tie(%hash,'GDBM_File',
 4736: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4737: 	  &GDBM_READER(),0640)) {
 4738:     my $version=$hash{"version:$symb"};
 4739:     $returnhash{'version'}=$version;
 4740:     my $scope;
 4741:     for ($scope=1;$scope<=$version;$scope++) {
 4742:       my $vkeys=$hash{"$scope:keys:$symb"};
 4743:       my @keys=split(/:/,$vkeys);
 4744:       my $key;
 4745:       $returnhash{"$scope:keys"}=$vkeys;
 4746:       foreach $key (@keys) {
 4747: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4748: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4749:       }
 4750:     }
 4751:     if (!(untie(%hash))) {
 4752:       return "error:$!";
 4753:     }
 4754:   } else {
 4755:     return "error:$!";
 4756:   }
 4757:   return %returnhash;
 4758: }
 4759: 
 4760: # ----------------------------------------------------------------------- Store
 4761: 
 4762: sub store {
 4763:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4764:     my $home='';
 4765: 
 4766:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4767: 
 4768:     $symb=&symbclean($symb);
 4769:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4770: 
 4771:     if (!$domain) { $domain=$env{'user.domain'}; }
 4772:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4773: 
 4774:     &devalidate($symb,$stuname,$domain);
 4775: 
 4776:     $symb=escape($symb);
 4777:     if (!$namespace) { 
 4778:        unless ($namespace=$env{'request.course.id'}) { 
 4779:           return ''; 
 4780:        } 
 4781:     }
 4782:     if (!$home) { $home=$env{'user.home'}; }
 4783: 
 4784:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4785:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4786: 
 4787:     my $namevalue='';
 4788:     foreach my $key (keys(%$storehash)) {
 4789:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4790:     }
 4791:     $namevalue=~s/\&$//;
 4792:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4793:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4794: }
 4795: 
 4796: # -------------------------------------------------------------- Critical Store
 4797: 
 4798: sub cstore {
 4799:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4800:     my $home='';
 4801: 
 4802:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4803: 
 4804:     $symb=&symbclean($symb);
 4805:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4806: 
 4807:     if (!$domain) { $domain=$env{'user.domain'}; }
 4808:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4809: 
 4810:     &devalidate($symb,$stuname,$domain);
 4811: 
 4812:     $symb=escape($symb);
 4813:     if (!$namespace) { 
 4814:        unless ($namespace=$env{'request.course.id'}) { 
 4815:           return ''; 
 4816:        } 
 4817:     }
 4818:     if (!$home) { $home=$env{'user.home'}; }
 4819: 
 4820:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4821:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4822: 
 4823:     my $namevalue='';
 4824:     foreach my $key (keys(%$storehash)) {
 4825:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4826:     }
 4827:     $namevalue=~s/\&$//;
 4828:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4829:     return critical
 4830:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4831: }
 4832: 
 4833: # --------------------------------------------------------------------- Restore
 4834: 
 4835: sub restore {
 4836:     my ($symb,$namespace,$domain,$stuname) = @_;
 4837:     my $home='';
 4838: 
 4839:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4840: 
 4841:     if (!$symb) {
 4842:         return if ($namespace eq 'courserequests');
 4843:         unless ($symb=escape(&symbread())) { return ''; }
 4844:     } else {
 4845:         unless ($namespace eq 'courserequests') {
 4846:             $symb=&escape(&symbclean($symb));
 4847:         }
 4848:     }
 4849:     if (!$namespace) { 
 4850:        unless ($namespace=$env{'request.course.id'}) { 
 4851:           return ''; 
 4852:        } 
 4853:     }
 4854:     if (!$domain) { $domain=$env{'user.domain'}; }
 4855:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4856:     if (!$home) { $home=$env{'user.home'}; }
 4857:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4858: 
 4859:     my %returnhash=();
 4860:     foreach my $line (split(/\&/,$answer)) {
 4861: 	my ($name,$value)=split(/\=/,$line);
 4862:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4863:     }
 4864:     my $version;
 4865:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4866:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4867:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4868:        }
 4869:     }
 4870:     return %returnhash;
 4871: }
 4872: 
 4873: # ---------------------------------------------------------- Course Description
 4874: #
 4875: #  
 4876: 
 4877: sub coursedescription {
 4878:     my ($courseid,$args)=@_;
 4879:     $courseid=~s/^\///;
 4880:     $courseid=~s/\_/\//g;
 4881:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4882:     my $chome=&homeserver($cnum,$cdomain);
 4883:     my $normalid=$cdomain.'_'.$cnum;
 4884:     # need to always cache even if we get errors otherwise we keep 
 4885:     # trying and trying and trying to get the course description.
 4886:     my %envhash=();
 4887:     my %returnhash=();
 4888:     
 4889:     my $expiretime=600;
 4890:     if ($env{'request.course.id'} eq $normalid) {
 4891: 	$expiretime=120;
 4892:     }
 4893: 
 4894:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4895:     if (!$args->{'freshen_cache'}
 4896: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4897: 	foreach my $key (keys(%env)) {
 4898: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4899: 	    my ($setting) = $1;
 4900: 	    $returnhash{$setting} = $env{$key};
 4901: 	}
 4902: 	return %returnhash;
 4903:     }
 4904: 
 4905:     # get the data again
 4906: 
 4907:     if (!$args->{'one_time'}) {
 4908: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4909:     }
 4910: 
 4911:     if ($chome ne 'no_host') {
 4912:        %returnhash=&dump('environment',$cdomain,$cnum);
 4913:        if (!exists($returnhash{'con_lost'})) {
 4914: 	   my $username = $env{'user.name'}; # Defult username
 4915: 	   if(defined $args->{'user'}) {
 4916: 	       $username = $args->{'user'};
 4917: 	   }
 4918:            $returnhash{'home'}= $chome;
 4919: 	   $returnhash{'domain'} = $cdomain;
 4920: 	   $returnhash{'num'} = $cnum;
 4921:            if (!defined($returnhash{'type'})) {
 4922:                $returnhash{'type'} = 'Course';
 4923:            }
 4924:            while (my ($name,$value) = each %returnhash) {
 4925:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4926:            }
 4927:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4928:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4929: 	       $username.'_'.$cdomain.'_'.$cnum;
 4930:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4931:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4932:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4933:        }
 4934:     }
 4935:     if (!$args->{'one_time'}) {
 4936: 	&appenv(\%envhash);
 4937:     }
 4938:     return %returnhash;
 4939: }
 4940: 
 4941: sub update_released_required {
 4942:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4943:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4944:         $cid = $env{'request.course.id'};
 4945:         $cdom = $env{'course.'.$cid.'.domain'};
 4946:         $cnum = $env{'course.'.$cid.'.num'};
 4947:         $chome = $env{'course.'.$cid.'.home'};
 4948:     }
 4949:     if ($needsrelease) {
 4950:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4951:         my $needsupdate;
 4952:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4953:             $needsupdate = 1;
 4954:         } else {
 4955:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4956:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4957:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4958:                 $needsupdate = 1;
 4959:             }
 4960:         }
 4961:         if ($needsupdate) {
 4962:             my %needshash = (
 4963:                              'internal.releaserequired' => $needsrelease,
 4964:                             );
 4965:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4966:             if ($putresult eq 'ok') {
 4967:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4968:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4969:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4970:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4971:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4972:                 }
 4973:             }
 4974:         }
 4975:     }
 4976:     return;
 4977: }
 4978: 
 4979: # -------------------------------------------------See if a user is privileged
 4980: 
 4981: sub privileged {
 4982:     my ($username,$domain,$possdomains,$possroles)=@_;
 4983:     my $now = time;
 4984:     my $roles;
 4985:     if (ref($possroles) eq 'ARRAY') {
 4986:         $roles = $possroles; 
 4987:     } else {
 4988:         $roles = ['dc','su'];
 4989:     }
 4990:     if (ref($possdomains) eq 'ARRAY') {
 4991:         my %privileged = &privileged_by_domain($possdomains,$roles);
 4992:         foreach my $dom (@{$possdomains}) {
 4993:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 4994:                 (ref($privileged{$dom}) eq 'HASH')) {
 4995:                 foreach my $role (@{$roles}) {
 4996:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 4997:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 4998:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 4999:                             return 1 unless (($end && $end < $now) ||
 5000:                                              ($start && $start > $now));
 5001:                         }
 5002:                     }
 5003:                 }
 5004:             }
 5005:         }
 5006:     } else {
 5007:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5008:         my $now = time;
 5009: 
 5010:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5011:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5012:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5013:                 return 1 unless ($tend && $tend < $now) 
 5014:                         or ($tstart && $tstart > $now);
 5015:             }
 5016:         }
 5017:     }
 5018:     return 0;
 5019: }
 5020: 
 5021: sub privileged_by_domain {
 5022:     my ($domains,$roles) = @_;
 5023:     my %privileged = ();
 5024:     my $cachetime = 60*60*24;
 5025:     my $now = time;
 5026:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5027:         return %privileged;
 5028:     }
 5029:     foreach my $dom (@{$domains}) {
 5030:         next if (ref($privileged{$dom}) eq 'HASH');
 5031:         my $needroles;
 5032:         foreach my $role (@{$roles}) {
 5033:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5034:             if (defined($cached)) {
 5035:                 if (ref($result) eq 'HASH') {
 5036:                     $privileged{$dom}{$role} = $result;
 5037:                 }
 5038:             } else {
 5039:                 $needroles = 1;
 5040:             }
 5041:         }
 5042:         if ($needroles) {
 5043:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5044:             $privileged{$dom} = {};
 5045:             foreach my $server (keys(%dompersonnel)) {
 5046:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5047:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5048:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5049:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5050:                         next if ($end && $end < $now);
 5051:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5052:                             $dompersonnel{$server}{$item};
 5053:                     }
 5054:                 }
 5055:             }
 5056:             if (ref($privileged{$dom}) eq 'HASH') {
 5057:                 foreach my $role (@{$roles}) {
 5058:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5059:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5060:                     } else {
 5061:                         my %hash = ();
 5062:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5063:                     }
 5064:                 }
 5065:             }
 5066:         }
 5067:     }
 5068:     return %privileged;
 5069: }
 5070: 
 5071: # -------------------------------------------------------- Get user privileges
 5072: 
 5073: sub rolesinit {
 5074:     my ($domain, $username) = @_;
 5075:     my %userroles = ('user.login.time' => time);
 5076:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5077: 
 5078:     # firstaccess and timerinterval are related to timed maps/resources. 
 5079:     # also, blocking can be triggered by an activating timer
 5080:     # it's saved in the user's %env.
 5081:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5082:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5083:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5084:         %timerintchk, %timerintenv);
 5085: 
 5086:     foreach my $key (keys(%firstaccess)) {
 5087:         my ($cid, $rest) = split(/\0/, $key);
 5088:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5089:     }
 5090: 
 5091:     foreach my $key (keys(%timerinterval)) {
 5092:         my ($cid,$rest) = split(/\0/,$key);
 5093:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5094:     }
 5095: 
 5096:     my %allroles=();
 5097:     my %allgroups=();
 5098: 
 5099:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5100:         my $role = $rolesdump{$area};
 5101:         $area =~ s/\_\w\w$//;
 5102: 
 5103:         my ($trole, $tend, $tstart, $group_privs);
 5104: 
 5105:         if ($role =~ /^cr/) {
 5106:         # Custom role, defined by a user 
 5107:         # e.g., user.role.cr/msu/smith/mynewrole
 5108:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5109:                 $trole = $1;
 5110:                 ($tend, $tstart) = split('_', $2);
 5111:             } else {
 5112:                 $trole = $role;
 5113:             }
 5114:         } elsif ($role =~ m|^gr/|) {
 5115:         # Role of member in a group, defined within a course/community
 5116:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5117:             ($trole, $tend, $tstart) = split(/_/, $role);
 5118:             next if $tstart eq '-1';
 5119:             ($trole, $group_privs) = split(/\//, $trole);
 5120:             $group_privs = &unescape($group_privs);
 5121:         } else {
 5122:         # Just a normal role, defined in roles.tab
 5123:             ($trole, $tend, $tstart) = split(/_/,$role);
 5124:         }
 5125: 
 5126:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5127:                  $username);
 5128:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5129: 
 5130:         # role expired or not available yet?
 5131:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5132:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5133: 
 5134:         next if $area eq '' or $trole eq '';
 5135: 
 5136:         my $spec = "$trole.$area";
 5137:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5138: 
 5139:         if ($trole =~ /^cr\//) {
 5140:         # Custom role, defined by a user
 5141:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5142:         } elsif ($trole eq 'gr') {
 5143:         # Role of a member in a group, defined within a course/community
 5144:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5145:             next;
 5146:         } else {
 5147:         # Normal role, defined in roles.tab
 5148:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5149:         }
 5150: 
 5151:         my $cid = $tdomain.'_'.$trest;
 5152:         unless ($firstaccchk{$cid}) {
 5153:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5154:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5155:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5156:                         $coursetimerstarts{$cid}{$item}; 
 5157:                 }
 5158:             }
 5159:             $firstaccchk{$cid} = 1;
 5160:         }
 5161:         unless ($timerintchk{$cid}) {
 5162:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5163:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5164:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5165:                        $coursetimerintervals{$cid}{$item};
 5166:                 }
 5167:             }
 5168:             $timerintchk{$cid} = 1;
 5169:         }
 5170:     }
 5171: 
 5172:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5173:         \%allroles, \%allgroups);
 5174:     $env{'user.adv'} = $userroles{'user.adv'};
 5175: 
 5176:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5177: }
 5178: 
 5179: sub set_arearole {
 5180:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5181:     unless ($nolog) {
 5182: # log the associated role with the area
 5183:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5184:     }
 5185:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5186: }
 5187: 
 5188: sub custom_roleprivs {
 5189:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5190:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5191:     my $homsvr=homeserver($rauthor,$rdomain);
 5192:     if (&hostname($homsvr) ne '') {
 5193:         my ($rdummy,$roledef)=
 5194:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5195:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5196:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5197:             if (defined($syspriv)) {
 5198:                 if ($trest =~ /^$match_community$/) {
 5199:                     $syspriv =~ s/bre\&S//; 
 5200:                 }
 5201:                 $$allroles{'cm./'}.=':'.$syspriv;
 5202:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5203:             }
 5204:             if ($tdomain ne '') {
 5205:                 if (defined($dompriv)) {
 5206:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5207:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5208:                 }
 5209:                 if (($trest ne '') && (defined($coursepriv))) {
 5210:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5211:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5212:                 }
 5213:             }
 5214:         }
 5215:     }
 5216: }
 5217: 
 5218: sub group_roleprivs {
 5219:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5220:     my $access = 1;
 5221:     my $now = time;
 5222:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5223:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5224:     if ($access) {
 5225:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5226:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5227:     }
 5228: }
 5229: 
 5230: sub standard_roleprivs {
 5231:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5232:     if (defined($pr{$trole.':s'})) {
 5233:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5234:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5235:     }
 5236:     if ($tdomain ne '') {
 5237:         if (defined($pr{$trole.':d'})) {
 5238:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5239:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5240:         }
 5241:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5242:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5243:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5244:         }
 5245:     }
 5246: }
 5247: 
 5248: sub set_userprivs {
 5249:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5250:     my $author=0;
 5251:     my $adv=0;
 5252:     my %grouproles = ();
 5253:     if (keys(%{$allgroups}) > 0) {
 5254:         my @groupkeys; 
 5255:         foreach my $role (keys(%{$allroles})) {
 5256:             push(@groupkeys,$role);
 5257:         }
 5258:         if (ref($groups_roles) eq 'HASH') {
 5259:             foreach my $key (keys(%{$groups_roles})) {
 5260:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5261:                     push(@groupkeys,$key);
 5262:                 }
 5263:             }
 5264:         }
 5265:         if (@groupkeys > 0) {
 5266:             foreach my $role (@groupkeys) {
 5267:                 my ($trole,$area,$sec,$extendedarea);
 5268:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5269:                     $trole = $1;
 5270:                     $area = $2;
 5271:                     $sec = $3;
 5272:                     $extendedarea = $area.$sec;
 5273:                     if (exists($$allgroups{$area})) {
 5274:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5275:                             my $spec = $trole.'.'.$extendedarea;
 5276:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5277:                                                 $$allgroups{$area}{$group};
 5278:                         }
 5279:                     }
 5280:                 }
 5281:             }
 5282:         }
 5283:     }
 5284:     foreach my $group (keys(%grouproles)) {
 5285:         $$allroles{$group} = $grouproles{$group};
 5286:     }
 5287:     foreach my $role (keys(%{$allroles})) {
 5288:         my %thesepriv;
 5289:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5290:         foreach my $item (split(/:/,$$allroles{$role})) {
 5291:             if ($item ne '') {
 5292:                 my ($privilege,$restrictions)=split(/&/,$item);
 5293:                 if ($restrictions eq '') {
 5294:                     $thesepriv{$privilege}='F';
 5295:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5296:                     $thesepriv{$privilege}.=$restrictions;
 5297:                 }
 5298:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5299:             }
 5300:         }
 5301:         my $thesestr='';
 5302:         foreach my $priv (sort(keys(%thesepriv))) {
 5303: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5304: 	}
 5305:         $userroles->{'user.priv.'.$role} = $thesestr;
 5306:     }
 5307:     return ($author,$adv);
 5308: }
 5309: 
 5310: sub role_status {
 5311:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5312:     my @pwhere = ();
 5313:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5314:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5315:         unless (!defined($$role) || $$role eq '') {
 5316:             $$where=join('.',@pwhere);
 5317:             $$trolecode=$$role.'.'.$$where;
 5318:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5319:             $$tstatus='is';
 5320:             if ($$tstart && $$tstart>$update) {
 5321:                 $$tstatus='future';
 5322:                 if ($$tstart<$now) {
 5323:                     if ($$tstart && $$tstart>$refresh) {
 5324:                         if (($$where ne '') && ($$role ne '')) {
 5325:                             my (%allroles,%allgroups,$group_privs,
 5326:                                 %groups_roles,@rolecodes);
 5327:                             my %userroles = (
 5328:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5329:                             );
 5330:                             @rolecodes = ('cm'); 
 5331:                             my $spec=$$role.'.'.$$where;
 5332:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5333:                             if ($$role =~ /^cr\//) {
 5334:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5335:                                 push(@rolecodes,'cr');
 5336:                             } elsif ($$role eq 'gr') {
 5337:                                 push(@rolecodes,$$role);
 5338:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5339:                                                     $env{'user.name'});
 5340:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5341:                                 (undef,my $group_privs) = split(/\//,$trole);
 5342:                                 $group_privs = &unescape($group_privs);
 5343:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5344:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5345:                                 &get_groups_roles($tdomain,$trest,
 5346:                                                   \%course_roles,\@rolecodes,
 5347:                                                   \%groups_roles);
 5348:                             } else {
 5349:                                 push(@rolecodes,$$role);
 5350:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5351:                             }
 5352:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5353:                             &appenv(\%userroles,\@rolecodes);
 5354:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5355:                         }
 5356:                     }
 5357:                     $$tstatus = 'is';
 5358:                 }
 5359:             }
 5360:             if ($$tend) {
 5361:                 if ($$tend<$update) {
 5362:                     $$tstatus='expired';
 5363:                 } elsif ($$tend<$now) {
 5364:                     $$tstatus='will_not';
 5365:                 }
 5366:             }
 5367:         }
 5368:     }
 5369: }
 5370: 
 5371: sub get_groups_roles {
 5372:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5373:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5374:                   (ref($rolecodes) eq 'ARRAY') && 
 5375:                   (ref($groups_roles) eq 'HASH')); 
 5376:     if (keys(%{$cdom_courseroles}) > 0) {
 5377:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5378:         if ($cdom ne '' && $cnum ne '') {
 5379:             foreach my $key (keys(%{$cdom_courseroles})) {
 5380:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5381:                     my $crsrole = $1;
 5382:                     my $crssec = $2;
 5383:                     if ($crsrole =~ /^cr/) {
 5384:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5385:                             push(@{$rolecodes},'cr');
 5386:                         }
 5387:                     } else {
 5388:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5389:                             push(@{$rolecodes},$crsrole);
 5390:                         }
 5391:                     }
 5392:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5393:                     if ($crssec ne '') {
 5394:                         $rolekey .= "/$crssec";
 5395:                     }
 5396:                     $rolekey .= './';
 5397:                     $groups_roles->{$rolekey} = $rolecodes;
 5398:                 }
 5399:             }
 5400:         }
 5401:     }
 5402:     return;
 5403: }
 5404: 
 5405: sub delete_env_groupprivs {
 5406:     my ($where,$courseroles,$possroles) = @_;
 5407:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5408:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5409:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5410:         %{$courseroles->{$udom}} =
 5411:             &get_my_roles('','','userroles',['active'],
 5412:                           $possroles,[$udom],1);
 5413:     }
 5414:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5415:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5416:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5417:             my $area = '/'.$cdom.'/'.$cnum;
 5418:             my $privkey = "user.priv.$crsrole.$area";
 5419:             if ($crssec ne '') {
 5420:                 $privkey .= '/'.$crssec;
 5421:             }
 5422:             $privkey .= ".$area/$group";
 5423:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5424:         }
 5425:     }
 5426:     return;
 5427: }
 5428: 
 5429: sub check_adhoc_privs {
 5430:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5431:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5432:     my $setprivs;
 5433:     if ($env{$cckey}) {
 5434:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5435:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5436:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5437:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5438:             $setprivs = 1;
 5439:         }
 5440:     } else {
 5441:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5442:         $setprivs = 1;
 5443:     }
 5444:     return $setprivs;
 5445: }
 5446: 
 5447: sub set_adhoc_privileges {
 5448: # role can be cc or ca
 5449:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5450:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5451:     my $spec = $role.'.'.$area;
 5452:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5453:                                   $env{'user.name'},1);
 5454:     my %ccrole = ();
 5455:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5456:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5457:     &appenv(\%userroles,[$role,'cm']);
 5458:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5459:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5460:         &appenv( {'request.role'        => $spec,
 5461:                   'request.role.domain' => $dcdom,
 5462:                   'request.course.sec'  => ''
 5463:                  }
 5464:                );
 5465:         my $tadv=0;
 5466:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5467:         &appenv({'request.role.adv'    => $tadv});
 5468:     }
 5469: }
 5470: 
 5471: # --------------------------------------------------------------- get interface
 5472: 
 5473: sub get {
 5474:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5475:    my $items='';
 5476:    foreach my $item (@$storearr) {
 5477:        $items.=&escape($item).'&';
 5478:    }
 5479:    $items=~s/\&$//;
 5480:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5481:    if (!$uname) { $uname=$env{'user.name'}; }
 5482:    my $uhome=&homeserver($uname,$udomain);
 5483: 
 5484:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5485:    my @pairs=split(/\&/,$rep);
 5486:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5487:      return @pairs;
 5488:    }
 5489:    my %returnhash=();
 5490:    my $i=0;
 5491:    foreach my $item (@$storearr) {
 5492:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5493:       $i++;
 5494:    }
 5495:    return %returnhash;
 5496: }
 5497: 
 5498: # --------------------------------------------------------------- del interface
 5499: 
 5500: sub del {
 5501:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5502:    my $items='';
 5503:    foreach my $item (@$storearr) {
 5504:        $items.=&escape($item).'&';
 5505:    }
 5506: 
 5507:    $items=~s/\&$//;
 5508:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5509:    if (!$uname) { $uname=$env{'user.name'}; }
 5510:    my $uhome=&homeserver($uname,$udomain);
 5511:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5512: }
 5513: 
 5514: # -------------------------------------------------------------- dump interface
 5515: 
 5516: sub unserialize {
 5517:     my ($rep, $escapedkeys) = @_;
 5518: 
 5519:     return {} if $rep =~ /^error/;
 5520: 
 5521:     my %returnhash=();
 5522: 	foreach my $item (split /\&/, $rep) {
 5523: 	    my ($key, $value) = split(/=/, $item, 2);
 5524: 	    $key = unescape($key) unless $escapedkeys;
 5525: 	    next if $key =~ /^error: 2 /;
 5526: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5527: 	}
 5528:     #return %returnhash;
 5529:     return \%returnhash;
 5530: }        
 5531: 
 5532: # see Lond::dump_with_regexp
 5533: # if $escapedkeys hash keys won't get unescaped.
 5534: sub dump {
 5535:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5536:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5537:     if (!$uname) { $uname=$env{'user.name'}; }
 5538:     my $uhome=&homeserver($uname,$udomain);
 5539: 
 5540:     my $reply;
 5541:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5542:         # user is hosted on this machine
 5543:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5544:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5545:         return %{unserialize($reply, $escapedkeys)};
 5546:     }
 5547:     if ($regexp) {
 5548: 	$regexp=&escape($regexp);
 5549:     } else {
 5550: 	$regexp='.';
 5551:     }
 5552:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5553:     my @pairs=split(/\&/,$rep);
 5554:     my %returnhash=();
 5555:     if (!($rep =~ /^error/ )) {
 5556: 	foreach my $item (@pairs) {
 5557: 	    my ($key,$value)=split(/=/,$item,2);
 5558:         $key = unescape($key) unless $escapedkeys;
 5559:         #$key = &unescape($key);
 5560: 	    next if ($key =~ /^error: 2 /);
 5561: 	    $returnhash{$key}=&thaw_unescape($value);
 5562: 	}
 5563:     }
 5564:     return %returnhash;
 5565: }
 5566: 
 5567: 
 5568: # --------------------------------------------------------- dumpstore interface
 5569: 
 5570: sub dumpstore {
 5571:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5572:    # same as dump but keys must be escaped. They may contain colon separated
 5573:    # lists of values that may themself contain colons (e.g. symbs).
 5574:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5575: }
 5576: 
 5577: # -------------------------------------------------------------- keys interface
 5578: 
 5579: sub getkeys {
 5580:    my ($namespace,$udomain,$uname)=@_;
 5581:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5582:    if (!$uname) { $uname=$env{'user.name'}; }
 5583:    my $uhome=&homeserver($uname,$udomain);
 5584:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5585:    my @keyarray=();
 5586:    foreach my $key (split(/\&/,$rep)) {
 5587:       next if ($key =~ /^error: 2 /);
 5588:       push(@keyarray,&unescape($key));
 5589:    }
 5590:    return @keyarray;
 5591: }
 5592: 
 5593: # --------------------------------------------------------------- currentdump
 5594: sub currentdump {
 5595:    my ($courseid,$sdom,$sname)=@_;
 5596:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5597:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5598:    $sname    = $env{'user.name'}         if (! defined($sname));
 5599:    my $uhome = &homeserver($sname,$sdom);
 5600:    my $rep;
 5601: 
 5602:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5603:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5604:                    $courseid)));
 5605:    } else {
 5606:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5607:    }
 5608: 
 5609:    return if ($rep =~ /^(error:|no_such_host)/);
 5610:    #
 5611:    my %returnhash=();
 5612:    #
 5613:    if ($rep eq "unknown_cmd") { 
 5614:        # an old lond will not know currentdump
 5615:        # Do a dump and make it look like a currentdump
 5616:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5617:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5618:        my %hash = @tmp;
 5619:        @tmp=();
 5620:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5621:    } else {
 5622:        my @pairs=split(/\&/,$rep);
 5623:        foreach my $pair (@pairs) {
 5624:            my ($key,$value)=split(/=/,$pair,2);
 5625:            my ($symb,$param) = split(/:/,$key);
 5626:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5627:                                                         &thaw_unescape($value);
 5628:        }
 5629:    }
 5630:    return %returnhash;
 5631: }
 5632: 
 5633: sub convert_dump_to_currentdump{
 5634:     my %hash = %{shift()};
 5635:     my %returnhash;
 5636:     # Code ripped from lond, essentially.  The only difference
 5637:     # here is the unescaping done by lonnet::dump().  Conceivably
 5638:     # we might run in to problems with parameter names =~ /^v\./
 5639:     while (my ($key,$value) = each(%hash)) {
 5640:         my ($v,$symb,$param) = split(/:/,$key);
 5641: 	$symb  = &unescape($symb);
 5642: 	$param = &unescape($param);
 5643:         next if ($v eq 'version' || $symb eq 'keys');
 5644:         next if (exists($returnhash{$symb}) &&
 5645:                  exists($returnhash{$symb}->{$param}) &&
 5646:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5647:         $returnhash{$symb}->{$param}=$value;
 5648:         $returnhash{$symb}->{'v.'.$param}=$v;
 5649:     }
 5650:     #
 5651:     # Remove all of the keys in the hashes which keep track of
 5652:     # the version of the parameter.
 5653:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5654:         # use a foreach because we are going to delete from the hash.
 5655:         foreach my $key (keys(%$param_hash)) {
 5656:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5657:         }
 5658:     }
 5659:     return \%returnhash;
 5660: }
 5661: 
 5662: # ------------------------------------------------------ critical inc interface
 5663: 
 5664: sub cinc {
 5665:     return &inc(@_,'critical');
 5666: }
 5667: 
 5668: # --------------------------------------------------------------- inc interface
 5669: 
 5670: sub inc {
 5671:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5672:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5673:     if (!$uname) { $uname=$env{'user.name'}; }
 5674:     my $uhome=&homeserver($uname,$udomain);
 5675:     my $items='';
 5676:     if (! ref($store)) {
 5677:         # got a single value, so use that instead
 5678:         $items = &escape($store).'=&';
 5679:     } elsif (ref($store) eq 'SCALAR') {
 5680:         $items = &escape($$store).'=&';        
 5681:     } elsif (ref($store) eq 'ARRAY') {
 5682:         $items = join('=&',map {&escape($_);} @{$store});
 5683:     } elsif (ref($store) eq 'HASH') {
 5684:         while (my($key,$value) = each(%{$store})) {
 5685:             $items.= &escape($key).'='.&escape($value).'&';
 5686:         }
 5687:     }
 5688:     $items=~s/\&$//;
 5689:     if ($critical) {
 5690: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5691:     } else {
 5692: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5693:     }
 5694: }
 5695: 
 5696: # --------------------------------------------------------------- put interface
 5697: 
 5698: sub put {
 5699:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5700:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5701:    if (!$uname) { $uname=$env{'user.name'}; }
 5702:    my $uhome=&homeserver($uname,$udomain);
 5703:    my $items='';
 5704:    foreach my $item (keys(%$storehash)) {
 5705:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5706:    }
 5707:    $items=~s/\&$//;
 5708:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5709: }
 5710: 
 5711: # ------------------------------------------------------------ newput interface
 5712: 
 5713: sub newput {
 5714:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5715:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5716:    if (!$uname) { $uname=$env{'user.name'}; }
 5717:    my $uhome=&homeserver($uname,$udomain);
 5718:    my $items='';
 5719:    foreach my $key (keys(%$storehash)) {
 5720:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5721:    }
 5722:    $items=~s/\&$//;
 5723:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5724: }
 5725: 
 5726: # ---------------------------------------------------------  putstore interface
 5727: 
 5728: sub putstore {
 5729:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5730:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5731:    if (!$uname) { $uname=$env{'user.name'}; }
 5732:    my $uhome=&homeserver($uname,$udomain);
 5733:    my $items='';
 5734:    foreach my $key (keys(%$storehash)) {
 5735:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5736:    }
 5737:    $items=~s/\&$//;
 5738:    my $esc_symb=&escape($symb);
 5739:    my $esc_v=&escape($version);
 5740:    my $reply =
 5741:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5742: 	      $uhome);
 5743:    if ($reply eq 'unknown_cmd') {
 5744:        # gfall back to way things use to be done
 5745:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5746: 			    $uname);
 5747:    }
 5748:    return $reply;
 5749: }
 5750: 
 5751: sub old_putstore {
 5752:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5753:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5754:     if (!$uname) { $uname=$env{'user.name'}; }
 5755:     my $uhome=&homeserver($uname,$udomain);
 5756:     my %newstorehash;
 5757:     foreach my $item (keys(%$storehash)) {
 5758: 	my $key = $version.':'.&escape($symb).':'.$item;
 5759: 	$newstorehash{$key} = $storehash->{$item};
 5760:     }
 5761:     my $items='';
 5762:     my %allitems = ();
 5763:     foreach my $item (keys(%newstorehash)) {
 5764: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5765: 	    my $key = $1.':keys:'.$2;
 5766: 	    $allitems{$key} .= $3.':';
 5767: 	}
 5768: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5769:     }
 5770:     foreach my $item (keys(%allitems)) {
 5771: 	$allitems{$item} =~ s/\:$//;
 5772: 	$items.= $item.'='.$allitems{$item}.'&';
 5773:     }
 5774:     $items=~s/\&$//;
 5775:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5776: }
 5777: 
 5778: # ------------------------------------------------------ critical put interface
 5779: 
 5780: sub cput {
 5781:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5782:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5783:    if (!$uname) { $uname=$env{'user.name'}; }
 5784:    my $uhome=&homeserver($uname,$udomain);
 5785:    my $items='';
 5786:    foreach my $item (keys(%$storehash)) {
 5787:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5788:    }
 5789:    $items=~s/\&$//;
 5790:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5791: }
 5792: 
 5793: # -------------------------------------------------------------- eget interface
 5794: 
 5795: sub eget {
 5796:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5797:    my $items='';
 5798:    foreach my $item (@$storearr) {
 5799:        $items.=&escape($item).'&';
 5800:    }
 5801:    $items=~s/\&$//;
 5802:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5803:    if (!$uname) { $uname=$env{'user.name'}; }
 5804:    my $uhome=&homeserver($uname,$udomain);
 5805:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5806:    my @pairs=split(/\&/,$rep);
 5807:    my %returnhash=();
 5808:    my $i=0;
 5809:    foreach my $item (@$storearr) {
 5810:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5811:       $i++;
 5812:    }
 5813:    return %returnhash;
 5814: }
 5815: 
 5816: # ------------------------------------------------------------ tmpput interface
 5817: sub tmpput {
 5818:     my ($storehash,$server,$context)=@_;
 5819:     my $items='';
 5820:     foreach my $item (keys(%$storehash)) {
 5821: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5822:     }
 5823:     $items=~s/\&$//;
 5824:     if (defined($context)) {
 5825:         $items .= ':'.&escape($context);
 5826:     }
 5827:     return &reply("tmpput:$items",$server);
 5828: }
 5829: 
 5830: # ------------------------------------------------------------ tmpget interface
 5831: sub tmpget {
 5832:     my ($token,$server)=@_;
 5833:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5834:     my $rep=&reply("tmpget:$token",$server);
 5835:     my %returnhash;
 5836:     foreach my $item (split(/\&/,$rep)) {
 5837: 	my ($key,$value)=split(/=/,$item);
 5838:         next if ($key =~ /^error: 2 /);
 5839: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5840:     }
 5841:     return %returnhash;
 5842: }
 5843: 
 5844: # ------------------------------------------------------------ tmpdel interface
 5845: sub tmpdel {
 5846:     my ($token,$server)=@_;
 5847:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5848:     return &reply("tmpdel:$token",$server);
 5849: }
 5850: 
 5851: # ------------------------------------------------------------ get_timebased_id 
 5852: 
 5853: sub get_timebased_id {
 5854:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5855:         $maxtries) = @_;
 5856:     my ($newid,$error,$dellock);
 5857:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5858:         return ('','ok','invalid call to get suffix');
 5859:     }
 5860: 
 5861: # set defaults for any optional args for which values were not supplied
 5862:     if ($who eq '') {
 5863:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5864:     }
 5865:     if (!$locktries) {
 5866:         $locktries = 3;
 5867:     }
 5868:     if (!$maxtries) {
 5869:         $maxtries = 10;
 5870:     }
 5871:     
 5872:     if (($cdom eq '') || ($cnum eq '')) {
 5873:         if ($env{'request.course.id'}) {
 5874:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5875:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5876:         }
 5877:         if (($cdom eq '') || ($cnum eq '')) {
 5878:             return ('','ok','call to get suffix not in course context');
 5879:         }
 5880:     }
 5881: 
 5882: # construct locking item
 5883:     my $lockhash = {
 5884:                       $prefix."\0".'locked_'.$keyid => $who,
 5885:                    };
 5886:     my $tries = 0;
 5887: 
 5888: # attempt to get lock on nohist_$namespace file
 5889:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5890:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5891:         $tries ++;
 5892:         sleep 1;
 5893:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5894:     }
 5895: 
 5896: # attempt to get unique identifier, based on current timestamp
 5897:     if ($gotlock eq 'ok') {
 5898:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5899:         my $id = time;
 5900:         $newid = $id;
 5901:         my $idtries = 0;
 5902:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5903:             if ($idtype eq 'concat') {
 5904:                 $newid = $id.$idtries;
 5905:             } else {
 5906:                 $newid ++;
 5907:             }
 5908:             $idtries ++;
 5909:         }
 5910:         if (!exists($inuse{$prefix."\0".$newid})) {
 5911:             my %new_item =  (
 5912:                               $prefix."\0".$newid => $who,
 5913:                             );
 5914:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5915:                                                  $cdom,$cnum);
 5916:             if ($putresult ne 'ok') {
 5917:                 undef($newid);
 5918:                 $error = 'error saving new item: '.$putresult;
 5919:             }
 5920:         } else {
 5921:              $error = ('error: no unique suffix available for the new item ');
 5922:         }
 5923: #  remove lock
 5924:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5925:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5926:     } else {
 5927:         $error = "error: could not obtain lockfile\n";
 5928:         $dellock = 'ok';
 5929:     }
 5930:     return ($newid,$dellock,$error);
 5931: }
 5932: 
 5933: # -------------------------------------------------- portfolio access checking
 5934: 
 5935: sub portfolio_access {
 5936:     my ($requrl) = @_;
 5937:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5938:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5939:     if ($result) {
 5940:         my %setters;
 5941:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5942:             my ($startblock,$endblock) =
 5943:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5944:             if ($startblock && $endblock) {
 5945:                 return 'B';
 5946:             }
 5947:         } else {
 5948:             my ($startblock,$endblock) =
 5949:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5950:             if ($startblock && $endblock) {
 5951:                 return 'B';
 5952:             }
 5953:         }
 5954:     }
 5955:     if ($result eq 'ok') {
 5956:        return 'F';
 5957:     } elsif ($result =~ /^[^:]+:guest_/) {
 5958:        return 'A';
 5959:     }
 5960:     return '';
 5961: }
 5962: 
 5963: sub get_portfolio_access {
 5964:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5965: 
 5966:     if (!ref($access_hash)) {
 5967: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5968: 	my %access_controls = &get_access_controls($current_perms,$group,
 5969: 						   $file_name);
 5970: 	$access_hash = $access_controls{$file_name};
 5971:     }
 5972: 
 5973:     my ($public,$guest,@domains,@users,@courses,@groups);
 5974:     my $now = time;
 5975:     if (ref($access_hash) eq 'HASH') {
 5976:         foreach my $key (keys(%{$access_hash})) {
 5977:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5978:             if ($start > $now) {
 5979:                 next;
 5980:             }
 5981:             if ($end && $end<$now) {
 5982:                 next;
 5983:             }
 5984:             if ($scope eq 'public') {
 5985:                 $public = $key;
 5986:                 last;
 5987:             } elsif ($scope eq 'guest') {
 5988:                 $guest = $key;
 5989:             } elsif ($scope eq 'domains') {
 5990:                 push(@domains,$key);
 5991:             } elsif ($scope eq 'users') {
 5992:                 push(@users,$key);
 5993:             } elsif ($scope eq 'course') {
 5994:                 push(@courses,$key);
 5995:             } elsif ($scope eq 'group') {
 5996:                 push(@groups,$key);
 5997:             }
 5998:         }
 5999:         if ($public) {
 6000:             return 'ok';
 6001:         }
 6002:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6003:             if ($guest) {
 6004:                 return $guest;
 6005:             }
 6006:         } else {
 6007:             if (@domains > 0) {
 6008:                 foreach my $domkey (@domains) {
 6009:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6010:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6011:                             return 'ok';
 6012:                         }
 6013:                     }
 6014:                 }
 6015:             }
 6016:             if (@users > 0) {
 6017:                 foreach my $userkey (@users) {
 6018:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6019:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6020:                             if (ref($item) eq 'HASH') {
 6021:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6022:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6023:                                     return 'ok';
 6024:                                 }
 6025:                             }
 6026:                         }
 6027:                     } 
 6028:                 }
 6029:             }
 6030:             my %roleshash;
 6031:             my @courses_and_groups = @courses;
 6032:             push(@courses_and_groups,@groups); 
 6033:             if (@courses_and_groups > 0) {
 6034:                 my (%allgroups,%allroles); 
 6035:                 my ($start,$end,$role,$sec,$group);
 6036:                 foreach my $envkey (%env) {
 6037:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6038:                         my $cid = $2.'_'.$3; 
 6039:                         if ($1 eq 'gr') {
 6040:                             $group = $4;
 6041:                             $allgroups{$cid}{$group} = $env{$envkey};
 6042:                         } else {
 6043:                             if ($4 eq '') {
 6044:                                 $sec = 'none';
 6045:                             } else {
 6046:                                 $sec = $4;
 6047:                             }
 6048:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6049:                         }
 6050:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6051:                         my $cid = $2.'_'.$3;
 6052:                         if ($4 eq '') {
 6053:                             $sec = 'none';
 6054:                         } else {
 6055:                             $sec = $4;
 6056:                         }
 6057:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6058:                     }
 6059:                 }
 6060:                 if (keys(%allroles) == 0) {
 6061:                     return;
 6062:                 }
 6063:                 foreach my $key (@courses_and_groups) {
 6064:                     my %content = %{$$access_hash{$key}};
 6065:                     my $cnum = $content{'number'};
 6066:                     my $cdom = $content{'domain'};
 6067:                     my $cid = $cdom.'_'.$cnum;
 6068:                     if (!exists($allroles{$cid})) {
 6069:                         next;
 6070:                     }    
 6071:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6072:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6073:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6074:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6075:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6076:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6077:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6078:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6079:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6080:                                         if (grep/^all$/,@sections) {
 6081:                                             return 'ok';
 6082:                                         } else {
 6083:                                             if (grep/^$sec$/,@sections) {
 6084:                                                 return 'ok';
 6085:                                             }
 6086:                                         }
 6087:                                     }
 6088:                                 }
 6089:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6090:                                     if (grep/^none$/,@groups) {
 6091:                                         return 'ok';
 6092:                                     }
 6093:                                 } else {
 6094:                                     if (grep/^all$/,@groups) {
 6095:                                         return 'ok';
 6096:                                     } 
 6097:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6098:                                         if (grep/^$group$/,@groups) {
 6099:                                             return 'ok';
 6100:                                         }
 6101:                                     }
 6102:                                 } 
 6103:                             }
 6104:                         }
 6105:                     }
 6106:                 }
 6107:             }
 6108:             if ($guest) {
 6109:                 return $guest;
 6110:             }
 6111:         }
 6112:     }
 6113:     return;
 6114: }
 6115: 
 6116: sub course_group_datechecker {
 6117:     my ($dates,$now,$status) = @_;
 6118:     my ($start,$end) = split(/\./,$dates);
 6119:     if (!$start && !$end) {
 6120:         return 'ok';
 6121:     }
 6122:     if (grep/^active$/,@{$status}) {
 6123:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6124:             return 'ok';
 6125:         }
 6126:     }
 6127:     if (grep/^previous$/,@{$status}) {
 6128:         if ($end > $now ) {
 6129:             return 'ok';
 6130:         }
 6131:     }
 6132:     if (grep/^future$/,@{$status}) {
 6133:         if ($start > $now) {
 6134:             return 'ok';
 6135:         }
 6136:     }
 6137:     return; 
 6138: }
 6139: 
 6140: sub parse_portfolio_url {
 6141:     my ($url) = @_;
 6142: 
 6143:     my ($type,$udom,$unum,$group,$file_name);
 6144:     
 6145:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6146: 	$type = 1;
 6147:         $udom = $1;
 6148:         $unum = $2;
 6149:         $file_name = $3;
 6150:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6151: 	$type = 2;
 6152:         $udom = $1;
 6153:         $unum = $2;
 6154:         $group = $3;
 6155:         $file_name = $3.'/'.$4;
 6156:     }
 6157:     if (wantarray) {
 6158: 	return ($type,$udom,$unum,$file_name,$group);
 6159:     }
 6160:     return $type;
 6161: }
 6162: 
 6163: sub is_portfolio_url {
 6164:     my ($url) = @_;
 6165:     return scalar(&parse_portfolio_url($url));
 6166: }
 6167: 
 6168: sub is_portfolio_file {
 6169:     my ($file) = @_;
 6170:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6171:         return 1;
 6172:     }
 6173:     return;
 6174: }
 6175: 
 6176: sub usertools_access {
 6177:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6178:     my ($access,%tools);
 6179:     if ($context eq '') {
 6180:         $context = 'tools';
 6181:     }
 6182:     if ($context eq 'requestcourses') {
 6183:         %tools = (
 6184:                       official   => 1,
 6185:                       unofficial => 1,
 6186:                       community  => 1,
 6187:                  );
 6188:     } elsif ($context eq 'requestauthor') {
 6189:         %tools = (
 6190:                       requestauthor => 1,
 6191:                  );
 6192:     } else {
 6193:         %tools = (
 6194:                       aboutme   => 1,
 6195:                       blog      => 1,
 6196:                       webdav    => 1,
 6197:                       portfolio => 1,
 6198:                  );
 6199:     }
 6200:     return if (!defined($tools{$tool}));
 6201: 
 6202:     if ((!defined($udom)) || (!defined($uname))) {
 6203:         $udom = $env{'user.domain'};
 6204:         $uname = $env{'user.name'};
 6205:     }
 6206: 
 6207:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6208:         if ($action ne 'reload') {
 6209:             if ($context eq 'requestcourses') {
 6210:                 return $env{'environment.canrequest.'.$tool};
 6211:             } elsif ($context eq 'requestauthor') {
 6212:                 return $env{'environment.canrequest.author'};
 6213:             } else {
 6214:                 return $env{'environment.availabletools.'.$tool};
 6215:             }
 6216:         }
 6217:     }
 6218: 
 6219:     my ($toolstatus,$inststatus,$envkey);
 6220:     if ($context eq 'requestauthor') {
 6221:         $envkey = $context; 
 6222:     } else {
 6223:         $envkey = $context.'.'.$tool;
 6224:     }
 6225: 
 6226:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6227:          ($action ne 'reload')) {
 6228:         $toolstatus = $env{'environment.'.$envkey};
 6229:         $inststatus = $env{'environment.inststatus'};
 6230:     } else {
 6231:         if (ref($userenvref) eq 'HASH') {
 6232:             $toolstatus = $userenvref->{$envkey};
 6233:             $inststatus = $userenvref->{'inststatus'};
 6234:         } else {
 6235:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6236:             $toolstatus = $userenv{$envkey};
 6237:             $inststatus = $userenv{'inststatus'};
 6238:         }
 6239:     }
 6240: 
 6241:     if ($toolstatus ne '') {
 6242:         if ($toolstatus) {
 6243:             $access = 1;
 6244:         } else {
 6245:             $access = 0;
 6246:         }
 6247:         return $access;
 6248:     }
 6249: 
 6250:     my ($is_adv,%domdef);
 6251:     if (ref($is_advref) eq 'HASH') {
 6252:         $is_adv = $is_advref->{'is_adv'};
 6253:     } else {
 6254:         $is_adv = &is_advanced_user($udom,$uname);
 6255:     }
 6256:     if (ref($domdefref) eq 'HASH') {
 6257:         %domdef = %{$domdefref};
 6258:     } else {
 6259:         %domdef = &get_domain_defaults($udom);
 6260:     }
 6261:     if (ref($domdef{$tool}) eq 'HASH') {
 6262:         if ($is_adv) {
 6263:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6264:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6265:                     $access = 1;
 6266:                 } else {
 6267:                     $access = 0;
 6268:                 }
 6269:                 return $access;
 6270:             }
 6271:         }
 6272:         if ($inststatus ne '') {
 6273:             my ($hasaccess,$hasnoaccess);
 6274:             foreach my $affiliation (split(/:/,$inststatus)) {
 6275:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6276:                     if ($domdef{$tool}{$affiliation}) {
 6277:                         $hasaccess = 1;
 6278:                     } else {
 6279:                         $hasnoaccess = 1;
 6280:                     }
 6281:                 }
 6282:             }
 6283:             if ($hasaccess || $hasnoaccess) {
 6284:                 if ($hasaccess) {
 6285:                     $access = 1;
 6286:                 } elsif ($hasnoaccess) {
 6287:                     $access = 0; 
 6288:                 }
 6289:                 return $access;
 6290:             }
 6291:         } else {
 6292:             if ($domdef{$tool}{'default'} ne '') {
 6293:                 if ($domdef{$tool}{'default'}) {
 6294:                     $access = 1;
 6295:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6296:                     $access = 0;
 6297:                 }
 6298:                 return $access;
 6299:             }
 6300:         }
 6301:     } else {
 6302:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6303:             $access = 1;
 6304:         } else {
 6305:             $access = 0;
 6306:         }
 6307:         return $access;
 6308:     }
 6309: }
 6310: 
 6311: sub is_course_owner {
 6312:     my ($cdom,$cnum,$udom,$uname) = @_;
 6313:     if (($udom eq '') || ($uname eq '')) {
 6314:         $udom = $env{'user.domain'};
 6315:         $uname = $env{'user.name'};
 6316:     }
 6317:     unless (($udom eq '') || ($uname eq '')) {
 6318:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6319:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6320:                 return 1;
 6321:             } else {
 6322:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6323:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6324:                     return 1;
 6325:                 }
 6326:             }
 6327:         }
 6328:     }
 6329:     return;
 6330: }
 6331: 
 6332: sub is_advanced_user {
 6333:     my ($udom,$uname) = @_;
 6334:     if ($udom ne '' && $uname ne '') {
 6335:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6336:             if (wantarray) {
 6337:                 return ($env{'user.adv'},$env{'user.author'});
 6338:             } else {
 6339:                 return $env{'user.adv'};
 6340:             }
 6341:         }
 6342:     }
 6343:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6344:     my %allroles;
 6345:     my ($is_adv,$is_author);
 6346:     foreach my $role (keys(%roleshash)) {
 6347:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6348:         my $area = '/'.$tdomain.'/'.$trest;
 6349:         if ($sec ne '') {
 6350:             $area .= '/'.$sec;
 6351:         }
 6352:         if (($area ne '') && ($trole ne '')) {
 6353:             my $spec=$trole.'.'.$area;
 6354:             if ($trole =~ /^cr\//) {
 6355:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6356:             } elsif ($trole ne 'gr') {
 6357:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6358:             }
 6359:             if ($trole eq 'au') {
 6360:                 $is_author = 1;
 6361:             }
 6362:         }
 6363:     }
 6364:     foreach my $role (keys(%allroles)) {
 6365:         last if ($is_adv);
 6366:         foreach my $item (split(/:/,$allroles{$role})) {
 6367:             if ($item ne '') {
 6368:                 my ($privilege,$restrictions)=split(/&/,$item);
 6369:                 if ($privilege eq 'adv') {
 6370:                     $is_adv = 1;
 6371:                     last;
 6372:                 }
 6373:             }
 6374:         }
 6375:     }
 6376:     if (wantarray) {
 6377:         return ($is_adv,$is_author);
 6378:     }
 6379:     return $is_adv;
 6380: }
 6381: 
 6382: sub check_can_request {
 6383:     my ($dom,$can_request,$request_domains) = @_;
 6384:     my $canreq = 0;
 6385:     my ($types,$typename) = &Apache::loncommon::course_types();
 6386:     my @options = ('approval','validate','autolimit');
 6387:     my $optregex = join('|',@options);
 6388:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6389:         foreach my $type (@{$types}) {
 6390:             if (&usertools_access($env{'user.name'},
 6391:                                   $env{'user.domain'},
 6392:                                   $type,undef,'requestcourses')) {
 6393:                 $canreq ++;
 6394:                 if (ref($request_domains) eq 'HASH') {
 6395:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6396:                 }
 6397:                 if ($dom eq $env{'user.domain'}) {
 6398:                     $can_request->{$type} = 1;
 6399:                 }
 6400:             }
 6401:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6402:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6403:                 if (@curr > 0) {
 6404:                     foreach my $item (@curr) {
 6405:                         if (ref($request_domains) eq 'HASH') {
 6406:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6407:                             if ($otherdom ne '') {
 6408:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6409:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6410:                                         push(@{$request_domains->{$type}},$otherdom);
 6411:                                     }
 6412:                                 } else {
 6413:                                     push(@{$request_domains->{$type}},$otherdom);
 6414:                                 }
 6415:                             }
 6416:                         }
 6417:                     }
 6418:                     unless($dom eq $env{'user.domain'}) {
 6419:                         $canreq ++;
 6420:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6421:                             $can_request->{$type} = 1;
 6422:                         }
 6423:                     }
 6424:                 }
 6425:             }
 6426:         }
 6427:     }
 6428:     return $canreq;
 6429: }
 6430: 
 6431: # ---------------------------------------------- Custom access rule evaluation
 6432: 
 6433: sub customaccess {
 6434:     my ($priv,$uri)=@_;
 6435:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6436:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6437:     $udom = &LONCAPA::clean_domain($udom);
 6438:     $ucrs = &LONCAPA::clean_username($ucrs);
 6439:     my $access=0;
 6440:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6441: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6442: 	if ($type eq 'user') {
 6443: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6444: 		my ($tdom,$tuname)=split(m{/},$scope);
 6445: 		if ($tdom) {
 6446: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6447: 		}
 6448: 		if ($tuname) {
 6449: 		    if ($tuname ne $env{'user.name'}) { next; }
 6450: 		}
 6451: 		$access=($effect eq 'allow');
 6452: 		last;
 6453: 	    }
 6454: 	} else {
 6455: 	    if ($role) {
 6456: 		if ($role ne $urole) { next; }
 6457: 	    }
 6458: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6459: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6460: 		if ($tdom) {
 6461: 		    if ($tdom ne $udom) { next; }
 6462: 		}
 6463: 		if ($tcrs) {
 6464: 		    if ($tcrs ne $ucrs) { next; }
 6465: 		}
 6466: 		if ($tsec) {
 6467: 		    if ($tsec ne $usec) { next; }
 6468: 		}
 6469: 		$access=($effect eq 'allow');
 6470: 		last;
 6471: 	    }
 6472: 	    if ($realm eq '' && $role eq '') {
 6473: 		$access=($effect eq 'allow');
 6474: 	    }
 6475: 	}
 6476:     }
 6477:     return $access;
 6478: }
 6479: 
 6480: # ------------------------------------------------- Check for a user privilege
 6481: 
 6482: sub allowed {
 6483:     my ($priv,$uri,$symb,$role)=@_;
 6484:     my $ver_orguri=$uri;
 6485:     $uri=&deversion($uri);
 6486:     my $orguri=$uri;
 6487:     $uri=&declutter($uri);
 6488: 
 6489:     if ($priv eq 'evb') {
 6490: # Evade communication block restrictions for specified role in a course
 6491:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6492:             return $1;
 6493:         } else {
 6494:             return;
 6495:         }
 6496:     }
 6497: 
 6498:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6499: # Free bre access to adm and meta resources
 6500:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6501: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6502: 	&& ($priv eq 'bre')) {
 6503: 	return 'F';
 6504:     }
 6505: 
 6506: # Free bre access to user's own portfolio contents
 6507:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6508:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6509: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6510:         my %setters;
 6511:         my ($startblock,$endblock) = 
 6512:             &Apache::loncommon::blockcheck(\%setters,'port');
 6513:         if ($startblock && $endblock) {
 6514:             return 'B';
 6515:         } else {
 6516:             return 'F';
 6517:         }
 6518:     }
 6519: 
 6520: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6521:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6522:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6523:         if (exists($env{'request.course.id'})) {
 6524:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6525:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6526:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6527:                 my $courseprivid=$env{'request.course.id'};
 6528:                 $courseprivid=~s/\_/\//;
 6529:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6530:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6531:                     return $1; 
 6532:                 } else {
 6533:                     if ($env{'request.course.sec'}) {
 6534:                         $courseprivid.='/'.$env{'request.course.sec'};
 6535:                     }
 6536:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6537:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6538:                         return $2;
 6539:                     }
 6540:                 }
 6541:             }
 6542:         }
 6543:     }
 6544: 
 6545: # Free bre to public access
 6546: 
 6547:     if ($priv eq 'bre') {
 6548:         my $copyright=&metadata($uri,'copyright');
 6549: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6550:            return 'F'; 
 6551:         }
 6552:         if ($copyright eq 'priv') {
 6553:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6554: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6555: 		return '';
 6556:             }
 6557:         }
 6558:         if ($copyright eq 'domain') {
 6559:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6560: 	    unless (($env{'user.domain'} eq $1) ||
 6561:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6562: 		return '';
 6563:             }
 6564:         }
 6565:         if ($env{'request.role'}=~ /li\.\//) {
 6566:             # Library role, so allow browsing of resources in this domain.
 6567:             return 'F';
 6568:         }
 6569:         if ($copyright eq 'custom') {
 6570: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6571:         }
 6572:     }
 6573:     # Domain coordinator is trying to create a course
 6574:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6575:         # uri is the requested domain in this case.
 6576:         # comparison to 'request.role.domain' shows if the user has selected
 6577:         # a role of dc for the domain in question.
 6578:         return 'F' if ($uri eq $env{'request.role.domain'});
 6579:     }
 6580: 
 6581:     my $thisallowed='';
 6582:     my $statecond=0;
 6583:     my $courseprivid='';
 6584: 
 6585:     my $ownaccess;
 6586:     # Community Coordinator or Assistant Co-author browsing resource space.
 6587:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6588:         if ($uri eq '') {
 6589:             $ownaccess = 1;
 6590:         } else {
 6591:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6592:                 my $udom = $env{'user.domain'};
 6593:                 my $uname = $env{'user.name'};
 6594:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6595:                     $ownaccess = 1;
 6596:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6597:                     unless ($uri =~ m{\.\./}) {
 6598:                         $ownaccess = 1;
 6599:                     }
 6600:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6601:                     my $now = time;
 6602:                     if ($uri =~ m{^([^/]+)/?$}) {
 6603:                         my $adom = $1;
 6604:                         foreach my $key (keys(%env)) {
 6605:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6606:                                 my ($start,$end) = split('.',$env{$key});
 6607:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6608:                                     $ownaccess = 1;
 6609:                                     last;
 6610:                                 }
 6611:                             }
 6612:                         }
 6613:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6614:                         my $adom = $1;
 6615:                         my $aname = $2;
 6616:                         foreach my $role ('ca','aa') { 
 6617:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6618:                                 my ($start,$end) =
 6619:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6620:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6621:                                     $ownaccess = 1;
 6622:                                     last;
 6623:                                 }
 6624:                             }
 6625:                         }
 6626:                     }
 6627:                 }
 6628:             }
 6629:         }
 6630:     }
 6631: 
 6632: # Course
 6633: 
 6634:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6635:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6636:             $thisallowed.=$1;
 6637:         }
 6638:     }
 6639: 
 6640: # Domain
 6641: 
 6642:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6643:        =~/\Q$priv\E\&([^\:]*)/) {
 6644:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6645:             $thisallowed.=$1;
 6646:         }
 6647:     }
 6648: 
 6649: # User who is not author or co-author might still be able to edit
 6650: # resource of an author in the domain (e.g., if Domain Coordinator).
 6651:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6652:         (&allowed('mdc',$env{'request.course.id'}))) {
 6653:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6654:             $thisallowed.=$1;
 6655:         }
 6656:     }
 6657: 
 6658: # Course: uri itself is a course
 6659:     my $courseuri=$uri;
 6660:     $courseuri=~s/\_(\d)/\/$1/;
 6661:     $courseuri=~s/^([^\/])/\/$1/;
 6662: 
 6663:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6664:        =~/\Q$priv\E\&([^\:]*)/) {
 6665:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6666:             $thisallowed.=$1;
 6667:         }
 6668:     }
 6669: 
 6670: # URI is an uploaded document for this course, default permissions don't matter
 6671: # not allowing 'edit' access (editupload) to uploaded course docs
 6672:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6673: 	$thisallowed='';
 6674:         my ($match)=&is_on_map($uri);
 6675:         if ($match) {
 6676:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6677:                   =~/\Q$priv\E\&([^\:]*)/) {
 6678:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6679:                 if (@blockers > 0) {
 6680:                     $thisallowed = 'B';
 6681:                 } else {
 6682:                     $thisallowed.=$1;
 6683:                 }
 6684:             }
 6685:         } else {
 6686:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6687:             if ($refuri) {
 6688:                 if ($refuri =~ m|^/adm/|) {
 6689:                     $thisallowed='F';
 6690:                 } else {
 6691:                     $refuri=&declutter($refuri);
 6692:                     my ($match) = &is_on_map($refuri);
 6693:                     if ($match) {
 6694:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6695:                         if (@blockers > 0) {
 6696:                             $thisallowed = 'B';
 6697:                         } else {
 6698:                             $thisallowed='F';
 6699:                         }
 6700:                     }
 6701:                 }
 6702:             }
 6703:         }
 6704:     }
 6705: 
 6706:     if ($priv eq 'bre'
 6707: 	&& $thisallowed ne 'F' 
 6708: 	&& $thisallowed ne '2'
 6709: 	&& &is_portfolio_url($uri)) {
 6710: 	$thisallowed = &portfolio_access($uri);
 6711:     }
 6712:     
 6713: # Full access at system, domain or course-wide level? Exit.
 6714:     if ($thisallowed=~/F/) {
 6715: 	return 'F';
 6716:     }
 6717: 
 6718: # If this is generating or modifying users, exit with special codes
 6719: 
 6720:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6721: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6722: 	    my ($audom,$auname)=split('/',$uri);
 6723: # no author name given, so this just checks on the general right to make a co-author in this domain
 6724: 	    unless ($auname) { return $thisallowed; }
 6725: # an author name is given, so we are about to actually make a co-author for a certain account
 6726: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6727: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6728: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6729: 	}
 6730: 	return $thisallowed;
 6731:     }
 6732: #
 6733: # Gathered so far: system, domain and course wide privileges
 6734: #
 6735: # Course: See if uri or referer is an individual resource that is part of 
 6736: # the course
 6737: 
 6738:     if ($env{'request.course.id'}) {
 6739: 
 6740:        $courseprivid=$env{'request.course.id'};
 6741:        if ($env{'request.course.sec'}) {
 6742:           $courseprivid.='/'.$env{'request.course.sec'};
 6743:        }
 6744:        $courseprivid=~s/\_/\//;
 6745:        my $checkreferer=1;
 6746:        my ($match,$cond)=&is_on_map($uri);
 6747:        if ($match) {
 6748:            $statecond=$cond;
 6749:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6750:                =~/\Q$priv\E\&([^\:]*)/) {
 6751:                my $value = $1;
 6752:                if ($priv eq 'bre') {
 6753:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6754:                    if (@blockers > 0) {
 6755:                        $thisallowed = 'B';
 6756:                    } else {
 6757:                        $thisallowed.=$value;
 6758:                    }
 6759:                } else {
 6760:                    $thisallowed.=$value;
 6761:                }
 6762:                $checkreferer=0;
 6763:            }
 6764:        }
 6765:        
 6766:        if ($checkreferer) {
 6767: 	  my $refuri=$env{'httpref.'.$orguri};
 6768:             unless ($refuri) {
 6769:                 foreach my $key (keys(%env)) {
 6770: 		    if ($key=~/^httpref\..*\*/) {
 6771: 			my $pattern=$key;
 6772:                         $pattern=~s/^httpref\.\/res\///;
 6773:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6774:                         $pattern=~s/\//\\\//g;
 6775:                         if ($orguri=~/$pattern/) {
 6776: 			    $refuri=$env{$key};
 6777:                         }
 6778:                     }
 6779:                 }
 6780:             }
 6781: 
 6782:          if ($refuri) { 
 6783: 	  $refuri=&declutter($refuri);
 6784:           my ($match,$cond)=&is_on_map($refuri);
 6785:             if ($match) {
 6786:               my $refstatecond=$cond;
 6787:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6788:                   =~/\Q$priv\E\&([^\:]*)/) {
 6789:                   my $value = $1;
 6790:                   if ($priv eq 'bre') {
 6791:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6792:                       if (@blockers > 0) {
 6793:                           $thisallowed = 'B';
 6794:                       } else {
 6795:                           $thisallowed.=$value;
 6796:                       }
 6797:                   } else {
 6798:                       $thisallowed.=$value;
 6799:                   }
 6800:                   $uri=$refuri;
 6801:                   $statecond=$refstatecond;
 6802:               }
 6803:           }
 6804:         }
 6805:        }
 6806:    }
 6807: 
 6808: #
 6809: # Gathered now: all privileges that could apply, and condition number
 6810: # 
 6811: #
 6812: # Full or no access?
 6813: #
 6814: 
 6815:     if ($thisallowed=~/F/) {
 6816: 	return 'F';
 6817:     }
 6818: 
 6819:     unless ($thisallowed) {
 6820:         return '';
 6821:     }
 6822: 
 6823: # Restrictions exist, deal with them
 6824: #
 6825: #   C:according to course preferences
 6826: #   R:according to resource settings
 6827: #   L:unless locked
 6828: #   X:according to user session state
 6829: #
 6830: 
 6831: # Possibly locked functionality, check all courses
 6832: # Locks might take effect only after 10 minutes cache expiration for other
 6833: # courses, and 2 minutes for current course
 6834: 
 6835:     my $envkey;
 6836:     if ($thisallowed=~/L/) {
 6837:         foreach $envkey (keys(%env)) {
 6838:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6839:                my $courseid=$2;
 6840:                my $roleid=$1.'.'.$2;
 6841:                $courseid=~s/^\///;
 6842:                my $expiretime=600;
 6843:                if ($env{'request.role'} eq $roleid) {
 6844: 		  $expiretime=120;
 6845:                }
 6846: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6847:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6848:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6849: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6850:                }
 6851:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6852:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6853: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6854:                        &log($env{'user.domain'},$env{'user.name'},
 6855:                             $env{'user.home'},
 6856:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6857:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6858:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6859: 		       return '';
 6860:                    }
 6861:                }
 6862:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6863:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6864: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6865:                        &log($env{'user.domain'},$env{'user.name'},
 6866:                             $env{'user.home'},
 6867:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6868:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6869:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6870: 		       return '';
 6871:                    }
 6872:                }
 6873: 	   }
 6874:        }
 6875:     }
 6876:    
 6877: #
 6878: # Rest of the restrictions depend on selected course
 6879: #
 6880: 
 6881:     unless ($env{'request.course.id'}) {
 6882: 	if ($thisallowed eq 'A') {
 6883: 	    return 'A';
 6884:         } elsif ($thisallowed eq 'B') {
 6885:             return 'B';
 6886: 	} else {
 6887: 	    return '1';
 6888: 	}
 6889:     }
 6890: 
 6891: #
 6892: # Now user is definitely in a course
 6893: #
 6894: 
 6895: 
 6896: # Course preferences
 6897: 
 6898:    if ($thisallowed=~/C/) {
 6899:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6900:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6901:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6902: 	   =~/\Q$rolecode\E/) {
 6903: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6904: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6905: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6906: 			$env{'request.course.id'});
 6907: 	   }
 6908:            return '';
 6909:        }
 6910: 
 6911:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6912: 	   =~/\Q$unamedom\E/) {
 6913: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6914: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6915: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6916: 			$env{'request.course.id'});
 6917: 	   }
 6918:            return '';
 6919:        }
 6920:    }
 6921: 
 6922: # Resource preferences
 6923: 
 6924:    if ($thisallowed=~/R/) {
 6925:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6926:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6927: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6928: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6929: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6930: 	   }
 6931: 	   return '';
 6932:        }
 6933:    }
 6934: 
 6935: # Restricted by state or randomout?
 6936: 
 6937:    if ($thisallowed=~/X/) {
 6938:       if ($env{'acc.randomout'}) {
 6939: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6940:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6941:             return ''; 
 6942:          }
 6943:       }
 6944:       if (&condval($statecond)) {
 6945: 	 return '2';
 6946:       } else {
 6947:          return '';
 6948:       }
 6949:    }
 6950: 
 6951:     if ($thisallowed eq 'A') {
 6952: 	return 'A';
 6953:     } elsif ($thisallowed eq 'B') {
 6954:         return 'B';
 6955:     }
 6956:    return 'F';
 6957: }
 6958: 
 6959: # ------------------------------------------- Check construction space access
 6960: 
 6961: sub constructaccess {
 6962:     my ($url,$setpriv)=@_;
 6963: 
 6964: # We do not allow editing of previous versions of files
 6965:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6966: 
 6967: # Get username and domain from URL
 6968:     my ($ownername,$ownerdomain,$ownerhome);
 6969: 
 6970:     ($ownerdomain,$ownername) =
 6971:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6972: 
 6973: # The URL does not really point to any authorspace, forget it
 6974:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6975: 
 6976: # Now we need to see if the user has access to the authorspace of
 6977: # $ownername at $ownerdomain
 6978: 
 6979:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6980: # Real author for this?
 6981:        $ownerhome = $env{'user.home'};
 6982:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6983:           return ($ownername,$ownerdomain,$ownerhome);
 6984:        }
 6985:     } else {
 6986: # Co-author for this?
 6987:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6988:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6989:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6990:             return ($ownername,$ownerdomain,$ownerhome);
 6991:         }
 6992:     }
 6993: 
 6994: # We don't have any access right now. If we are not possibly going to do anything about this,
 6995: # we might as well leave
 6996:    unless ($setpriv) { return ''; }
 6997: 
 6998: # Backdoor access?
 6999:     my $allowed=&allowed('eco',$ownerdomain);
 7000: # Nope
 7001:     unless ($allowed) { return ''; }
 7002: # Looks like we may have access, but could be locked by the owner of the construction space
 7003:     if ($allowed eq 'U') {
 7004:         my %blocked=&get('environment',['domcoord.author'],
 7005:                          $ownerdomain,$ownername);
 7006: # Is blocked by owner
 7007:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7008:     }
 7009:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7010: # Grant temporary access
 7011:         my $then=$env{'user.login.time'};
 7012:         my $update=$env{'user.update.time'};
 7013:         if (!$update) { $update = $then; }
 7014:         my $refresh=$env{'user.refresh.time'};
 7015:         if (!$refresh) { $refresh = $update; }
 7016:         my $now = time;
 7017:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7018:                            $now,'ca','constructaccess');
 7019:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7020:         return($ownername,$ownerdomain,$ownerhome);
 7021:     }
 7022: # No business here
 7023:     return '';
 7024: }
 7025: 
 7026: sub get_comm_blocks {
 7027:     my ($cdom,$cnum) = @_;
 7028:     if ($cdom eq '' || $cnum eq '') {
 7029:         return unless ($env{'request.course.id'});
 7030:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7031:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7032:     }
 7033:     my %commblocks;
 7034:     my $hashid=$cdom.'_'.$cnum;
 7035:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7036:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7037:         %commblocks = %{$blocksref};
 7038:     } else {
 7039:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7040:         my $cachetime = 600;
 7041:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7042:     }
 7043:     return %commblocks;
 7044: }
 7045: 
 7046: sub has_comm_blocking {
 7047:     my ($priv,$symb,$uri,$blocks) = @_;
 7048:     return unless ($env{'request.course.id'});
 7049:     return unless ($priv eq 'bre');
 7050:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7051:     my %commblocks;
 7052:     if (ref($blocks) eq 'HASH') {
 7053:         %commblocks = %{$blocks};
 7054:     } else {
 7055:         %commblocks = &get_comm_blocks();
 7056:     }
 7057:     return unless (keys(%commblocks) > 0);
 7058:     if (!$symb) { $symb=&symbread($uri,1); }
 7059:     my ($map,$resid,undef)=&decode_symb($symb);
 7060:     my %tocheck = (
 7061:                     maps      => $map,
 7062:                     resources => $symb,
 7063:                   );
 7064:     my @blockers;
 7065:     my $now = time;
 7066:     my $navmap = Apache::lonnavmaps::navmap->new();
 7067:     foreach my $block (keys(%commblocks)) {
 7068:         if ($block =~ /^(\d+)____(\d+)$/) {
 7069:             my ($start,$end) = ($1,$2);
 7070:             if ($start <= $now && $end >= $now) {
 7071:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7072:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7073:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7074:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7075:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7076:                                     push(@blockers,$block);
 7077:                                 }
 7078:                             }
 7079:                         }
 7080:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7081:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7082:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7083:                                     push(@blockers,$block);
 7084:                                 }
 7085:                             }
 7086:                         }
 7087:                     }
 7088:                 }
 7089:             }
 7090:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7091:             my $item = $1;
 7092:             my @to_test;
 7093:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7094:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7095:                     my $check_interval;
 7096:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7097:                         my @interval;
 7098:                         my $type = 'map';
 7099:                         if ($item eq 'course') {
 7100:                             $type = 'course';
 7101:                             @interval=&EXT("resource.0.interval");
 7102:                         } else {
 7103:                             if ($item =~ /___\d+___/) {
 7104:                                 $type = 'resource';
 7105:                                 @interval=&EXT("resource.0.interval",$item);
 7106:                                 if (ref($navmap)) {                        
 7107:                                     my $res = $navmap->getBySymb($item); 
 7108:                                     push(@to_test,$res);
 7109:                                 }
 7110:                             } else {
 7111:                                 my $mapsymb = &symbread($item,1);
 7112:                                 if ($mapsymb) {
 7113:                                     if (ref($navmap)) {
 7114:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7115:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7116:                                         foreach my $res (@to_test) {
 7117:                                             my $symb = $res->symb();
 7118:                                             next if ($symb eq $mapsymb);
 7119:                                             if ($symb ne '') {
 7120:                                                 @interval=&EXT("resource.0.interval",$symb);
 7121:                                                 last;
 7122:                                             }
 7123:                                         }
 7124:                                     }
 7125:                                 }
 7126:                             }
 7127:                         }
 7128:                         if ($interval[0] =~ /\d+/) {
 7129:                             my $first_access;
 7130:                             if ($type eq 'resource') {
 7131:                                 $first_access=&get_first_access($interval[1],$item);
 7132:                             } elsif ($type eq 'map') {
 7133:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7134:                             } else {
 7135:                                 $first_access=&get_first_access($interval[1]);
 7136:                             }
 7137:                             if ($first_access) {
 7138:                                 my $timesup = $first_access+$interval[0];
 7139:                                 if ($timesup > $now) {
 7140:                                     foreach my $res (@to_test) {
 7141:                                         if ($res->is_problem()) {
 7142:                                             if ($res->completable()) {
 7143:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7144:                                                     push(@blockers,$block);
 7145:                                                 }
 7146:                                                 last;
 7147:                                             }
 7148:                                         }
 7149:                                     }
 7150:                                 }
 7151:                             }
 7152:                         }
 7153:                     }
 7154:                 }
 7155:             }
 7156:         }
 7157:     }
 7158:     return @blockers;
 7159: }
 7160: 
 7161: sub check_docs_block {
 7162:     my ($docsblock,$tocheck) =@_;
 7163:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7164:         return;
 7165:     }
 7166:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7167:         if ($tocheck->{'maps'}) {
 7168:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7169:                 return 1;
 7170:             }
 7171:         }
 7172:     }
 7173:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7174:         if ($tocheck->{'resources'}) {
 7175:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7176:                 return 1;
 7177:             }
 7178:         }
 7179:     }
 7180:     return;
 7181: }
 7182: 
 7183: #
 7184: #   Removes the versino from a URI and
 7185: #   splits it in to its filename and path to the filename.
 7186: #   Seems like File::Basename could have done this more clearly.
 7187: #   Parameters:
 7188: #      $uri   - input URI
 7189: #   Returns:
 7190: #     Two element list consisting of 
 7191: #     $pathname  - the URI up to and excluding the trailing /
 7192: #     $filename  - The part of the URI following the last /
 7193: #  NOTE:
 7194: #    Another realization of this is simply:
 7195: #    use File::Basename;
 7196: #    ...
 7197: #    $uri = shift;
 7198: #    $filename = basename($uri);
 7199: #    $path     = dirname($uri);
 7200: #    return ($filename, $path);
 7201: #
 7202: #     The implementation below is probably faster however.
 7203: #
 7204: sub split_uri_for_cond {
 7205:     my $uri=&deversion(&declutter(shift));
 7206:     my @uriparts=split(/\//,$uri);
 7207:     my $filename=pop(@uriparts);
 7208:     my $pathname=join('/',@uriparts);
 7209:     return ($pathname,$filename);
 7210: }
 7211: # --------------------------------------------------- Is a resource on the map?
 7212: 
 7213: sub is_on_map {
 7214:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7215:     #Trying to find the conditional for the file
 7216:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7217: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7218:     if ($match) {
 7219: 	return (1,$1);
 7220:     } else {
 7221: 	return (0,0);
 7222:     }
 7223: }
 7224: 
 7225: # --------------------------------------------------------- Get symb from alias
 7226: 
 7227: sub get_symb_from_alias {
 7228:     my $symb=shift;
 7229:     my ($map,$resid,$url)=&decode_symb($symb);
 7230: # Already is a symb
 7231:     if ($url) { return $symb; }
 7232: # Must be an alias
 7233:     my $aliassymb='';
 7234:     my %bighash;
 7235:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7236:                             &GDBM_READER(),0640)) {
 7237:         my $rid=$bighash{'mapalias_'.$symb};
 7238: 	if ($rid) {
 7239: 	    my ($mapid,$resid)=split(/\./,$rid);
 7240: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7241: 				    $resid,$bighash{'src_'.$rid});
 7242: 	}
 7243:         untie %bighash;
 7244:     }
 7245:     return $aliassymb;
 7246: }
 7247: 
 7248: # ----------------------------------------------------------------- Define Role
 7249: 
 7250: sub definerole {
 7251:   if (allowed('mcr','/')) {
 7252:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7253:     foreach my $role (split(':',$sysrole)) {
 7254: 	my ($crole,$cqual)=split(/\&/,$role);
 7255:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7256:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7257: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7258:                return "refused:s:$crole&$cqual"; 
 7259:             }
 7260:         }
 7261:     }
 7262:     foreach my $role (split(':',$domrole)) {
 7263: 	my ($crole,$cqual)=split(/\&/,$role);
 7264:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7265:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7266: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7267:                return "refused:d:$crole&$cqual"; 
 7268:             }
 7269:         }
 7270:     }
 7271:     foreach my $role (split(':',$courole)) {
 7272: 	my ($crole,$cqual)=split(/\&/,$role);
 7273:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7274:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7275: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7276:                return "refused:c:$crole&$cqual"; 
 7277:             }
 7278:         }
 7279:     }
 7280:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7281:                 "$env{'user.domain'}:$env{'user.name'}:".
 7282: 	        "rolesdef_$rolename=".
 7283:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7284:     return reply($command,$env{'user.home'});
 7285:   } else {
 7286:     return 'refused';
 7287:   }
 7288: }
 7289: 
 7290: # ---------------- Make a metadata query against the network of library servers
 7291: 
 7292: sub metadata_query {
 7293:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7294:     my %rhash;
 7295:     my %libserv = &all_library();
 7296:     my @server_list = (defined($server_array) ? @$server_array
 7297:                                               : keys(%libserv) );
 7298:     for my $server (@server_list) {
 7299:         my $domains = ''; 
 7300:         if (ref($domains_hash) eq 'HASH') {
 7301:             $domains = $domains_hash->{$server}; 
 7302:         }
 7303: 	unless ($custom or $customshow) {
 7304: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7305: 	    $rhash{$server}=$reply;
 7306: 	}
 7307: 	else {
 7308: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7309: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7310: 			     $server);
 7311: 	    $rhash{$server}=$reply;
 7312: 	}
 7313:     }
 7314:     return \%rhash;
 7315: }
 7316: 
 7317: # ----------------------------------------- Send log queries and wait for reply
 7318: 
 7319: sub log_query {
 7320:     my ($uname,$udom,$query,%filters)=@_;
 7321:     my $uhome=&homeserver($uname,$udom);
 7322:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7323:     my $uhost=&hostname($uhome);
 7324:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7325:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7326:                        $uhome);
 7327:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7328:     return get_query_reply($queryid);
 7329: }
 7330: 
 7331: # -------------------------- Update MySQL table for portfolio file
 7332: 
 7333: sub update_portfolio_table {
 7334:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7335:     if ($group ne '') {
 7336:         $file_name =~s /^\Q$group\E//;
 7337:     }
 7338:     my $homeserver = &homeserver($uname,$udom);
 7339:     my $queryid=
 7340:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7341:                ':'.&escape($file_name).':'.$action,$homeserver);
 7342:     my $reply = &get_query_reply($queryid);
 7343:     return $reply;
 7344: }
 7345: 
 7346: # -------------------------- Update MySQL allusers table
 7347: 
 7348: sub update_allusers_table {
 7349:     my ($uname,$udom,$names) = @_;
 7350:     my $homeserver = &homeserver($uname,$udom);
 7351:     my $queryid=
 7352:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7353:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7354:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7355:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7356:                'generation='.&escape($names->{'generation'}).'%%'.
 7357:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7358:                'id='.&escape($names->{'id'}),$homeserver);
 7359:     return;
 7360: }
 7361: 
 7362: # ------- Request retrieval of institutional classlists for course(s)
 7363: 
 7364: sub fetch_enrollment_query {
 7365:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7366:     my $homeserver;
 7367:     my $maxtries = 1;
 7368:     if ($context eq 'automated') {
 7369:         $homeserver = $perlvar{'lonHostID'};
 7370:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7371:     } else {
 7372:         $homeserver = &homeserver($cnum,$dom);
 7373:     }
 7374:     my $host=&hostname($homeserver);
 7375:     my $cmd = '';
 7376:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7377:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7378:     }
 7379:     $cmd =~ s/%%$//;
 7380:     $cmd = &escape($cmd);
 7381:     my $query = 'fetchenrollment';
 7382:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7383:     unless ($queryid=~/^\Q$host\E\_/) { 
 7384:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7385:         return 'error: '.$queryid;
 7386:     }
 7387:     my $reply = &get_query_reply($queryid);
 7388:     my $tries = 1;
 7389:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7390:         $reply = &get_query_reply($queryid);
 7391:         $tries ++;
 7392:     }
 7393:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7394:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7395:     } else {
 7396:         my @responses = split(/:/,$reply);
 7397:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7398:             foreach my $line (@responses) {
 7399:                 my ($key,$value) = split(/=/,$line,2);
 7400:                 $$replyref{$key} = $value;
 7401:             }
 7402:         } else {
 7403:             my $pathname = LONCAPA::tempdir();
 7404:             foreach my $line (@responses) {
 7405:                 my ($key,$value) = split(/=/,$line);
 7406:                 $$replyref{$key} = $value;
 7407:                 if ($value > 0) {
 7408:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7409:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7410:                         my $destname = $pathname.'/'.$filename;
 7411:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7412:                         if ($xml_classlist =~ /^error/) {
 7413:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7414:                         } else {
 7415:                             if ( open(FILE,">$destname") ) {
 7416:                                 print FILE &unescape($xml_classlist);
 7417:                                 close(FILE);
 7418:                             } else {
 7419:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7420:                             }
 7421:                         }
 7422:                     }
 7423:                 }
 7424:             }
 7425:         }
 7426:         return 'ok';
 7427:     }
 7428:     return 'error';
 7429: }
 7430: 
 7431: sub get_query_reply {
 7432:     my $queryid=shift;
 7433:     my $replyfile=LONCAPA::tempdir().$queryid;
 7434:     my $reply='';
 7435:     for (1..100) {
 7436: 	sleep 2;
 7437:         if (-e $replyfile.'.end') {
 7438: 	    if (open(my $fh,$replyfile)) {
 7439: 		$reply = join('',<$fh>);
 7440: 		close($fh);
 7441: 	   } else { return 'error: reply_file_error'; }
 7442:            return &unescape($reply);
 7443: 	}
 7444:     }
 7445:     return 'timeout:'.$queryid;
 7446: }
 7447: 
 7448: sub courselog_query {
 7449: #
 7450: # possible filters:
 7451: # url: url or symb
 7452: # username
 7453: # domain
 7454: # action: view, submit, grade
 7455: # start: timestamp
 7456: # end: timestamp
 7457: #
 7458:     my (%filters)=@_;
 7459:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7460:     if ($filters{'url'}) {
 7461: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7462:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7463:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7464:     }
 7465:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7466:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7467:     return &log_query($cname,$cdom,'courselog',%filters);
 7468: }
 7469: 
 7470: sub userlog_query {
 7471: #
 7472: # possible filters:
 7473: # action: log check role
 7474: # start: timestamp
 7475: # end: timestamp
 7476: #
 7477:     my ($uname,$udom,%filters)=@_;
 7478:     return &log_query($uname,$udom,'userlog',%filters);
 7479: }
 7480: 
 7481: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7482: 
 7483: sub auto_run {
 7484:     my ($cnum,$cdom) = @_;
 7485:     my $response = 0;
 7486:     my $settings;
 7487:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7488:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7489:         $settings = $domconfig{'autoenroll'};
 7490:         if ($settings->{'run'} eq '1') {
 7491:             $response = 1;
 7492:         }
 7493:     } else {
 7494:         my $homeserver;
 7495:         if (&is_course($cdom,$cnum)) {
 7496:             $homeserver = &homeserver($cnum,$cdom);
 7497:         } else {
 7498:             $homeserver = &domain($cdom,'primary');
 7499:         }
 7500:         if ($homeserver ne 'no_host') {
 7501:             $response = &reply('autorun:'.$cdom,$homeserver);
 7502:         }
 7503:     }
 7504:     return $response;
 7505: }
 7506: 
 7507: sub auto_get_sections {
 7508:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7509:     my $homeserver;
 7510:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7511:         $homeserver = &homeserver($cnum,$cdom);
 7512:     }
 7513:     if (!defined($homeserver)) { 
 7514:         if ($cdom =~ /^$match_domain$/) {
 7515:             $homeserver = &domain($cdom,'primary');
 7516:         }
 7517:     }
 7518:     my @secs;
 7519:     if (defined($homeserver)) {
 7520:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7521:         unless ($response eq 'refused') {
 7522:             @secs = split(/:/,$response);
 7523:         }
 7524:     }
 7525:     return @secs;
 7526: }
 7527: 
 7528: sub auto_new_course {
 7529:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7530:     my $homeserver = &homeserver($cnum,$cdom);
 7531:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7532:     return $response;
 7533: }
 7534: 
 7535: sub auto_validate_courseID {
 7536:     my ($cnum,$cdom,$inst_course_id) = @_;
 7537:     my $homeserver = &homeserver($cnum,$cdom);
 7538:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7539:     return $response;
 7540: }
 7541: 
 7542: sub auto_validate_instcode {
 7543:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7544:     my ($homeserver,$response);
 7545:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7546:         $homeserver = &homeserver($cnum,$cdom);
 7547:     }
 7548:     if (!defined($homeserver)) {
 7549:         if ($cdom =~ /^$match_domain$/) {
 7550:             $homeserver = &domain($cdom,'primary');
 7551:         }
 7552:     }
 7553:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7554:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7555:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7556:     return ($outcome,$description,$defaultcredits);
 7557: }
 7558: 
 7559: sub auto_create_password {
 7560:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7561:     my ($homeserver,$response);
 7562:     my $create_passwd = 0;
 7563:     my $authchk = '';
 7564:     if ($udom =~ /^$match_domain$/) {
 7565:         $homeserver = &domain($udom,'primary');
 7566:     }
 7567:     if ($homeserver eq '') {
 7568:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7569:             $homeserver = &homeserver($cnum,$cdom);
 7570:         }
 7571:     }
 7572:     if ($homeserver eq '') {
 7573:         $authchk = 'nodomain';
 7574:     } else {
 7575:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7576:         if ($response eq 'refused') {
 7577:             $authchk = 'refused';
 7578:         } else {
 7579:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7580:         }
 7581:     }
 7582:     return ($authparam,$create_passwd,$authchk);
 7583: }
 7584: 
 7585: sub auto_photo_permission {
 7586:     my ($cnum,$cdom,$students) = @_;
 7587:     my $homeserver = &homeserver($cnum,$cdom);
 7588:     my ($outcome,$perm_reqd,$conditions) = 
 7589: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7590:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7591: 	return (undef,undef);
 7592:     }
 7593:     return ($outcome,$perm_reqd,$conditions);
 7594: }
 7595: 
 7596: sub auto_checkphotos {
 7597:     my ($uname,$udom,$pid) = @_;
 7598:     my $homeserver = &homeserver($uname,$udom);
 7599:     my ($result,$resulttype);
 7600:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7601: 				   &escape($uname).':'.&escape($pid),
 7602: 				   $homeserver));
 7603:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7604: 	return (undef,undef);
 7605:     }
 7606:     if ($outcome) {
 7607:         ($result,$resulttype) = split(/:/,$outcome);
 7608:     } 
 7609:     return ($result,$resulttype);
 7610: }
 7611: 
 7612: sub auto_photochoice {
 7613:     my ($cnum,$cdom) = @_;
 7614:     my $homeserver = &homeserver($cnum,$cdom);
 7615:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7616: 						       &escape($cdom),
 7617: 						       $homeserver)));
 7618:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7619: 	return (undef,undef);
 7620:     }
 7621:     return ($update,$comment);
 7622: }
 7623: 
 7624: sub auto_photoupdate {
 7625:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7626:     my $homeserver = &homeserver($cnum,$dom);
 7627:     my $host=&hostname($homeserver);
 7628:     my $cmd = '';
 7629:     my $maxtries = 1;
 7630:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7631:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7632:     }
 7633:     $cmd =~ s/%%$//;
 7634:     $cmd = &escape($cmd);
 7635:     my $query = 'institutionalphotos';
 7636:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7637:     unless ($queryid=~/^\Q$host\E\_/) {
 7638:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7639:         return 'error: '.$queryid;
 7640:     }
 7641:     my $reply = &get_query_reply($queryid);
 7642:     my $tries = 1;
 7643:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7644:         $reply = &get_query_reply($queryid);
 7645:         $tries ++;
 7646:     }
 7647:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7648:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7649:     } else {
 7650:         my @responses = split(/:/,$reply);
 7651:         my $outcome = shift(@responses); 
 7652:         foreach my $item (@responses) {
 7653:             my ($key,$value) = split(/=/,$item);
 7654:             $$photo{$key} = $value;
 7655:         }
 7656:         return $outcome;
 7657:     }
 7658:     return 'error';
 7659: }
 7660: 
 7661: sub auto_instcode_format {
 7662:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7663: 	$cat_order) = @_;
 7664:     my $courses = '';
 7665:     my @homeservers;
 7666:     if ($caller eq 'global') {
 7667: 	my %servers = &get_servers($codedom,'library');
 7668: 	foreach my $tryserver (keys(%servers)) {
 7669: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7670: 		push(@homeservers,$tryserver);
 7671: 	    }
 7672:         }
 7673:     } elsif ($caller eq 'requests') {
 7674:         if ($codedom =~ /^$match_domain$/) {
 7675:             my $chome = &domain($codedom,'primary');
 7676:             unless ($chome eq 'no_host') {
 7677:                 push(@homeservers,$chome);
 7678:             }
 7679:         }
 7680:     } else {
 7681:         push(@homeservers,&homeserver($caller,$codedom));
 7682:     }
 7683:     foreach my $code (keys(%{$instcodes})) {
 7684:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7685:     }
 7686:     chop($courses);
 7687:     my $ok_response = 0;
 7688:     my $response;
 7689:     while (@homeservers > 0 && $ok_response == 0) {
 7690:         my $server = shift(@homeservers); 
 7691:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7692:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7693:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7694: 		split(/:/,$response);
 7695:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7696:             push(@{$codetitles},&str2array($codetitles_str));
 7697:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7698:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7699:             $ok_response = 1;
 7700:         }
 7701:     }
 7702:     if ($ok_response) {
 7703:         return 'ok';
 7704:     } else {
 7705:         return $response;
 7706:     }
 7707: }
 7708: 
 7709: sub auto_instcode_defaults {
 7710:     my ($domain,$returnhash,$code_order) = @_;
 7711:     my @homeservers;
 7712: 
 7713:     my %servers = &get_servers($domain,'library');
 7714:     foreach my $tryserver (keys(%servers)) {
 7715: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7716: 	    push(@homeservers,$tryserver);
 7717: 	}
 7718:     }
 7719: 
 7720:     my $response;
 7721:     foreach my $server (@homeservers) {
 7722:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7723:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7724: 	
 7725: 	foreach my $pair (split(/\&/,$response)) {
 7726: 	    my ($name,$value)=split(/\=/,$pair);
 7727: 	    if ($name eq 'code_order') {
 7728: 		@{$code_order} = split(/\&/,&unescape($value));
 7729: 	    } else {
 7730: 		$returnhash->{&unescape($name)}=&unescape($value);
 7731: 	    }
 7732: 	}
 7733: 	return 'ok';
 7734:     }
 7735: 
 7736:     return $response;
 7737: }
 7738: 
 7739: sub auto_possible_instcodes {
 7740:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7741:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7742:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7743:         return;
 7744:     }
 7745:     my (@homeservers,$uhome);
 7746:     if (defined(&domain($domain,'primary'))) {
 7747:         $uhome=&domain($domain,'primary');
 7748:         push(@homeservers,&domain($domain,'primary'));
 7749:     } else {
 7750:         my %servers = &get_servers($domain,'library');
 7751:         foreach my $tryserver (keys(%servers)) {
 7752:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7753:                 push(@homeservers,$tryserver);
 7754:             }
 7755:         }
 7756:     }
 7757:     my $response;
 7758:     foreach my $server (@homeservers) {
 7759:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7760:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7761:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7762:             split(':',$response);
 7763:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7764:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7765:         foreach my $item (split('&',$cat_title)) {   
 7766:             my ($name,$value)=split('=',$item);
 7767:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7768:         }
 7769:         foreach my $item (split('&',$cat_order)) {
 7770:             my ($name,$value)=split('=',$item);
 7771:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7772:         }
 7773:         return 'ok';
 7774:     }
 7775:     return $response;
 7776: }
 7777: 
 7778: sub auto_courserequest_checks {
 7779:     my ($dom) = @_;
 7780:     my ($homeserver,%validations);
 7781:     if ($dom =~ /^$match_domain$/) {
 7782:         $homeserver = &domain($dom,'primary');
 7783:     }
 7784:     unless ($homeserver eq 'no_host') {
 7785:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7786:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7787:             my @items = split(/&/,$response);
 7788:             foreach my $item (@items) {
 7789:                 my ($key,$value) = split('=',$item);
 7790:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7791:             }
 7792:         }
 7793:     }
 7794:     return %validations; 
 7795: }
 7796: 
 7797: sub auto_courserequest_validation {
 7798:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7799:     my ($homeserver,$response);
 7800:     if ($dom =~ /^$match_domain$/) {
 7801:         $homeserver = &domain($dom,'primary');
 7802:     }
 7803:     unless ($homeserver eq 'no_host') {  
 7804:           
 7805:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7806:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7807:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7808:                                     $homeserver));
 7809:     }
 7810:     return $response;
 7811: }
 7812: 
 7813: sub auto_validate_class_sec {
 7814:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7815:     my $homeserver = &homeserver($cnum,$cdom);
 7816:     my $ownerlist;
 7817:     if (ref($owners) eq 'ARRAY') {
 7818:         $ownerlist = join(',',@{$owners});
 7819:     } else {
 7820:         $ownerlist = $owners;
 7821:     }
 7822:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7823:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7824:     return $response;
 7825: }
 7826: 
 7827: # ------------------------------------------------------- Course Group routines
 7828: 
 7829: sub get_coursegroups {
 7830:     my ($cdom,$cnum,$group,$namespace) = @_;
 7831:     return(&dump($namespace,$cdom,$cnum,$group));
 7832: }
 7833: 
 7834: sub modify_coursegroup {
 7835:     my ($cdom,$cnum,$groupsettings) = @_;
 7836:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7837: }
 7838: 
 7839: sub toggle_coursegroup_status {
 7840:     my ($cdom,$cnum,$group,$action) = @_;
 7841:     my ($from_namespace,$to_namespace);
 7842:     if ($action eq 'delete') {
 7843:         $from_namespace = 'coursegroups';
 7844:         $to_namespace = 'deleted_groups';
 7845:     } else {
 7846:         $from_namespace = 'deleted_groups';
 7847:         $to_namespace = 'coursegroups';
 7848:     }
 7849:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7850:     if (my $tmp = &error(%curr_group)) {
 7851:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7852:         return ('read error',$tmp);
 7853:     } else {
 7854:         my %savedsettings = %curr_group; 
 7855:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7856:         my $deloutcome;
 7857:         if ($result eq 'ok') {
 7858:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7859:         } else {
 7860:             return ('write error',$result);
 7861:         }
 7862:         if ($deloutcome eq 'ok') {
 7863:             return 'ok';
 7864:         } else {
 7865:             return ('delete error',$deloutcome);
 7866:         }
 7867:     }
 7868: }
 7869: 
 7870: sub modify_group_roles {
 7871:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7872:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7873:     my $role = 'gr/'.&escape($userprivs);
 7874:     my ($uname,$udom) = split(/:/,$user);
 7875:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7876:     if ($result eq 'ok') {
 7877:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7878:     }
 7879:     return $result;
 7880: }
 7881: 
 7882: sub modify_coursegroup_membership {
 7883:     my ($cdom,$cnum,$membership) = @_;
 7884:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7885:     return $result;
 7886: }
 7887: 
 7888: sub get_active_groups {
 7889:     my ($udom,$uname,$cdom,$cnum) = @_;
 7890:     my $now = time;
 7891:     my %groups = ();
 7892:     foreach my $key (keys(%env)) {
 7893:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7894:             my ($start,$end) = split(/\./,$env{$key});
 7895:             if (($end!=0) && ($end<$now)) { next; }
 7896:             if (($start!=0) && ($start>$now)) { next; }
 7897:             if ($1 eq $cdom && $2 eq $cnum) {
 7898:                 $groups{$3} = $env{$key} ;
 7899:             }
 7900:         }
 7901:     }
 7902:     return %groups;
 7903: }
 7904: 
 7905: sub get_group_membership {
 7906:     my ($cdom,$cnum,$group) = @_;
 7907:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7908: }
 7909: 
 7910: sub get_users_groups {
 7911:     my ($udom,$uname,$courseid) = @_;
 7912:     my @usersgroups;
 7913:     my $cachetime=1800;
 7914: 
 7915:     my $hashid="$udom:$uname:$courseid";
 7916:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7917:     if (defined($cached)) {
 7918:         @usersgroups = split(/:/,$grouplist);
 7919:     } else {  
 7920:         $grouplist = '';
 7921:         my $courseurl = &courseid_to_courseurl($courseid);
 7922:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7923:         my $access_end = $env{'course.'.$courseid.
 7924:                               '.default_enrollment_end_date'};
 7925:         my $now = time;
 7926:         foreach my $key (keys(%roleshash)) {
 7927:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7928:                 my $group = $1;
 7929:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7930:                     my $start = $2;
 7931:                     my $end = $1;
 7932:                     if ($start == -1) { next; } # deleted from group
 7933:                     if (($start!=0) && ($start>$now)) { next; }
 7934:                     if (($end!=0) && ($end<$now)) {
 7935:                         if ($access_end && $access_end < $now) {
 7936:                             if ($access_end - $end < 86400) {
 7937:                                 push(@usersgroups,$group);
 7938:                             }
 7939:                         }
 7940:                         next;
 7941:                     }
 7942:                     push(@usersgroups,$group);
 7943:                 }
 7944:             }
 7945:         }
 7946:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7947:         $grouplist = join(':',@usersgroups);
 7948:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7949:     }
 7950:     return @usersgroups;
 7951: }
 7952: 
 7953: sub devalidate_getgroups_cache {
 7954:     my ($udom,$uname,$cdom,$cnum)=@_;
 7955:     my $courseid = $cdom.'_'.$cnum;
 7956: 
 7957:     my $hashid="$udom:$uname:$courseid";
 7958:     &devalidate_cache_new('getgroups',$hashid);
 7959: }
 7960: 
 7961: # ------------------------------------------------------------------ Plain Text
 7962: 
 7963: sub plaintext {
 7964:     my ($short,$type,$cid,$forcedefault) = @_;
 7965:     if ($short =~ m{^cr/}) {
 7966: 	return (split('/',$short))[-1];
 7967:     }
 7968:     if (!defined($cid)) {
 7969:         $cid = $env{'request.course.id'};
 7970:     }
 7971:     my %rolenames = (
 7972:                       Course    => 'std',
 7973:                       Community => 'alt1',
 7974:                     );
 7975:     if ($cid ne '') {
 7976:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7977:             unless ($forcedefault) {
 7978:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7979:                 &Apache::lonlocal::mt_escape(\$roletext);
 7980:                 return &Apache::lonlocal::mt($roletext);
 7981:             }
 7982:         }
 7983:     }
 7984:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7985:         (defined($rolenames{$type})) && 
 7986:         (defined($prp{$short}{$rolenames{$type}}))) {
 7987:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7988:     } elsif ($cid ne '') {
 7989:         my $crstype = $env{'course.'.$cid.'.type'};
 7990:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7991:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7992:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7993:         }
 7994:     }
 7995:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7996: }
 7997: 
 7998: # ----------------------------------------------------------------- Assign Role
 7999: 
 8000: sub assignrole {
 8001:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8002:         $context)=@_;
 8003:     my $mrole;
 8004:     if ($role =~ /^cr\//) {
 8005:         my $cwosec=$url;
 8006:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8007: 	unless (&allowed('ccr',$cwosec)) {
 8008:            my $refused = 1;
 8009:            if ($context eq 'requestcourses') {
 8010:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8011:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8012:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8013:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8014:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8015:                            if ($crsenv{'internal.courseowner'} eq
 8016:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8017:                                $refused = '';
 8018:                            }
 8019:                        }
 8020:                    }
 8021:                }
 8022:            }
 8023:            if ($refused) {
 8024:                &logthis('Refused custom assignrole: '.
 8025:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8026:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8027:                return 'refused';
 8028:            }
 8029:         }
 8030:         $mrole='cr';
 8031:     } elsif ($role =~ /^gr\//) {
 8032:         my $cwogrp=$url;
 8033:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8034:         unless (&allowed('mdg',$cwogrp)) {
 8035:             &logthis('Refused group assignrole: '.
 8036:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8037:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8038:             return 'refused';
 8039:         }
 8040:         $mrole='gr';
 8041:     } else {
 8042:         my $cwosec=$url;
 8043:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8044:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8045:             my $refused;
 8046:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8047:                 if (!(&allowed('c'.$role,$url))) {
 8048:                     $refused = 1;
 8049:                 }
 8050:             } else {
 8051:                 $refused = 1;
 8052:             }
 8053:             if ($refused) {
 8054:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8055:                 if (!$selfenroll && $context eq 'course') {
 8056:                     my %crsenv;
 8057:                     if ($role eq 'cc' || $role eq 'co') {
 8058:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8059:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8060:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8061:                                 if ($crsenv{'internal.courseowner'} eq 
 8062:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8063:                                     $refused = '';
 8064:                                 }
 8065:                             }
 8066:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8067:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8068:                                 if ($crsenv{'internal.courseowner'} eq 
 8069:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8070:                                     $refused = '';
 8071:                                 }
 8072:                             }
 8073:                         }
 8074:                     }
 8075:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8076:                     $refused = '';
 8077:                 } elsif ($context eq 'requestcourses') {
 8078:                     my @possroles = ('st','ta','ep','in','cc','co');
 8079:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8080:                         my $wrongcc;
 8081:                         if ($cnum =~ /^$match_community$/) {
 8082:                             $wrongcc = 1 if ($role eq 'cc');
 8083:                         } else {
 8084:                             $wrongcc = 1 if ($role eq 'co');
 8085:                         }
 8086:                         unless ($wrongcc) {
 8087:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8088:                             if ($crsenv{'internal.courseowner'} eq 
 8089:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8090:                                 $refused = '';
 8091:                             }
 8092:                         }
 8093:                     }
 8094:                 } elsif ($context eq 'requestauthor') {
 8095:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8096:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8097:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8098:                             $refused = '';
 8099:                         } else {
 8100:                             my %domdefaults = &get_domain_defaults($udom);
 8101:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8102:                                 my $checkbystatus;
 8103:                                 if ($env{'user.adv'}) { 
 8104:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8105:                                     if ($disposition eq 'automatic') {
 8106:                                         $refused = '';
 8107:                                     } elsif ($disposition eq '') {
 8108:                                         $checkbystatus = 1;
 8109:                                     } 
 8110:                                 } else {
 8111:                                     $checkbystatus = 1;
 8112:                                 }
 8113:                                 if ($checkbystatus) {
 8114:                                     if ($env{'environment.inststatus'}) {
 8115:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8116:                                         foreach my $type (@inststatuses) {
 8117:                                             if (($type ne '') &&
 8118:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8119:                                                 $refused = '';
 8120:                                             }
 8121:                                         }
 8122:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8123:                                         $refused = '';
 8124:                                     }
 8125:                                 }
 8126:                             }
 8127:                         }
 8128:                     }
 8129:                 }
 8130:                 if ($refused) {
 8131:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8132:                              ' '.$role.' '.$end.' '.$start.' by '.
 8133: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8134:                     return 'refused';
 8135:                 }
 8136:             }
 8137:         } elsif ($role eq 'au') {
 8138:             if ($url ne '/'.$udom.'/') {
 8139:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8140:                          ' to assign author role for '.$uname.':'.$udom.
 8141:                          ' in domain: '.$url.' refused (wrong domain).');
 8142:                 return 'refused';
 8143:             }
 8144:         }
 8145:         $mrole=$role;
 8146:     }
 8147:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8148:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8149:     if ($end) { $command.='_'.$end; }
 8150:     if ($start) {
 8151: 	if ($end) { 
 8152:            $command.='_'.$start; 
 8153:         } else {
 8154:            $command.='_0_'.$start;
 8155:         }
 8156:     }
 8157:     my $origstart = $start;
 8158:     my $origend = $end;
 8159:     my $delflag;
 8160: # actually delete
 8161:     if ($deleteflag) {
 8162: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8163: # modify command to delete the role
 8164:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8165:                 "$udom:$uname:$url".'_'."$mrole";
 8166: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8167: # set start and finish to negative values for userrolelog
 8168:            $start=-1;
 8169:            $end=-1;
 8170:            $delflag = 1;
 8171:         }
 8172:     }
 8173: # send command
 8174:     my $answer=&reply($command,&homeserver($uname,$udom));
 8175: # log new user role if status is ok
 8176:     if ($answer eq 'ok') {
 8177: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8178:         if (($role eq 'cc') || ($role eq 'in') ||
 8179:             ($role eq 'ep') || ($role eq 'ad') ||
 8180:             ($role eq 'ta') || ($role eq 'st') ||
 8181:             ($role=~/^cr/) || ($role eq 'gr') ||
 8182:             ($role eq 'co')) {
 8183: # for course roles, perform group memberships changes triggered by role change.
 8184:             unless ($role =~ /^gr/) {
 8185:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8186:                                                  $origstart,$selfenroll,$context);
 8187:             }
 8188:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8189:                            $selfenroll,$context);
 8190:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8191:                  ($role eq 'au') || ($role eq 'dc')) {
 8192:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8193:                            $context);
 8194:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8195:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8196:                              $context); 
 8197:         }
 8198:         if ($role eq 'cc') {
 8199:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8200:         }
 8201:     }
 8202:     return $answer;
 8203: }
 8204: 
 8205: sub autoupdate_coowners {
 8206:     my ($url,$end,$start,$uname,$udom) = @_;
 8207:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8208:     if (($cdom ne '') && ($cnum ne '')) {
 8209:         my $now = time;
 8210:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8211:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8212:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8213:             my $instcode = $coursehash{'internal.coursecode'};
 8214:             if ($instcode ne '') {
 8215:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8216:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8217:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8218:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8219:                         if ($result eq 'valid') {
 8220:                             if ($coursehash{'internal.co-owners'}) {
 8221:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8222:                                     push(@newcoowners,$coowner);
 8223:                                 }
 8224:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8225:                                     push(@newcoowners,$uname.':'.$udom);
 8226:                                 }
 8227:                                 @newcoowners = sort(@newcoowners);
 8228:                             } else {
 8229:                                 push(@newcoowners,$uname.':'.$udom);
 8230:                             }
 8231:                         } else {
 8232:                             if ($coursehash{'internal.co-owners'}) {
 8233:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8234:                                     unless ($coowner eq $uname.':'.$udom) {
 8235:                                         push(@newcoowners,$coowner);
 8236:                                     }
 8237:                                 }
 8238:                                 unless (@newcoowners > 0) {
 8239:                                     $delcoowners = 1;
 8240:                                     $coowners = '';
 8241:                                 }
 8242:                             }
 8243:                         }
 8244:                         if (@newcoowners || $delcoowners) {
 8245:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8246:                                             $delcoowners,@newcoowners);
 8247:                         }
 8248:                     }
 8249:                 }
 8250:             }
 8251:         }
 8252:     }
 8253: }
 8254: 
 8255: sub store_coowners {
 8256:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8257:     my $cid = $cdom.'_'.$cnum;
 8258:     my ($coowners,$delresult,$putresult);
 8259:     if (@newcoowners) {
 8260:         $coowners = join(',',@newcoowners);
 8261:         my %coownershash = (
 8262:                             'internal.co-owners' => $coowners,
 8263:                            );
 8264:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8265:         if ($putresult eq 'ok') {
 8266:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8267:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8268:             }
 8269:         }
 8270:     }
 8271:     if ($delcoowners) {
 8272:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8273:         if ($delresult eq 'ok') {
 8274:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8275:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8276:             }
 8277:         }
 8278:     }
 8279:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8280:         my %crsinfo =
 8281:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8282:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8283:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8284:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8285:         }
 8286:     }
 8287: }
 8288: 
 8289: # -------------------------------------------------- Modify user authentication
 8290: # Overrides without validation
 8291: 
 8292: sub modifyuserauth {
 8293:     my ($udom,$uname,$umode,$upass)=@_;
 8294:     my $uhome=&homeserver($uname,$udom);
 8295:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8296:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8297:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8298:              ' in domain '.$env{'request.role.domain'});  
 8299:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8300: 		     &escape($upass),$uhome);
 8301:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8302:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8303:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8304:     &log($udom,,$uname,$uhome,
 8305:         'Authentication changed by '.$env{'user.domain'}.', '.
 8306:                                      $env{'user.name'}.', '.$umode.
 8307:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8308:     unless ($reply eq 'ok') {
 8309:         &logthis('Authentication mode error: '.$reply);
 8310: 	return 'error: '.$reply;
 8311:     }   
 8312:     return 'ok';
 8313: }
 8314: 
 8315: # --------------------------------------------------------------- Modify a user
 8316: 
 8317: sub modifyuser {
 8318:     my ($udom,    $uname, $uid,
 8319:         $umode,   $upass, $first,
 8320:         $middle,  $last,  $gene,
 8321:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8322:     $udom= &LONCAPA::clean_domain($udom);
 8323:     $uname=&LONCAPA::clean_username($uname);
 8324:     my $showcandelete = 'none';
 8325:     if (ref($candelete) eq 'ARRAY') {
 8326:         if (@{$candelete} > 0) {
 8327:             $showcandelete = join(', ',@{$candelete});
 8328:         }
 8329:     }
 8330:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8331:              $umode.', '.$first.', '.$middle.', '.
 8332: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8333:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8334:                                      ' desiredhome not specified'). 
 8335:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8336:              ' in domain '.$env{'request.role.domain'});
 8337:     my $uhome=&homeserver($uname,$udom,'true');
 8338:     my $newuser;
 8339:     if ($uhome eq 'no_host') {
 8340:         $newuser = 1;
 8341:     }
 8342: # ----------------------------------------------------------------- Create User
 8343:     if (($uhome eq 'no_host') && 
 8344: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8345:         my $unhome='';
 8346:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8347:             $unhome = $desiredhome;
 8348: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8349: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8350:         } else { # load balancing routine for determining $unhome
 8351:             my $loadm=10000000;
 8352: 	    my %servers = &get_servers($udom,'library');
 8353: 	    foreach my $tryserver (keys(%servers)) {
 8354: 		my $answer=reply('load',$tryserver);
 8355: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8356: 		    $loadm=$answer;
 8357: 		    $unhome=$tryserver;
 8358: 		}
 8359: 	    }
 8360:         }
 8361:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8362: 	    return 'error: unable to find a home server for '.$uname.
 8363:                    ' in domain '.$udom;
 8364:         }
 8365:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8366:                          &escape($upass),$unhome);
 8367: 	unless ($reply eq 'ok') {
 8368:             return 'error: '.$reply;
 8369:         }   
 8370:         $uhome=&homeserver($uname,$udom,'true');
 8371:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8372: 	    return 'error: unable verify users home machine.';
 8373:         }
 8374:     }   # End of creation of new user
 8375: # ---------------------------------------------------------------------- Add ID
 8376:     if ($uid) {
 8377:        $uid=~tr/A-Z/a-z/;
 8378:        my %uidhash=&idrget($udom,$uname);
 8379:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8380:          && (!$forceid)) {
 8381: 	  unless ($uid eq $uidhash{$uname}) {
 8382: 	      return 'error: user id "'.$uid.'" does not match '.
 8383:                   'current user id "'.$uidhash{$uname}.'".';
 8384:           }
 8385:        } else {
 8386: 	  &idput($udom,($uname => $uid));
 8387:        }
 8388:     }
 8389: # -------------------------------------------------------------- Add names, etc
 8390:     my @tmp=&get('environment',
 8391: 		   ['firstname','middlename','lastname','generation','id',
 8392:                     'permanentemail','inststatus'],
 8393: 		   $udom,$uname);
 8394:     my (%names,%oldnames);
 8395:     if ($tmp[0] =~ m/^error:.*/) { 
 8396:         %names=(); 
 8397:     } else {
 8398:         %names = @tmp;
 8399:         %oldnames = %names;
 8400:     }
 8401: #
 8402: # If name, email and/or uid are blank (e.g., because an uploaded file
 8403: # of users did not contain them), do not overwrite existing values
 8404: # unless field is in $candelete array ref.  
 8405: #
 8406: 
 8407:     my @fields = ('firstname','middlename','lastname','generation',
 8408:                   'permanentemail','id');
 8409:     my %newvalues;
 8410:     if (ref($candelete) eq 'ARRAY') {
 8411:         foreach my $field (@fields) {
 8412:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8413:                 if ($field eq 'firstname') {
 8414:                     $names{$field} = $first;
 8415:                 } elsif ($field eq 'middlename') {
 8416:                     $names{$field} = $middle;
 8417:                 } elsif ($field eq 'lastname') {
 8418:                     $names{$field} = $last;
 8419:                 } elsif ($field eq 'generation') { 
 8420:                     $names{$field} = $gene;
 8421:                 } elsif ($field eq 'permanentemail') {
 8422:                     $names{$field} = $email;
 8423:                 } elsif ($field eq 'id') {
 8424:                     $names{$field}  = $uid;
 8425:                 }
 8426:             }
 8427:         }
 8428:     }
 8429:     if ($first)  { $names{'firstname'}  = $first; }
 8430:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8431:     if ($last)   { $names{'lastname'}   = $last; }
 8432:     if (defined($gene))   { $names{'generation'} = $gene; }
 8433:     if ($email) {
 8434:        $email=~s/[^\w\@\.\-\,]//gs;
 8435:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8436:     }
 8437:     if ($uid) { $names{'id'}  = $uid; }
 8438:     if (defined($inststatus)) {
 8439:         $names{'inststatus'} = '';
 8440:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8441:         if (ref($usertypes) eq 'HASH') {
 8442:             my @okstatuses; 
 8443:             foreach my $item (split(/:/,$inststatus)) {
 8444:                 if (defined($usertypes->{$item})) {
 8445:                     push(@okstatuses,$item);  
 8446:                 }
 8447:             }
 8448:             if (@okstatuses) {
 8449:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8450:             }
 8451:         }
 8452:     }
 8453:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8454:                  $umode.', '.$first.', '.$middle.', '.
 8455:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8456:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8457:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8458:     } else {
 8459:         $logmsg .= ' during self creation';
 8460:     }
 8461:     my $changed;
 8462:     if ($newuser) {
 8463:         $changed = 1;
 8464:     } else {
 8465:         foreach my $field (@fields) {
 8466:             if ($names{$field} ne $oldnames{$field}) {
 8467:                 $changed = 1;
 8468:                 last;
 8469:             }
 8470:         }
 8471:     }
 8472:     unless ($changed) {
 8473:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8474:         &logthis($logmsg);
 8475:         return 'ok';
 8476:     }
 8477:     my $reply = &put('environment', \%names, $udom,$uname);
 8478:     if ($reply ne 'ok') { 
 8479:         return 'error: '.$reply;
 8480:     }
 8481:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8482:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8483:     }
 8484:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8485:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8486:     $logmsg = 'Success modifying user '.$logmsg;
 8487:     &logthis($logmsg);
 8488:     return 'ok';
 8489: }
 8490: 
 8491: # -------------------------------------------------------------- Modify student
 8492: 
 8493: sub modifystudent {
 8494:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8495:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8496:         $selfenroll,$context,$inststatus,$credits)=@_;
 8497:     if (!$cid) {
 8498: 	unless ($cid=$env{'request.course.id'}) {
 8499: 	    return 'not_in_class';
 8500: 	}
 8501:     }
 8502: # --------------------------------------------------------------- Make the user
 8503:     my $reply=&modifyuser
 8504: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8505:          $desiredhome,$email,$inststatus);
 8506:     unless ($reply eq 'ok') { return $reply; }
 8507:     # This will cause &modify_student_enrollment to get the uid from the
 8508:     # student's environment
 8509:     $uid = undef if (!$forceid);
 8510:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8511:                                         $gene,$usec,$end,$start,$type,$locktype,
 8512:                                         $cid,$selfenroll,$context,$credits);
 8513:     return $reply;
 8514: }
 8515: 
 8516: sub modify_student_enrollment {
 8517:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8518:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8519:     my ($cdom,$cnum,$chome);
 8520:     if (!$cid) {
 8521: 	unless ($cid=$env{'request.course.id'}) {
 8522: 	    return 'not_in_class';
 8523: 	}
 8524: 	$cdom=$env{'course.'.$cid.'.domain'};
 8525: 	$cnum=$env{'course.'.$cid.'.num'};
 8526:     } else {
 8527: 	($cdom,$cnum)=split(/_/,$cid);
 8528:     }
 8529:     $chome=$env{'course.'.$cid.'.home'};
 8530:     if (!$chome) {
 8531: 	$chome=&homeserver($cnum,$cdom);
 8532:     }
 8533:     if (!$chome) { return 'unknown_course'; }
 8534:     # Make sure the user exists
 8535:     my $uhome=&homeserver($uname,$udom);
 8536:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8537: 	return 'error: no such user';
 8538:     }
 8539:     # Get student data if we were not given enough information
 8540:     if (!defined($first)  || $first  eq '' || 
 8541:         !defined($last)   || $last   eq '' || 
 8542:         !defined($uid)    || $uid    eq '' || 
 8543:         !defined($middle) || $middle eq '' || 
 8544:         !defined($gene)   || $gene   eq '') {
 8545:         # They did not supply us with enough data to enroll the student, so
 8546:         # we need to pick up more information.
 8547:         my %tmp = &get('environment',
 8548:                        ['firstname','middlename','lastname', 'generation','id']
 8549:                        ,$udom,$uname);
 8550: 
 8551:         #foreach my $key (keys(%tmp)) {
 8552:         #    &logthis("key $key = ".$tmp{$key});
 8553:         #}
 8554:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8555:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8556:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8557:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8558:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8559:     }
 8560:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8561:     my $user = "$uname:$udom";
 8562:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8563:     my $reply=cput('classlist',
 8564: 		   {$user => 
 8565: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8566: 		   $cdom,$cnum);
 8567:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8568:         &devalidate_getsection_cache($udom,$uname,$cid);
 8569:     } else { 
 8570: 	return 'error: '.$reply;
 8571:     }
 8572:     # Add student role to user
 8573:     my $uurl='/'.$cid;
 8574:     $uurl=~s/\_/\//g;
 8575:     if ($usec) {
 8576: 	$uurl.='/'.$usec;
 8577:     }
 8578:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8579:                              $selfenroll,$context);
 8580:     if ($result ne 'ok') {
 8581:         if ($old_entry{$user} ne '') {
 8582:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8583:         } else {
 8584:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8585:         }
 8586:     }
 8587:     return $result; 
 8588: }
 8589: 
 8590: sub format_name {
 8591:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8592:     my $name;
 8593:     if ($first ne 'lastname') {
 8594: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8595:     } else {
 8596: 	if ($lastname=~/\S/) {
 8597: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8598: 	    $name=~s/\s+,/,/;
 8599: 	} else {
 8600: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8601: 	}
 8602:     }
 8603:     $name=~s/^\s+//;
 8604:     $name=~s/\s+$//;
 8605:     $name=~s/\s+/ /g;
 8606:     return $name;
 8607: }
 8608: 
 8609: # ------------------------------------------------- Write to course preferences
 8610: 
 8611: sub writecoursepref {
 8612:     my ($courseid,%prefs)=@_;
 8613:     $courseid=~s/^\///;
 8614:     $courseid=~s/\_/\//g;
 8615:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8616:     my $chome=homeserver($cnum,$cdomain);
 8617:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8618: 	return 'error: no such course';
 8619:     }
 8620:     my $cstring='';
 8621:     foreach my $pref (keys(%prefs)) {
 8622: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8623:     }
 8624:     $cstring=~s/\&$//;
 8625:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8626: }
 8627: 
 8628: # ---------------------------------------------------------- Make/modify course
 8629: 
 8630: sub createcourse {
 8631:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8632:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8633:     $url=&declutter($url);
 8634:     my $cid='';
 8635:     if ($context eq 'requestcourses') {
 8636:         my $can_create = 0;
 8637:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8638:         if ($udom eq $ownerdom) {
 8639:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8640:                                   $context)) {
 8641:                 $can_create = 1;
 8642:             }
 8643:         } else {
 8644:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8645:                                            $category);
 8646:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8647:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8648:                 if (@curr > 0) {
 8649:                     my @options = qw(approval validate autolimit);
 8650:                     my $optregex = join('|',@options);
 8651:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8652:                         $can_create = 1;
 8653:                     }
 8654:                 }
 8655:             }
 8656:         }
 8657:         if ($can_create) {
 8658:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8659:                 unless (&allowed('ccc',$udom)) {
 8660:                     return 'refused'; 
 8661:                 }
 8662:             }
 8663:         } else {
 8664:             return 'refused';
 8665:         }
 8666:     } elsif (!&allowed('ccc',$udom)) {
 8667:         return 'refused';
 8668:     }
 8669: # --------------------------------------------------------------- Get Unique ID
 8670:     my $uname;
 8671:     if ($cnum =~ /^$match_courseid$/) {
 8672:         my $chome=&homeserver($cnum,$udom,'true');
 8673:         if (($chome eq '') || ($chome eq 'no_host')) {
 8674:             $uname = $cnum;
 8675:         } else {
 8676:             $uname = &generate_coursenum($udom,$crstype);
 8677:         }
 8678:     } else {
 8679:         $uname = &generate_coursenum($udom,$crstype);
 8680:     }
 8681:     return $uname if ($uname =~ /^error/);
 8682: # -------------------------------------------------- Check supplied server name
 8683:     if (!defined($course_server)) {
 8684:         if (defined(&domain($udom,'primary'))) {
 8685:             $course_server = &domain($udom,'primary');
 8686:         } else {
 8687:             $course_server = $env{'user.home'}; 
 8688:         }
 8689:     }
 8690:     my %host_servers =
 8691:         &Apache::lonnet::get_servers($udom,'library');
 8692:     unless ($host_servers{$course_server}) {
 8693:         return 'error: invalid home server for course: '.$course_server;
 8694:     }
 8695: # ------------------------------------------------------------- Make the course
 8696:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8697:                       $course_server);
 8698:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8699:     my $uhome=&homeserver($uname,$udom,'true');
 8700:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8701: 	return 'error: no such course';
 8702:     }
 8703: # ----------------------------------------------------------------- Course made
 8704: # log existence
 8705:     my $now = time;
 8706:     my $newcourse = {
 8707:                     $udom.'_'.$uname => {
 8708:                                      description => $description,
 8709:                                      inst_code   => $inst_code,
 8710:                                      owner       => $course_owner,
 8711:                                      type        => $crstype,
 8712:                                      creator     => $env{'user.name'}.':'.
 8713:                                                     $env{'user.domain'},
 8714:                                      created     => $now,
 8715:                                      context     => $context,
 8716:                                                 },
 8717:                     };
 8718:     &courseidput($udom,$newcourse,$uhome,'notime');
 8719: # set toplevel url
 8720:     my $topurl=$url;
 8721:     unless ($nonstandard) {
 8722: # ------------------------------------------ For standard courses, make top url
 8723:         my $mapurl=&clutter($url);
 8724:         if ($mapurl eq '/res/') { $mapurl=''; }
 8725:         $env{'form.initmap'}=(<<ENDINITMAP);
 8726: <map>
 8727: <resource id="1" type="start"></resource>
 8728: <resource id="2" src="$mapurl"></resource>
 8729: <resource id="3" type="finish"></resource>
 8730: <link index="1" from="1" to="2"></link>
 8731: <link index="2" from="2" to="3"></link>
 8732: </map>
 8733: ENDINITMAP
 8734:         $topurl=&declutter(
 8735:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8736:                           );
 8737:     }
 8738: # ----------------------------------------------------------- Write preferences
 8739:     &writecoursepref($udom.'_'.$uname,
 8740:                      ('description'              => $description,
 8741:                       'url'                      => $topurl,
 8742:                       'internal.creator'         => $env{'user.name'}.':'.
 8743:                                                     $env{'user.domain'},
 8744:                       'internal.created'         => $now,
 8745:                       'internal.creationcontext' => $context)
 8746:                     );
 8747:     return '/'.$udom.'/'.$uname;
 8748: }
 8749: 
 8750: # ------------------------------------------------------------------- Create ID
 8751: sub generate_coursenum {
 8752:     my ($udom,$crstype) = @_;
 8753:     my $domdesc = &domain($udom);
 8754:     return 'error: invalid domain' if ($domdesc eq '');
 8755:     my $first;
 8756:     if ($crstype eq 'Community') {
 8757:         $first = '0';
 8758:     } else {
 8759:         $first = int(1+rand(9)); 
 8760:     } 
 8761:     my $uname=$first.
 8762:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8763:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8764:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8765: # ----------------------------------------------- Make sure that does not exist
 8766:     my $uhome=&homeserver($uname,$udom,'true');
 8767:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8768:         if ($crstype eq 'Community') {
 8769:             $first = '0';
 8770:         } else {
 8771:             $first = int(1+rand(9));
 8772:         }
 8773:         $uname=$first.
 8774:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8775:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8776:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8777:         $uhome=&homeserver($uname,$udom,'true');
 8778:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8779:             return 'error: unable to generate unique course-ID';
 8780:         }
 8781:     }
 8782:     return $uname;
 8783: }
 8784: 
 8785: sub is_course {
 8786:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8787:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8788: 
 8789:     return unless $cdom and $cnum;
 8790: 
 8791:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8792:         '.');
 8793: 
 8794:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8795:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8796: }
 8797: 
 8798: sub store_userdata {
 8799:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8800:     my $result;
 8801:     if ($datakey ne '') {
 8802:         if (ref($storehash) eq 'HASH') {
 8803:             if ($udom eq '' || $uname eq '') {
 8804:                 $udom = $env{'user.domain'};
 8805:                 $uname = $env{'user.name'};
 8806:             }
 8807:             my $uhome=&homeserver($uname,$udom);
 8808:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8809:                 $result = 'error: no_host';
 8810:             } else {
 8811:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8812:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8813: 
 8814:                 my $namevalue='';
 8815:                 foreach my $key (keys(%{$storehash})) {
 8816:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8817:                 }
 8818:                 $namevalue=~s/\&$//;
 8819:                 unless ($namespace eq 'courserequests') {
 8820:                     $datakey = &escape($datakey);
 8821:                 }
 8822:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8823:                                   $namevalue,$uhome);
 8824:             }
 8825:         } else {
 8826:             $result = 'error: data to store was not a hash reference'; 
 8827:         }
 8828:     } else {
 8829:         $result= 'error: invalid requestkey'; 
 8830:     }
 8831:     return $result;
 8832: }
 8833: 
 8834: # ---------------------------------------------------------- Assign Custom Role
 8835: 
 8836: sub assigncustomrole {
 8837:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8838:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8839:                        $end,$start,$deleteflag,$selfenroll,$context);
 8840: }
 8841: 
 8842: # ----------------------------------------------------------------- Revoke Role
 8843: 
 8844: sub revokerole {
 8845:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8846:     my $now=time;
 8847:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8848: }
 8849: 
 8850: # ---------------------------------------------------------- Revoke Custom Role
 8851: 
 8852: sub revokecustomrole {
 8853:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8854:     my $now=time;
 8855:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8856:            $deleteflag,$selfenroll,$context);
 8857: }
 8858: 
 8859: # ------------------------------------------------------------ Disk usage
 8860: sub diskusage {
 8861:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8862:     $directorypath =~ s/\/$//;
 8863:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8864:                        .&escape($getpropath).':'.&escape($uname).':'
 8865:                        .&escape($udom),homeserver($uname,$udom));
 8866:     if ($listing eq 'unknown_cmd') {
 8867:         if ($getpropath) {
 8868:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8869:         }
 8870:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8871:     }
 8872:     return $listing;
 8873: }
 8874: 
 8875: sub is_locked {
 8876:     my ($file_name, $domain, $user, $which) = @_;
 8877:     my @check;
 8878:     my $is_locked;
 8879:     push (@check,$file_name);
 8880:     my %locked = &get('file_permissions',\@check,
 8881: 		      $env{'user.domain'},$env{'user.name'});
 8882:     my ($tmp)=keys(%locked);
 8883:     if ($tmp=~/^error:/) { undef(%locked); }
 8884:     
 8885:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8886:         $is_locked = 'false';
 8887:         foreach my $entry (@{$locked{$file_name}}) {
 8888:            if (ref($entry) eq 'ARRAY') {
 8889:                $is_locked = 'true';
 8890:                if (ref($which) eq 'ARRAY') {
 8891:                    push(@{$which},$entry);
 8892:                } else {
 8893:                    last;
 8894:                }
 8895:            }
 8896:        }
 8897:     } else {
 8898:         $is_locked = 'false';
 8899:     }
 8900:     return $is_locked;
 8901: }
 8902: 
 8903: sub declutter_portfile {
 8904:     my ($file) = @_;
 8905:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8906:     return $file;
 8907: }
 8908: 
 8909: # ------------------------------------------------------------- Mark as Read Only
 8910: 
 8911: sub mark_as_readonly {
 8912:     my ($domain,$user,$files,$what) = @_;
 8913:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8914:     my ($tmp)=keys(%current_permissions);
 8915:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8916:     foreach my $file (@{$files}) {
 8917: 	$file = &declutter_portfile($file);
 8918:         push(@{$current_permissions{$file}},$what);
 8919:     }
 8920:     &put('file_permissions',\%current_permissions,$domain,$user);
 8921:     return;
 8922: }
 8923: 
 8924: # ------------------------------------------------------------Save Selected Files
 8925: 
 8926: sub save_selected_files {
 8927:     my ($user, $path, @files) = @_;
 8928:     my $filename = $user."savedfiles";
 8929:     my @other_files = &files_not_in_path($user, $path);
 8930:     open (OUT, '>'.$tmpdir.$filename);
 8931:     foreach my $file (@files) {
 8932:         print (OUT $env{'form.currentpath'}.$file."\n");
 8933:     }
 8934:     foreach my $file (@other_files) {
 8935:         print (OUT $file."\n");
 8936:     }
 8937:     close (OUT);
 8938:     return 'ok';
 8939: }
 8940: 
 8941: sub clear_selected_files {
 8942:     my ($user) = @_;
 8943:     my $filename = $user."savedfiles";
 8944:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8945:     print (OUT undef);
 8946:     close (OUT);
 8947:     return ("ok");    
 8948: }
 8949: 
 8950: sub files_in_path {
 8951:     my ($user, $path) = @_;
 8952:     my $filename = $user."savedfiles";
 8953:     my %return_files;
 8954:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8955:     while (my $line_in = <IN>) {
 8956:         chomp ($line_in);
 8957:         my @paths_and_file = split (m!/!, $line_in);
 8958:         my $file_part = pop (@paths_and_file);
 8959:         my $path_part = join ('/', @paths_and_file);
 8960:         $path_part.='/';
 8961:         my $path_and_file = $path_part.$file_part;
 8962:         if ($path_part eq $path) {
 8963:             $return_files{$file_part}= 'selected';
 8964:         }
 8965:     }
 8966:     close (IN);
 8967:     return (\%return_files);
 8968: }
 8969: 
 8970: # called in portfolio select mode, to show files selected NOT in current directory
 8971: sub files_not_in_path {
 8972:     my ($user, $path) = @_;
 8973:     my $filename = $user."savedfiles";
 8974:     my @return_files;
 8975:     my $path_part;
 8976:     open(IN, '<'.LONCAPA::.$filename);
 8977:     while (my $line = <IN>) {
 8978:         #ok, I know it's clunky, but I want it to work
 8979:         my @paths_and_file = split(m|/|, $line);
 8980:         my $file_part = pop(@paths_and_file);
 8981:         chomp($file_part);
 8982:         my $path_part = join('/', @paths_and_file);
 8983:         $path_part .= '/';
 8984:         my $path_and_file = $path_part.$file_part;
 8985:         if ($path_part ne $path) {
 8986:             push(@return_files, ($path_and_file));
 8987:         }
 8988:     }
 8989:     close(OUT);
 8990:     return (@return_files);
 8991: }
 8992: 
 8993: #----------------------------------------------Get portfolio file permissions
 8994: 
 8995: sub get_portfile_permissions {
 8996:     my ($domain,$user) = @_;
 8997:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8998:     my ($tmp)=keys(%current_permissions);
 8999:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9000:     return \%current_permissions;
 9001: }
 9002: 
 9003: #---------------------------------------------Get portfolio file access controls
 9004: 
 9005: sub get_access_controls {
 9006:     my ($current_permissions,$group,$file) = @_;
 9007:     my %access;
 9008:     my $real_file = $file;
 9009:     $file =~ s/\.meta$//;
 9010:     if (defined($file)) {
 9011:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9012:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9013:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9014:             }
 9015:         }
 9016:     } else {
 9017:         foreach my $key (keys(%{$current_permissions})) {
 9018:             if ($key =~ /\0accesscontrol$/) {
 9019:                 if (defined($group)) {
 9020:                     if ($key !~ m-^\Q$group\E/-) {
 9021:                         next;
 9022:                     }
 9023:                 }
 9024:                 my ($fullpath) = split(/\0/,$key);
 9025:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9026:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9027:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9028:                     }
 9029:                 }
 9030:             }
 9031:         }
 9032:     }
 9033:     return %access;
 9034: }
 9035: 
 9036: sub modify_access_controls {
 9037:     my ($file_name,$changes,$domain,$user)=@_;
 9038:     my ($outcome,$deloutcome);
 9039:     my %store_permissions;
 9040:     my %new_values;
 9041:     my %new_control;
 9042:     my %translation;
 9043:     my @deletions = ();
 9044:     my $now = time;
 9045:     if (exists($$changes{'activate'})) {
 9046:         if (ref($$changes{'activate'}) eq 'HASH') {
 9047:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9048:             my $numnew = scalar(@newitems);
 9049:             for (my $i=0; $i<$numnew; $i++) {
 9050:                 my $newkey = $newitems[$i];
 9051:                 my $newid = &Apache::loncommon::get_cgi_id();
 9052:                 if ($newkey =~ /^\d+:/) { 
 9053:                     $newkey =~ s/^(\d+)/$newid/;
 9054:                     $translation{$1} = $newid;
 9055:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9056:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9057:                     $translation{$1} = $newid;
 9058:                 }
 9059:                 $new_values{$file_name."\0".$newkey} = 
 9060:                                           $$changes{'activate'}{$newitems[$i]};
 9061:                 $new_control{$newkey} = $now;
 9062:             }
 9063:         }
 9064:     }
 9065:     my %todelete;
 9066:     my %changed_items;
 9067:     foreach my $action ('delete','update') {
 9068:         if (exists($$changes{$action})) {
 9069:             if (ref($$changes{$action}) eq 'HASH') {
 9070:                 foreach my $key (keys(%{$$changes{$action}})) {
 9071:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9072:                     if ($action eq 'delete') { 
 9073:                         $todelete{$itemnum} = 1;
 9074:                     } else {
 9075:                         $changed_items{$itemnum} = $key;
 9076:                     }
 9077:                 }
 9078:             }
 9079:         }
 9080:     }
 9081:     # get lock on access controls for file.
 9082:     my $lockhash = {
 9083:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9084:                                                        ':'.$env{'user.domain'},
 9085:                    }; 
 9086:     my $tries = 0;
 9087:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9088:    
 9089:     while (($gotlock ne 'ok') && $tries <3) {
 9090:         $tries ++;
 9091:         sleep 1;
 9092:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9093:     }
 9094:     if ($gotlock eq 'ok') {
 9095:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9096:         my ($tmp)=keys(%curr_permissions);
 9097:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9098:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9099:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9100:             if (ref($curr_controls) eq 'HASH') {
 9101:                 foreach my $control_item (keys(%{$curr_controls})) {
 9102:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9103:                     if (defined($todelete{$itemnum})) {
 9104:                         push(@deletions,$file_name."\0".$control_item);
 9105:                     } else {
 9106:                         if (defined($changed_items{$itemnum})) {
 9107:                             $new_control{$changed_items{$itemnum}} = $now;
 9108:                             push(@deletions,$file_name."\0".$control_item);
 9109:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9110:                         } else {
 9111:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9112:                         }
 9113:                     }
 9114:                 }
 9115:             }
 9116:         }
 9117:         my ($group);
 9118:         if (&is_course($domain,$user)) {
 9119:             ($group,my $file) = split(/\//,$file_name,2);
 9120:         }
 9121:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9122:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9123:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9124:         #  remove lock
 9125:         my @del_lock = ($file_name."\0".'locked_access_records');
 9126:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9127:         my $sqlresult =
 9128:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9129:                                     $group);
 9130:     } else {
 9131:         $outcome = "error: could not obtain lockfile\n";  
 9132:     }
 9133:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9134: }
 9135: 
 9136: sub make_public_indefinitely {
 9137:     my ($requrl) = @_;
 9138:     my $now = time;
 9139:     my $action = 'activate';
 9140:     my $aclnum = 0;
 9141:     if (&is_portfolio_url($requrl)) {
 9142:         my (undef,$udom,$unum,$file_name,$group) =
 9143:             &parse_portfolio_url($requrl);
 9144:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9145:         my %access_controls = &get_access_controls($current_perms,
 9146:                                                    $group,$file_name);
 9147:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9148:             my ($num,$scope,$end,$start) = 
 9149:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9150:             if ($scope eq 'public') {
 9151:                 if ($start <= $now && $end == 0) {
 9152:                     $action = 'none';
 9153:                 } else {
 9154:                     $action = 'update';
 9155:                     $aclnum = $num;
 9156:                 }
 9157:                 last;
 9158:             }
 9159:         }
 9160:         if ($action eq 'none') {
 9161:              return 'ok';
 9162:         } else {
 9163:             my %changes;
 9164:             my $newend = 0;
 9165:             my $newstart = $now;
 9166:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9167:             $changes{$action}{$newkey} = {
 9168:                 type => 'public',
 9169:                 time => {
 9170:                     start => $newstart,
 9171:                     end   => $newend,
 9172:                 },
 9173:             };
 9174:             my ($outcome,$deloutcome,$new_values,$translation) =
 9175:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9176:             return $outcome;
 9177:         }
 9178:     } else {
 9179:         return 'invalid';
 9180:     }
 9181: }
 9182: 
 9183: #------------------------------------------------------Get Marked as Read Only
 9184: 
 9185: sub get_marked_as_readonly {
 9186:     my ($domain,$user,$what,$group) = @_;
 9187:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9188:     my @readonly_files;
 9189:     my $cmp1=$what;
 9190:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9191:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9192:         if (defined($group)) {
 9193:             if ($file_name !~ m-^\Q$group\E/-) {
 9194:                 next;
 9195:             }
 9196:         }
 9197:         if (ref($value) eq "ARRAY"){
 9198:             foreach my $stored_what (@{$value}) {
 9199:                 my $cmp2=$stored_what;
 9200:                 if (ref($stored_what) eq 'ARRAY') {
 9201:                     $cmp2=join('',@{$stored_what});
 9202:                 }
 9203:                 if ($cmp1 eq $cmp2) {
 9204:                     push(@readonly_files, $file_name);
 9205:                     last;
 9206:                 } elsif (!defined($what)) {
 9207:                     push(@readonly_files, $file_name);
 9208:                     last;
 9209:                 }
 9210:             }
 9211:         }
 9212:     }
 9213:     return @readonly_files;
 9214: }
 9215: #-----------------------------------------------------------Get Marked as Read Only Hash
 9216: 
 9217: sub get_marked_as_readonly_hash {
 9218:     my ($current_permissions,$group,$what) = @_;
 9219:     my %readonly_files;
 9220:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9221:         if (defined($group)) {
 9222:             if ($file_name !~ m-^\Q$group\E/-) {
 9223:                 next;
 9224:             }
 9225:         }
 9226:         if (ref($value) eq "ARRAY"){
 9227:             foreach my $stored_what (@{$value}) {
 9228:                 if (ref($stored_what) eq 'ARRAY') {
 9229:                     foreach my $lock_descriptor(@{$stored_what}) {
 9230:                         if ($lock_descriptor eq 'graded') {
 9231:                             $readonly_files{$file_name} = 'graded';
 9232:                         } elsif ($lock_descriptor eq 'handback') {
 9233:                             $readonly_files{$file_name} = 'handback';
 9234:                         } else {
 9235:                             if (!exists($readonly_files{$file_name})) {
 9236:                                 $readonly_files{$file_name} = 'locked';
 9237:                             }
 9238:                         }
 9239:                     }
 9240:                 } 
 9241:             }
 9242:         } 
 9243:     }
 9244:     return %readonly_files;
 9245: }
 9246: # ------------------------------------------------------------ Unmark as Read Only
 9247: 
 9248: sub unmark_as_readonly {
 9249:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9250:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9251:     my ($domain,$user,$what,$file_name,$group) = @_;
 9252:     $file_name = &declutter_portfile($file_name);
 9253:     my $symb_crs = $what;
 9254:     if (ref($what)) { $symb_crs=join('',@$what); }
 9255:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9256:     my ($tmp)=keys(%current_permissions);
 9257:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9258:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9259:     foreach my $file (@readonly_files) {
 9260: 	my $clean_file = &declutter_portfile($file);
 9261: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9262: 	my $current_locks = $current_permissions{$file};
 9263:         my @new_locks;
 9264:         my @del_keys;
 9265:         if (ref($current_locks) eq "ARRAY"){
 9266:             foreach my $locker (@{$current_locks}) {
 9267:                 my $compare=$locker;
 9268:                 if (ref($locker) eq 'ARRAY') {
 9269:                     $compare=join('',@{$locker});
 9270:                     if ($compare ne $symb_crs) {
 9271:                         push(@new_locks, $locker);
 9272:                     }
 9273:                 }
 9274:             }
 9275:             if (scalar(@new_locks) > 0) {
 9276:                 $current_permissions{$file} = \@new_locks;
 9277:             } else {
 9278:                 push(@del_keys, $file);
 9279:                 &del('file_permissions',\@del_keys, $domain, $user);
 9280:                 delete($current_permissions{$file});
 9281:             }
 9282:         }
 9283:     }
 9284:     &put('file_permissions',\%current_permissions,$domain,$user);
 9285:     return;
 9286: }
 9287: 
 9288: # ------------------------------------------------------------ Directory lister
 9289: 
 9290: sub dirlist {
 9291:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9292:     $uri=~s/^\///;
 9293:     $uri=~s/\/$//;
 9294:     my ($udom, $uname);
 9295:     if ($getuserdir) {
 9296:         $udom = $userdomain;
 9297:         $uname = $username;
 9298:     } else {
 9299:         (undef,$udom,$uname)=split(/\//,$uri);
 9300:         if(defined($userdomain)) {
 9301:             $udom = $userdomain;
 9302:         }
 9303:         if(defined($username)) {
 9304:             $uname = $username;
 9305:         }
 9306:     }
 9307:     my ($dirRoot,$listing,@listing_results);
 9308: 
 9309:     $dirRoot = $perlvar{'lonDocRoot'};
 9310:     if (defined($getpropath)) {
 9311:         $dirRoot = &propath($udom,$uname);
 9312:         $dirRoot =~ s/\/$//;
 9313:     } elsif (defined($getuserdir)) {
 9314:         my $subdir=$uname.'__';
 9315:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9316:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9317:                    ."/$udom/$subdir/$uname";
 9318:     } elsif (defined($alternateRoot)) {
 9319:         $dirRoot = $alternateRoot;
 9320:     }
 9321: 
 9322:     if($udom) {
 9323:         if($uname) {
 9324:             my $uhome = &homeserver($uname,$udom);
 9325:             if ($uhome eq 'no_host') {
 9326:                 return ([],'no_host');
 9327:             }
 9328:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9329:                               .$getuserdir.':'.&escape($dirRoot)
 9330:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9331:             if ($listing eq 'unknown_cmd') {
 9332:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9333:             } else {
 9334:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9335:             }
 9336:             if ($listing eq 'unknown_cmd') {
 9337:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9338:                 @listing_results = split(/:/,$listing);
 9339:             } else {
 9340:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9341:             }
 9342:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9343:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9344:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9345:                 return ([],$listing);
 9346:             } else {
 9347:                 return (\@listing_results);
 9348:             }
 9349:         } elsif(!$alternateRoot) {
 9350:             my (%allusers,%listerror);
 9351: 	    my %servers = &get_servers($udom,'library');
 9352:  	    foreach my $tryserver (keys(%servers)) {
 9353:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9354:                                   &escape($udom),$tryserver);
 9355:                 if ($listing eq 'unknown_cmd') {
 9356: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9357: 				      $udom, $tryserver);
 9358:                 } else {
 9359:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9360:                 }
 9361: 		if ($listing eq 'unknown_cmd') {
 9362: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9363: 				      $udom, $tryserver);
 9364: 		    @listing_results = split(/:/,$listing);
 9365: 		} else {
 9366: 		    @listing_results =
 9367: 			map { &unescape($_); } split(/:/,$listing);
 9368: 		}
 9369:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9370:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9371:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9372:                     $listerror{$tryserver} = $listing;
 9373:                 } else {
 9374: 		    foreach my $line (@listing_results) {
 9375: 			my ($entry) = split(/&/,$line,2);
 9376: 			$allusers{$entry} = 1;
 9377: 		    }
 9378: 		}
 9379:             }
 9380:             my @alluserslist=();
 9381:             foreach my $user (sort(keys(%allusers))) {
 9382:                 push(@alluserslist,$user.'&user');
 9383:             }
 9384:             return (\@alluserslist);
 9385:         } else {
 9386:             return ([],'missing username');
 9387:         }
 9388:     } elsif(!defined($getpropath)) {
 9389:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9390:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9391:         return (\@all_domains);
 9392:     } else {
 9393:         return ([],'missing domain');
 9394:     }
 9395: }
 9396: 
 9397: # --------------------------------------------- GetFileTimestamp
 9398: # This function utilizes dirlist and returns the date stamp for
 9399: # when it was last modified.  It will also return an error of -1
 9400: # if an error occurs
 9401: 
 9402: sub GetFileTimestamp {
 9403:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9404:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9405:     $studentName   = &LONCAPA::clean_username($studentName);
 9406:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9407:                                     undef,$getuserdir);
 9408:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9409:         return -1;
 9410:     }
 9411:     if (ref($fileref) eq 'ARRAY') {
 9412:         my @stats = split('&',$fileref->[0]);
 9413:         # @stats contains first the filename, then the stat output
 9414:         return $stats[10]; # so this is 10 instead of 9.
 9415:     } else {
 9416:         return -1;
 9417:     }
 9418: }
 9419: 
 9420: sub stat_file {
 9421:     my ($uri) = @_;
 9422:     $uri = &clutter_with_no_wrapper($uri);
 9423: 
 9424:     my ($udom,$uname,$file);
 9425:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9426: 	($udom,$uname,$file) =
 9427: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9428: 	$file = 'userfiles/'.$file;
 9429:     }
 9430:     if ($uri =~ m-^/res/-) {
 9431: 	($udom,$uname) = 
 9432: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9433: 	$file = $uri;
 9434:     }
 9435: 
 9436:     if (!$udom || !$uname || !$file) {
 9437: 	# unable to handle the uri
 9438: 	return ();
 9439:     }
 9440:     my $getpropath;
 9441:     if ($file =~ /^userfiles\//) {
 9442:         $getpropath = 1;
 9443:     }
 9444:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9445:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9446:         return ();
 9447:     } else {
 9448:         if (ref($listref) eq 'ARRAY') {
 9449:             my @stats = split('&',$listref->[0]);
 9450: 	    shift(@stats); #filename is first
 9451: 	    return @stats;
 9452:         }
 9453:     }
 9454:     return ();
 9455: }
 9456: 
 9457: # -------------------------------------------------------- Value of a Condition
 9458: 
 9459: # gets the value of a specific preevaluated condition
 9460: #    stored in the string  $env{user.state.<cid>}
 9461: # or looks up a condition reference in the bighash and if if hasn't
 9462: # already been evaluated recurses into docondval to get the value of
 9463: # the condition, then memoizing it to 
 9464: #   $env{user.state.<cid>.<condition>}
 9465: sub directcondval {
 9466:     my $number=shift;
 9467:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9468: 	&Apache::lonuserstate::evalstate();
 9469:     }
 9470:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9471: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9472:     } elsif ($number =~ /^_/) {
 9473: 	my $sub_condition;
 9474: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9475: 		&GDBM_READER(),0640)) {
 9476: 	    $sub_condition=$bighash{'conditions'.$number};
 9477: 	    untie(%bighash);
 9478: 	}
 9479: 	my $value = &docondval($sub_condition);
 9480: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9481: 	return $value;
 9482:     }
 9483:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9484:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9485:     } else {
 9486:        return 2;
 9487:     }
 9488: }
 9489: 
 9490: # get the collection of conditions for this resource
 9491: sub condval {
 9492:     my $condidx=shift;
 9493:     my $allpathcond='';
 9494:     foreach my $cond (split(/\|/,$condidx)) {
 9495: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9496: 	    $allpathcond.=
 9497: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9498: 	}
 9499:     }
 9500:     $allpathcond=~s/\|$//;
 9501:     return &docondval($allpathcond);
 9502: }
 9503: 
 9504: #evaluates an expression of conditions
 9505: sub docondval {
 9506:     my ($allpathcond) = @_;
 9507:     my $result=0;
 9508:     if ($env{'request.course.id'}
 9509: 	&& defined($allpathcond)) {
 9510: 	my $operand='|';
 9511: 	my @stack;
 9512: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9513: 	    if ($chunk eq '(') {
 9514: 		push @stack,($operand,$result);
 9515: 	    } elsif ($chunk eq ')') {
 9516: 		my $before=pop @stack;
 9517: 		if (pop @stack eq '&') {
 9518: 		    $result=$result>$before?$before:$result;
 9519: 		} else {
 9520: 		    $result=$result>$before?$result:$before;
 9521: 		}
 9522: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9523: 		$operand=$chunk;
 9524: 	    } else {
 9525: 		my $new=directcondval($chunk);
 9526: 		if ($operand eq '&') {
 9527: 		    $result=$result>$new?$new:$result;
 9528: 		} else {
 9529: 		    $result=$result>$new?$result:$new;
 9530: 		}
 9531: 	    }
 9532: 	}
 9533:     }
 9534:     return $result;
 9535: }
 9536: 
 9537: # ---------------------------------------------------- Devalidate courseresdata
 9538: 
 9539: sub devalidatecourseresdata {
 9540:     my ($coursenum,$coursedomain)=@_;
 9541:     my $hashid=$coursenum.':'.$coursedomain;
 9542:     &devalidate_cache_new('courseres',$hashid);
 9543: }
 9544: 
 9545: 
 9546: # --------------------------------------------------- Course Resourcedata Query
 9547: #
 9548: #  Parameters:
 9549: #      $coursenum    - Number of the course.
 9550: #      $coursedomain - Domain at which the course was created.
 9551: #  Returns:
 9552: #     A hash of the course parameters along (I think) with timestamps
 9553: #     and version info.
 9554: 
 9555: sub get_courseresdata {
 9556:     my ($coursenum,$coursedomain)=@_;
 9557:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9558:     my $hashid=$coursenum.':'.$coursedomain;
 9559:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9560:     my %dumpreply;
 9561:     unless (defined($cached)) {
 9562: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9563: 	$result=\%dumpreply;
 9564: 	my ($tmp) = keys(%dumpreply);
 9565: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9566: 	    &do_cache_new('courseres',$hashid,$result,600);
 9567: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9568: 	    return $tmp;
 9569: 	} elsif ($tmp =~ /^(error)/) {
 9570: 	    $result=undef;
 9571: 	    &do_cache_new('courseres',$hashid,$result,600);
 9572: 	}
 9573:     }
 9574:     return $result;
 9575: }
 9576: 
 9577: sub devalidateuserresdata {
 9578:     my ($uname,$udom)=@_;
 9579:     my $hashid="$udom:$uname";
 9580:     &devalidate_cache_new('userres',$hashid);
 9581: }
 9582: 
 9583: sub get_userresdata {
 9584:     my ($uname,$udom)=@_;
 9585:     #most student don\'t have any data set, check if there is some data
 9586:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9587: 
 9588:     my $hashid="$udom:$uname";
 9589:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9590:     if (!defined($cached)) {
 9591: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9592: 	$result=\%resourcedata;
 9593: 	&do_cache_new('userres',$hashid,$result,600);
 9594:     }
 9595:     my ($tmp)=keys(%$result);
 9596:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9597: 	return $result;
 9598:     }
 9599:     #error 2 occurs when the .db doesn't exist
 9600:     if ($tmp!~/error: 2 /) {
 9601: 	&logthis("<font color=\"blue\">WARNING:".
 9602: 		 " Trying to get resource data for ".
 9603: 		 $uname." at ".$udom.": ".
 9604: 		 $tmp."</font>");
 9605:     } elsif ($tmp=~/error: 2 /) {
 9606: 	#&EXT_cache_set($udom,$uname);
 9607: 	&do_cache_new('userres',$hashid,undef,600);
 9608: 	undef($tmp); # not really an error so don't send it back
 9609:     }
 9610:     return $tmp;
 9611: }
 9612: #----------------------------------------------- resdata - return resource data
 9613: #  Purpose:
 9614: #    Return resource data for either users or for a course.
 9615: #  Parameters:
 9616: #     $name      - Course/user name.
 9617: #     $domain    - Name of the domain the user/course is registered on.
 9618: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9619: #     @which     - Array of names of resources desired.
 9620: #  Returns:
 9621: #     The value of the first reasource in @which that is found in the
 9622: #     resource hash.
 9623: #  Exceptional Conditions:
 9624: #     If the $type passed in is not valid (not the string 'course' or 
 9625: #     'user', an undefined  reference is returned.
 9626: #     If none of the resources are found, an undef is returned
 9627: sub resdata {
 9628:     my ($name,$domain,$type,@which)=@_;
 9629:     my $result;
 9630:     if ($type eq 'course') {
 9631: 	$result=&get_courseresdata($name,$domain);
 9632:     } elsif ($type eq 'user') {
 9633: 	$result=&get_userresdata($name,$domain);
 9634:     }
 9635:     if (!ref($result)) { return $result; }    
 9636:     foreach my $item (@which) {
 9637: 	if (defined($result->{$item->[0]})) {
 9638: 	    return [$result->{$item->[0]},$item->[1]];
 9639: 	}
 9640:     }
 9641:     return undef;
 9642: }
 9643: 
 9644: sub get_numsuppfiles {
 9645:     my ($cnum,$cdom,$ignorecache)=@_;
 9646:     my $hashid=$cnum.':'.$cdom;
 9647:     my ($suppcount,$cached);
 9648:     unless ($ignorecache) {
 9649:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9650:     }
 9651:     unless (defined($cached)) {
 9652:         my $chome=&homeserver($cnum,$cdom);
 9653:         unless ($chome eq 'no_host') {
 9654:             ($suppcount,my $errors) = (0,0);
 9655:             my $suppmap = 'supplemental.sequence';
 9656:             ($suppcount,$errors) = 
 9657:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9658:         }
 9659:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9660:     }
 9661:     return $suppcount;
 9662: }
 9663: 
 9664: #
 9665: # EXT resource caching routines
 9666: #
 9667: 
 9668: sub clear_EXT_cache_status {
 9669:     &delenv('cache.EXT.');
 9670: }
 9671: 
 9672: sub EXT_cache_status {
 9673:     my ($target_domain,$target_user) = @_;
 9674:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9675:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9676:         # We know already the user has no data
 9677:         return 1;
 9678:     } else {
 9679:         return 0;
 9680:     }
 9681: }
 9682: 
 9683: sub EXT_cache_set {
 9684:     my ($target_domain,$target_user) = @_;
 9685:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9686:     #&appenv({$cachename => time});
 9687: }
 9688: 
 9689: # --------------------------------------------------------- Value of a Variable
 9690: sub EXT {
 9691: 
 9692:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9693:     unless ($varname) { return ''; }
 9694:     #get real user name/domain, courseid and symb
 9695:     my $courseid;
 9696:     my $publicuser;
 9697:     if ($symbparm) {
 9698: 	$symbparm=&get_symb_from_alias($symbparm);
 9699:     }
 9700:     if (!($uname && $udom)) {
 9701:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9702:       if (!$symbparm) {	$symbparm=$cursymb; }
 9703:     } else {
 9704: 	$courseid=$env{'request.course.id'};
 9705:     }
 9706:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9707:     my $rest;
 9708:     if (defined($therest[0])) {
 9709:        $rest=join('.',@therest);
 9710:     } else {
 9711:        $rest='';
 9712:     }
 9713: 
 9714:     my $qualifierrest=$qualifier;
 9715:     if ($rest) { $qualifierrest.='.'.$rest; }
 9716:     my $spacequalifierrest=$space;
 9717:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9718:     if ($realm eq 'user') {
 9719: # --------------------------------------------------------------- user.resource
 9720: 	if ($space eq 'resource') {
 9721: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9722: 		  || defined($Apache::lonhomework::parsing_a_task))
 9723: 		 &&
 9724: 		 ($symbparm eq &symbread()) ) {	
 9725: 		# if we are in the middle of processing the resource the
 9726: 		# get the value we are planning on committing
 9727:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9728:                     return $Apache::lonhomework::results{$qualifierrest};
 9729:                 } else {
 9730:                     return $Apache::lonhomework::history{$qualifierrest};
 9731:                 }
 9732: 	    } else {
 9733: 		my %restored;
 9734: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9735: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9736: 		} else {
 9737: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9738: 		}
 9739: 		return $restored{$qualifierrest};
 9740: 	    }
 9741: # ----------------------------------------------------------------- user.access
 9742:         } elsif ($space eq 'access') {
 9743: 	    # FIXME - not supporting calls for a specific user
 9744:             return &allowed($qualifier,$rest);
 9745: # ------------------------------------------ user.preferences, user.environment
 9746:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9747: 	    if (($uname eq $env{'user.name'}) &&
 9748: 		($udom eq $env{'user.domain'})) {
 9749: 		return $env{join('.',('environment',$qualifierrest))};
 9750: 	    } else {
 9751: 		my %returnhash;
 9752: 		if (!$publicuser) {
 9753: 		    %returnhash=&userenvironment($udom,$uname,
 9754: 						 $qualifierrest);
 9755: 		}
 9756: 		return $returnhash{$qualifierrest};
 9757: 	    }
 9758: # ----------------------------------------------------------------- user.course
 9759:         } elsif ($space eq 'course') {
 9760: 	    # FIXME - not supporting calls for a specific user
 9761:             return $env{join('.',('request.course',$qualifier))};
 9762: # ------------------------------------------------------------------- user.role
 9763:         } elsif ($space eq 'role') {
 9764: 	    # FIXME - not supporting calls for a specific user
 9765:             my ($role,$where)=split(/\./,$env{'request.role'});
 9766:             if ($qualifier eq 'value') {
 9767: 		return $role;
 9768:             } elsif ($qualifier eq 'extent') {
 9769:                 return $where;
 9770:             }
 9771: # ----------------------------------------------------------------- user.domain
 9772:         } elsif ($space eq 'domain') {
 9773:             return $udom;
 9774: # ------------------------------------------------------------------- user.name
 9775:         } elsif ($space eq 'name') {
 9776:             return $uname;
 9777: # ---------------------------------------------------- Any other user namespace
 9778:         } else {
 9779: 	    my %reply;
 9780: 	    if (!$publicuser) {
 9781: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9782: 	    }
 9783: 	    return $reply{$qualifierrest};
 9784:         }
 9785:     } elsif ($realm eq 'query') {
 9786: # ---------------------------------------------- pull stuff out of query string
 9787:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9788: 						[$spacequalifierrest]);
 9789: 	return $env{'form.'.$spacequalifierrest}; 
 9790:    } elsif ($realm eq 'request') {
 9791: # ------------------------------------------------------------- request.browser
 9792:         if ($space eq 'browser') {
 9793:             return $env{'browser.'.$qualifier};
 9794: # ------------------------------------------------------------ request.filename
 9795:         } else {
 9796:             return $env{'request.'.$spacequalifierrest};
 9797:         }
 9798:     } elsif ($realm eq 'course') {
 9799: # ---------------------------------------------------------- course.description
 9800:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9801:     } elsif ($realm eq 'resource') {
 9802: 
 9803: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9804: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9805: 	}
 9806: 
 9807:         if ($qualifier eq '') {
 9808: 	    if ($space eq 'title') {
 9809: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9810: 	        return &gettitle($symbparm);
 9811: 	    }
 9812: 	
 9813: 	    if ($space eq 'map') {
 9814: 	        my ($map) = &decode_symb($symbparm);
 9815: 	        return &symbread($map);
 9816: 	    }
 9817:             if ($space eq 'maptitle') {
 9818:                 my ($map) = &decode_symb($symbparm);
 9819:                 return &gettitle($map);
 9820:             }
 9821: 	    if ($space eq 'filename') {
 9822: 	        if ($symbparm) {
 9823: 		    return &clutter((&decode_symb($symbparm))[2]);
 9824: 	        }
 9825: 	        return &hreflocation('',$env{'request.filename'});
 9826: 	    }
 9827: 
 9828:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9829:                 if ($space eq 'visibleparts') {
 9830:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9831:                     my $item;
 9832:                     if (ref($navmap)) {
 9833:                         my $res = $navmap->getBySymb($symbparm);
 9834:                         my $parts = $res->parts();
 9835:                         if (ref($parts) eq 'ARRAY') {
 9836:                             $item = join(',',@{$parts});
 9837:                         }
 9838:                         undef($navmap);
 9839:                     }
 9840:                     return $item;
 9841:                 }
 9842:             }
 9843:         }
 9844: 
 9845: 	my ($section, $group, @groups);
 9846: 	my ($courselevelm,$courselevel);
 9847:         if (($courseid eq '') && ($cid)) {
 9848:             $courseid = $cid;
 9849:         }
 9850: 	if (($symbparm && $courseid) && 
 9851: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
 9852: 
 9853: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9854: 
 9855: # ----------------------------------------------------- Cascading lookup scheme
 9856: 	    my $symbp=$symbparm;
 9857: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9858: 
 9859: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9860: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9861: 
 9862: 	    if (($env{'user.name'} eq $uname) &&
 9863: 		($env{'user.domain'} eq $udom)) {
 9864: 		$section=$env{'request.course.sec'};
 9865:                 @groups = split(/:/,$env{'request.course.groups'});  
 9866:                 @groups=&sort_course_groups($courseid,@groups); 
 9867: 	    } else {
 9868: 		if (! defined($usection)) {
 9869: 		    $section=&getsection($udom,$uname,$courseid);
 9870: 		} else {
 9871: 		    $section = $usection;
 9872: 		}
 9873:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9874: 	    }
 9875: 
 9876: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9877: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9878: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9879: 
 9880: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9881: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9882: 	    $courselevelm=$courseid.'.'.$mapparm;
 9883: 
 9884: # ----------------------------------------------------------- first, check user
 9885: 
 9886: 	    my $userreply=&resdata($uname,$udom,'user',
 9887: 				       ([$courselevelr,'resource'],
 9888: 					[$courselevelm,'map'     ],
 9889: 					[$courselevel, 'course'  ]));
 9890: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9891: 
 9892: # ------------------------------------------------ second, check some of course
 9893:             my $coursereply;
 9894:             if (@groups > 0) {
 9895:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9896:                                        $mapparm,$spacequalifierrest);
 9897:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9898:             }
 9899: 
 9900: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9901: 				  $env{'course.'.$courseid.'.domain'},
 9902: 				  'course',
 9903: 				  ([$seclevelr,   'resource'],
 9904: 				   [$seclevelm,   'map'     ],
 9905: 				   [$seclevel,    'course'  ],
 9906: 				   [$courselevelr,'resource']));
 9907: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9908: 
 9909: # ------------------------------------------------------ third, check map parms
 9910: 	    my %parmhash=();
 9911: 	    my $thisparm='';
 9912: 	    if (tie(%parmhash,'GDBM_File',
 9913: 		    $env{'request.course.fn'}.'_parms.db',
 9914: 		    &GDBM_READER(),0640)) {
 9915: 		$thisparm=$parmhash{$symbparm};
 9916: 		untie(%parmhash);
 9917: 	    }
 9918: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9919: 	}
 9920: # ------------------------------------------ fourth, look in resource metadata
 9921: 
 9922: 	$spacequalifierrest=~s/\./\_/;
 9923: 	my $filename;
 9924: 	if (!$symbparm) { $symbparm=&symbread(); }
 9925: 	if ($symbparm) {
 9926: 	    $filename=(&decode_symb($symbparm))[2];
 9927: 	} else {
 9928: 	    $filename=$env{'request.filename'};
 9929: 	}
 9930: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9931: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9932: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9933: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9934: 
 9935: # ---------------------------------------------- fourth, look in rest of course
 9936: 	if ($symbparm && defined($courseid) && 
 9937: 	    $courseid eq $env{'request.course.id'}) {
 9938: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9939: 				     $env{'course.'.$courseid.'.domain'},
 9940: 				     'course',
 9941: 				     ([$courselevelm,'map'   ],
 9942: 				      [$courselevel, 'course']));
 9943: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9944: 	}
 9945: # ------------------------------------------------------------------ Cascade up
 9946: 	unless ($space eq '0') {
 9947: 	    my @parts=split(/_/,$space);
 9948: 	    my $id=pop(@parts);
 9949: 	    my $part=join('_',@parts);
 9950: 	    if ($part eq '') { $part='0'; }
 9951: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9952: 				 $symbparm,$udom,$uname,$section,1);
 9953: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9954: 	}
 9955: 	if ($recurse) { return undef; }
 9956: 	my $pack_def=&packages_tab_default($filename,$varname);
 9957: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9958: # ---------------------------------------------------- Any other user namespace
 9959:     } elsif ($realm eq 'environment') {
 9960: # ----------------------------------------------------------------- environment
 9961: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9962: 	    return $env{'environment.'.$spacequalifierrest};
 9963: 	} else {
 9964: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9965: 		return '';
 9966: 	    }
 9967: 	    my %returnhash=&userenvironment($udom,$uname,
 9968: 					    $spacequalifierrest);
 9969: 	    return $returnhash{$spacequalifierrest};
 9970: 	}
 9971:     } elsif ($realm eq 'system') {
 9972: # ----------------------------------------------------------------- system.time
 9973: 	if ($space eq 'time') {
 9974: 	    return time;
 9975:         }
 9976:     } elsif ($realm eq 'server') {
 9977: # ----------------------------------------------------------------- system.time
 9978: 	if ($space eq 'name') {
 9979: 	    return $ENV{'SERVER_NAME'};
 9980:         }
 9981:     }
 9982:     return '';
 9983: }
 9984: 
 9985: sub get_reply {
 9986:     my ($reply_value) = @_;
 9987:     if (ref($reply_value) eq 'ARRAY') {
 9988:         if (wantarray) {
 9989: 	    return @$reply_value;
 9990:         }
 9991:         return $reply_value->[0];
 9992:     } else {
 9993:         return $reply_value;
 9994:     }
 9995: }
 9996: 
 9997: sub check_group_parms {
 9998:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9999:     my @groupitems = ();
10000:     my $resultitem;
10001:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10002:     foreach my $group (@{$groups}) {
10003:         foreach my $level (@levels) {
10004:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10005:              push(@groupitems,[$item,$level->[1]]);
10006:         }
10007:     }
10008:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10009:                             $env{'course.'.$courseid.'.domain'},
10010:                                      'course',@groupitems);
10011:     return $coursereply;
10012: }
10013: 
10014: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10015:     my ($courseid,@groups) = @_;
10016:     @groups = sort(@groups);
10017:     return @groups;
10018: }
10019: 
10020: sub packages_tab_default {
10021:     my ($uri,$varname)=@_;
10022:     my (undef,$part,$name)=split(/\./,$varname);
10023: 
10024:     my (@extension,@specifics,$do_default);
10025:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10026: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10027: 	if ($pack_type eq 'default') {
10028: 	    $do_default=1;
10029: 	} elsif ($pack_type eq 'extension') {
10030: 	    push(@extension,[$package,$pack_type,$pack_part]);
10031: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10032: 	    # only look at packages defaults for packages that this id is
10033: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10034: 	}
10035:     }
10036:     # first look for a package that matches the requested part id
10037:     foreach my $package (@specifics) {
10038: 	my (undef,$pack_type,$pack_part)=@{$package};
10039: 	next if ($pack_part ne $part);
10040: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10041: 	    return $packagetab{"$pack_type&$name&default"};
10042: 	}
10043:     }
10044:     # look for any possible matching non extension_ package
10045:     foreach my $package (@specifics) {
10046: 	my (undef,$pack_type,$pack_part)=@{$package};
10047: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10048: 	    return $packagetab{"$pack_type&$name&default"};
10049: 	}
10050: 	if ($pack_type eq 'part') { $pack_part='0'; }
10051: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10052: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10053: 	}
10054:     }
10055:     # look for any posible extension_ match
10056:     foreach my $package (@extension) {
10057: 	my ($package,$pack_type)=@{$package};
10058: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10059: 	    return $packagetab{"$pack_type&$name&default"};
10060: 	}
10061: 	if (defined($packagetab{$package."&$name&default"})) {
10062: 	    return $packagetab{$package."&$name&default"};
10063: 	}
10064:     }
10065:     # look for a global default setting
10066:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10067: 	return $packagetab{"default&$name&default"};
10068:     }
10069:     return undef;
10070: }
10071: 
10072: sub add_prefix_and_part {
10073:     my ($prefix,$part)=@_;
10074:     my $keyroot;
10075:     if (defined($prefix) && $prefix !~ /^__/) {
10076: 	# prefix that has a part already
10077: 	$keyroot=$prefix;
10078:     } elsif (defined($prefix)) {
10079: 	# prefix that is missing a part
10080: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10081:     } else {
10082: 	# no prefix at all
10083: 	if (defined($part)) { $keyroot='_'.$part; }
10084:     }
10085:     return $keyroot;
10086: }
10087: 
10088: # ---------------------------------------------------------------- Get metadata
10089: 
10090: my %metaentry;
10091: my %importedpartids;
10092: sub metadata {
10093:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10094:     $uri=&declutter($uri);
10095:     # if it is a non metadata possible uri return quickly
10096:     if (($uri eq '') || 
10097: 	(($uri =~ m|^/*adm/|) && 
10098: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10099:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10100: 	return undef;
10101:     }
10102:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10103: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10104: 	return undef;
10105:     }
10106:     my $filename=$uri;
10107:     $uri=~s/\.meta$//;
10108: #
10109: # Is the metadata already cached?
10110: # Look at timestamp of caching
10111: # Everything is cached by the main uri, libraries are never directly cached
10112: #
10113:     if (!defined($liburi)) {
10114: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10115: 	if (defined($cached)) { return $result->{':'.$what}; }
10116:     }
10117:     {
10118: # Imported parts would go here
10119:         my %importedids=();
10120:         my @origfileimportpartids=();
10121:         my $importedparts=0;
10122: #
10123: # Is this a recursive call for a library?
10124: #
10125: #	if (! exists($metacache{$uri})) {
10126: #	    $metacache{$uri}={};
10127: #	}
10128: 	my $cachetime = 60*60;
10129:         if ($liburi) {
10130: 	    $liburi=&declutter($liburi);
10131:             $filename=$liburi;
10132:         } else {
10133: 	    &devalidate_cache_new('meta',$uri);
10134: 	    undef(%metaentry);
10135: 	}
10136:         my %metathesekeys=();
10137:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10138: 	my $metastring;
10139: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10140: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10141: 	    $metastring = 
10142: 		&Apache::lonnet::ssi_body($which,
10143: 					  ('grade_target' => 'meta'));
10144: 	    $cachetime = 1; # only want this cached in the child not long term
10145: 	} elsif (($uri !~ m -^(editupload)/-) && 
10146:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10147: 	    my $file=&filelocation('',&clutter($filename));
10148: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10149: 	    $metastring=&getfile($file);
10150: 	}
10151:         my $parser=HTML::LCParser->new(\$metastring);
10152:         my $token;
10153:         undef %metathesekeys;
10154:         while ($token=$parser->get_token) {
10155: 	    if ($token->[0] eq 'S') {
10156: 		if (defined($token->[2]->{'package'})) {
10157: #
10158: # This is a package - get package info
10159: #
10160: 		    my $package=$token->[2]->{'package'};
10161: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10162: 		    if (defined($token->[2]->{'id'})) { 
10163: 			$keyroot.='_'.$token->[2]->{'id'}; 
10164: 		    }
10165: 		    if ($metaentry{':packages'}) {
10166: 			$metaentry{':packages'}.=','.$package.$keyroot;
10167: 		    } else {
10168: 			$metaentry{':packages'}=$package.$keyroot;
10169: 		    }
10170: 		    foreach my $pack_entry (keys(%packagetab)) {
10171: 			my $part=$keyroot;
10172: 			$part=~s/^\_//;
10173: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10174: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10175: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10176: 			    # ignore package.tab specified default values
10177:                             # here &package_tab_default() will fetch those
10178: 			    if ($subp eq 'default') { next; }
10179: 			    my $value=$packagetab{$pack_entry};
10180: 			    my $unikey;
10181: 			    if ($pack =~ /_0$/) {
10182: 				$unikey='parameter_0_'.$name;
10183: 				$part=0;
10184: 			    } else {
10185: 				$unikey='parameter'.$keyroot.'_'.$name;
10186: 			    }
10187: 			    if ($subp eq 'display') {
10188: 				$value.=' [Part: '.$part.']';
10189: 			    }
10190: 			    $metaentry{':'.$unikey.'.part'}=$part;
10191: 			    $metathesekeys{$unikey}=1;
10192: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10193: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10194: 			    }
10195: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10196: 				$metaentry{':'.$unikey}=
10197: 				    $metaentry{':'.$unikey.'.default'};
10198: 			    }
10199: 			}
10200: 		    }
10201: 		} else {
10202: #
10203: # This is not a package - some other kind of start tag
10204: #
10205: 		    my $entry=$token->[1];
10206: 		    my $unikey='';
10207: 
10208: 		    if ($entry eq 'import') {
10209: #
10210: # Importing a library here
10211: #
10212:                         my $location=$parser->get_text('/import');
10213:                         my $dir=$filename;
10214:                         $dir=~s|[^/]*$||;
10215:                         $location=&filelocation($dir,$location);
10216:                        
10217:                         my $importmode=$token->[2]->{'importmode'};
10218:                         if ($importmode eq 'problem') {
10219: # Import as problem/response
10220:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10221:                         } elsif ($importmode eq 'part') {
10222: # Import as part(s)
10223:                            $importedparts=1;
10224: # We need to get the original file and the imported file to get the part order correct
10225: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10226: # Load and inspect original file
10227:                            if ($#origfileimportpartids<0) {
10228:                               undef(%importedpartids);
10229:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10230:                               my $origfile=&getfile($origfilelocation);
10231:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10232:                            }
10233: 
10234: # Load and inspect imported file
10235:                            my $impfile=&getfile($location);
10236:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10237:                            if ($#impfilepartids>=0) {
10238: # This problem had parts
10239:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10240:                            } else {
10241: # Importing by turning a single problem into a problem part
10242: # It gets the import-tags ID as part-ID
10243:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10244:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10245:                            }
10246:                         } else {
10247: # Normal import
10248:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10249:                            if (defined($token->[2]->{'id'})) {
10250:                               $unikey.='_'.$token->[2]->{'id'};
10251:                            }
10252:                         }
10253: 
10254: 			if ($depthcount<20) {
10255: 			    my $metadata = 
10256: 				&metadata($uri,'keys', $location,$unikey,
10257: 					  $depthcount+1);
10258: 			    foreach my $meta (split(',',$metadata)) {
10259: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10260: 				$metathesekeys{$meta}=1;
10261: 			    }
10262: 			
10263:                         }
10264: 		    } else {
10265: #
10266: # Not importing, some other kind of non-package, non-library start tag
10267: # 
10268:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10269:                         if (defined($token->[2]->{'id'})) {
10270:                             $unikey.='_'.$token->[2]->{'id'};
10271:                         }
10272: 			if (defined($token->[2]->{'name'})) { 
10273: 			    $unikey.='_'.$token->[2]->{'name'}; 
10274: 			}
10275: 			$metathesekeys{$unikey}=1;
10276: 			foreach my $param (@{$token->[3]}) {
10277: 			    $metaentry{':'.$unikey.'.'.$param} =
10278: 				$token->[2]->{$param};
10279: 			}
10280: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10281: 			my $default=$metaentry{':'.$unikey.'.default'};
10282: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10283: 		 # only ws inside the tag, and not in default, so use default
10284: 		 # as value
10285: 			    $metaentry{':'.$unikey}=$default;
10286: 			} elsif ( $internaltext =~ /\S/ ) {
10287: 		  # something interesting inside the tag
10288: 			    $metaentry{':'.$unikey}=$internaltext;
10289: 			} else {
10290: 		  # no interesting values, don't set a default
10291: 			}
10292: # end of not-a-package not-a-library import
10293: 		    }
10294: # end of not-a-package start tag
10295: 		}
10296: # the next is the end of "start tag"
10297: 	    }
10298: 	}
10299: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10300: 	$extension = lc($extension);
10301: 	if ($extension eq 'htm') { $extension='html'; }
10302: 
10303: 	foreach my $key (keys(%packagetab)) {
10304: 	    #no specific packages #how's our extension
10305: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10306: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10307: 					 \%metathesekeys);
10308: 	}
10309: 
10310: 	if (!exists($metaentry{':packages'})
10311: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10312: 	    foreach my $key (keys(%packagetab)) {
10313: 		#no specific packages well let's get default then
10314: 		if ($key!~/^default&/) { next; }
10315: 		&metadata_create_package_def($uri,$key,'default',
10316: 					     \%metathesekeys);
10317: 	    }
10318: 	}
10319: # are there custom rights to evaluate
10320: 	if ($metaentry{':copyright'} eq 'custom') {
10321: 
10322:     #
10323:     # Importing a rights file here
10324:     #
10325: 	    unless ($depthcount) {
10326: 		my $location=$metaentry{':customdistributionfile'};
10327: 		my $dir=$filename;
10328: 		$dir=~s|[^/]*$||;
10329: 		$location=&filelocation($dir,$location);
10330: 		my $rights_metadata =
10331: 		    &metadata($uri,'keys',$location,'_rights',
10332: 			      $depthcount+1);
10333: 		foreach my $rights (split(',',$rights_metadata)) {
10334: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10335: 		    $metathesekeys{$rights}=1;
10336: 		}
10337: 	    }
10338: 	}
10339: 	# uniqifiy package listing
10340: 	my %seen;
10341: 	my @uniq_packages =
10342: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10343: 	$metaentry{':packages'} = join(',',@uniq_packages);
10344: 
10345:         if ($importedparts) {
10346: # We had imported parts and need to rebuild partorder
10347:            $metaentry{':partorder'}='';
10348:            $metathesekeys{'partorder'}=1;
10349:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10350:                if ($origfileimportpartids[$index] eq 'part') {
10351: # original part, part of the problem
10352:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10353:                } else {
10354: # we have imported parts at this position
10355:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10356:                }
10357:            }
10358:            $metaentry{':partorder'}=~s/^\,//;
10359:         }
10360: 
10361: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10362: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10363: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10364: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10365: # this is the end of "was not already recently cached
10366:     }
10367:     return $metaentry{':'.$what};
10368: }
10369: 
10370: sub metadata_create_package_def {
10371:     my ($uri,$key,$package,$metathesekeys)=@_;
10372:     my ($pack,$name,$subp)=split(/\&/,$key);
10373:     if ($subp eq 'default') { next; }
10374:     
10375:     if (defined($metaentry{':packages'})) {
10376: 	$metaentry{':packages'}.=','.$package;
10377:     } else {
10378: 	$metaentry{':packages'}=$package;
10379:     }
10380:     my $value=$packagetab{$key};
10381:     my $unikey;
10382:     $unikey='parameter_0_'.$name;
10383:     $metaentry{':'.$unikey.'.part'}=0;
10384:     $$metathesekeys{$unikey}=1;
10385:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10386: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10387:     }
10388:     if (defined($metaentry{':'.$unikey.'.default'})) {
10389: 	$metaentry{':'.$unikey}=
10390: 	    $metaentry{':'.$unikey.'.default'};
10391:     }
10392: }
10393: 
10394: sub metadata_generate_part0 {
10395:     my ($metadata,$metacache,$uri) = @_;
10396:     my %allnames;
10397:     foreach my $metakey (keys(%$metadata)) {
10398: 	if ($metakey=~/^parameter\_(.*)/) {
10399: 	  my $part=$$metacache{':'.$metakey.'.part'};
10400: 	  my $name=$$metacache{':'.$metakey.'.name'};
10401: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10402: 	    $allnames{$name}=$part;
10403: 	  }
10404: 	}
10405:     }
10406:     foreach my $name (keys(%allnames)) {
10407:       $$metadata{"parameter_0_$name"}=1;
10408:       my $key=":parameter_0_$name";
10409:       $$metacache{"$key.part"}='0';
10410:       $$metacache{"$key.name"}=$name;
10411:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10412: 					   $allnames{$name}.'_'.$name.
10413: 					   '.type'};
10414:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10415: 			     '.display'};
10416:       my $expr='[Part: '.$allnames{$name}.']';
10417:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10418:       $$metacache{"$key.display"}=$olddis;
10419:     }
10420: }
10421: 
10422: # ------------------------------------------------------ Devalidate title cache
10423: 
10424: sub devalidate_title_cache {
10425:     my ($url)=@_;
10426:     if (!$env{'request.course.id'}) { return; }
10427:     my $symb=&symbread($url);
10428:     if (!$symb) { return; }
10429:     my $key=$env{'request.course.id'}."\0".$symb;
10430:     &devalidate_cache_new('title',$key);
10431: }
10432: 
10433: # ------------------------------------------------- Get the title of a course
10434: 
10435: sub current_course_title {
10436:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10437: }
10438: # ------------------------------------------------- Get the title of a resource
10439: 
10440: sub gettitle {
10441:     my $urlsymb=shift;
10442:     my $symb=&symbread($urlsymb);
10443:     if ($symb) {
10444: 	my $key=$env{'request.course.id'}."\0".$symb;
10445: 	my ($result,$cached)=&is_cached_new('title',$key);
10446: 	if (defined($cached)) { 
10447: 	    return $result;
10448: 	}
10449: 	my ($map,$resid,$url)=&decode_symb($symb);
10450: 	my $title='';
10451: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10452: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10453: 	} else {
10454: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10455: 		    &GDBM_READER(),0640)) {
10456: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10457: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10458: 		untie(%bighash);
10459: 	    }
10460: 	}
10461: 	$title=~s/\&colon\;/\:/gs;
10462: 	if ($title) {
10463: # Remember both $symb and $title for dynamic metadata
10464:             $accesshash{$symb.'___crstitle'}=$title;
10465:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10466: # Cache this title and then return it
10467: 	    return &do_cache_new('title',$key,$title,600);
10468: 	}
10469: 	$urlsymb=$url;
10470:     }
10471:     my $title=&metadata($urlsymb,'title');
10472:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10473:     return $title;
10474: }
10475: 
10476: sub get_slot {
10477:     my ($which,$cnum,$cdom)=@_;
10478:     if (!$cnum || !$cdom) {
10479: 	(undef,my $courseid)=&whichuser();
10480: 	$cdom=$env{'course.'.$courseid.'.domain'};
10481: 	$cnum=$env{'course.'.$courseid.'.num'};
10482:     }
10483:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10484:     my %slotinfo;
10485:     if (exists($remembered{$key})) {
10486: 	$slotinfo{$which} = $remembered{$key};
10487:     } else {
10488: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10489: 	&Apache::lonhomework::showhash(%slotinfo);
10490: 	my ($tmp)=keys(%slotinfo);
10491: 	if ($tmp=~/^error:/) { return (); }
10492: 	$remembered{$key} = $slotinfo{$which};
10493:     }
10494:     if (ref($slotinfo{$which}) eq 'HASH') {
10495: 	return %{$slotinfo{$which}};
10496:     }
10497:     return $slotinfo{$which};
10498: }
10499: 
10500: sub get_reservable_slots {
10501:     my ($cnum,$cdom,$uname,$udom) = @_;
10502:     my $now = time;
10503:     my $reservable_info;
10504:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10505:     if (exists($remembered{$key})) {
10506:         $reservable_info = $remembered{$key};
10507:     } else {
10508:         my %resv;
10509:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10510:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10511:         $reservable_info = \%resv;
10512:         $remembered{$key} = $reservable_info;
10513:     }
10514:     return $reservable_info;
10515: }
10516: 
10517: sub get_course_slots {
10518:     my ($cnum,$cdom) = @_;
10519:     my $hashid=$cnum.':'.$cdom;
10520:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10521:     if (defined($cached)) {
10522:         if (ref($result) eq 'HASH') {
10523:             return %{$result};
10524:         }
10525:     } else {
10526:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10527:         my ($tmp) = keys(%slots);
10528:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10529:             &do_cache_new('allslots',$hashid,\%slots,600);
10530:             return %slots;
10531:         }
10532:     }
10533:     return;
10534: }
10535: 
10536: sub devalidate_slots_cache {
10537:     my ($cnum,$cdom)=@_;
10538:     my $hashid=$cnum.':'.$cdom;
10539:     &devalidate_cache_new('allslots',$hashid);
10540: }
10541: 
10542: sub get_coursechange {
10543:     my ($cdom,$cnum) = @_;
10544:     if ($cdom eq '' || $cnum eq '') {
10545:         return unless ($env{'request.course.id'});
10546:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10547:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10548:     }
10549:     my $hashid=$cdom.'_'.$cnum;
10550:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10551:     if ((defined($cached)) && ($change ne '')) {
10552:         return $change;
10553:     } else {
10554:         my %crshash;
10555:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10556:         if ($crshash{'internal.contentchange'} eq '') {
10557:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10558:             if ($change eq '') {
10559:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10560:                 $change = $crshash{'internal.created'};
10561:             }
10562:         } else {
10563:             $change = $crshash{'internal.contentchange'};
10564:         }
10565:         my $cachetime = 600;
10566:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10567:     }
10568:     return $change;
10569: }
10570: 
10571: sub devalidate_coursechange_cache {
10572:     my ($cnum,$cdom)=@_;
10573:     my $hashid=$cnum.':'.$cdom;
10574:     &devalidate_cache_new('crschange',$hashid);
10575: }
10576: 
10577: # ------------------------------------------------- Update symbolic store links
10578: 
10579: sub symblist {
10580:     my ($mapname,%newhash)=@_;
10581:     $mapname=&deversion(&declutter($mapname));
10582:     my %hash;
10583:     if (($env{'request.course.fn'}) && (%newhash)) {
10584:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10585:                       &GDBM_WRCREAT(),0640)) {
10586: 	    foreach my $url (keys(%newhash)) {
10587: 		next if ($url eq 'last_known'
10588: 			 && $env{'form.no_update_last_known'});
10589: 		$hash{declutter($url)}=&encode_symb($mapname,
10590: 						    $newhash{$url}->[1],
10591: 						    $newhash{$url}->[0]);
10592:             }
10593:             if (untie(%hash)) {
10594: 		return 'ok';
10595:             }
10596:         }
10597:     }
10598:     return 'error';
10599: }
10600: 
10601: # --------------------------------------------------------------- Verify a symb
10602: 
10603: sub symbverify {
10604:     my ($symb,$thisurl,$encstate)=@_;
10605:     my $thisfn=$thisurl;
10606:     $thisfn=&declutter($thisfn);
10607: # direct jump to resource in page or to a sequence - will construct own symbs
10608:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10609: # check URL part
10610:     my ($map,$resid,$url)=&decode_symb($symb);
10611: 
10612:     unless ($url eq $thisfn) { return 0; }
10613: 
10614:     $symb=&symbclean($symb);
10615:     $thisurl=&deversion($thisurl);
10616:     $thisfn=&deversion($thisfn);
10617: 
10618:     my %bighash;
10619:     my $okay=0;
10620: 
10621:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10622:                             &GDBM_READER(),0640)) {
10623:         my $noclutter;
10624:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10625:             $thisurl =~ s/\?.+$//;
10626:             if ($map =~ m{^uploaded/.+\.page$}) {
10627:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10628:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10629:                 $noclutter = 1;
10630:             }
10631:         }
10632:         my $ids;
10633:         if ($noclutter) {
10634:             $ids=$bighash{'ids_'.$thisurl};
10635:         } else {
10636:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10637:         }
10638:         unless ($ids) {
10639:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10640:             $ids=$bighash{$idkey};
10641:         }
10642:         if ($ids) {
10643: # ------------------------------------------------------------------- Has ID(s)
10644:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10645:                 $symb =~ s/\?.+$//;
10646:             }
10647: 	    foreach my $id (split(/\,/,$ids)) {
10648: 	       my ($mapid,$resid)=split(/\./,$id);
10649:                if (
10650:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10651:    eq $symb) {
10652:                    if (ref($encstate)) {
10653:                        $$encstate = $bighash{'encrypted_'.$id};
10654:                    }
10655: 		   if (($env{'request.role.adv'}) ||
10656: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10657:                        ($thisurl eq '/adm/navmaps')) {
10658: 		       $okay=1;
10659:                        last;
10660: 		   }
10661: 	       }
10662: 	   }
10663:         }
10664: 	untie(%bighash);
10665:     }
10666:     return $okay;
10667: }
10668: 
10669: # --------------------------------------------------------------- Clean-up symb
10670: 
10671: sub symbclean {
10672:     my $symb=shift;
10673:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10674: # remove version from map
10675:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10676: 
10677: # remove version from URL
10678:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10679: 
10680: # remove wrapper
10681: 
10682:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10683:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10684:     return $symb;
10685: }
10686: 
10687: # ---------------------------------------------- Split symb to find map and url
10688: 
10689: sub encode_symb {
10690:     my ($map,$resid,$url)=@_;
10691:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10692: }
10693: 
10694: sub decode_symb {
10695:     my $symb=shift;
10696:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10697:     my ($map,$resid,$url)=split(/___/,$symb);
10698:     return (&fixversion($map),$resid,&fixversion($url));
10699: }
10700: 
10701: sub fixversion {
10702:     my $fn=shift;
10703:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10704:     my %bighash;
10705:     my $uri=&clutter($fn);
10706:     my $key=$env{'request.course.id'}.'_'.$uri;
10707: # is this cached?
10708:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10709:     if (defined($cached)) { return $result; }
10710: # unfortunately not cached, or expired
10711:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10712: 	    &GDBM_READER(),0640)) {
10713:  	if ($bighash{'version_'.$uri}) {
10714:  	    my $version=$bighash{'version_'.$uri};
10715:  	    unless (($version eq 'mostrecent') || 
10716: 		    ($version==&getversion($uri))) {
10717:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10718:  	    }
10719:  	}
10720:  	untie %bighash;
10721:     }
10722:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10723: }
10724: 
10725: sub deversion {
10726:     my $url=shift;
10727:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10728:     return $url;
10729: }
10730: 
10731: # ------------------------------------------------------ Return symb list entry
10732: 
10733: sub symbread {
10734:     my ($thisfn,$donotrecurse)=@_;
10735:     my $cache_str;
10736:     if ($thisfn ne '') {
10737:         $cache_str='request.symbread.cached.'.$thisfn;
10738:         if ($env{$cache_str} ne '') {
10739:             return $env{$cache_str};
10740:         }
10741:     } else {
10742: # no filename provided? try from environment
10743:         if ($env{'request.symb'}) {
10744: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10745: 	}
10746: 	$thisfn=$env{'request.filename'};
10747:     }
10748:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10749: # is that filename actually a symb? Verify, clean, and return
10750:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10751: 	if (&symbverify($thisfn,$1)) {
10752: 	    return $env{$cache_str}=&symbclean($thisfn);
10753: 	}
10754:     }
10755:     $thisfn=declutter($thisfn);
10756:     my %hash;
10757:     my %bighash;
10758:     my $syval='';
10759:     if (($env{'request.course.fn'}) && ($thisfn)) {
10760:         my $targetfn = $thisfn;
10761:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10762:             $targetfn = 'adm/wrapper/'.$thisfn;
10763:         }
10764: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10765: 	    $targetfn=$1;
10766: 	}
10767:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10768:                       &GDBM_READER(),0640)) {
10769: 	    $syval=$hash{$targetfn};
10770:             untie(%hash);
10771:         }
10772: # ---------------------------------------------------------- There was an entry
10773:         if ($syval) {
10774: 	    #unless ($syval=~/\_\d+$/) {
10775: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10776: 		    #&appenv({'request.ambiguous' => $thisfn});
10777: 		    #return $env{$cache_str}='';
10778: 		#}    
10779: 		#$syval.=$1;
10780: 	    #}
10781:         } else {
10782: # ------------------------------------------------------- Was not in symb table
10783:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10784:                             &GDBM_READER(),0640)) {
10785: # ---------------------------------------------- Get ID(s) for current resource
10786:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10787:               unless ($ids) { 
10788:                  $ids=$bighash{'ids_/'.$thisfn};
10789:               }
10790:               unless ($ids) {
10791: # alias?
10792: 		  $ids=$bighash{'mapalias_'.$thisfn};
10793:               }
10794:               if ($ids) {
10795: # ------------------------------------------------------------------- Has ID(s)
10796:                  my @possibilities=split(/\,/,$ids);
10797:                  if ($#possibilities==0) {
10798: # ----------------------------------------------- There is only one possibility
10799: 		     my ($mapid,$resid)=split(/\./,$ids);
10800: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10801: 						    $resid,$thisfn);
10802:                  } elsif (!$donotrecurse) {
10803: # ------------------------------------------ There is more than one possibility
10804:                      my $realpossible=0;
10805:                      foreach my $id (@possibilities) {
10806: 			 my $file=$bighash{'src_'.$id};
10807:                          if (&allowed('bre',$file)) {
10808:          		    my ($mapid,$resid)=split(/\./,$id);
10809:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10810: 				$realpossible++;
10811:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10812: 						    $resid,$thisfn);
10813:                             }
10814: 			 }
10815:                      }
10816: 		     if ($realpossible!=1) { $syval=''; }
10817:                  } else {
10818:                      $syval='';
10819:                  }
10820: 	      }
10821:               untie(%bighash)
10822:            }
10823:         }
10824:         if ($syval) {
10825: 	    return $env{$cache_str}=$syval;
10826:         }
10827:     }
10828:     &appenv({'request.ambiguous' => $thisfn});
10829:     return $env{$cache_str}='';
10830: }
10831: 
10832: # ---------------------------------------------------------- Return random seed
10833: 
10834: sub numval {
10835:     my $txt=shift;
10836:     $txt=~tr/A-J/0-9/;
10837:     $txt=~tr/a-j/0-9/;
10838:     $txt=~tr/K-T/0-9/;
10839:     $txt=~tr/k-t/0-9/;
10840:     $txt=~tr/U-Z/0-5/;
10841:     $txt=~tr/u-z/0-5/;
10842:     $txt=~s/\D//g;
10843:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10844:     return int($txt);
10845: }
10846: 
10847: sub numval2 {
10848:     my $txt=shift;
10849:     $txt=~tr/A-J/0-9/;
10850:     $txt=~tr/a-j/0-9/;
10851:     $txt=~tr/K-T/0-9/;
10852:     $txt=~tr/k-t/0-9/;
10853:     $txt=~tr/U-Z/0-5/;
10854:     $txt=~tr/u-z/0-5/;
10855:     $txt=~s/\D//g;
10856:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10857:     my $total;
10858:     foreach my $val (@txts) { $total+=$val; }
10859:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10860:     return int($total);
10861: }
10862: 
10863: sub numval3 {
10864:     use integer;
10865:     my $txt=shift;
10866:     $txt=~tr/A-J/0-9/;
10867:     $txt=~tr/a-j/0-9/;
10868:     $txt=~tr/K-T/0-9/;
10869:     $txt=~tr/k-t/0-9/;
10870:     $txt=~tr/U-Z/0-5/;
10871:     $txt=~tr/u-z/0-5/;
10872:     $txt=~s/\D//g;
10873:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10874:     my $total;
10875:     foreach my $val (@txts) { $total+=$val; }
10876:     if ($_64bit) { $total=(($total<<32)>>32); }
10877:     return $total;
10878: }
10879: 
10880: sub digest {
10881:     my ($data)=@_;
10882:     my $digest=&Digest::MD5::md5($data);
10883:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10884:     my ($e,$f);
10885:     {
10886:         use integer;
10887:         $e=($a+$b);
10888:         $f=($c+$d);
10889:         if ($_64bit) {
10890:             $e=(($e<<32)>>32);
10891:             $f=(($f<<32)>>32);
10892:         }
10893:     }
10894:     if (wantarray) {
10895: 	return ($e,$f);
10896:     } else {
10897: 	my $g;
10898: 	{
10899: 	    use integer;
10900: 	    $g=($e+$f);
10901: 	    if ($_64bit) {
10902: 		$g=(($g<<32)>>32);
10903: 	    }
10904: 	}
10905: 	return $g;
10906:     }
10907: }
10908: 
10909: sub latest_rnd_algorithm_id {
10910:     return '64bit5';
10911: }
10912: 
10913: sub get_rand_alg {
10914:     my ($courseid)=@_;
10915:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10916:     if ($courseid) {
10917: 	return $env{"course.$courseid.rndseed"};
10918:     }
10919:     return &latest_rnd_algorithm_id();
10920: }
10921: 
10922: sub validCODE {
10923:     my ($CODE)=@_;
10924:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10925:     return 0;
10926: }
10927: 
10928: sub getCODE {
10929:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10930:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10931: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10932: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10933: 	return $Apache::lonhomework::history{'resource.CODE'};
10934:     }
10935:     return undef;
10936: }
10937: #
10938: #  Determines the random seed for a specific context:
10939: #
10940: # parameters:
10941: #   symb      - in course context the symb for the seed.
10942: #   course_id - The course id of the form domain_coursenum.
10943: #   domain    - Domain for the user.
10944: #   course    - Course for the user.
10945: #   cenv      - environment of the course.
10946: #
10947: # NOTE:
10948: #   All parameters are picked out of the environment if missing
10949: #   or not defined.
10950: #   If a symb cannot be determined the current time is used instead.
10951: #
10952: #  For a given well defined symb, courside, domain, username,
10953: #  and course environment, the seed is reproducible.
10954: #
10955: sub rndseed {
10956:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10957:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10958:     if (!defined($symb)) {
10959: 	unless ($symb=$wsymb) { return time; }
10960:     }
10961:     if (!defined $courseid) { 
10962: 	$courseid=$wcourseid; 
10963:     }
10964:     if (!defined $domain) { $domain=$wdomain; }
10965:     if (!defined $username) { $username=$wusername }
10966: 
10967:     my $which;
10968:     if (defined($cenv->{'rndseed'})) {
10969: 	$which = $cenv->{'rndseed'};
10970:     } else {
10971: 	$which =&get_rand_alg($courseid);
10972:     }
10973:     if (defined(&getCODE())) {
10974: 
10975: 	if ($which eq '64bit5') {
10976: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10977: 	} elsif ($which eq '64bit4') {
10978: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10979: 	} else {
10980: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10981: 	}
10982:     } elsif ($which eq '64bit5') {
10983: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10984:     } elsif ($which eq '64bit4') {
10985: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10986:     } elsif ($which eq '64bit3') {
10987: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10988:     } elsif ($which eq '64bit2') {
10989: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10990:     } elsif ($which eq '64bit') {
10991: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10992:     }
10993:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10994: }
10995: 
10996: sub rndseed_32bit {
10997:     my ($symb,$courseid,$domain,$username)=@_;
10998:     {
10999: 	use integer;
11000: 	my $symbchck=unpack("%32C*",$symb) << 27;
11001: 	my $symbseed=numval($symb) << 22;
11002: 	my $namechck=unpack("%32C*",$username) << 17;
11003: 	my $nameseed=numval($username) << 12;
11004: 	my $domainseed=unpack("%32C*",$domain) << 7;
11005: 	my $courseseed=unpack("%32C*",$courseid);
11006: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11007: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11008: 	#&logthis("rndseed :$num:$symb");
11009: 	if ($_64bit) { $num=(($num<<32)>>32); }
11010: 	return $num;
11011:     }
11012: }
11013: 
11014: sub rndseed_64bit {
11015:     my ($symb,$courseid,$domain,$username)=@_;
11016:     {
11017: 	use integer;
11018: 	my $symbchck=unpack("%32S*",$symb) << 21;
11019: 	my $symbseed=numval($symb) << 10;
11020: 	my $namechck=unpack("%32S*",$username);
11021: 	
11022: 	my $nameseed=numval($username) << 21;
11023: 	my $domainseed=unpack("%32S*",$domain) << 10;
11024: 	my $courseseed=unpack("%32S*",$courseid);
11025: 	
11026: 	my $num1=$symbchck+$symbseed+$namechck;
11027: 	my $num2=$nameseed+$domainseed+$courseseed;
11028: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11029: 	#&logthis("rndseed :$num:$symb");
11030: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11031: 	return "$num1,$num2";
11032:     }
11033: }
11034: 
11035: sub rndseed_64bit2 {
11036:     my ($symb,$courseid,$domain,$username)=@_;
11037:     {
11038: 	use integer;
11039: 	# strings need to be an even # of cahracters long, it it is odd the
11040:         # last characters gets thrown away
11041: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11042: 	my $symbseed=numval($symb) << 10;
11043: 	my $namechck=unpack("%32S*",$username.' ');
11044: 	
11045: 	my $nameseed=numval($username) << 21;
11046: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11047: 	my $courseseed=unpack("%32S*",$courseid.' ');
11048: 	
11049: 	my $num1=$symbchck+$symbseed+$namechck;
11050: 	my $num2=$nameseed+$domainseed+$courseseed;
11051: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11052: 	#&logthis("rndseed :$num:$symb");
11053: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11054: 	return "$num1,$num2";
11055:     }
11056: }
11057: 
11058: sub rndseed_64bit3 {
11059:     my ($symb,$courseid,$domain,$username)=@_;
11060:     {
11061: 	use integer;
11062: 	# strings need to be an even # of cahracters long, it it is odd the
11063:         # last characters gets thrown away
11064: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11065: 	my $symbseed=numval2($symb) << 10;
11066: 	my $namechck=unpack("%32S*",$username.' ');
11067: 	
11068: 	my $nameseed=numval2($username) << 21;
11069: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11070: 	my $courseseed=unpack("%32S*",$courseid.' ');
11071: 	
11072: 	my $num1=$symbchck+$symbseed+$namechck;
11073: 	my $num2=$nameseed+$domainseed+$courseseed;
11074: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11075: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11076: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11077: 	
11078: 	return "$num1:$num2";
11079:     }
11080: }
11081: 
11082: sub rndseed_64bit4 {
11083:     my ($symb,$courseid,$domain,$username)=@_;
11084:     {
11085: 	use integer;
11086: 	# strings need to be an even # of cahracters long, it it is odd the
11087:         # last characters gets thrown away
11088: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11089: 	my $symbseed=numval3($symb) << 10;
11090: 	my $namechck=unpack("%32S*",$username.' ');
11091: 	
11092: 	my $nameseed=numval3($username) << 21;
11093: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11094: 	my $courseseed=unpack("%32S*",$courseid.' ');
11095: 	
11096: 	my $num1=$symbchck+$symbseed+$namechck;
11097: 	my $num2=$nameseed+$domainseed+$courseseed;
11098: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11099: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11100: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11101: 	
11102: 	return "$num1:$num2";
11103:     }
11104: }
11105: 
11106: sub rndseed_64bit5 {
11107:     my ($symb,$courseid,$domain,$username)=@_;
11108:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11109:     return "$num1:$num2";
11110: }
11111: 
11112: sub rndseed_CODE_64bit {
11113:     my ($symb,$courseid,$domain,$username)=@_;
11114:     {
11115: 	use integer;
11116: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11117: 	my $symbseed=numval2($symb);
11118: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11119: 	my $CODEseed=numval(&getCODE());
11120: 	my $courseseed=unpack("%32S*",$courseid.' ');
11121: 	my $num1=$symbseed+$CODEchck;
11122: 	my $num2=$CODEseed+$courseseed+$symbchck;
11123: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11124: 	#&logthis("rndseed :$num1:$num2:$symb");
11125: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11126: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11127: 	return "$num1:$num2";
11128:     }
11129: }
11130: 
11131: sub rndseed_CODE_64bit4 {
11132:     my ($symb,$courseid,$domain,$username)=@_;
11133:     {
11134: 	use integer;
11135: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11136: 	my $symbseed=numval3($symb);
11137: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11138: 	my $CODEseed=numval3(&getCODE());
11139: 	my $courseseed=unpack("%32S*",$courseid.' ');
11140: 	my $num1=$symbseed+$CODEchck;
11141: 	my $num2=$CODEseed+$courseseed+$symbchck;
11142: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11143: 	#&logthis("rndseed :$num1:$num2:$symb");
11144: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11145: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11146: 	return "$num1:$num2";
11147:     }
11148: }
11149: 
11150: sub rndseed_CODE_64bit5 {
11151:     my ($symb,$courseid,$domain,$username)=@_;
11152:     my $code = &getCODE();
11153:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11154:     return "$num1:$num2";
11155: }
11156: 
11157: sub setup_random_from_rndseed {
11158:     my ($rndseed)=@_;
11159:     if ($rndseed =~/([,:])/) {
11160: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11161: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11162:     } else {
11163: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11164:     }
11165: }
11166: 
11167: sub latest_receipt_algorithm_id {
11168:     return 'receipt3';
11169: }
11170: 
11171: sub recunique {
11172:     my $fucourseid=shift;
11173:     my $unique;
11174:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11175: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11176: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11177:     } else {
11178: 	$unique=$perlvar{'lonReceipt'};
11179:     }
11180:     return unpack("%32C*",$unique);
11181: }
11182: 
11183: sub recprefix {
11184:     my $fucourseid=shift;
11185:     my $prefix;
11186:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11187: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11188: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11189:     } else {
11190: 	$prefix=$perlvar{'lonHostID'};
11191:     }
11192:     return unpack("%32C*",$prefix);
11193: }
11194: 
11195: sub ireceipt {
11196:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11197: 
11198:     my $return =&recprefix($fucourseid).'-';
11199: 
11200:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11201: 	$env{'request.state'} eq 'construct') {
11202: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11203: 	return $return;
11204:     }
11205: 
11206:     my $cuname=unpack("%32C*",$funame);
11207:     my $cudom=unpack("%32C*",$fudom);
11208:     my $cucourseid=unpack("%32C*",$fucourseid);
11209:     my $cusymb=unpack("%32C*",$fusymb);
11210:     my $cunique=&recunique($fucourseid);
11211:     my $cpart=unpack("%32S*",$part);
11212:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11213: 
11214: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11215: 			       
11216: 	$return.= ($cunique%$cuname+
11217: 		   $cunique%$cudom+
11218: 		   $cusymb%$cuname+
11219: 		   $cusymb%$cudom+
11220: 		   $cucourseid%$cuname+
11221: 		   $cucourseid%$cudom+
11222: 		   $cpart%$cuname+
11223: 		   $cpart%$cudom);
11224:     } else {
11225: 	$return.= ($cunique%$cuname+
11226: 		   $cunique%$cudom+
11227: 		   $cusymb%$cuname+
11228: 		   $cusymb%$cudom+
11229: 		   $cucourseid%$cuname+
11230: 		   $cucourseid%$cudom);
11231:     }
11232:     return $return;
11233: }
11234: 
11235: sub receipt {
11236:     my ($part)=@_;
11237:     my ($symb,$courseid,$domain,$name) = &whichuser();
11238:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11239: }
11240: 
11241: sub whichuser {
11242:     my ($passedsymb)=@_;
11243:     my ($symb,$courseid,$domain,$name,$publicuser);
11244:     if (defined($env{'form.grade_symb'})) {
11245: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11246: 	my $allowed=&allowed('vgr',$tmp_courseid);
11247: 	if (!$allowed &&
11248: 	    exists($env{'request.course.sec'}) &&
11249: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11250: 	    $allowed=&allowed('vgr',$tmp_courseid.
11251: 			      '/'.$env{'request.course.sec'});
11252: 	}
11253: 	if ($allowed) {
11254: 	    ($symb)=&get_env_multiple('form.grade_symb');
11255: 	    $courseid=$tmp_courseid;
11256: 	    ($domain)=&get_env_multiple('form.grade_domain');
11257: 	    ($name)=&get_env_multiple('form.grade_username');
11258: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11259: 	}
11260:     }
11261:     if (!$passedsymb) {
11262: 	$symb=&symbread();
11263:     } else {
11264: 	$symb=$passedsymb;
11265:     }
11266:     $courseid=$env{'request.course.id'};
11267:     $domain=$env{'user.domain'};
11268:     $name=$env{'user.name'};
11269:     if ($name eq 'public' && $domain eq 'public') {
11270: 	if (!defined($env{'form.username'})) {
11271: 	    $env{'form.username'}.=time.rand(10000000);
11272: 	}
11273: 	$name.=$env{'form.username'};
11274:     }
11275:     return ($symb,$courseid,$domain,$name,$publicuser);
11276: 
11277: }
11278: 
11279: # ------------------------------------------------------------ Serves up a file
11280: # returns either the contents of the file or 
11281: # -1 if the file doesn't exist
11282: #
11283: # if the target is a file that was uploaded via DOCS, 
11284: # a check will be made to see if a current copy exists on the local server,
11285: # if it does this will be served, otherwise a copy will be retrieved from
11286: # the home server for the course and stored in /home/httpd/html/userfiles on
11287: # the local server.   
11288: 
11289: sub getfile {
11290:     my ($file) = @_;
11291:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11292:     &repcopy($file);
11293:     return &readfile($file);
11294: }
11295: 
11296: sub repcopy_userfile {
11297:     my ($file)=@_;
11298:     my $londocroot = $perlvar{'lonDocRoot'};
11299:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11300:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11301:     my ($cdom,$cnum,$filename) = 
11302: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11303:     my $uri="/uploaded/$cdom/$cnum/$filename";
11304:     if (-e "$file") {
11305: # we already have a local copy, check it out
11306: 	my @fileinfo = stat($file);
11307: 	my $rtncode;
11308: 	my $info;
11309: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11310: 	if ($lwpresp ne 'ok') {
11311: # there is no such file anymore, even though we had a local copy
11312: 	    if ($rtncode eq '404') {
11313: 		unlink($file);
11314: 	    }
11315: 	    return -1;
11316: 	}
11317: 	if ($info < $fileinfo[9]) {
11318: # nice, the file we have is up-to-date, just say okay
11319: 	    return 'ok';
11320: 	} else {
11321: # the file is outdated, get rid of it
11322: 	    unlink($file);
11323: 	}
11324:     }
11325: # one way or the other, at this point, we don't have the file
11326: # construct the correct path for the file
11327:     my @parts = ($cdom,$cnum); 
11328:     if ($filename =~ m|^(.+)/[^/]+$|) {
11329: 	push @parts, split(/\//,$1);
11330:     }
11331:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11332:     foreach my $part (@parts) {
11333: 	$path .= '/'.$part;
11334: 	if (!-e $path) {
11335: 	    mkdir($path,0770);
11336: 	}
11337:     }
11338: # now the path exists for sure
11339: # get a user agent
11340:     my $ua=new LWP::UserAgent;
11341:     my $transferfile=$file.'.in.transfer';
11342: # FIXME: this should flock
11343:     if (-e $transferfile) { return 'ok'; }
11344:     my $request;
11345:     $uri=~s/^\///;
11346:     my $homeserver = &homeserver($cnum,$cdom);
11347:     my $protocol = $protocol{$homeserver};
11348:     $protocol = 'http' if ($protocol ne 'https');
11349:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11350:     my $response=$ua->request($request,$transferfile);
11351: # did it work?
11352:     if ($response->is_error()) {
11353: 	unlink($transferfile);
11354: 	&logthis("Userfile repcopy failed for $uri");
11355: 	return -1;
11356:     }
11357: # worked, rename the transfer file
11358:     rename($transferfile,$file);
11359:     return 'ok';
11360: }
11361: 
11362: sub tokenwrapper {
11363:     my $uri=shift;
11364:     $uri=~s|^https?\://([^/]+)||;
11365:     $uri=~s|^/||;
11366:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11367:     my $token=$1;
11368:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11369:     if ($udom && $uname && $file) {
11370: 	$file=~s|(\?\.*)*$||;
11371:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11372:         my $homeserver = &homeserver($uname,$udom);
11373:         my $protocol = $protocol{$homeserver};
11374:         $protocol = 'http' if ($protocol ne 'https');
11375:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11376:                (($uri=~/\?/)?'&':'?').'token='.$token.
11377:                                '&tokenissued='.$perlvar{'lonHostID'};
11378:     } else {
11379:         return '/adm/notfound.html';
11380:     }
11381: }
11382: 
11383: # call with reqtype HEAD: get last modification time
11384: # call with reqtype GET: get the file contents
11385: # Do not call this with reqtype GET for large files! It loads everything into memory
11386: #
11387: sub getuploaded {
11388:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11389:     $uri=~s/^\///;
11390:     my $homeserver = &homeserver($cnum,$cdom);
11391:     my $protocol = $protocol{$homeserver};
11392:     $protocol = 'http' if ($protocol ne 'https');
11393:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11394:     my $ua=new LWP::UserAgent;
11395:     my $request=new HTTP::Request($reqtype,$uri);
11396:     my $response=$ua->request($request);
11397:     $$rtncode = $response->code;
11398:     if (! $response->is_success()) {
11399: 	return 'failed';
11400:     }      
11401:     if ($reqtype eq 'HEAD') {
11402: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11403:     } elsif ($reqtype eq 'GET') {
11404: 	$$info = $response->content;
11405:     }
11406:     return 'ok';
11407: }
11408: 
11409: sub readfile {
11410:     my $file = shift;
11411:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11412:     my $fh;
11413:     open($fh,"<$file");
11414:     my $a='';
11415:     while (my $line = <$fh>) { $a .= $line; }
11416:     return $a;
11417: }
11418: 
11419: sub filelocation {
11420:     my ($dir,$file) = @_;
11421:     my $location;
11422:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11423: 
11424:     if ($file =~ m-^/adm/-) {
11425: 	$file=~s-^/adm/wrapper/-/-;
11426: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11427:     }
11428: 
11429:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11430:         $location = $file;
11431:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11432:         my ($udom,$uname,$filename)=
11433:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11434:         my $home=&homeserver($uname,$udom);
11435:         my $is_me=0;
11436:         my @ids=&current_machine_ids();
11437:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11438:         if ($is_me) {
11439:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11440:         } else {
11441:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11442:   	      $udom.'/'.$uname.'/'.$filename;
11443:         }
11444:     } elsif ($file =~ m-^/adm/-) {
11445: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11446:     } else {
11447:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11448:         $file=~s:^/(res|priv)/:/:;
11449:         my $space=$1;
11450:         if ( !( $file =~ m:^/:) ) {
11451:             $location = $dir. '/'.$file;
11452:         } else {
11453:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11454:         }
11455:     }
11456:     $location=~s://+:/:g; # remove duplicate /
11457:     while ($location=~m{/\.\./}) {
11458: 	if ($location =~ m{/[^/]+/\.\./}) {
11459: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11460: 	} else {
11461: 	    $location=~ s{/\.\./}{/}g;
11462: 	}
11463:     } #remove dir/..
11464:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11465:     return $location;
11466: }
11467: 
11468: sub hreflocation {
11469:     my ($dir,$file)=@_;
11470:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11471: 	$file=filelocation($dir,$file);
11472:     } elsif ($file=~m-^/adm/-) {
11473: 	$file=~s-^/adm/wrapper/-/-;
11474: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11475:     }
11476:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11477: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11478:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11479: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11480: 	        {/uploaded/$1/$2/}x;
11481:     }
11482:     if ($file=~ m{^/userfiles/}) {
11483: 	$file =~ s{^/userfiles/}{/uploaded/};
11484:     }
11485:     return $file;
11486: }
11487: 
11488: 
11489: 
11490: 
11491: 
11492: sub current_machine_domains {
11493:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11494: }
11495: 
11496: sub machine_domains {
11497:     my ($hostname) = @_;
11498:     my @domains;
11499:     my %hostname = &all_hostnames();
11500:     while( my($id, $name) = each(%hostname)) {
11501: #	&logthis("-$id-$name-$hostname-");
11502: 	if ($hostname eq $name) {
11503: 	    push(@domains,&host_domain($id));
11504: 	}
11505:     }
11506:     return @domains;
11507: }
11508: 
11509: sub current_machine_ids {
11510:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11511: }
11512: 
11513: sub machine_ids {
11514:     my ($hostname) = @_;
11515:     $hostname ||= &hostname($perlvar{'lonHostID'});
11516:     my @ids;
11517:     my %name_to_host = &all_names();
11518:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11519: 	return @{ $name_to_host{$hostname} };
11520:     }
11521:     return;
11522: }
11523: 
11524: sub additional_machine_domains {
11525:     my @domains;
11526:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11527:     while( my $line = <$fh>) {
11528:         $line =~ s/\s//g;
11529:         push(@domains,$line);
11530:     }
11531:     return @domains;
11532: }
11533: 
11534: sub default_login_domain {
11535:     my $domain = $perlvar{'lonDefDomain'};
11536:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11537:     foreach my $posdom (&current_machine_domains(),
11538:                         &additional_machine_domains()) {
11539:         if (lc($posdom) eq lc($testdomain)) {
11540:             $domain=$posdom;
11541:             last;
11542:         }
11543:     }
11544:     return $domain;
11545: }
11546: 
11547: # ------------------------------------------------------------- Declutters URLs
11548: 
11549: sub declutter {
11550:     my $thisfn=shift;
11551:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11552:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11553:     $thisfn=~s/^\///;
11554:     $thisfn=~s|^adm/wrapper/||;
11555:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11556:     $thisfn=~s/^res\///;
11557:     $thisfn=~s/^priv\///;
11558:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11559:         $thisfn=~s/\?.+$//;
11560:     }
11561:     return $thisfn;
11562: }
11563: 
11564: # ------------------------------------------------------------- Clutter up URLs
11565: 
11566: sub clutter {
11567:     my $thisfn='/'.&declutter(shift);
11568:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11569: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11570:        $thisfn='/res'.$thisfn; 
11571:     }
11572:     if ($thisfn !~m|^/adm|) {
11573: 	if ($thisfn =~ m|^/ext/|) {
11574: 	    $thisfn='/adm/wrapper'.$thisfn;
11575: 	} else {
11576: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11577: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11578: 	    if ($embstyle eq 'ssi'
11579: 		|| ($embstyle eq 'hdn')
11580: 		|| ($embstyle eq 'rat')
11581: 		|| ($embstyle eq 'prv')
11582: 		|| ($embstyle eq 'ign')) {
11583: 		#do nothing with these
11584: 	    } elsif (($embstyle eq 'img') 
11585: 		|| ($embstyle eq 'emb')
11586: 		|| ($embstyle eq 'wrp')) {
11587: 		$thisfn='/adm/wrapper'.$thisfn;
11588: 	    } elsif ($embstyle eq 'unk'
11589: 		     && $thisfn!~/\.(sequence|page)$/) {
11590: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11591: 	    } else {
11592: #		&logthis("Got a blank emb style");
11593: 	    }
11594: 	}
11595:     }
11596:     return $thisfn;
11597: }
11598: 
11599: sub clutter_with_no_wrapper {
11600:     my $uri = &clutter(shift);
11601:     if ($uri =~ m-^/adm/-) {
11602: 	$uri =~ s-^/adm/wrapper/-/-;
11603: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11604:     }
11605:     return $uri;
11606: }
11607: 
11608: sub freeze_escape {
11609:     my ($value)=@_;
11610:     if (ref($value)) {
11611: 	$value=&nfreeze($value);
11612: 	return '__FROZEN__'.&escape($value);
11613:     }
11614:     return &escape($value);
11615: }
11616: 
11617: 
11618: sub thaw_unescape {
11619:     my ($value)=@_;
11620:     if ($value =~ /^__FROZEN__/) {
11621: 	substr($value,0,10,undef);
11622: 	$value=&unescape($value);
11623: 	return &thaw($value);
11624:     }
11625:     return &unescape($value);
11626: }
11627: 
11628: sub correct_line_ends {
11629:     my ($result)=@_;
11630:     $$result =~s/\r\n/\n/mg;
11631:     $$result =~s/\r/\n/mg;
11632: }
11633: # ================================================================ Main Program
11634: 
11635: sub goodbye {
11636:    &logthis("Starting Shut down");
11637: #not converted to using infrastruture and probably shouldn't be
11638:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11639: #converted
11640: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11641:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11642: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11643: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11644: #1.1 only
11645: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11646: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11647: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11648: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11649:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11650:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11651:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11652:    &flushcourselogs();
11653:    &logthis("Shutting down");
11654: }
11655: 
11656: sub get_dns {
11657:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11658:     if (!$ignore_cache) {
11659: 	my ($content,$cached)=
11660: 	    &Apache::lonnet::is_cached_new('dns',$url);
11661: 	if ($cached) {
11662: 	    &$func($content,$hashref);
11663: 	    return;
11664: 	}
11665:     }
11666: 
11667:     my %alldns;
11668:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11669:     foreach my $dns (<$config>) {
11670: 	next if ($dns !~ /^\^(\S*)/x);
11671:         my $line = $1;
11672:         my ($host,$protocol) = split(/:/,$line);
11673:         if ($protocol ne 'https') {
11674:             $protocol = 'http';
11675:         }
11676: 	$alldns{$host} = $protocol;
11677:     }
11678:     while (%alldns) {
11679: 	my ($dns) = keys(%alldns);
11680: 	my $ua=new LWP::UserAgent;
11681:         $ua->timeout(30);
11682: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11683: 	my $response=$ua->request($request);
11684:         delete($alldns{$dns});
11685: 	next if ($response->is_error());
11686: 	my @content = split("\n",$response->content);
11687: 	unless ($nocache) {
11688: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11689: 	}
11690: 	&$func(\@content,$hashref);
11691: 	return;
11692:     }
11693:     close($config);
11694:     my $which = (split('/',$url))[3];
11695:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11696:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11697:     my @content = <$config>;
11698:     &$func(\@content,$hashref);
11699:     return;
11700: }
11701: 
11702: # ------------------------------------------------------Get DNS checksums file
11703: sub parse_dns_checksums_tab {
11704:     my ($lines,$hashref) = @_;
11705:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11706:     my $loncaparev = &get_server_loncaparev($machine_dom);
11707:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11708:     my (%chksum,%revnum);
11709:     if (ref($lines) eq 'ARRAY') {
11710:         chomp(@{$lines});
11711:         my $version = shift(@{$lines});
11712:         if ($version eq $release) {  
11713:             foreach my $line (@{$lines}) {
11714:                 my ($file,$version,$shasum) = split(/,/,$line);
11715:                 $chksum{$file} = $shasum;
11716:                 $revnum{$file} = $version;
11717:             }
11718:             if (ref($hashref) eq 'HASH') {
11719:                 %{$hashref} = (
11720:                                 sums     => \%chksum,
11721:                                 versions => \%revnum,
11722:                               );
11723:             }
11724:         }
11725:     }
11726:     return;
11727: }
11728: 
11729: sub fetch_dns_checksums {
11730:     my %checksums;
11731:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11732:     my $loncaparev = &get_server_loncaparev($machine_dom);
11733:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11734:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11735:              \%checksums);
11736:     return \%checksums;
11737: }
11738: 
11739: # ------------------------------------------------------------ Read domain file
11740: {
11741:     my $loaded;
11742:     my %domain;
11743: 
11744:     sub parse_domain_tab {
11745: 	my ($lines) = @_;
11746: 	foreach my $line (@$lines) {
11747: 	    next if ($line =~ /^(\#|\s*$ )/x);
11748: 
11749: 	    chomp($line);
11750: 	    my ($name,@elements) = split(/:/,$line,9);
11751: 	    my %this_domain;
11752: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11753: 			       'lang_def', 'city', 'longi', 'lati',
11754: 			       'primary') {
11755: 		$this_domain{$field} = shift(@elements);
11756: 	    }
11757: 	    $domain{$name} = \%this_domain;
11758: 	}
11759:     }
11760: 
11761:     sub reset_domain_info {
11762: 	undef($loaded);
11763: 	undef(%domain);
11764:     }
11765: 
11766:     sub load_domain_tab {
11767: 	my ($ignore_cache) = @_;
11768: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11769: 	my $fh;
11770: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11771: 	    my @lines = <$fh>;
11772: 	    &parse_domain_tab(\@lines);
11773: 	}
11774: 	close($fh);
11775: 	$loaded = 1;
11776:     }
11777: 
11778:     sub domain {
11779: 	&load_domain_tab() if (!$loaded);
11780: 
11781: 	my ($name,$what) = @_;
11782: 	return if ( !exists($domain{$name}) );
11783: 
11784: 	if (!$what) {
11785: 	    return $domain{$name}{'description'};
11786: 	}
11787: 	return $domain{$name}{$what};
11788:     }
11789: 
11790:     sub domain_info {
11791:         &load_domain_tab() if (!$loaded);
11792:         return %domain;
11793:     }
11794: 
11795: }
11796: 
11797: 
11798: # ------------------------------------------------------------- Read hosts file
11799: {
11800:     my %hostname;
11801:     my %hostdom;
11802:     my %libserv;
11803:     my $loaded;
11804:     my %name_to_host;
11805:     my %internetdom;
11806:     my %LC_dns_serv;
11807: 
11808:     sub parse_hosts_tab {
11809: 	my ($file) = @_;
11810: 	foreach my $configline (@$file) {
11811: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11812:             chomp($configline);
11813: 	    if ($configline =~ /^\^/) {
11814:                 if ($configline =~ /^\^([\w.\-]+)/) {
11815:                     $LC_dns_serv{$1} = 1;
11816:                 }
11817:                 next;
11818:             }
11819: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11820: 	    $name=~s/\s//g;
11821: 	    if ($id && $domain && $role && $name) {
11822: 		$hostname{$id}=$name;
11823: 		push(@{$name_to_host{$name}}, $id);
11824: 		$hostdom{$id}=$domain;
11825: 		if ($role eq 'library') { $libserv{$id}=$name; }
11826:                 if (defined($protocol)) {
11827:                     if ($protocol eq 'https') {
11828:                         $protocol{$id} = $protocol;
11829:                     } else {
11830:                         $protocol{$id} = 'http'; 
11831:                     }
11832:                 } else {
11833:                     $protocol{$id} = 'http';
11834:                 }
11835:                 if (defined($intdom)) {
11836:                     $internetdom{$id} = $intdom;
11837:                 }
11838: 	    }
11839: 	}
11840:     }
11841:     
11842:     sub reset_hosts_info {
11843: 	&purge_remembered();
11844: 	&reset_domain_info();
11845: 	&reset_hosts_ip_info();
11846: 	undef(%name_to_host);
11847: 	undef(%hostname);
11848: 	undef(%hostdom);
11849: 	undef(%libserv);
11850: 	undef($loaded);
11851:     }
11852: 
11853:     sub load_hosts_tab {
11854: 	my ($ignore_cache) = @_;
11855: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11856: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11857: 	my @config = <$config>;
11858: 	&parse_hosts_tab(\@config);
11859: 	close($config);
11860: 	$loaded=1;
11861:     }
11862: 
11863:     sub hostname {
11864: 	&load_hosts_tab() if (!$loaded);
11865: 
11866: 	my ($lonid) = @_;
11867: 	return $hostname{$lonid};
11868:     }
11869: 
11870:     sub all_hostnames {
11871: 	&load_hosts_tab() if (!$loaded);
11872: 
11873: 	return %hostname;
11874:     }
11875: 
11876:     sub all_names {
11877: 	&load_hosts_tab() if (!$loaded);
11878: 
11879: 	return %name_to_host;
11880:     }
11881: 
11882:     sub all_host_domain {
11883:         &load_hosts_tab() if (!$loaded);
11884:         return %hostdom;
11885:     }
11886: 
11887:     sub is_library {
11888: 	&load_hosts_tab() if (!$loaded);
11889: 
11890: 	return exists($libserv{$_[0]});
11891:     }
11892: 
11893:     sub all_library {
11894: 	&load_hosts_tab() if (!$loaded);
11895: 
11896: 	return %libserv;
11897:     }
11898: 
11899:     sub unique_library {
11900: 	#2x reverse removes all hostnames that appear more than once
11901:         my %unique = reverse &all_library();
11902:         return reverse %unique;
11903:     }
11904: 
11905:     sub get_servers {
11906: 	&load_hosts_tab() if (!$loaded);
11907: 
11908: 	my ($domain,$type) = @_;
11909: 	my %possible_hosts = ($type eq 'library') ? %libserv
11910: 	                                          : %hostname;
11911: 	my %result;
11912: 	if (ref($domain) eq 'ARRAY') {
11913: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11914: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11915: 		    $result{$host} = $hostname;
11916: 		}
11917: 	    }
11918: 	} else {
11919: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11920: 		if ($hostdom{$host} eq $domain) {
11921: 		    $result{$host} = $hostname;
11922: 		}
11923: 	    }
11924: 	}
11925: 	return %result;
11926:     }
11927: 
11928:     sub get_unique_servers {
11929:         my %unique = reverse &get_servers(@_);
11930: 	return reverse %unique;
11931:     }
11932: 
11933:     sub host_domain {
11934: 	&load_hosts_tab() if (!$loaded);
11935: 
11936: 	my ($lonid) = @_;
11937: 	return $hostdom{$lonid};
11938:     }
11939: 
11940:     sub all_domains {
11941: 	&load_hosts_tab() if (!$loaded);
11942: 
11943: 	my %seen;
11944: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11945: 	return @uniq;
11946:     }
11947: 
11948:     sub internet_dom {
11949:         &load_hosts_tab() if (!$loaded);
11950: 
11951:         my ($lonid) = @_;
11952:         return $internetdom{$lonid};
11953:     }
11954: 
11955:     sub is_LC_dns {
11956:         &load_hosts_tab() if (!$loaded);
11957: 
11958:         my ($hostname) = @_;
11959:         return exists($LC_dns_serv{$hostname});
11960:     }
11961: 
11962: }
11963: 
11964: { 
11965:     my %iphost;
11966:     my %name_to_ip;
11967:     my %lonid_to_ip;
11968: 
11969:     sub get_hosts_from_ip {
11970: 	my ($ip) = @_;
11971: 	my %iphosts = &get_iphost();
11972: 	if (ref($iphosts{$ip})) {
11973: 	    return @{$iphosts{$ip}};
11974: 	}
11975: 	return;
11976:     }
11977:     
11978:     sub reset_hosts_ip_info {
11979: 	undef(%iphost);
11980: 	undef(%name_to_ip);
11981: 	undef(%lonid_to_ip);
11982:     }
11983: 
11984:     sub get_host_ip {
11985: 	my ($lonid) = @_;
11986: 	if (exists($lonid_to_ip{$lonid})) {
11987: 	    return $lonid_to_ip{$lonid};
11988: 	}
11989: 	my $name=&hostname($lonid);
11990:    	my $ip = gethostbyname($name);
11991: 	return if (!$ip || length($ip) ne 4);
11992: 	$ip=inet_ntoa($ip);
11993: 	$name_to_ip{$name}   = $ip;
11994: 	$lonid_to_ip{$lonid} = $ip;
11995: 	return $ip;
11996:     }
11997:     
11998:     sub get_iphost {
11999: 	my ($ignore_cache) = @_;
12000: 
12001: 	if (!$ignore_cache) {
12002: 	    if (%iphost) {
12003: 		return %iphost;
12004: 	    }
12005: 	    my ($ip_info,$cached)=
12006: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12007: 	    if ($cached) {
12008: 		%iphost      = %{$ip_info->[0]};
12009: 		%name_to_ip  = %{$ip_info->[1]};
12010: 		%lonid_to_ip = %{$ip_info->[2]};
12011: 		return %iphost;
12012: 	    }
12013: 	}
12014: 
12015: 	# get yesterday's info for fallback
12016: 	my %old_name_to_ip;
12017: 	my ($ip_info,$cached)=
12018: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12019: 	if ($cached) {
12020: 	    %old_name_to_ip = %{$ip_info->[1]};
12021: 	}
12022: 
12023: 	my %name_to_host = &all_names();
12024: 	foreach my $name (keys(%name_to_host)) {
12025: 	    my $ip;
12026: 	    if (!exists($name_to_ip{$name})) {
12027: 		$ip = gethostbyname($name);
12028: 		if (!$ip || length($ip) ne 4) {
12029: 		    if (defined($old_name_to_ip{$name})) {
12030: 			$ip = $old_name_to_ip{$name};
12031: 			&logthis("Can't find $name defaulting to old $ip");
12032: 		    } else {
12033: 			&logthis("Name $name no IP found");
12034: 			next;
12035: 		    }
12036: 		} else {
12037: 		    $ip=inet_ntoa($ip);
12038: 		}
12039: 		$name_to_ip{$name} = $ip;
12040: 	    } else {
12041: 		$ip = $name_to_ip{$name};
12042: 	    }
12043: 	    foreach my $id (@{ $name_to_host{$name} }) {
12044: 		$lonid_to_ip{$id} = $ip;
12045: 	    }
12046: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12047: 	}
12048: 	&do_cache_new('iphost','iphost',
12049: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12050: 		      48*60*60);
12051: 
12052: 	return %iphost;
12053:     }
12054: 
12055:     #
12056:     #  Given a DNS returns the loncapa host name for that DNS 
12057:     # 
12058:     sub host_from_dns {
12059:         my ($dns) = @_;
12060:         my @hosts;
12061:         my $ip;
12062: 
12063:         if (exists($name_to_ip{$dns})) {
12064:             $ip = $name_to_ip{$dns};
12065:         }
12066:         if (!$ip) {
12067:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12068:             if (length($ip) == 4) { 
12069: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12070:             }
12071:         }
12072:         if ($ip) {
12073: 	    @hosts = get_hosts_from_ip($ip);
12074: 	    return $hosts[0];
12075:         }
12076:         return undef;
12077:     }
12078: 
12079:     sub get_internet_names {
12080:         my ($lonid) = @_;
12081:         return if ($lonid eq '');
12082:         my ($idnref,$cached)=
12083:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12084:         if ($cached) {
12085:             return $idnref;
12086:         }
12087:         my $ip = &get_host_ip($lonid);
12088:         my @hosts = &get_hosts_from_ip($ip);
12089:         my %iphost = &get_iphost();
12090:         my (@idns,%seen);
12091:         foreach my $id (@hosts) {
12092:             my $dom = &host_domain($id);
12093:             my $prim_id = &domain($dom,'primary');
12094:             my $prim_ip = &get_host_ip($prim_id);
12095:             next if ($seen{$prim_ip});
12096:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12097:                 foreach my $id (@{$iphost{$prim_ip}}) {
12098:                     my $intdom = &internet_dom($id);
12099:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12100:                         push(@idns,$intdom);
12101:                     }
12102:                 }
12103:             }
12104:             $seen{$prim_ip} = 1;
12105:         }
12106:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12107:     }
12108: 
12109: }
12110: 
12111: sub all_loncaparevs {
12112:     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);
12113: }
12114: 
12115: # ---------------------------------------------------------- Read loncaparev table
12116: {
12117:     sub load_loncaparevs { 
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: 
12131: # ---------------------------------------------------------- Read serverhostID table
12132: {
12133:     sub load_serverhomeIDs {
12134:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12135:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12136:                 while (my $configline=<$config>) {
12137:                     chomp($configline);
12138:                     my ($name,$id)=split(/:/,$configline);
12139:                     $serverhomeIDs{$name}=$id;
12140:                 }
12141:                 close($config);
12142:             }
12143:         }
12144:     }
12145: }
12146: 
12147: 
12148: BEGIN {
12149: 
12150: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12151:     unless ($readit) {
12152: {
12153:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12154:     %perlvar = (%perlvar,%{$configvars});
12155: }
12156: 
12157: 
12158: # ------------------------------------------------------ Read spare server file
12159: {
12160:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12161: 
12162:     while (my $configline=<$config>) {
12163:        chomp($configline);
12164:        if ($configline) {
12165: 	   my ($host,$type) = split(':',$configline,2);
12166: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12167: 	   push(@{ $spareid{$type} }, $host);
12168:        }
12169:     }
12170:     close($config);
12171: }
12172: # ------------------------------------------------------------ Read permissions
12173: {
12174:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12175: 
12176:     while (my $configline=<$config>) {
12177: 	chomp($configline);
12178: 	if ($configline) {
12179: 	    my ($role,$perm)=split(/ /,$configline);
12180: 	    if ($perm ne '') { $pr{$role}=$perm; }
12181: 	}
12182:     }
12183:     close($config);
12184: }
12185: 
12186: # -------------------------------------------- Read plain texts for permissions
12187: {
12188:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12189: 
12190:     while (my $configline=<$config>) {
12191: 	chomp($configline);
12192: 	if ($configline) {
12193: 	    my ($short,@plain)=split(/:/,$configline);
12194:             %{$prp{$short}} = ();
12195: 	    if (@plain > 0) {
12196:                 $prp{$short}{'std'} = $plain[0];
12197:                 for (my $i=1; $i<@plain; $i++) {
12198:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12199:                 }
12200:             }
12201: 	}
12202:     }
12203:     close($config);
12204: }
12205: 
12206: # ---------------------------------------------------------- Read package table
12207: {
12208:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12209: 
12210:     while (my $configline=<$config>) {
12211: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12212: 	chomp($configline);
12213: 	my ($short,$plain)=split(/:/,$configline);
12214: 	my ($pack,$name)=split(/\&/,$short);
12215: 	if ($plain ne '') {
12216: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12217: 	    $packagetab{$short}=$plain; 
12218: 	}
12219:     }
12220:     close($config);
12221: }
12222: 
12223: # ---------------------------------------------------------- Read loncaparev table
12224: 
12225: &load_loncaparevs();
12226: 
12227: # ---------------------------------------------------------- Read serverhostID table
12228: 
12229: &load_serverhomeIDs();
12230: 
12231: # ---------------------------------------------------------- Read releaseslist XML
12232: {
12233:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12234:     if (-e $file) {
12235:         my $parser = HTML::LCParser->new($file);
12236:         while (my $token = $parser->get_token()) {
12237:             if ($token->[0] eq 'S') {
12238:                 my $item = $token->[1];
12239:                 my $name = $token->[2]{'name'};
12240:                 my $value = $token->[2]{'value'};
12241:                 if ($item ne '' && $name ne '' && $value ne '') {
12242:                     my $release = $parser->get_text();
12243:                     $release =~ s/(^\s*|\s*$ )//gx;
12244:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12245:                 }
12246:             }
12247:         }
12248:     }
12249: }
12250: 
12251: # ---------------------------------------------------------- Read managers table
12252: {
12253:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12254:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12255:             while (my $configline=<$config>) {
12256:                 chomp($configline);
12257:                 next if ($configline =~ /^\#/);
12258:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12259:                     $managerstab{$configline} = 1;
12260:                 }
12261:             }
12262:             close($config);
12263:         }
12264:     }
12265: }
12266: 
12267: # ------------- set up temporary directory
12268: {
12269:     $tmpdir = LONCAPA::tempdir();
12270: 
12271: }
12272: 
12273: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12274: 				'compress_threshold'=> 20_000,
12275:  			        });
12276: 
12277: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12278: $dumpcount=0;
12279: $locknum=0;
12280: 
12281: &logtouch();
12282: &logthis('<font color="yellow">INFO: Read configuration</font>');
12283: $readit=1;
12284:     {
12285: 	use integer;
12286: 	my $test=(2**32)+1;
12287: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12288: 	&logthis(" Detected 64bit platform ($_64bit)");
12289:     }
12290: 
12291:     {
12292:         eval {
12293:             ($apache) =
12294:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12295:         };
12296:         if ($@) {
12297:            $apache = 1.3;
12298:         }
12299:     }
12300: 
12301: }
12302: }
12303: 
12304: 1;
12305: __END__
12306: 
12307: =pod
12308: 
12309: =head1 NAME
12310: 
12311: Apache::lonnet - Subroutines to ask questions about things in the network.
12312: 
12313: =head1 SYNOPSIS
12314: 
12315: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12316: 
12317:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12318: 
12319: Common parameters:
12320: 
12321: =over 4
12322: 
12323: =item *
12324: 
12325: $uname : an internal username (if $cname expecting a course Id specifically)
12326: 
12327: =item *
12328: 
12329: $udom : a domain (if $cdom expecting a course's domain specifically)
12330: 
12331: =item *
12332: 
12333: $symb : a resource instance identifier
12334: 
12335: =item *
12336: 
12337: $namespace : the name of a .db file that contains the data needed or
12338: being set.
12339: 
12340: =back
12341: 
12342: =head1 OVERVIEW
12343: 
12344: lonnet provides subroutines which interact with the
12345: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12346: about classes, users, and resources.
12347: 
12348: For many of these objects you can also use this to store data about
12349: them or modify them in various ways.
12350: 
12351: =head2 Symbs
12352: 
12353: To identify a specific instance of a resource, LON-CAPA uses symbols
12354: or "symbs"X<symb>. These identifiers are built from the URL of the
12355: map, the resource number of the resource in the map, and the URL of
12356: the resource itself. The latter is somewhat redundant, but might help
12357: if maps change.
12358: 
12359: An example is
12360: 
12361:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12362: 
12363: The respective map entry is
12364: 
12365:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12366:   title="Problem 2">
12367:  </resource>
12368: 
12369: Symbs are used by the random number generator, as well as to store and
12370: restore data specific to a certain instance of for example a problem.
12371: 
12372: =head2 Storing And Retrieving Data
12373: 
12374: X<store()>X<cstore()>X<restore()>Three of the most important functions
12375: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12376: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12377: is is the non-critical message twin of cstore. These functions are for
12378: handlers to store a perl hash to a user's permanent data space in an
12379: easy manner, and to retrieve it again on another call. It is expected
12380: that a handler would use this once at the beginning to retrieve data,
12381: and then again once at the end to send only the new data back.
12382: 
12383: The data is stored in the user's data directory on the user's
12384: homeserver under the ID of the course.
12385: 
12386: The hash that is returned by restore will have all of the previous
12387: value for all of the elements of the hash.
12388: 
12389: Example:
12390: 
12391:  #creating a hash
12392:  my %hash;
12393:  $hash{'foo'}='bar';
12394: 
12395:  #storing it
12396:  &Apache::lonnet::cstore(\%hash);
12397: 
12398:  #changing a value
12399:  $hash{'foo'}='notbar';
12400: 
12401:  #adding a new value
12402:  $hash{'bar'}='foo';
12403:  &Apache::lonnet::cstore(\%hash);
12404: 
12405:  #retrieving the hash
12406:  my %history=&Apache::lonnet::restore();
12407: 
12408:  #print the hash
12409:  foreach my $key (sort(keys(%history))) {
12410:    print("\%history{$key} = $history{$key}");
12411:  }
12412: 
12413: Will print out:
12414: 
12415:  %history{1:foo} = bar
12416:  %history{1:keys} = foo:timestamp
12417:  %history{1:timestamp} = 990455579
12418:  %history{2:bar} = foo
12419:  %history{2:foo} = notbar
12420:  %history{2:keys} = foo:bar:timestamp
12421:  %history{2:timestamp} = 990455580
12422:  %history{bar} = foo
12423:  %history{foo} = notbar
12424:  %history{timestamp} = 990455580
12425:  %history{version} = 2
12426: 
12427: Note that the special hash entries C<keys>, C<version> and
12428: C<timestamp> were added to the hash. C<version> will be equal to the
12429: total number of versions of the data that have been stored. The
12430: C<timestamp> attribute will be the UNIX time the hash was
12431: stored. C<keys> is available in every historical section to list which
12432: keys were added or changed at a specific historical revision of a
12433: hash.
12434: 
12435: B<Warning>: do not store the hash that restore returns directly. This
12436: will cause a mess since it will restore the historical keys as if the
12437: were new keys. I.E. 1:foo will become 1:1:foo etc.
12438: 
12439: Calling convention:
12440: 
12441:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12442:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12443: 
12444: For more detailed information, see lonnet specific documentation.
12445: 
12446: =head1 RETURN MESSAGES
12447: 
12448: =over 4
12449: 
12450: =item * B<con_lost>: unable to contact remote host
12451: 
12452: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12453: when the connection is brought back up
12454: 
12455: =item * B<con_failed>: unable to contact remote host and unable to save message
12456: for later delivery
12457: 
12458: =item * B<error:>: an error a occurred, a description of the error follows the :
12459: 
12460: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12461: that was requested
12462: 
12463: =back
12464: 
12465: =head1 PUBLIC SUBROUTINES
12466: 
12467: =head2 Session Environment Functions
12468: 
12469: =over 4
12470: 
12471: =item * 
12472: X<appenv()>
12473: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12474: the user envirnoment file, and will be restored for each access this
12475: user makes during this session, also modifies the %env for the current
12476: process. Optional rolesarrayref - if defined contains a reference to an array
12477: of roles which are exempt from the restriction on modifying user.role entries 
12478: in the user's environment.db and in %env.    
12479: 
12480: =item *
12481: X<delenv()>
12482: B<delenv($delthis,$regexp)>: removes all items from the session
12483: environment file that begin with $delthis. If the 
12484: optional second arg - $regexp - is true, $delthis is treated as a 
12485: regular expression, otherwise \Q$delthis\E is used. 
12486: The values are also deleted from the current processes %env.
12487: 
12488: =item * get_env_multiple($name) 
12489: 
12490: gets $name from the %env hash, it seemlessly handles the cases where multiple
12491: values may be defined and end up as an array ref.
12492: 
12493: returns an array of values
12494: 
12495: =back
12496: 
12497: =head2 User Information
12498: 
12499: =over 4
12500: 
12501: =item *
12502: X<queryauthenticate()>
12503: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12504: authentication scheme
12505: 
12506: =item *
12507: X<authenticate()>
12508: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12509: authenticate user from domain's lib servers (first use the current
12510: one). C<$upass> should be the users password.
12511: $checkdefauth is optional (value is 1 if a check should be made to
12512:    authenticate user using default authentication method, and allow
12513:    account creation if username does not have account in the domain).
12514: $clientcancheckhost is optional (value is 1 if checking whether the
12515:    server can host will occur on the client side in lonauth.pm).   
12516: 
12517: =item *
12518: X<homeserver()>
12519: B<homeserver($uname,$udom)>: find the server which has
12520: the user's directory and files (there must be only one), this caches
12521: the answer, and also caches if there is a borken connection.
12522: 
12523: =item *
12524: X<idget()>
12525: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12526: (IDs are a unique resource in a domain, there must be only 1 ID per
12527: username, and only 1 username per ID in a specific domain) (returns
12528: hash: id=>name,id=>name)
12529: 
12530: =item *
12531: X<idrget()>
12532: B<idrget($udom,@unames)>: find the IDs behind a list of
12533: usernames (returns hash: name=>id,name=>id)
12534: 
12535: =item *
12536: X<idput()>
12537: B<idput($udom,%ids)>: store away a list of names and associated IDs
12538: 
12539: =item *
12540: X<rolesinit()>
12541: B<rolesinit($udom,$username)>: get user privileges.
12542: returns user role, first access and timer interval hashes
12543: 
12544: =item *
12545: X<privileged()>
12546: B<privileged($username,$domain)>: returns a true if user has a
12547: privileged and active role (i.e. su or dc), false otherwise.
12548: 
12549: =item *
12550: X<getsection()>
12551: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12552: course $cname, return section name/number or '' for "not in course"
12553: and '-1' for "no section"
12554: 
12555: =item *
12556: X<userenvironment()>
12557: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12558: passed in @what from the requested user's environment, returns a hash
12559: 
12560: =item * 
12561: X<userlog_query()>
12562: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12563: activity.log file. %filters defines filters applied when parsing the
12564: log file. These can be start or end timestamps, or the type of action
12565: - log to look for Login or Logout events, check for Checkin or
12566: Checkout, role for role selection. The response is in the form
12567: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12568: escaped strings of the action recorded in the activity.log file.
12569: 
12570: =back
12571: 
12572: =head2 User Roles
12573: 
12574: =over 4
12575: 
12576: =item *
12577: 
12578: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12579:  F: full access
12580:  U,I,K: authentication modes (cxx only)
12581:  '': forbidden
12582:  1: user needs to choose course
12583:  2: browse allowed
12584:  A: passphrase authentication needed
12585: 
12586: =item *
12587: 
12588: constructaccess($url,$setpriv) : check for access to construction space URL
12589: 
12590: See if the owner domain and name in the URL match those in the
12591: expected environment.  If so, return three element list
12592: ($ownername,$ownerdomain,$ownerhome).
12593: 
12594: Otherwise return the null string.
12595: 
12596: If second argument 'setpriv' is true, it assigns the privileges,
12597: and returns the same three element list, unless the owner has
12598: blocked "ad hoc" Domain Coordinator access to the Author Space,
12599: in which case the null string is returned.
12600: 
12601: =item *
12602: 
12603: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12604: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12605: and course level
12606: 
12607: =item *
12608: 
12609: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12610: (rolesplain.tab); plain text explanation of a user role term.
12611: $type is Course (default) or Community.
12612: If $forcedefault evaluates to true, text returned will be default 
12613: text for $type. Otherwise, if this is a course, the text returned 
12614: will be a custom name for the role (if defined in the course's 
12615: environment).  If no custom name is defined the default is returned.
12616:    
12617: =item *
12618: 
12619: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12620: All arguments are optional. Returns a hash of a roles, either for
12621: co-author/assistant author roles for a user's Construction Space
12622: (default), or if $context is 'userroles', roles for the user himself,
12623: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12624: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12625: For each key, value is set to colon-separated start and end times for
12626: the role.  If no username and domain are specified, will default to
12627: current user/domain. Types, roles, and roledoms are references to arrays
12628: of role statuses (active, future or previous), roles 
12629: (e.g., cc,in, st etc.) and domains of the roles which can be used
12630: to restrict the list of roles reported. If no array ref is 
12631: provided for types, will default to return only active roles.
12632: 
12633: =item *
12634: 
12635: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12636: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12637: 
12638: Additional optional arguments are: $type (if role checking is to be restricted 
12639: to certain user status types -- previous (expired roles), active (currently
12640: available roles) or future (roles available in the future), and
12641: $hideprivileged -- if true will not report course roles for users who
12642: have active Domain Coordinator role in course's domain or in additional
12643: domains (specified in 'Domains to check for privileged users' in course
12644: environment -- set via:  Course Settings -> Classlists and staff listing).
12645: 
12646: =item *
12647: 
12648: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12649: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12650: $possdomains and $possroles are optional array refs -- to domains to check and
12651: roles to check.  If $possdomains is not specified, a dump will be done of the
12652: users' roles.db to check for a dc or su role in any domain. This can be
12653: time consuming if &privileged is called repeatedly (e.g., when displaying a
12654: classlist), so in such cases, supplying a $possdomains array is preferred, as
12655: this then allows &privileged_by_domain() to be used, which caches the identity
12656: of privileged users, eliminating the need for repeated calls to &dump().
12657: 
12658: =item *
12659: 
12660: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12661: where the outer hash keys are domains specified in the $possdomains array ref,
12662: next inner hash keys are privileged roles specified in the $roles array ref,
12663: and the innermost hash contains key = value pairs for username:domain = end:start
12664: for active or future "privileged" users with that role in that domain. To avoid
12665: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12666: innerhash are cached using priv_$role and $dom as the identifiers.
12667: 
12668: =back
12669: 
12670: =head2 User Modification
12671: 
12672: =over 4
12673: 
12674: =item *
12675: 
12676: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12677: user for the level given by URL.  Optional start and end dates (leave empty
12678: string or zero for "no date")
12679: 
12680: =item *
12681: 
12682: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12683: change a users, password, possible return values are: ok,
12684: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12685: refused
12686: 
12687: =item *
12688: 
12689: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12690: 
12691: =item *
12692: 
12693: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12694:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12695: 
12696: will update user information (firstname,middlename,lastname,generation,
12697: permanentemail), and if forceid is true, student/employee ID also.
12698: A user's institutional affiliation(s) can also be updated.
12699: User information fields will not be overwritten with empty entries 
12700: unless the field is included in the $candelete array reference.
12701: This array is included when a single user is modified via "Manage Users",
12702: or when Autoupdate.pl is run by cron in a domain.
12703: 
12704: =item *
12705: 
12706: modifystudent
12707: 
12708: modify a student's enrollment and identification information.
12709: The course id is resolved based on the current user's environment.  
12710: This means the invoking user must be a course coordinator or otherwise
12711: associated with a course.
12712: 
12713: This call is essentially a wrapper for lonnet::modifyuser and
12714: lonnet::modify_student_enrollment
12715: 
12716: Inputs: 
12717: 
12718: =over 4
12719: 
12720: =item B<$udom> Student's loncapa domain
12721: 
12722: =item B<$uname> Student's loncapa login name
12723: 
12724: =item B<$uid> Student/Employee ID
12725: 
12726: =item B<$umode> Student's authentication mode
12727: 
12728: =item B<$upass> Student's password
12729: 
12730: =item B<$first> Student's first name
12731: 
12732: =item B<$middle> Student's middle name
12733: 
12734: =item B<$last> Student's last name
12735: 
12736: =item B<$gene> Student's generation
12737: 
12738: =item B<$usec> Student's section in course
12739: 
12740: =item B<$end> Unix time of the roles expiration
12741: 
12742: =item B<$start> Unix time of the roles start date
12743: 
12744: =item B<$forceid> If defined, allow $uid to be changed
12745: 
12746: =item B<$desiredhome> server to use as home server for student
12747: 
12748: =item B<$email> Student's permanent e-mail address
12749: 
12750: =item B<$type> Type of enrollment (auto or manual)
12751: 
12752: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12753: 
12754: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12755: 
12756: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12757: 
12758: =item B<$context> role change context (shown in User Management Logs display in a course)
12759: 
12760: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12761: 
12762: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
12763: 
12764: =back
12765: 
12766: =item *
12767: 
12768: modify_student_enrollment
12769: 
12770: Change a student's enrollment status in a class.  The environment variable
12771: 'role.request.course' must be defined for this function to proceed.
12772: 
12773: Inputs:
12774: 
12775: =over 4
12776: 
12777: =item $udom, student's domain
12778: 
12779: =item $uname, student's name
12780: 
12781: =item $uid, student's user id
12782: 
12783: =item $first, student's first name
12784: 
12785: =item $middle
12786: 
12787: =item $last
12788: 
12789: =item $gene
12790: 
12791: =item $usec
12792: 
12793: =item $end
12794: 
12795: =item $start
12796: 
12797: =item $type
12798: 
12799: =item $locktype
12800: 
12801: =item $cid
12802: 
12803: =item $selfenroll
12804: 
12805: =item $context
12806: 
12807: =item $credits, number of credits student will earn from this class
12808: 
12809: =back
12810: 
12811: 
12812: =item *
12813: 
12814: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12815: custom role; give a custom role to a user for the level given by URL.  Specify
12816: name and domain of role author, and role name
12817: 
12818: =item *
12819: 
12820: revokerole($udom,$uname,$url,$role) : revoke a role for url
12821: 
12822: =item *
12823: 
12824: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12825: 
12826: =back
12827: 
12828: =head2 Course Infomation
12829: 
12830: =over 4
12831: 
12832: =item *
12833: 
12834: coursedescription($courseid,$options) : returns a hash of information about the
12835: specified course id, including all environment settings for the
12836: course, the description of the course will be in the hash under the
12837: key 'description'
12838: 
12839: $options is an optional parameter that if supplied is a hash reference that controls
12840: what how this function works.  It has the following key/values:
12841: 
12842: =over 4
12843: 
12844: =item freshen_cache
12845: 
12846: If defined, and the environment cache for the course is valid, it is 
12847: returned in the returned hash.
12848: 
12849: =item one_time
12850: 
12851: If defined, the last cache time is set to _now_
12852: 
12853: =item user
12854: 
12855: If defined, the supplied username is used instead of the current user.
12856: 
12857: 
12858: =back
12859: 
12860: =item *
12861: 
12862: resdata($name,$domain,$type,@which) : request for current parameter
12863: setting for a specific $type, where $type is either 'course' or 'user',
12864: @what should be a list of parameters to ask about. This routine caches
12865: answers for 10 minutes.
12866: 
12867: =item *
12868: 
12869: get_courseresdata($courseid, $domain) : dump the entire course resource
12870: data base, returning a hash that is keyed by the resource name and has
12871: values that are the resource value.  I believe that the timestamps and
12872: versions are also returned.
12873: 
12874: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12875: supplemental content area. This routine caches the number of files for 
12876: 10 minutes.
12877: 
12878: =back
12879: 
12880: =head2 Course Modification
12881: 
12882: =over 4
12883: 
12884: =item *
12885: 
12886: writecoursepref($courseid,%prefs) : write preferences (environment
12887: database) for a course
12888: 
12889: =item *
12890: 
12891: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12892: 
12893: =item *
12894: 
12895: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12896: 
12897: =item *
12898: 
12899: is_course($courseid), is_course($cdom, $cnum)
12900: 
12901: Accepts either a combined $courseid (in the form of domain_courseid) or the
12902: two component version $cdom, $cnum. It checks if the specified course exists.
12903: 
12904: Returns:
12905:     undef if the course doesn't exist, otherwise
12906:     in scalar context the combined courseid.
12907:     in list context the two components of the course identifier, domain and 
12908:     courseid.    
12909: 
12910: =back
12911: 
12912: =head2 Resource Subroutines
12913: 
12914: =over 4
12915: 
12916: =item *
12917: 
12918: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12919: 
12920: =item *
12921: 
12922: repcopy($filename) : subscribes to the requested file, and attempts to
12923: replicate from the owning library server, Might return
12924: 'unavailable', 'not_found', 'forbidden', 'ok', or
12925: 'bad_request', also attempts to grab the metadata for the
12926: resource. Expects the local filesystem pathname
12927: (/home/httpd/html/res/....)
12928: 
12929: =back
12930: 
12931: =head2 Resource Information
12932: 
12933: =over 4
12934: 
12935: =item *
12936: 
12937: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
12938: and returns the value of a variety of different possible values,
12939: $varname should be a request string, and the other parameters can be
12940: used to specify who and what one is asking about. Ordinarily, $cid 
12941: does not need to be specified, as it is retrived from 
12942: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12943: within lonuserstate::loadmap() when initializing a course, before
12944: $env{'request.course.id'} has been set, so it needs to be provided
12945: in that one case.
12946: 
12947: Possible values for $varname are environment.lastname (or other item
12948: from the envirnment hash), user.name (or someother aspect about the
12949: user), resource.0.maxtries (or some other part and parameter of a
12950: resource)
12951: 
12952: =item *
12953: 
12954: directcondval($number) : get current value of a condition; reads from a state
12955: string
12956: 
12957: =item *
12958: 
12959: condval($condidx) : value of condition index based on state
12960: 
12961: =item *
12962: 
12963: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12964: resource's metadata, $what should be either a specific key, or either
12965: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12966: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12967: 
12968: this function automatically caches all requests
12969: 
12970: =item *
12971: 
12972: metadata_query($query,$custom,$customshow) : make a metadata query against the
12973: network of library servers; returns file handle of where SQL and regex results
12974: will be stored for query
12975: 
12976: =item *
12977: 
12978: symbread($filename) : return symbolic list entry (filename argument optional);
12979: returns the data handle
12980: 
12981: =item *
12982: 
12983: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12984: and is a possible symb for the URL in $thisfn, and if is an encrypted
12985: resource that the user accessed using /enc/ returns a 1 on success, 0
12986: on failure, user must be in a course, as it assumes the existence of
12987: the course initial hash, and uses $env('request.course.id'}.  The third
12988: arg is an optional reference to a scalar.  If this arg is passed in the 
12989: call to symbverify, it will be set to 1 if the symb has been set to be 
12990: encrypted; otherwise it will be null.  
12991: 
12992: =item *
12993: 
12994: symbclean($symb) : removes versions numbers from a symb, returns the
12995: cleaned symb
12996: 
12997: =item *
12998: 
12999: is_on_map($uri) : checks if the $uri is somewhere on the current
13000: course map, user must be in a course for it to work.
13001: 
13002: =item *
13003: 
13004: numval($salt) : return random seed value (addend for rndseed)
13005: 
13006: =item *
13007: 
13008: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13009: a random seed, all arguments are optional, if they aren't sent it uses the
13010: environment to derive them. Note: if symb isn't sent and it can't get one
13011: from &symbread it will use the current time as its return value
13012: 
13013: =item *
13014: 
13015: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13016: unfakeable, receipt
13017: 
13018: =item *
13019: 
13020: receipt() : API to ireceipt working off of env values; given out to users
13021: 
13022: =item *
13023: 
13024: countacc($url) : count the number of accesses to a given URL
13025: 
13026: =item *
13027: 
13028: 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
13029: 
13030: =item *
13031: 
13032: 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)
13033: 
13034: =item *
13035: 
13036: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13037: 
13038: =item *
13039: 
13040: devalidate($symb) : devalidate temporary spreadsheet calculations,
13041: forcing spreadsheet to reevaluate the resource scores next time.
13042: 
13043: =item * 
13044: 
13045: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13046: when viewing in course context.
13047: 
13048:  input: six args -- filename (decluttered), course number, course domain,
13049:                     url, symb (if registered) and group (if this is a 
13050:                     group item -- e.g., bulletin board, group page etc.).
13051: 
13052:  output: array of five scalars --
13053:          $cfile -- url for file editing if editable on current server
13054:          $home -- homeserver of resource (i.e., for author if published,
13055:                                           or course if uploaded.).
13056:          $switchserver --  1 if server switch will be needed.
13057:          $forceedit -- 1 if icon/link should be to go to edit mode 
13058:          $forceview -- 1 if icon/link should be to go to view mode
13059: 
13060: =item *
13061: 
13062: is_course_upload($file,$cnum,$cdom)
13063: 
13064: Used in course context to determine if current file was uploaded to 
13065: the course (i.e., would be found in /userfiles/docs on the course's 
13066: homeserver.
13067: 
13068:   input: 3 args -- filename (decluttered), course number and course domain.
13069:   output: boolean -- 1 if file was uploaded.
13070: 
13071: =back
13072: 
13073: =head2 Storing/Retreiving Data
13074: 
13075: =over 4
13076: 
13077: =item *
13078: 
13079: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13080: for this url; hashref needs to be given and should be a \%hashname; the
13081: remaining args aren't required and if they aren't passed or are '' they will
13082: be derived from the env
13083: 
13084: =item *
13085: 
13086: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13087: uses critical subroutine
13088: 
13089: =item *
13090: 
13091: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13092: all args are optional
13093: 
13094: =item *
13095: 
13096: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13097: dumps the complete (or key matching regexp) namespace into a hash
13098: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13099: normally &store()ed into
13100: 
13101: $range should be either an integer '100' (give me the first 100
13102:                                            matching records)
13103:               or be  two integers sperated by a - with no spaces
13104:                  '30-50' (give me the 30th through the 50th matching
13105:                           records)
13106: 
13107: 
13108: =item *
13109: 
13110: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13111: replaces a &store() version of data with a replacement set of data
13112: for a particular resource in a namespace passed in the $storehash hash 
13113: reference
13114: 
13115: =item *
13116: 
13117: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13118: works very similar to store/cstore, but all data is stored in a
13119: temporary location and can be reset using tmpreset, $storehash should
13120: be a hash reference, returns nothing on success
13121: 
13122: =item *
13123: 
13124: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13125: similar to restore, but all data is stored in a temporary location and
13126: can be reset using tmpreset. Returns a hash of values on success,
13127: error string otherwise.
13128: 
13129: =item *
13130: 
13131: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13132: deltes all keys for $symb form the temporary storage hash.
13133: 
13134: =item *
13135: 
13136: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13137: reference filled in from namesp ($udom and $uname are optional)
13138: 
13139: =item *
13140: 
13141: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13142: namesp ($udom and $uname are optional)
13143: 
13144: =item *
13145: 
13146: dump($namespace,$udom,$uname,$regexp,$range) : 
13147: dumps the complete (or key matching regexp) namespace into a hash
13148: ($udom, $uname, $regexp, $range are optional)
13149: 
13150: $range should be either an integer '100' (give me the first 100
13151:                                            matching records)
13152:               or be  two integers sperated by a - with no spaces
13153:                  '30-50' (give me the 30th through the 50th matching
13154:                           records)
13155: =item *
13156: 
13157: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13158: $store can be a scalar, an array reference, or if the amount to be 
13159: incremented is > 1, a hash reference.
13160: 
13161: ($udom and $uname are optional)
13162: 
13163: =item *
13164: 
13165: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13166: ($udom and $uname are optional)
13167: 
13168: =item *
13169: 
13170: cput($namespace,$storehash,$udom,$uname) : critical put
13171: ($udom and $uname are optional)
13172: 
13173: =item *
13174: 
13175: newput($namespace,$storehash,$udom,$uname) :
13176: 
13177: Attempts to store the items in the $storehash, but only if they don't
13178: currently exist, if this succeeds you can be certain that you have 
13179: successfully created a new key value pair in the $namespace db.
13180: 
13181: 
13182: Args:
13183:  $namespace: name of database to store values to
13184:  $storehash: hashref to store to the db
13185:  $udom: (optional) domain of user containing the db
13186:  $uname: (optional) name of user caontaining the db
13187: 
13188: Returns:
13189:  'ok' -> succeeded in storing all keys of $storehash
13190:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13191:                         least <key> already existed in the db (other
13192:                         requested keys may also already exist)
13193:  'error: <msg>' -> unable to tie the DB or other error occurred
13194:  'con_lost' -> unable to contact request server
13195:  'refused' -> action was not allowed by remote machine
13196: 
13197: 
13198: =item *
13199: 
13200: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13201: reference filled in from namesp (encrypts the return communication)
13202: ($udom and $uname are optional)
13203: 
13204: =item *
13205: 
13206: log($udom,$name,$home,$message) : write to permanent log for user; use
13207: critical subroutine
13208: 
13209: =item *
13210: 
13211: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13212: array reference filled in from namespace found in domain level on either
13213: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13214: 
13215: =item *
13216: 
13217: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13218: domain level either on specified domain server ($uhome) or primary domain 
13219: server ($udom and $uhome are optional)
13220: 
13221: =item * 
13222: 
13223: get_domain_defaults($target_domain) : returns hash with defaults for
13224: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
13225: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
13226: or localauth), initial password or a kerberos realm, language (e.g., en-us).
13227: Values are retrieved from cache (if current), or from domain's configuration.db
13228: (if available), or lastly from values in lonTabs/dns_domain,tab, 
13229: or lonTabs/domain.tab. 
13230: 
13231: %domdefaults = &get_auth_defaults($target_domain);
13232: 
13233: =back
13234: 
13235: =head2 Network Status Functions
13236: 
13237: =over 4
13238: 
13239: =item *
13240: 
13241: dirlist() : return directory list based on URI (first arg).
13242: 
13243: Inputs: 1 required, 5 optional.
13244: 
13245: =over
13246: 
13247: =item 
13248: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13249: 
13250: =item
13251: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13252: 
13253: =item
13254: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13255: 
13256: =item
13257: $getpropath - boolean: 1 if prepend path using &propath(). 
13258: 
13259: =item
13260: $getuserdir - boolean: 1 if prepend path for "userfiles".
13261: 
13262: =item 
13263: $alternateRoot - path to prepend in place of path from $uri.
13264: 
13265: =back
13266: 
13267: Returns: Array of up to two items.
13268: 
13269: =over
13270: 
13271: a reference to an array of files/subdirectories
13272: 
13273: =over
13274: 
13275: Each element in the array of files/subdirectories is a & separated list of
13276: item name and the result of running stat on the item.  If dirlist was requested
13277: for a file instead of a directory, the item name will be ''. For a directory 
13278: listing, if the item is a metadata file, the element will end &N&M 
13279: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13280: default copyright set (1).  
13281: 
13282: =back
13283: 
13284: a scalar containing error condition (if encountered).
13285: 
13286: =over
13287: 
13288: =item 
13289: no_host (no homeserver identified for $username:$domain).
13290: 
13291: =item 
13292: no_such_host (server contacted for listing not identified as valid host).
13293: 
13294: =item 
13295: con_lost (connection to remote server failed).
13296: 
13297: =item 
13298: refused (invalid $username:$domain received on lond side).
13299: 
13300: =item 
13301: no_such_dir (directory at specified path on lond side does not exist). 
13302: 
13303: =item 
13304: empty (directory at specified path on lond side is empty).
13305: 
13306: =over
13307: 
13308: This is currently not encountered because the &ls3, &ls2, 
13309: &ls (_handler) routines on the lond side do not filter out
13310: . and .. from a directory listing. 
13311: 
13312: =back
13313: 
13314: =back
13315: 
13316: =back
13317: 
13318: =item *
13319: 
13320: spareserver() : find server with least workload from spare.tab
13321: 
13322: 
13323: =item *
13324: 
13325: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13326: if there is no corresponding loncapa host.
13327: 
13328: =back
13329: 
13330: 
13331: =head2 Apache Request
13332: 
13333: =over 4
13334: 
13335: =item *
13336: 
13337: ssi($url,%hash) : server side include, does a complete request cycle on url to
13338: localhost, posts hash
13339: 
13340: =back
13341: 
13342: =head2 Data to String to Data
13343: 
13344: =over 4
13345: 
13346: =item *
13347: 
13348: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13349: and '&' separators, supports elements that are arrayrefs and hashrefs
13350: 
13351: =item *
13352: 
13353: hashref2str($hashref) : convert a hashref into a string complete with
13354: escaping and '=' and '&' separators, supports elements that are
13355: arrayrefs and hashrefs
13356: 
13357: =item *
13358: 
13359: arrayref2str($arrayref) : convert an arrayref into a string complete
13360: with escaping and '&' separators, supports elements that are arrayrefs
13361: and hashrefs
13362: 
13363: =item *
13364: 
13365: str2hash($string) : convert string to hash using unescaping and
13366: splitting on '=' and '&', supports elements that are arrayrefs and
13367: hashrefs
13368: 
13369: =item *
13370: 
13371: str2array($string) : convert string to hash using unescaping and
13372: splitting on '&', supports elements that are arrayrefs and hashrefs
13373: 
13374: =back
13375: 
13376: =head2 Logging Routines
13377: 
13378: 
13379: These routines allow one to make log messages in the lonnet.log and
13380: lonnet.perm logfiles.
13381: 
13382: =over 4
13383: 
13384: =item *
13385: 
13386: logtouch() : make sure the logfile, lonnet.log, exists
13387: 
13388: =item *
13389: 
13390: logthis() : append message to the normal lonnet.log file, it gets
13391: preiodically rolled over and deleted.
13392: 
13393: =item *
13394: 
13395: logperm() : append a permanent message to lonnet.perm.log, this log
13396: file never gets deleted by any automated portion of the system, only
13397: messages of critical importance should go in here.
13398: 
13399: 
13400: =back
13401: 
13402: =head2 General File Helper Routines
13403: 
13404: =over 4
13405: 
13406: =item *
13407: 
13408: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13409: (a) files in /uploaded
13410:   (i) If a local copy of the file exists - 
13411:       compares modification date of local copy with last-modified date for 
13412:       definitive version stored on home server for course. If local copy is 
13413:       stale, requests a new version from the home server and stores it. 
13414:       If the original has been removed from the home server, then local copy 
13415:       is unlinked.
13416:   (ii) If local copy does not exist -
13417:       requests the file from the home server and stores it. 
13418:   
13419:   If $caller is 'uploadrep':  
13420:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13421:     for request for files originally uploaded via DOCS. 
13422:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13423:   
13424:   Otherwise:
13425:      This indicates a call from the content generation phase of the request.
13426:      -  returns the entire contents of the file or -1.
13427:      
13428: (b) files in /res
13429:    - returns the entire contents of a file or -1; 
13430:    it properly subscribes to and replicates the file if neccessary.
13431: 
13432: 
13433: =item *
13434: 
13435: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13436:                   reference
13437: 
13438: returns either a stat() list of data about the file or an empty list
13439: if the file doesn't exist or couldn't find out about it (connection
13440: problems or user unknown)
13441: 
13442: =item *
13443: 
13444: filelocation($dir,$file) : returns file system location of a file
13445: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13446: directory that relative $file lookups are to looked in ($dir of /a/dir
13447: and a file of ../bob will become /a/bob)
13448: 
13449: =item *
13450: 
13451: hreflocation($dir,$file) : returns file system location or a URL; same as
13452: filelocation except for hrefs
13453: 
13454: =item *
13455: 
13456: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13457: 
13458: =back
13459: 
13460: =head2 Usererfile file routines (/uploaded*)
13461: 
13462: =over 4
13463: 
13464: =item *
13465: 
13466: userfileupload(): main rotine for putting a file in a user or course's
13467:                   filespace, arguments are,
13468: 
13469:  formname - required - this is the name of the element in $env where the
13470:            filename, and the contents of the file to create/modifed exist
13471:            the filename is in $env{'form.'.$formname.'.filename'} and the
13472:            contents of the file is located in $env{'form.'.$formname}
13473:  context - if coursedoc, store the file in the course of the active role
13474:              of the current user; 
13475:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13476:            if 'canceloverwrite': delete file in tmp/overwrites directory
13477:  subdir - required - subdirectory to put the file in under ../userfiles/
13478:          if undefined, it will be placed in "unknown"
13479: 
13480:  (This routine calls clean_filename() to remove any dangerous
13481:  characters from the filename, and then calls finuserfileupload() to
13482:  complete the transaction)
13483: 
13484:  returns either the url of the uploaded file (/uploaded/....) if successful
13485:  and /adm/notfound.html if unsuccessful
13486: 
13487: =item *
13488: 
13489: clean_filename(): routine for cleaing a filename up for storage in
13490:                  userfile space, argument is:
13491: 
13492:  filename - proposed filename
13493: 
13494: returns: the new clean filename
13495: 
13496: =item *
13497: 
13498: finishuserfileupload(): routine that creates and sends the file to
13499: userspace, probably shouldn't be called directly
13500: 
13501:   docuname: username or courseid of destination for the file
13502:   docudom: domain of user/course of destination for the file
13503:   formname: same as for userfileupload()
13504:   fname: filename (including subdirectories) for the file
13505:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13506:   allfiles: reference to hash used to store objects found by parser
13507:   codebase: reference to hash used for codebases of java objects found by parser
13508:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13509:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13510:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13511:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13512:   context: if 'overwrite', will move the uploaded file from its temporary location to
13513:             userfiles to facilitate overwriting a previously uploaded file with same name.
13514:   mimetype: reference to scalar to accommodate mime type determined
13515:             from File::MMagic if $parser = parse.
13516: 
13517:  returns either the url of the uploaded file (/uploaded/....) if successful
13518:  and /adm/notfound.html if unsuccessful (or an error message if context 
13519:  was 'overwrite').
13520:  
13521: 
13522: =item *
13523: 
13524: renameuserfile(): renames an existing userfile to a new name
13525: 
13526:   Args:
13527:    docuname: username or courseid of destination for the file
13528:    docudom: domain of user/course of destination for the file
13529:    old: current file name (including any subdirs under userfiles)
13530:    new: desired file name (including any subdirs under userfiles)
13531: 
13532: =item *
13533: 
13534: mkdiruserfile(): creates a directory is a userfiles dir
13535: 
13536:   Args:
13537:    docuname: username or courseid of destination for the file
13538:    docudom: domain of user/course of destination for the file
13539:    dir: dir to create (including any subdirs under userfiles)
13540: 
13541: =item *
13542: 
13543: removeuserfile(): removes a file that exists in userfiles
13544: 
13545:   Args:
13546:    docuname: username or courseid of destination for the file
13547:    docudom: domain of user/course of destination for the file
13548:    fname: filname to delete (including any subdirs under userfiles)
13549: 
13550: =item *
13551: 
13552: removeuploadedurl(): convience function for removeuserfile()
13553: 
13554:   Args:
13555:    url:  a full /uploaded/... url to delete
13556: 
13557: =item * 
13558: 
13559: get_portfile_permissions():
13560:   Args:
13561:     domain: domain of user or course contain the portfolio files
13562:     user: name of user or num of course contain the portfolio files
13563:   Returns:
13564:     hashref of a dump of the proper file_permissions.db
13565:    
13566: 
13567: =item * 
13568: 
13569: get_access_controls():
13570: 
13571: Args:
13572:   current_permissions: the hash ref returned from get_portfile_permissions()
13573:   group: (optional) the group you want the files associated with
13574:   file: (optional) the file you want access info on
13575: 
13576: Returns:
13577:     a hash (keys are file names) of hashes containing
13578:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13579:         values are XML containing access control settings (see below) 
13580: 
13581: Internal notes:
13582: 
13583:  access controls are stored in file_permissions.db as key=value pairs.
13584:     key -> path to file/file_name\0uniqueID:scope_end_start
13585:         where scope -> public,guest,course,group,domains or users.
13586:               end -> UNIX time for end of access (0 -> no end date)
13587:               start -> UNIX time for start of access
13588: 
13589:     value -> XML description of access control
13590:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13591:             <start></start>
13592:             <end></end>
13593: 
13594:             <password></password>  for scope type = guest
13595: 
13596:             <domain></domain>     for scope type = course or group
13597:             <number></number>
13598:             <roles id="">
13599:              <role></role>
13600:              <access></access>
13601:              <section></section>
13602:              <group></group>
13603:             </roles>
13604: 
13605:             <dom></dom>         for scope type = domains
13606: 
13607:             <users>             for scope type = users
13608:              <user>
13609:               <uname></uname>
13610:               <udom></udom>
13611:              </user>
13612:             </users>
13613:            </scope> 
13614:               
13615:  Access data is also aggregated for each file in an additional key=value pair:
13616:  key -> path to file/file_name\0accesscontrol 
13617:  value -> reference to hash
13618:           hash contains key = value pairs
13619:           where key = uniqueID:scope_end_start
13620:                 value = UNIX time record was last updated
13621: 
13622:           Used to improve speed of look-ups of access controls for each file.  
13623:  
13624:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13625: 
13626: =item *
13627: 
13628: modify_access_controls():
13629: 
13630: Modifies access controls for a portfolio file
13631: Args
13632: 1. file name
13633: 2. reference to hash of required changes,
13634: 3. domain
13635: 4. username
13636:   where domain,username are the domain of the portfolio owner 
13637:   (either a user or a course) 
13638: 
13639: Returns:
13640: 1. result of additions or updates ('ok' or 'error', with error message). 
13641: 2. result of deletions ('ok' or 'error', with error message).
13642: 3. reference to hash of any new or updated access controls.
13643: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13644:    key = integer (inbound ID)
13645:    value = uniqueID
13646: 
13647: =item *
13648: 
13649: get_timebased_id():
13650: 
13651: Attempts to get a unique timestamp-based suffix for use with items added to a 
13652: course via the Course Editor (e.g., folders, composite pages, 
13653: group bulletin boards).
13654: 
13655: Args: (first three required; six others optional)
13656: 
13657: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13658:    docssequence, or name of group
13659: 
13660: 2. keyid (alphanumeric): name of temporary locking key in hash,
13661:    e.g., num, boardids
13662: 
13663: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13664:    file will be named nohist_namespace.db
13665: 
13666: 4. cdom: domain of course; default is current course domain from %env
13667: 
13668: 5. cnum: course number; default is current course number from %env
13669: 
13670: 6. idtype: set to concat if an additional digit is to be appended to the 
13671:    unix timestamp to form the suffix, if the plain timestamp is already
13672:    in use.  Default is to not do this, but simply increment the unix 
13673:    timestamp by 1 until a unique key is obtained.
13674: 
13675: 7. who: holder of locking key; defaults to user:domain for user.
13676: 
13677: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13678:    retrying); default is 3.
13679: 
13680: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13681: 
13682: Returns:
13683: 
13684: 1. suffix obtained (numeric)
13685: 
13686: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13687: 
13688: 3. error: contains (localized) error message if an error occurred.
13689: 
13690: 
13691: =back
13692: 
13693: =head2 HTTP Helper Routines
13694: 
13695: =over 4
13696: 
13697: =item *
13698: 
13699: escape() : unpack non-word characters into CGI-compatible hex codes
13700: 
13701: =item *
13702: 
13703: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13704: 
13705: =back
13706: 
13707: =head1 PRIVATE SUBROUTINES
13708: 
13709: =head2 Underlying communication routines (Shouldn't call)
13710: 
13711: =over 4
13712: 
13713: =item *
13714: 
13715: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13716: 
13717: =item *
13718: 
13719: reply() : uses subreply to send a message to remote machine, logs all failures
13720: 
13721: =item *
13722: 
13723: critical() : passes a critical message to another server; if cannot
13724: get through then place message in connection buffer directory and
13725: returns con_delayed, if incapable of saving message, returns
13726: con_failed
13727: 
13728: =item *
13729: 
13730: reconlonc() : tries to reconnect lonc client processes.
13731: 
13732: =back
13733: 
13734: =head2 Resource Access Logging
13735: 
13736: =over 4
13737: 
13738: =item *
13739: 
13740: flushcourselogs() : flush (save) buffer logs and access logs
13741: 
13742: =item *
13743: 
13744: courselog($what) : save message for course in hash
13745: 
13746: =item *
13747: 
13748: courseacclog($what) : save message for course using &courselog().  Perform
13749: special processing for specific resource types (problems, exams, quizzes, etc).
13750: 
13751: =item *
13752: 
13753: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13754: as a PerlChildExitHandler
13755: 
13756: =back
13757: 
13758: =head2 Other
13759: 
13760: =over 4
13761: 
13762: =item *
13763: 
13764: symblist($mapname,%newhash) : update symbolic storage links
13765: 
13766: =back
13767: 
13768: =cut
13769: 

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