File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1216: download - view: text, annotated - select for diffs
Fri Mar 1 04:17:31 2013 UTC (11 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Domain configuration to specify defaults for credits earned in a course
  (Course defaults) for official or unofficial courses.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1216 2013/03/01 04:17:31 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$name,$id) = @_;
  360:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  361:     return $response;
  362: }
  363: 
  364: # -------------------------------------------------- Non-critical communication
  365: sub subreply {
  366:     my ($cmd,$server)=@_;
  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  368:     #
  369:     #  With loncnew process trimming, there's a timing hole between lonc server
  370:     #  process exit and the master server picking up the listen on the AF_UNIX
  371:     #  socket.  In that time interval, a lock file will exist:
  372: 
  373:     my $lockfile=$peerfile.".lock";
  374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  375: 	sleep(1);
  376:     }
  377:     # At this point, either a loncnew parent is listening or an old lonc
  378:     # or loncnew child is listening so we can connect or everything's dead.
  379:     #
  380:     #   We'll give the connection a few tries before abandoning it.  If
  381:     #   connection is not possible, we'll con_lost back to the client.
  382:     #   
  383:     my $client;
  384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  386: 				      Type    => SOCK_STREAM,
  387: 				      Timeout => 10);
  388: 	if ($client) {
  389: 	    last;		# Connected!
  390: 	} else {
  391: 	    &create_connection(&hostname($server),$server);
  392: 	}
  393:         sleep(1);		# Try again later if failed connection.
  394:     }
  395:     my $answer;
  396:     if ($client) {
  397: 	print $client "sethost:$server:$cmd\n";
  398: 	$answer=<$client>;
  399: 	if (!$answer) { $answer="con_lost"; }
  400: 	chomp($answer);
  401:     } else {
  402: 	$answer = 'con_lost';	# Failed connection.
  403:     }
  404:     return $answer;
  405: }
  406: 
  407: sub reply {
  408:     my ($cmd,$server)=@_;
  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  410:     my $answer=subreply($cmd,$server);
  411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  412:        &logthis("<font color=\"blue\">WARNING:".
  413:                 " $cmd to $server returned $answer</font>");
  414:     }
  415:     return $answer;
  416: }
  417: 
  418: # ----------------------------------------------------------- Send USR1 to lonc
  419: 
  420: sub reconlonc {
  421:     my ($lonid) = @_;
  422:     my $hostname = &hostname($lonid);
  423:     if ($lonid) {
  424: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  425: 	if ($hostname && -e $peerfile) {
  426: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  427: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  428: 					     Type    => SOCK_STREAM,
  429: 					     Timeout => 10);
  430: 	    if ($client) {
  431: 		print $client ("reset_retries\n");
  432: 		my $answer=<$client>;
  433: 		#reset just this one.
  434: 	    }
  435: 	}
  436: 	return;
  437:     }
  438: 
  439:     &logthis("Trying to reconnect lonc");
  440:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  441:     if (open(my $fh,"<$loncfile")) {
  442: 	my $loncpid=<$fh>;
  443:         chomp($loncpid);
  444:         if (kill 0 => $loncpid) {
  445: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  446:             kill USR1 => $loncpid;
  447:             sleep 1;
  448:          } else {
  449: 	    &logthis(
  450:                "<font color=\"blue\">WARNING:".
  451:                " lonc at pid $loncpid not responding, giving up</font>");
  452:         }
  453:     } else {
  454: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  455:     }
  456: }
  457: 
  458: # ------------------------------------------------------ Critical communication
  459: 
  460: sub critical {
  461:     my ($cmd,$server)=@_;
  462:     unless (&hostname($server)) {
  463:         &logthis("<font color=\"blue\">WARNING:".
  464:                " Critical message to unknown server ($server)</font>");
  465:         return 'no_such_host';
  466:     }
  467:     my $answer=reply($cmd,$server);
  468:     if ($answer eq 'con_lost') {
  469: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  470: 	my $answer=reply($cmd,$server);
  471:         if ($answer eq 'con_lost') {
  472:             my $now=time;
  473:             my $middlename=$cmd;
  474:             $middlename=substr($middlename,0,16);
  475:             $middlename=~s/\W//g;
  476:             my $dfilename=
  477:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  478:             $dumpcount++;
  479:             {
  480: 		my $dfh;
  481: 		if (open($dfh,">$dfilename")) {
  482: 		    print $dfh "$cmd\n"; 
  483: 		    close($dfh);
  484: 		}
  485:             }
  486:             sleep 2;
  487:             my $wcmd='';
  488:             {
  489: 		my $dfh;
  490: 		if (open($dfh,"<$dfilename")) {
  491: 		    $wcmd=<$dfh>; 
  492: 		    close($dfh);
  493: 		}
  494:             }
  495:             chomp($wcmd);
  496:             if ($wcmd eq $cmd) {
  497: 		&logthis("<font color=\"blue\">WARNING: ".
  498:                          "Connection buffer $dfilename: $cmd</font>");
  499:                 &logperm("D:$server:$cmd");
  500: 	        return 'con_delayed';
  501:             } else {
  502:                 &logthis("<font color=\"red\">CRITICAL:"
  503:                         ." Critical connection failed: $server $cmd</font>");
  504:                 &logperm("F:$server:$cmd");
  505:                 return 'con_failed';
  506:             }
  507:         }
  508:     }
  509:     return $answer;
  510: }
  511: 
  512: # ------------------------------------------- check if return value is an error
  513: 
  514: sub error {
  515:     my ($result) = @_;
  516:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  517: 	if ($2 == 2) { return undef; }
  518: 	return $1;
  519:     }
  520:     return undef;
  521: }
  522: 
  523: sub convert_and_load_session_env {
  524:     my ($lonidsdir,$handle)=@_;
  525:     my @profile;
  526:     {
  527: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  528: 	if (!$opened) {
  529: 	    return 0;
  530: 	}
  531: 	flock($idf,LOCK_SH);
  532: 	@profile=<$idf>;
  533: 	close($idf);
  534:     }
  535:     my %temp_env;
  536:     foreach my $line (@profile) {
  537: 	if ($line !~ m/=/) {
  538: 	    return 0;
  539: 	}
  540: 	chomp($line);
  541: 	my ($envname,$envvalue)=split(/=/,$line,2);
  542: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  543:     }
  544:     unlink("$lonidsdir/$handle.id");
  545:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  546: 	    0640)) {
  547: 	%disk_env = %temp_env;
  548: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  549: 	untie(%disk_env);
  550:     }
  551:     return 1;
  552: }
  553: 
  554: # ------------------------------------------- Transfer profile into environment
  555: my $env_loaded;
  556: sub transfer_profile_to_env {
  557:     my ($lonidsdir,$handle,$force_transfer) = @_;
  558:     if (!$force_transfer && $env_loaded) { return; } 
  559: 
  560:     if (!defined($lonidsdir)) {
  561: 	$lonidsdir = $perlvar{'lonIDsDir'};
  562:     }
  563:     if (!defined($handle)) {
  564:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  565:     }
  566: 
  567:     my $convert;
  568:     {
  569:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  570: 	if (!$opened) {
  571: 	    return;
  572: 	}
  573: 	flock($idf,LOCK_SH);
  574: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  575: 		&GDBM_READER(),0640)) {
  576: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  577: 	    untie(%disk_env);
  578: 	} else {
  579: 	    $convert = 1;
  580: 	}
  581:     }
  582:     if ($convert) {
  583: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  584: 	    &logthis("Failed to load session, or convert session.");
  585: 	}
  586:     }
  587: 
  588:     my %remove;
  589:     while ( my $envname = each(%env) ) {
  590:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  591:             if ($time < time-300) {
  592:                 $remove{$key}++;
  593:             }
  594:         }
  595:     }
  596: 
  597:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  598:     $env_loaded=1;
  599:     foreach my $expired_key (keys(%remove)) {
  600:         &delenv($expired_key);
  601:     }
  602: }
  603: 
  604: # ---------------------------------------------------- Check for valid session 
  605: sub check_for_valid_session {
  606:     my ($r,$name) = @_;
  607:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  608:     if ($name eq '') {
  609:         $name = 'lonID';
  610:     }
  611:     my $lonid=$cookies{$name};
  612:     return undef if (!$lonid);
  613: 
  614:     my $handle=&LONCAPA::clean_handle($lonid->value);
  615:     my $lonidsdir;
  616:     if ($name eq 'lonDAV') {
  617:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  618:     } else {
  619:         $lonidsdir=$r->dir_config('lonIDsDir');
  620:     }
  621:     return undef if (!-e "$lonidsdir/$handle.id");
  622: 
  623:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  624:     return undef if (!$opened);
  625: 
  626:     flock($idf,LOCK_SH);
  627:     my %disk_env;
  628:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  629: 	    &GDBM_READER(),0640)) {
  630: 	return undef;	
  631:     }
  632: 
  633:     if (!defined($disk_env{'user.name'})
  634: 	|| !defined($disk_env{'user.domain'})) {
  635: 	return undef;
  636:     }
  637:     if (($r->user() eq '') && ($apache >= 2.4)) {
  638:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
  639:             $r->user($disk_env{'user.name'});
  640:         } else {
  641:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
  642:         }
  643:     }
  644:     return $handle;
  645: }
  646: 
  647: sub timed_flock {
  648:     my ($file,$lock_type) = @_;
  649:     my $failed=0;
  650:     eval {
  651: 	local $SIG{__DIE__}='DEFAULT';
  652: 	local $SIG{ALRM}=sub {
  653: 	    $failed=1;
  654: 	    die("failed lock");
  655: 	};
  656: 	alarm(13);
  657: 	flock($file,$lock_type);
  658: 	alarm(0);
  659:     };
  660:     if ($failed) {
  661: 	return undef;
  662:     } else {
  663: 	return 1;
  664:     }
  665: }
  666: 
  667: # ---------------------------------------------------------- Append Environment
  668: 
  669: sub appenv {
  670:     my ($newenv,$roles) = @_;
  671:     if (ref($newenv) eq 'HASH') {
  672:         foreach my $key (keys(%{$newenv})) {
  673:             my $refused = 0;
  674: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  675:                 $refused = 1;
  676:                 if (ref($roles) eq 'ARRAY') {
  677:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  678:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  679:                         $refused = 0;
  680:                     }
  681:                 }
  682:             }
  683:             if ($refused) {
  684:                 &logthis("<font color=\"blue\">WARNING: ".
  685:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  686:                          .'</font>');
  687: 	        delete($newenv->{$key});
  688:             } else {
  689:                 $env{$key}=$newenv->{$key};
  690:             }
  691:         }
  692:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  693:         if ($opened
  694: 	    && &timed_flock($env_file,LOCK_EX)
  695: 	    &&
  696: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  697: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  698: 	    while (my ($key,$value) = each(%{$newenv})) {
  699: 	        $disk_env{$key} = $value;
  700: 	    }
  701: 	    untie(%disk_env);
  702:         }
  703:     }
  704:     return 'ok';
  705: }
  706: # ----------------------------------------------------- Delete from Environment
  707: 
  708: sub delenv {
  709:     my ($delthis,$regexp,$roles) = @_;
  710:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  711:         my $refused = 1;
  712:         if (ref($roles) eq 'ARRAY') {
  713:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  714:             if (grep(/^\Q$role\E$/,@{$roles})) {
  715:                 $refused = 0;
  716:             }
  717:         }
  718:         if ($refused) {
  719:             &logthis("<font color=\"blue\">WARNING: ".
  720:                      "Attempt to delete from environment ".$delthis);
  721:             return 'error';
  722:         }
  723:     }
  724:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  725:     if ($opened
  726: 	&& &timed_flock($env_file,LOCK_EX)
  727: 	&&
  728: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  729: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  730: 	foreach my $key (keys(%disk_env)) {
  731: 	    if ($regexp) {
  732:                 if ($key=~/^$delthis/) {
  733:                     delete($env{$key});
  734:                     delete($disk_env{$key});
  735:                 } 
  736:             } else {
  737:                 if ($key=~/^\Q$delthis\E/) {
  738: 		    delete($env{$key});
  739: 		    delete($disk_env{$key});
  740: 	        }
  741:             }
  742: 	}
  743: 	untie(%disk_env);
  744:     }
  745:     return 'ok';
  746: }
  747: 
  748: sub get_env_multiple {
  749:     my ($name) = @_;
  750:     my @values;
  751:     if (defined($env{$name})) {
  752:         # exists is it an array
  753:         if (ref($env{$name})) {
  754:             @values=@{ $env{$name} };
  755:         } else {
  756:             $values[0]=$env{$name};
  757:         }
  758:     }
  759:     return(@values);
  760: }
  761: 
  762: # ------------------------------------------------------------------- Locking
  763: 
  764: sub set_lock {
  765:     my ($text)=@_;
  766:     $locknum++;
  767:     my $id=$$.'-'.$locknum;
  768:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  769:              'session.lock.'.$id => $text});
  770:     return $id;
  771: }
  772: 
  773: sub get_locks {
  774:     my $num=0;
  775:     my %texts=();
  776:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  777:        if ($lock=~/\w/) {
  778:           $num++;
  779:           $texts{$lock}=$env{'session.lock.'.$lock};
  780:        }
  781:    }
  782:    return ($num,%texts);
  783: }
  784: 
  785: sub remove_lock {
  786:     my ($id)=@_;
  787:     my $newlocks='';
  788:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  789:        if (($lock=~/\w/) && ($lock ne $id)) {
  790:           $newlocks.=','.$lock;
  791:        }
  792:     }
  793:     &appenv({'session.locks' => $newlocks});
  794:     &delenv('session.lock.'.$id);
  795: }
  796: 
  797: sub remove_all_locks {
  798:     my $activelocks=$env{'session.locks'};
  799:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  800:        if ($lock=~/\w/) {
  801:           &remove_lock($lock);
  802:        }
  803:     }
  804: }
  805: 
  806: 
  807: # ------------------------------------------ Find out current server userload
  808: sub userload {
  809:     my $numusers=0;
  810:     {
  811: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  812: 	my $filename;
  813: 	my $curtime=time;
  814: 	while ($filename=readdir(LONIDS)) {
  815: 	    next if ($filename eq '.' || $filename eq '..');
  816: 	    next if ($filename =~ /publicuser_\d+\.id/);
  817: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  818: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  819: 	}
  820: 	closedir(LONIDS);
  821:     }
  822:     my $userloadpercent=0;
  823:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  824:     if ($maxuserload) {
  825: 	$userloadpercent=100*$numusers/$maxuserload;
  826:     }
  827:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  828:     return $userloadpercent;
  829: }
  830: 
  831: # ------------------------------ Find server with least workload from spare.tab
  832: 
  833: sub spareserver {
  834:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  835:     my $spare_server;
  836:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  837:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  838:                                                      :  $userloadpercent;
  839:     my ($uint_dom,$remotesessions);
  840:     if (($udom ne '') && (&domain($udom) ne '')) {
  841:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  842:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  843:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  844:         $remotesessions = $udomdefaults{'remotesessions'};
  845:     }
  846:     my $spareshash = &this_host_spares($udom);
  847:     if (ref($spareshash) eq 'HASH') {
  848:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  849:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  850:                 if ($uint_dom) {
  851:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  852:                                                  $try_server));
  853:                 }
  854: 	        ($spare_server, $lowest_load) =
  855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  856:             }
  857:         }
  858: 
  859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  860: 
  861:         if (!$found_server) {
  862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  864:                     if ($uint_dom) {
  865:                         next unless (&spare_can_host($udom,$uint_dom,
  866:                                                      $remotesessions,$try_server));
  867:                     }
  868: 	            ($spare_server, $lowest_load) =
  869: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  870:                 }
  871: 	    }
  872:         }
  873:     }
  874: 
  875:     if (!$want_server_name) {
  876:         my $protocol = 'http';
  877:         if ($protocol{$spare_server} eq 'https') {
  878:             $protocol = $protocol{$spare_server};
  879:         }
  880:         if (defined($spare_server)) {
  881:             my $hostname = &hostname($spare_server);
  882:             if (defined($hostname)) {
  883: 	        $spare_server = $protocol.'://'.$hostname;
  884:             }
  885:         }
  886:     }
  887:     return $spare_server;
  888: }
  889: 
  890: sub compare_server_load {
  891:     my ($try_server, $spare_server, $lowest_load) = @_;
  892: 
  893:     my $loadans     = &reply('load',    $try_server);
  894:     my $userloadans = &reply('userload',$try_server);
  895: 
  896:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  897: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  898:     }
  899: 
  900:     my $load;
  901:     if ($loadans =~ /\d/) {
  902: 	if ($userloadans =~ /\d/) {
  903: 	    #both are numbers, pick the bigger one
  904: 	    $load = ($loadans > $userloadans) ? $loadans 
  905: 		                              : $userloadans;
  906: 	} else {
  907: 	    $load = $loadans;
  908: 	}
  909:     } else {
  910: 	$load = $userloadans;
  911:     }
  912: 
  913:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  914: 	$spare_server = $try_server;
  915: 	$lowest_load  = $load;
  916:     }
  917:     return ($spare_server,$lowest_load);
  918: }
  919: 
  920: # --------------------------- ask offload servers if user already has a session
  921: sub find_existing_session {
  922:     my ($udom,$uname) = @_;
  923:     my $spareshash = &this_host_spares($udom);
  924:     if (ref($spareshash) eq 'HASH') {
  925:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  926:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  927:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  928:             }
  929:         }
  930:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  931:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  932:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  933:             }
  934:         }
  935:     }
  936:     return;
  937: }
  938: 
  939: # -------------------------------- ask if server already has a session for user
  940: sub has_user_session {
  941:     my ($lonid,$udom,$uname) = @_;
  942:     my $result = &reply(join(':','userhassession',
  943: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  944:     return 1 if ($result eq 'ok');
  945: 
  946:     return 0;
  947: }
  948: 
  949: # --------- determine least loaded server in a user's domain which allows login
  950: 
  951: sub choose_server {
  952:     my ($udom,$checkloginvia) = @_;
  953:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  954:     my %servers = &get_servers($udom);
  955:     my $lowest_load = 30000;
  956:     my ($login_host,$hostname,$portal_path,$isredirect);
  957:     foreach my $lonhost (keys(%servers)) {
  958:         my $loginvia;
  959:         if ($checkloginvia) {
  960:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  961:             if ($loginvia) {
  962:                 my ($server,$path) = split(/:/,$loginvia);
  963:                 ($login_host, $lowest_load) =
  964:                     &compare_server_load($server, $login_host, $lowest_load);
  965:                 if ($login_host eq $server) {
  966:                     $portal_path = $path;
  967:                     $isredirect = 1;
  968:                 }
  969:             } else {
  970:                 ($login_host, $lowest_load) =
  971:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  972:                 if ($login_host eq $lonhost) {
  973:                     $portal_path = '';
  974:                     $isredirect = ''; 
  975:                 }
  976:             }
  977:         } else {
  978:             ($login_host, $lowest_load) =
  979:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  980:         }
  981:     }
  982:     if ($login_host ne '') {
  983:         $hostname = &hostname($login_host);
  984:     }
  985:     return ($login_host,$hostname,$portal_path,$isredirect);
  986: }
  987: 
  988: # --------------------------------------------- Try to change a user's password
  989: 
  990: sub changepass {
  991:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  992:     $currentpass = &escape($currentpass);
  993:     $newpass     = &escape($newpass);
  994:     my $lonhost = $perlvar{'lonHostID'};
  995:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  996: 		       $server);
  997:     if (! $answer) {
  998: 	&logthis("No reply on password change request to $server ".
  999: 		 "by $uname in domain $udom.");
 1000:     } elsif ($answer =~ "^ok") {
 1001:         &logthis("$uname in $udom successfully changed their password ".
 1002: 		 "on $server.");
 1003:     } elsif ($answer =~ "^pwchange_failure") {
 1004: 	&logthis("$uname in $udom was unable to change their password ".
 1005: 		 "on $server.  The action was blocked by either lcpasswd ".
 1006: 		 "or pwchange");
 1007:     } elsif ($answer =~ "^non_authorized") {
 1008:         &logthis("$uname in $udom did not get their password correct when ".
 1009: 		 "attempting to change it on $server.");
 1010:     } elsif ($answer =~ "^auth_mode_error") {
 1011:         &logthis("$uname in $udom attempted to change their password despite ".
 1012: 		 "not being locally or internally authenticated on $server.");
 1013:     } elsif ($answer =~ "^unknown_user") {
 1014:         &logthis("$uname in $udom attempted to change their password ".
 1015: 		 "on $server but were unable to because $server is not ".
 1016: 		 "their home server.");
 1017:     } elsif ($answer =~ "^refused") {
 1018: 	&logthis("$server refused to change $uname in $udom password because ".
 1019: 		 "it was sent an unencrypted request to change the password.");
 1020:     } elsif ($answer =~ "invalid_client") {
 1021:         &logthis("$server refused to change $uname in $udom password because ".
 1022:                  "it was a reset by e-mail originating from an invalid server.");
 1023:     }
 1024:     return $answer;
 1025: }
 1026: 
 1027: # ----------------------- Try to determine user's current authentication scheme
 1028: 
 1029: sub queryauthenticate {
 1030:     my ($uname,$udom)=@_;
 1031:     my $uhome=&homeserver($uname,$udom);
 1032:     if (!$uhome) {
 1033: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1034: 	return 'no_host';
 1035:     }
 1036:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1037:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1038: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1039:     }
 1040:     return $answer;
 1041: }
 1042: 
 1043: # --------- Try to authenticate user from domain's lib servers (first this one)
 1044: 
 1045: sub authenticate {
 1046:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1047:     $upass=&escape($upass);
 1048:     $uname= &LONCAPA::clean_username($uname);
 1049:     my $uhome=&homeserver($uname,$udom,1);
 1050:     my $newhome;
 1051:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1052: # Maybe the machine was offline and only re-appeared again recently?
 1053:         &reconlonc();
 1054: # One more
 1055: 	$uhome=&homeserver($uname,$udom,1);
 1056:         if (($uhome eq 'no_host') && $checkdefauth) {
 1057:             if (defined(&domain($udom,'primary'))) {
 1058:                 $newhome=&domain($udom,'primary');
 1059:             }
 1060:             if ($newhome ne '') {
 1061:                 $uhome = $newhome;
 1062:             }
 1063:         }
 1064: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1065: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1066: 	    return 'no_host';
 1067:         }
 1068:     }
 1069:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1070:     if ($answer eq 'authorized') {
 1071:         if ($newhome) {
 1072:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1073:             return 'no_account_on_host'; 
 1074:         } else {
 1075:             &logthis("User $uname at $udom authorized by $uhome");
 1076:             return $uhome;
 1077:         }
 1078:     }
 1079:     if ($answer eq 'non_authorized') {
 1080: 	&logthis("User $uname at $udom rejected by $uhome");
 1081: 	return 'no_host'; 
 1082:     }
 1083:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1084:     return 'no_host';
 1085: }
 1086: 
 1087: sub can_host_session {
 1088:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1089:     my $canhost = 1;
 1090:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1091:     if (ref($remotesessions) eq 'HASH') {
 1092:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1094:                 $canhost = 0;
 1095:             } else {
 1096:                 $canhost = 1;
 1097:             }
 1098:         }
 1099:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1100:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1101:                 $canhost = 1;
 1102:             } else {
 1103:                 $canhost = 0;
 1104:             }
 1105:         }
 1106:         if ($canhost) {
 1107:             if ($remotesessions->{'version'} ne '') {
 1108:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1109:                 if ($reqmajor ne '' && $reqminor ne '') {
 1110:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1111:                         my $major = $1;
 1112:                         my $minor = $2;
 1113:                         if (($major < $reqmajor ) ||
 1114:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1115:                             $canhost = 0;
 1116:                         }
 1117:                     } else {
 1118:                         $canhost = 0;
 1119:                     }
 1120:                 }
 1121:             }
 1122:         }
 1123:     }
 1124:     if ($canhost) {
 1125:         if (ref($hostedsessions) eq 'HASH') {
 1126:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1127:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1128:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1129:                 if (($uint_dom ne '') && 
 1130:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1131:                     $canhost = 0;
 1132:                 } else {
 1133:                     $canhost = 1;
 1134:                 }
 1135:             }
 1136:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1137:                 if (($uint_dom ne '') && 
 1138:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1139:                     $canhost = 1;
 1140:                 } else {
 1141:                     $canhost = 0;
 1142:                 }
 1143:             }
 1144:         }
 1145:     }
 1146:     return $canhost;
 1147: }
 1148: 
 1149: sub spare_can_host {
 1150:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1151:     my $canhost=1;
 1152:     my @intdoms;
 1153:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1154:     if (ref($internet_names) eq 'ARRAY') {
 1155:         @intdoms = @{$internet_names};
 1156:     }
 1157:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1158:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1159:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1160:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1161:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1162:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1163:                                      $remotesessions,
 1164:                                      $defdomdefaults{'hostedsessions'});
 1165:     }
 1166:     return $canhost;
 1167: }
 1168: 
 1169: sub this_host_spares {
 1170:     my ($dom) = @_;
 1171:     my ($dom_in_use,$lonhost_in_use,$result);
 1172:     my @hosts = &current_machine_ids();
 1173:     foreach my $lonhost (@hosts) {
 1174:         if (&host_domain($lonhost) eq $dom) {
 1175:             $dom_in_use = $dom;
 1176:             $lonhost_in_use = $lonhost;
 1177:             last;
 1178:         }
 1179:     }
 1180:     if ($dom_in_use ne '') {
 1181:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1182:     }
 1183:     if (ref($result) ne 'HASH') {
 1184:         $lonhost_in_use = $perlvar{'lonHostID'};
 1185:         $dom_in_use = &host_domain($lonhost_in_use);
 1186:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1187:         if (ref($result) ne 'HASH') {
 1188:             $result = \%spareid;
 1189:         }
 1190:     }
 1191:     return $result;
 1192: }
 1193: 
 1194: sub spares_for_offload  {
 1195:     my ($dom_in_use,$lonhost_in_use) = @_;
 1196:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1197:     if (defined($cached)) {
 1198:         return $result;
 1199:     } else {
 1200:         my $cachetime = 60*60*24;
 1201:         my %domconfig =
 1202:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1203:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1204:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1205:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1206:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1207:                 }
 1208:             }
 1209:         }
 1210:     }
 1211:     return;
 1212: }
 1213: 
 1214: sub get_lonbalancer_config {
 1215:     my ($servers) = @_;
 1216:     my ($currbalancer,$currtargets);
 1217:     if (ref($servers) eq 'HASH') {
 1218:         foreach my $server (keys(%{$servers})) {
 1219:             my %what = (
 1220:                          spareid => 1,
 1221:                          perlvar => 1,
 1222:                        );
 1223:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1224:             if ($result eq 'ok') {
 1225:                 if (ref($returnhash) eq 'HASH') {
 1226:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1227:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1228:                             $currbalancer = $server;
 1229:                             $currtargets = {};
 1230:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1231:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1232:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1233:                                 }
 1234:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1235:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1236:                                 }
 1237:                             }
 1238:                             last;
 1239:                         }
 1240:                     }
 1241:                 }
 1242:             }
 1243:         }
 1244:     }
 1245:     return ($currbalancer,$currtargets);
 1246: }
 1247: 
 1248: sub check_loadbalancing {
 1249:     my ($uname,$udom) = @_;
 1250:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1251:         $rule_in_effect,$offloadto,$otherserver);
 1252:     my $lonhost = $perlvar{'lonHostID'};
 1253:     my @hosts = &current_machine_ids();
 1254:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1255:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1256:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1257:     my $serverhomedom = &host_domain($lonhost);
 1258: 
 1259:     my $cachetime = 60*60*24;
 1260: 
 1261:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1262:         $dom_in_use = $udom;
 1263:         $homeintdom = 1;
 1264:     } else {
 1265:         $dom_in_use = $serverhomedom;
 1266:     }
 1267:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1268:     unless (defined($cached)) {
 1269:         my %domconfig =
 1270:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1271:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1272:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1273:         }
 1274:     }
 1275:     if (ref($result) eq 'HASH') {
 1276:         ($is_balancer,$currtargets,$currrules) = 
 1277:             &check_balancer_result($result,@hosts);
 1278:         if ($is_balancer) {
 1279:             if (ref($currrules) eq 'HASH') {
 1280:                 if ($homeintdom) {
 1281:                     if ($uname ne '') {
 1282:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1283:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1284:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1285:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1286:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1287:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1288:                             }
 1289:                         }
 1290:                         if ($rule_in_effect eq '') {
 1291:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1292:                             if ($userenv{'inststatus'} ne '') {
 1293:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1294:                                 my ($othertitle,$usertypes,$types) =
 1295:                                     &Apache::loncommon::sorted_inst_types($udom);
 1296:                                 if (ref($types) eq 'ARRAY') {
 1297:                                     foreach my $type (@{$types}) {
 1298:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1299:                                             if (exists($currrules->{$type})) {
 1300:                                                 $rule_in_effect = $currrules->{$type};
 1301:                                             }
 1302:                                         }
 1303:                                     }
 1304:                                 }
 1305:                             } else {
 1306:                                 if (exists($currrules->{'default'})) {
 1307:                                     $rule_in_effect = $currrules->{'default'};
 1308:                                 }
 1309:                             }
 1310:                         }
 1311:                     } else {
 1312:                         if (exists($currrules->{'default'})) {
 1313:                             $rule_in_effect = $currrules->{'default'};
 1314:                         }
 1315:                     }
 1316:                 } else {
 1317:                     if ($currrules->{'_LC_external'} ne '') {
 1318:                         $rule_in_effect = $currrules->{'_LC_external'};
 1319:                     }
 1320:                 }
 1321:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1322:                                                        $uname,$udom);
 1323:             }
 1324:         }
 1325:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1326:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1327:         unless (defined($cached)) {
 1328:             my %domconfig =
 1329:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1330:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1331:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1332:             }
 1333:         }
 1334:         if (ref($result) eq 'HASH') {
 1335:             ($is_balancer,$currtargets,$currrules) = 
 1336:                 &check_balancer_result($result,@hosts);
 1337:             if ($is_balancer) {
 1338:                 if (ref($currrules) eq 'HASH') {
 1339:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1340:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1341:                     }
 1342:                 }
 1343:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1344:                                                        $uname,$udom);
 1345:             }
 1346:         } else {
 1347:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1348:                 $is_balancer = 1;
 1349:                 $offloadto = &this_host_spares($dom_in_use);
 1350:             }
 1351:         }
 1352:     } else {
 1353:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1354:             $is_balancer = 1;
 1355:             $offloadto = &this_host_spares($dom_in_use);
 1356:         }
 1357:     }
 1358:     if ($is_balancer) {
 1359:         my $lowest_load = 30000;
 1360:         if (ref($offloadto) eq 'HASH') {
 1361:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1362:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1363:                     ($otherserver,$lowest_load) =
 1364:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1365:                 }
 1366:             }
 1367:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1368: 
 1369:             if (!$found_server) {
 1370:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1371:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1372:                         ($otherserver,$lowest_load) =
 1373:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1374:                     }
 1375:                 }
 1376:             }
 1377:         } elsif (ref($offloadto) eq 'ARRAY') {
 1378:             if (@{$offloadto} == 1) {
 1379:                 $otherserver = $offloadto->[0];
 1380:             } elsif (@{$offloadto} > 1) {
 1381:                 foreach my $try_server (@{$offloadto}) {
 1382:                     ($otherserver,$lowest_load) =
 1383:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1384:                 }
 1385:             }
 1386:         }
 1387:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1388:             $is_balancer = 0;
 1389:             if ($uname ne '' && $udom ne '') {
 1390:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1391:                     
 1392:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1393:                              'user.loadbalcheck.time' => time});
 1394:                 }
 1395:             }
 1396:         }
 1397:     }
 1398:     return ($is_balancer,$otherserver);
 1399: }
 1400: 
 1401: sub check_balancer_result {
 1402:     my ($result,@hosts) = @_;
 1403:     my ($is_balancer,$currtargets,$currrules);
 1404:     if (ref($result) eq 'HASH') {
 1405:         if ($result->{'lonhost'} ne '') {
 1406:             my $currbalancer = $result->{'lonhost'};
 1407:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1408:                 $is_balancer = 1;
 1409:                 $currtargets = $result->{'targets'};
 1410:                 $currrules = $result->{'rules'};
 1411:             }
 1412:         } else {
 1413:             foreach my $key (keys(%{$result})) {
 1414:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1415:                     (ref($result->{$key}) eq 'HASH')) {
 1416:                     $is_balancer = 1;
 1417:                     $currrules = $result->{$key}{'rules'};
 1418:                     $currtargets = $result->{$key}{'targets'};
 1419:                     last;
 1420:                 }
 1421:             }
 1422:         }
 1423:     }
 1424:     return ($is_balancer,$currtargets,$currrules);
 1425: }
 1426: 
 1427: sub get_loadbalancer_targets {
 1428:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1429:     my $offloadto;
 1430:     if ($rule_in_effect eq 'none') {
 1431:         return [$perlvar{'lonHostID'}];
 1432:     } elsif ($rule_in_effect eq '') {
 1433:         $offloadto = $currtargets;
 1434:     } else {
 1435:         if ($rule_in_effect eq 'homeserver') {
 1436:             my $homeserver = &homeserver($uname,$udom);
 1437:             if ($homeserver ne 'no_host') {
 1438:                 $offloadto = [$homeserver];
 1439:             }
 1440:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1441:             my %domconfig =
 1442:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1443:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1444:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1445:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1446:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1447:                     }
 1448:                 }
 1449:             } else {
 1450:                 my %servers = &internet_dom_servers($udom);
 1451:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1452:                 if (&hostname($remotebalancer) ne '') {
 1453:                     $offloadto = [$remotebalancer];
 1454:                 }
 1455:             }
 1456:         } elsif (&hostname($rule_in_effect) ne '') {
 1457:             $offloadto = [$rule_in_effect];
 1458:         }
 1459:     }
 1460:     return $offloadto;
 1461: }
 1462: 
 1463: sub internet_dom_servers {
 1464:     my ($dom) = @_;
 1465:     my (%uniqservers,%servers);
 1466:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1467:     my @machinedoms = &machine_domains($primaryserver);
 1468:     foreach my $mdom (@machinedoms) {
 1469:         my %currservers = %servers;
 1470:         my %server = &get_servers($mdom);
 1471:         %servers = (%currservers,%server);
 1472:     }
 1473:     my %by_hostname;
 1474:     foreach my $id (keys(%servers)) {
 1475:         push(@{$by_hostname{$servers{$id}}},$id);
 1476:     }
 1477:     foreach my $hostname (sort(keys(%by_hostname))) {
 1478:         if (@{$by_hostname{$hostname}} > 1) {
 1479:             my $match = 0;
 1480:             foreach my $id (@{$by_hostname{$hostname}}) {
 1481:                 if (&host_domain($id) eq $dom) {
 1482:                     $uniqservers{$id} = $hostname;
 1483:                     $match = 1;
 1484:                 }
 1485:             }
 1486:             unless ($match) {
 1487:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1488:             }
 1489:         } else {
 1490:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1491:         }
 1492:     }
 1493:     return %uniqservers;
 1494: }
 1495: 
 1496: # ---------------------- Find the homebase for a user from domain's lib servers
 1497: 
 1498: my %homecache;
 1499: sub homeserver {
 1500:     my ($uname,$udom,$ignoreBadCache)=@_;
 1501:     my $index="$uname:$udom";
 1502: 
 1503:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1504: 
 1505:     my %servers = &get_servers($udom,'library');
 1506:     foreach my $tryserver (keys(%servers)) {
 1507:         next if ($ignoreBadCache ne 'true' && 
 1508: 		 exists($badServerCache{$tryserver}));
 1509: 
 1510: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1511: 	if ($answer eq 'found') {
 1512: 	    delete($badServerCache{$tryserver}); 
 1513: 	    return $homecache{$index}=$tryserver;
 1514: 	} elsif ($answer eq 'no_host') {
 1515: 	    $badServerCache{$tryserver}=1;
 1516: 	}
 1517:     }    
 1518:     return 'no_host';
 1519: }
 1520: 
 1521: # ------------------------------------- Find the usernames behind a list of IDs
 1522: 
 1523: sub idget {
 1524:     my ($udom,@ids)=@_;
 1525:     my %returnhash=();
 1526:     
 1527:     my %servers = &get_servers($udom,'library');
 1528:     foreach my $tryserver (keys(%servers)) {
 1529: 	my $idlist=join('&',@ids);
 1530: 	$idlist=~tr/A-Z/a-z/; 
 1531: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1532: 	my @answer=();
 1533: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1534: 	    @answer=split(/\&/,$reply);
 1535: 	}                    ;
 1536: 	my $i;
 1537: 	for ($i=0;$i<=$#ids;$i++) {
 1538: 	    if ($answer[$i]) {
 1539: 		$returnhash{$ids[$i]}=$answer[$i];
 1540: 	    } 
 1541: 	}
 1542:     } 
 1543:     return %returnhash;
 1544: }
 1545: 
 1546: # ------------------------------------- Find the IDs behind a list of usernames
 1547: 
 1548: sub idrget {
 1549:     my ($udom,@unames)=@_;
 1550:     my %returnhash=();
 1551:     foreach my $uname (@unames) {
 1552:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1553:     }
 1554:     return %returnhash;
 1555: }
 1556: 
 1557: # ------------------------------- Store away a list of names and associated IDs
 1558: 
 1559: sub idput {
 1560:     my ($udom,%ids)=@_;
 1561:     my %servers=();
 1562:     foreach my $uname (keys(%ids)) {
 1563: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1564:         my $uhom=&homeserver($uname,$udom);
 1565:         if ($uhom ne 'no_host') {
 1566:             my $id=&escape($ids{$uname});
 1567:             $id=~tr/A-Z/a-z/;
 1568:             my $esc_unam=&escape($uname);
 1569: 	    if ($servers{$uhom}) {
 1570: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1571:             } else {
 1572:                 $servers{$uhom}=$id.'='.$esc_unam;
 1573:             }
 1574:         }
 1575:     }
 1576:     foreach my $server (keys(%servers)) {
 1577:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1578:     }
 1579: }
 1580: 
 1581: # ------------------------------dump from db file owned by domainconfig user
 1582: sub dump_dom {
 1583:     my ($namespace, $udom, $regexp) = @_;
 1584: 
 1585:     $udom ||= $env{'user.domain'};
 1586: 
 1587:     return () unless $udom;
 1588: 
 1589:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1590: }
 1591: 
 1592: # ------------------------------------------ get items from domain db files   
 1593: 
 1594: sub get_dom {
 1595:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1596:     my $items='';
 1597:     foreach my $item (@$storearr) {
 1598:         $items.=&escape($item).'&';
 1599:     }
 1600:     $items=~s/\&$//;
 1601:     if (!$udom) {
 1602:         $udom=$env{'user.domain'};
 1603:         if (defined(&domain($udom,'primary'))) {
 1604:             $uhome=&domain($udom,'primary');
 1605:         } else {
 1606:             undef($uhome);
 1607:         }
 1608:     } else {
 1609:         if (!$uhome) {
 1610:             if (defined(&domain($udom,'primary'))) {
 1611:                 $uhome=&domain($udom,'primary');
 1612:             }
 1613:         }
 1614:     }
 1615:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1616:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1617:         my %returnhash;
 1618:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1619:             return %returnhash;
 1620:         }
 1621:         my @pairs=split(/\&/,$rep);
 1622:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1623:             return @pairs;
 1624:         }
 1625:         my $i=0;
 1626:         foreach my $item (@$storearr) {
 1627:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1628:             $i++;
 1629:         }
 1630:         return %returnhash;
 1631:     } else {
 1632:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1633:     }
 1634: }
 1635: 
 1636: # -------------------------------------------- put items in domain db files 
 1637: 
 1638: sub put_dom {
 1639:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1640:     if (!$udom) {
 1641:         $udom=$env{'user.domain'};
 1642:         if (defined(&domain($udom,'primary'))) {
 1643:             $uhome=&domain($udom,'primary');
 1644:         } else {
 1645:             undef($uhome);
 1646:         }
 1647:     } else {
 1648:         if (!$uhome) {
 1649:             if (defined(&domain($udom,'primary'))) {
 1650:                 $uhome=&domain($udom,'primary');
 1651:             }
 1652:         }
 1653:     } 
 1654:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1655:         my $items='';
 1656:         foreach my $item (keys(%$storehash)) {
 1657:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1658:         }
 1659:         $items=~s/\&$//;
 1660:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1661:     } else {
 1662:         &logthis("put_dom failed - no homeserver and/or domain");
 1663:     }
 1664: }
 1665: 
 1666: # --------------------- newput for items in db file owned by domainconfig user
 1667: sub newput_dom {
 1668:     my ($namespace,$storehash,$udom) = @_;
 1669:     my $result;
 1670:     if (!$udom) {
 1671:         $udom=$env{'user.domain'};
 1672:     }
 1673:     if ($udom) {
 1674:         my $uname = &get_domainconfiguser($udom);
 1675:         $result = &newput($namespace,$storehash,$udom,$uname);
 1676:     }
 1677:     return $result;
 1678: }
 1679: 
 1680: # --------------------- delete for items in db file owned by domainconfig user
 1681: sub del_dom {
 1682:     my ($namespace,$storearr,$udom)=@_;
 1683:     if (ref($storearr) eq 'ARRAY') {
 1684:         if (!$udom) {
 1685:             $udom=$env{'user.domain'};
 1686:         }
 1687:         if ($udom) {
 1688:             my $uname = &get_domainconfiguser($udom); 
 1689:             return &del($namespace,$storearr,$udom,$uname);
 1690:         }
 1691:     }
 1692: }
 1693: 
 1694: # ----------------------------------construct domainconfig user for a domain 
 1695: sub get_domainconfiguser {
 1696:     my ($udom) = @_;
 1697:     return $udom.'-domainconfig';
 1698: }
 1699: 
 1700: sub retrieve_inst_usertypes {
 1701:     my ($udom) = @_;
 1702:     my (%returnhash,@order);
 1703:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1704:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1705:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1706:         %returnhash = %{$domdefs{'inststatustypes'}};
 1707:         @order = @{$domdefs{'inststatusorder'}};
 1708:     } else {
 1709:         if (defined(&domain($udom,'primary'))) {
 1710:             my $uhome=&domain($udom,'primary');
 1711:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1712:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1713:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1714:                 return (\%returnhash,\@order);
 1715:             }
 1716:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1717:             my @pairs=split(/\&/,$hashitems);
 1718:             foreach my $item (@pairs) {
 1719:                 my ($key,$value)=split(/=/,$item,2);
 1720:                 $key = &unescape($key);
 1721:                 next if ($key =~ /^error: 2 /);
 1722:                 $returnhash{$key}=&thaw_unescape($value);
 1723:             }
 1724:             my @esc_order = split(/\&/,$orderitems);
 1725:             foreach my $item (@esc_order) {
 1726:                 push(@order,&unescape($item));
 1727:             }
 1728:         } else {
 1729:             &logthis("get_dom failed - no primary domain server for $udom");
 1730:         }
 1731:     }
 1732:     return (\%returnhash,\@order);
 1733: }
 1734: 
 1735: sub is_domainimage {
 1736:     my ($url) = @_;
 1737:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1738:         if (&domain($1) ne '') {
 1739:             return '1';
 1740:         }
 1741:     }
 1742:     return;
 1743: }
 1744: 
 1745: sub inst_directory_query {
 1746:     my ($srch) = @_;
 1747:     my $udom = $srch->{'srchdomain'};
 1748:     my %results;
 1749:     my $homeserver = &domain($udom,'primary');
 1750:     my $outcome;
 1751:     if ($homeserver ne '') {
 1752: 	my $queryid=&reply("querysend:instdirsearch:".
 1753: 			   &escape($srch->{'srchby'}).':'.
 1754: 			   &escape($srch->{'srchterm'}).':'.
 1755: 			   &escape($srch->{'srchtype'}),$homeserver);
 1756: 	my $host=&hostname($homeserver);
 1757: 	if ($queryid !~/^\Q$host\E\_/) {
 1758: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1759: 	    return;
 1760: 	}
 1761: 	my $response = &get_query_reply($queryid);
 1762: 	my $maxtries = 5;
 1763: 	my $tries = 1;
 1764: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1765: 	    $response = &get_query_reply($queryid);
 1766: 	    $tries ++;
 1767: 	}
 1768: 
 1769:         if (!&error($response) && $response ne 'refused') {
 1770:             if ($response eq 'unavailable') {
 1771:                 $outcome = $response;
 1772:             } else {
 1773:                 $outcome = 'ok';
 1774:                 my @matches = split(/\n/,$response);
 1775:                 foreach my $match (@matches) {
 1776:                     my ($key,$value) = split(/=/,$match);
 1777:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1778:                 }
 1779:             }
 1780:         }
 1781:     }
 1782:     return ($outcome,%results);
 1783: }
 1784: 
 1785: sub usersearch {
 1786:     my ($srch) = @_;
 1787:     my $dom = $srch->{'srchdomain'};
 1788:     my %results;
 1789:     my %libserv = &all_library();
 1790:     my $query = 'usersearch';
 1791:     foreach my $tryserver (keys(%libserv)) {
 1792:         if (&host_domain($tryserver) eq $dom) {
 1793:             my $host=&hostname($tryserver);
 1794:             my $queryid=
 1795:                 &reply("querysend:".&escape($query).':'.
 1796:                        &escape($srch->{'srchby'}).':'.
 1797:                        &escape($srch->{'srchtype'}).':'.
 1798:                        &escape($srch->{'srchterm'}),$tryserver);
 1799:             if ($queryid !~/^\Q$host\E\_/) {
 1800:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1801:                 next;
 1802:             }
 1803:             my $reply = &get_query_reply($queryid);
 1804:             my $maxtries = 1;
 1805:             my $tries = 1;
 1806:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1807:                 $reply = &get_query_reply($queryid);
 1808:                 $tries ++;
 1809:             }
 1810:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1811:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1812:             } else {
 1813:                 my @matches;
 1814:                 if ($reply =~ /\n/) {
 1815:                     @matches = split(/\n/,$reply);
 1816:                 } else {
 1817:                     @matches = split(/\&/,$reply);
 1818:                 }
 1819:                 foreach my $match (@matches) {
 1820:                     my ($uname,$udom,%userhash);
 1821:                     foreach my $entry (split(/:/,$match)) {
 1822:                         my ($key,$value) =
 1823:                             map {&unescape($_);} split(/=/,$entry);
 1824:                         $userhash{$key} = $value;
 1825:                         if ($key eq 'username') {
 1826:                             $uname = $value;
 1827:                         } elsif ($key eq 'domain') {
 1828:                             $udom = $value;
 1829:                         }
 1830:                     }
 1831:                     $results{$uname.':'.$udom} = \%userhash;
 1832:                 }
 1833:             }
 1834:         }
 1835:     }
 1836:     return %results;
 1837: }
 1838: 
 1839: sub get_instuser {
 1840:     my ($udom,$uname,$id) = @_;
 1841:     my $homeserver = &domain($udom,'primary');
 1842:     my ($outcome,%results);
 1843:     if ($homeserver ne '') {
 1844:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1845:                            &escape($id).':'.&escape($udom),$homeserver);
 1846:         my $host=&hostname($homeserver);
 1847:         if ($queryid !~/^\Q$host\E\_/) {
 1848:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1849:             return;
 1850:         }
 1851:         my $response = &get_query_reply($queryid);
 1852:         my $maxtries = 5;
 1853:         my $tries = 1;
 1854:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1855:             $response = &get_query_reply($queryid);
 1856:             $tries ++;
 1857:         }
 1858:         if (!&error($response) && $response ne 'refused') {
 1859:             if ($response eq 'unavailable') {
 1860:                 $outcome = $response;
 1861:             } else {
 1862:                 $outcome = 'ok';
 1863:                 my @matches = split(/\n/,$response);
 1864:                 foreach my $match (@matches) {
 1865:                     my ($key,$value) = split(/=/,$match);
 1866:                     $results{&unescape($key)} = &thaw_unescape($value);
 1867:                 }
 1868:             }
 1869:         }
 1870:     }
 1871:     my %userinfo;
 1872:     if (ref($results{$uname}) eq 'HASH') {
 1873:         %userinfo = %{$results{$uname}};
 1874:     } 
 1875:     return ($outcome,%userinfo);
 1876: }
 1877: 
 1878: sub inst_rulecheck {
 1879:     my ($udom,$uname,$id,$item,$rules) = @_;
 1880:     my %returnhash;
 1881:     if ($udom ne '') {
 1882:         if (ref($rules) eq 'ARRAY') {
 1883:             @{$rules} = map {&escape($_);} (@{$rules});
 1884:             my $rulestr = join(':',@{$rules});
 1885:             my $homeserver=&domain($udom,'primary');
 1886:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1887:                 my $response;
 1888:                 if ($item eq 'username') {                
 1889:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1890:                                               ':'.&escape($uname).':'.$rulestr,
 1891:                                               $homeserver));
 1892:                 } elsif ($item eq 'id') {
 1893:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1894:                                               ':'.&escape($id).':'.$rulestr,
 1895:                                               $homeserver));
 1896:                 } elsif ($item eq 'selfcreate') {
 1897:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1898:                                                &escape($udom).':'.&escape($uname).
 1899:                                               ':'.$rulestr,$homeserver));
 1900:                 }
 1901:                 if ($response ne 'refused') {
 1902:                     my @pairs=split(/\&/,$response);
 1903:                     foreach my $item (@pairs) {
 1904:                         my ($key,$value)=split(/=/,$item,2);
 1905:                         $key = &unescape($key);
 1906:                         next if ($key =~ /^error: 2 /);
 1907:                         $returnhash{$key}=&thaw_unescape($value);
 1908:                     }
 1909:                 }
 1910:             }
 1911:         }
 1912:     }
 1913:     return %returnhash;
 1914: }
 1915: 
 1916: sub inst_userrules {
 1917:     my ($udom,$check) = @_;
 1918:     my (%ruleshash,@ruleorder);
 1919:     if ($udom ne '') {
 1920:         my $homeserver=&domain($udom,'primary');
 1921:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1922:             my $response;
 1923:             if ($check eq 'id') {
 1924:                 $response=&reply('instidrules:'.&escape($udom),
 1925:                                  $homeserver);
 1926:             } elsif ($check eq 'email') {
 1927:                 $response=&reply('instemailrules:'.&escape($udom),
 1928:                                  $homeserver);
 1929:             } else {
 1930:                 $response=&reply('instuserrules:'.&escape($udom),
 1931:                                  $homeserver);
 1932:             }
 1933:             if (($response ne 'refused') && ($response ne 'error') && 
 1934:                 ($response ne 'unknown_cmd') && 
 1935:                 ($response ne 'no_such_host')) {
 1936:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1937:                 my @pairs=split(/\&/,$hashitems);
 1938:                 foreach my $item (@pairs) {
 1939:                     my ($key,$value)=split(/=/,$item,2);
 1940:                     $key = &unescape($key);
 1941:                     next if ($key =~ /^error: 2 /);
 1942:                     $ruleshash{$key}=&thaw_unescape($value);
 1943:                 }
 1944:                 my @esc_order = split(/\&/,$orderitems);
 1945:                 foreach my $item (@esc_order) {
 1946:                     push(@ruleorder,&unescape($item));
 1947:                 }
 1948:             }
 1949:         }
 1950:     }
 1951:     return (\%ruleshash,\@ruleorder);
 1952: }
 1953: 
 1954: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1955: 
 1956: sub get_domain_defaults {
 1957:     my ($domain) = @_;
 1958:     my $cachetime = 60*60*24;
 1959:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1960:     if (defined($cached)) {
 1961:         if (ref($result) eq 'HASH') {
 1962:             return %{$result};
 1963:         }
 1964:     }
 1965:     my %domdefaults;
 1966:     my %domconfig =
 1967:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1968:                                   'requestcourses','inststatus',
 1969:                                   'coursedefaults','usersessions',
 1970:                                   'requestauthor'],$domain);
 1971:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1972:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1973:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1974:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1975:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1976:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1977:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1978:     } else {
 1979:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1980:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1981:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1982:     }
 1983:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1984:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1985:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1986:         } else {
 1987:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1988:         } 
 1989:         my @usertools = ('aboutme','blog','webdav','portfolio');
 1990:         foreach my $item (@usertools) {
 1991:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1992:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1993:             }
 1994:         }
 1995:     }
 1996:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1997:         foreach my $item ('official','unofficial','community') {
 1998:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1999:         }
 2000:     }
 2001:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2002:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2003:     }
 2004:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2005:         foreach my $item ('inststatustypes','inststatusorder') {
 2006:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2007:         }
 2008:     }
 2009:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2010:         foreach my $item ('canuse_pdfforms') {
 2011:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 2012:         }
 2013:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2014:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
 2015:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
 2016:         }
 2017:     }
 2018:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2019:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2020:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2021:         }
 2022:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2023:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2024:         }
 2025:     }
 2026:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 2027:                                   $cachetime);
 2028:     return %domdefaults;
 2029: }
 2030: 
 2031: # --------------------------------------------------- Assign a key to a student
 2032: 
 2033: sub assign_access_key {
 2034: #
 2035: # a valid key looks like uname:udom#comments
 2036: # comments are being appended
 2037: #
 2038:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2039:     $kdom=
 2040:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2041:     $knum=
 2042:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2043:     $cdom=
 2044:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2045:     $cnum=
 2046:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2047:     $udom=$env{'user.name'} unless (defined($udom));
 2048:     $uname=$env{'user.domain'} unless (defined($uname));
 2049:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2050:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2051:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2052:                                                   # assigned to this person
 2053:                                                   # - this should not happen,
 2054:                                                   # unless something went wrong
 2055:                                                   # the first time around
 2056: # ready to assign
 2057:         $logentry=$1.'; '.$logentry;
 2058:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2059:                                                  $kdom,$knum) eq 'ok') {
 2060: # key now belongs to user
 2061: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2062:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2063:                 &appenv({'environment.'.$envkey => $ckey});
 2064:                 return 'ok';
 2065:             } else {
 2066:                 return 
 2067:   'error: Count not permanently assign key, will need to be re-entered later.';
 2068: 	    }
 2069:         } else {
 2070:             return 'error: Could not assign key, try again later.';
 2071:         }
 2072:     } elsif (!$existing{$ckey}) {
 2073: # the key does not exist
 2074: 	return 'error: The key does not exist';
 2075:     } else {
 2076: # the key is somebody else's
 2077: 	return 'error: The key is already in use';
 2078:     }
 2079: }
 2080: 
 2081: # ------------------------------------------ put an additional comment on a key
 2082: 
 2083: sub comment_access_key {
 2084: #
 2085: # a valid key looks like uname:udom#comments
 2086: # comments are being appended
 2087: #
 2088:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2089:     $cdom=
 2090:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2091:     $cnum=
 2092:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2093:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2094:     if ($existing{$ckey}) {
 2095:         $existing{$ckey}.='; '.$logentry;
 2096: # ready to assign
 2097:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2098:                                                  $cdom,$cnum) eq 'ok') {
 2099: 	    return 'ok';
 2100:         } else {
 2101: 	    return 'error: Count not store comment.';
 2102:         }
 2103:     } else {
 2104: # the key does not exist
 2105: 	return 'error: The key does not exist';
 2106:     }
 2107: }
 2108: 
 2109: # ------------------------------------------------------ Generate a set of keys
 2110: 
 2111: sub generate_access_keys {
 2112:     my ($number,$cdom,$cnum,$logentry)=@_;
 2113:     $cdom=
 2114:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2115:     $cnum=
 2116:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2117:     unless (&allowed('mky',$cdom)) { return 0; }
 2118:     unless (($cdom) && ($cnum)) { return 0; }
 2119:     if ($number>10000) { return 0; }
 2120:     sleep(2); # make sure don't get same seed twice
 2121:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2122:     my $total=0;
 2123:     for (my $i=1;$i<=$number;$i++) {
 2124:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2125:                   sprintf("%lx",int(100000*rand)).'-'.
 2126:                   sprintf("%lx",int(100000*rand));
 2127:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2128:        $newkey=~s/0/h/g; # and also 0 and O
 2129:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2130:        if ($existing{$newkey}) {
 2131:            $i--;
 2132:        } else {
 2133: 	  if (&put('accesskeys',
 2134:               { $newkey => '# generated '.localtime().
 2135:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2136:                            '; '.$logentry },
 2137: 		   $cdom,$cnum) eq 'ok') {
 2138:               $total++;
 2139: 	  }
 2140:        }
 2141:     }
 2142:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2143:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2144:     return $total;
 2145: }
 2146: 
 2147: # ------------------------------------------------------- Validate an accesskey
 2148: 
 2149: sub validate_access_key {
 2150:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2151:     $cdom=
 2152:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2153:     $cnum=
 2154:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2155:     $udom=$env{'user.domain'} unless (defined($udom));
 2156:     $uname=$env{'user.name'} unless (defined($uname));
 2157:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2158:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2159: }
 2160: 
 2161: # ------------------------------------- Find the section of student in a course
 2162: sub devalidate_getsection_cache {
 2163:     my ($udom,$unam,$courseid)=@_;
 2164:     my $hashid="$udom:$unam:$courseid";
 2165:     &devalidate_cache_new('getsection',$hashid);
 2166: }
 2167: 
 2168: sub courseid_to_courseurl {
 2169:     my ($courseid) = @_;
 2170:     #already url style courseid
 2171:     return $courseid if ($courseid =~ m{^/});
 2172: 
 2173:     if (exists($env{'course.'.$courseid.'.num'})) {
 2174: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2175: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2176: 	return "/$cdom/$cnum";
 2177:     }
 2178: 
 2179:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2180:     if (exists($courseinfo{'num'})) {
 2181: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2182:     }
 2183: 
 2184:     return undef;
 2185: }
 2186: 
 2187: sub getsection {
 2188:     my ($udom,$unam,$courseid)=@_;
 2189:     my $cachetime=1800;
 2190: 
 2191:     my $hashid="$udom:$unam:$courseid";
 2192:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2193:     if (defined($cached)) { return $result; }
 2194: 
 2195:     my %Pending; 
 2196:     my %Expired;
 2197:     #
 2198:     # Each role can either have not started yet (pending), be active, 
 2199:     #    or have expired.
 2200:     #
 2201:     # If there is an active role, we are done.
 2202:     #
 2203:     # If there is more than one role which has not started yet, 
 2204:     #     choose the one which will start sooner
 2205:     # If there is one role which has not started yet, return it.
 2206:     #
 2207:     # If there is more than one expired role, choose the one which ended last.
 2208:     # If there is a role which has expired, return it.
 2209:     #
 2210:     $courseid = &courseid_to_courseurl($courseid);
 2211:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2212:     foreach my $key (keys(%roleshash)) {
 2213:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2214:         my $section=$1;
 2215:         if ($key eq $courseid.'_st') { $section=''; }
 2216:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2217:         my $now=time;
 2218:         if (defined($end) && $end && ($now > $end)) {
 2219:             $Expired{$end}=$section;
 2220:             next;
 2221:         }
 2222:         if (defined($start) && $start && ($now < $start)) {
 2223:             $Pending{$start}=$section;
 2224:             next;
 2225:         }
 2226:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2227:     }
 2228:     #
 2229:     # Presumedly there will be few matching roles from the above
 2230:     # loop and the sorting time will be negligible.
 2231:     if (scalar(keys(%Pending))) {
 2232:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2233:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2234:     } 
 2235:     if (scalar(keys(%Expired))) {
 2236:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2237:         my $time = pop(@sorted);
 2238:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2239:     }
 2240:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2241: }
 2242: 
 2243: sub save_cache {
 2244:     &purge_remembered();
 2245:     #&Apache::loncommon::validate_page();
 2246:     undef(%env);
 2247:     undef($env_loaded);
 2248: }
 2249: 
 2250: my $to_remember=-1;
 2251: my %remembered;
 2252: my %accessed;
 2253: my $kicks=0;
 2254: my $hits=0;
 2255: sub make_key {
 2256:     my ($name,$id) = @_;
 2257:     if (length($id) > 65 
 2258: 	&& length(&escape($id)) > 200) {
 2259: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2260:     }
 2261:     return &escape($name.':'.$id);
 2262: }
 2263: 
 2264: sub devalidate_cache_new {
 2265:     my ($name,$id,$debug) = @_;
 2266:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2267:     $id=&make_key($name,$id);
 2268:     $memcache->delete($id);
 2269:     delete($remembered{$id});
 2270:     delete($accessed{$id});
 2271: }
 2272: 
 2273: sub is_cached_new {
 2274:     my ($name,$id,$debug) = @_;
 2275:     $id=&make_key($name,$id);
 2276:     if (exists($remembered{$id})) {
 2277: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2278: 	$accessed{$id}=[&gettimeofday()];
 2279: 	$hits++;
 2280: 	return ($remembered{$id},1);
 2281:     }
 2282:     my $value = $memcache->get($id);
 2283:     if (!(defined($value))) {
 2284: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2285: 	return (undef,undef);
 2286:     }
 2287:     if ($value eq '__undef__') {
 2288: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2289: 	$value=undef;
 2290:     }
 2291:     &make_room($id,$value,$debug);
 2292:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2293:     return ($value,1);
 2294: }
 2295: 
 2296: sub do_cache_new {
 2297:     my ($name,$id,$value,$time,$debug) = @_;
 2298:     $id=&make_key($name,$id);
 2299:     my $setvalue=$value;
 2300:     if (!defined($setvalue)) {
 2301: 	$setvalue='__undef__';
 2302:     }
 2303:     if (!defined($time) ) {
 2304: 	$time=600;
 2305:     }
 2306:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2307:     my $result = $memcache->set($id,$setvalue,$time);
 2308:     if (! $result) {
 2309: 	&logthis("caching of id -> $id  failed");
 2310: 	$memcache->disconnect_all();
 2311:     }
 2312:     # need to make a copy of $value
 2313:     &make_room($id,$value,$debug);
 2314:     return $value;
 2315: }
 2316: 
 2317: sub make_room {
 2318:     my ($id,$value,$debug)=@_;
 2319: 
 2320:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2321:                                     : $value;
 2322:     if ($to_remember<0) { return; }
 2323:     $accessed{$id}=[&gettimeofday()];
 2324:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2325:     my $to_kick;
 2326:     my $max_time=0;
 2327:     foreach my $other (keys(%accessed)) {
 2328: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2329: 	    $to_kick=$other;
 2330: 	    $max_time=&tv_interval($accessed{$other});
 2331: 	}
 2332:     }
 2333:     delete($remembered{$to_kick});
 2334:     delete($accessed{$to_kick});
 2335:     $kicks++;
 2336:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2337:     return;
 2338: }
 2339: 
 2340: sub purge_remembered {
 2341:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2342:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2343:     undef(%remembered);
 2344:     undef(%accessed);
 2345: }
 2346: # ------------------------------------- Read an entry from a user's environment
 2347: 
 2348: sub userenvironment {
 2349:     my ($udom,$unam,@what)=@_;
 2350:     my $items;
 2351:     foreach my $item (@what) {
 2352:         $items.=&escape($item).'&';
 2353:     }
 2354:     $items=~s/\&$//;
 2355:     my %returnhash=();
 2356:     my $uhome = &homeserver($unam,$udom);
 2357:     unless ($uhome eq 'no_host') {
 2358:         my @answer=split(/\&/, 
 2359:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2360:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2361:             return %returnhash;
 2362:         }
 2363:         my $i;
 2364:         for ($i=0;$i<=$#what;$i++) {
 2365: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2366:         }
 2367:     }
 2368:     return %returnhash;
 2369: }
 2370: 
 2371: # ---------------------------------------------------------- Get a studentphoto
 2372: sub studentphoto {
 2373:     my ($udom,$unam,$ext) = @_;
 2374:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2375:     if (defined($env{'request.course.id'})) {
 2376:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2377:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2378:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2379:             } else {
 2380:                 my ($result,$perm_reqd)=
 2381: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2382:                 if ($result eq 'ok') {
 2383:                     if (!($perm_reqd eq 'yes')) {
 2384:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2385:                     }
 2386:                 }
 2387:             }
 2388:         }
 2389:     } else {
 2390:         my ($result,$perm_reqd) = 
 2391: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2392:         if ($result eq 'ok') {
 2393:             if (!($perm_reqd eq 'yes')) {
 2394:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2395:             }
 2396:         }
 2397:     }
 2398:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2399: }
 2400: 
 2401: sub retrievestudentphoto {
 2402:     my ($udom,$unam,$ext,$type) = @_;
 2403:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2404:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2405:     if ($ret eq 'ok') {
 2406:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2407:         if ($type eq 'thumbnail') {
 2408:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2409:         }
 2410:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2411:         return $tokenurl;
 2412:     } else {
 2413:         if ($type eq 'thumbnail') {
 2414:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2415:         } else { 
 2416:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2417:         }
 2418:     }
 2419: }
 2420: 
 2421: # -------------------------------------------------------------------- New chat
 2422: 
 2423: sub chatsend {
 2424:     my ($newentry,$anon,$group)=@_;
 2425:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2426:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2427:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2428:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2429: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2430: 		   &escape($newentry)).':'.$group,$chome);
 2431: }
 2432: 
 2433: # ------------------------------------------ Find current version of a resource
 2434: 
 2435: sub getversion {
 2436:     my $fname=&clutter(shift);
 2437:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2438:     return &currentversion(&filelocation('',$fname));
 2439: }
 2440: 
 2441: sub currentversion {
 2442:     my $fname=shift;
 2443:     my $author=$fname;
 2444:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2445:     my ($udom,$uname)=split(/\//,$author);
 2446:     my $home=&homeserver($uname,$udom);
 2447:     if ($home eq 'no_host') { 
 2448:         return -1; 
 2449:     }
 2450:     my $answer=&reply("currentversion:$fname",$home);
 2451:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2452: 	return -1;
 2453:     }
 2454:     return $answer;
 2455: }
 2456: 
 2457: #
 2458: # Return special version number of resource if set by override, empty otherwise
 2459: #
 2460: sub usedversion {
 2461:     my $fname=shift;
 2462:     unless ($fname) { $fname=$env{'request.uri'}; }
 2463:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2464:     if ($urlversion) { return $urlversion; }
 2465:     return '';
 2466: }
 2467: 
 2468: # ----------------------------- Subscribe to a resource, return URL if possible
 2469: 
 2470: sub subscribe {
 2471:     my $fname=shift;
 2472:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2473:     $fname=~s/[\n\r]//g;
 2474:     my $author=$fname;
 2475:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2476:     my ($udom,$uname)=split(/\//,$author);
 2477:     my $home=homeserver($uname,$udom);
 2478:     if ($home eq 'no_host') {
 2479:         return 'not_found';
 2480:     }
 2481:     my $answer=reply("sub:$fname",$home);
 2482:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2483: 	$answer.=' by '.$home;
 2484:     }
 2485:     return $answer;
 2486: }
 2487:     
 2488: # -------------------------------------------------------------- Replicate file
 2489: 
 2490: sub repcopy {
 2491:     my $filename=shift;
 2492:     $filename=~s/\/+/\//g;
 2493:     my $londocroot = $perlvar{'lonDocRoot'};
 2494:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2495:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2496:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2497: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2498: 	return &repcopy_userfile($filename);
 2499:     }
 2500:     $filename=~s/[\n\r]//g;
 2501:     my $transname="$filename.in.transfer";
 2502: # FIXME: this should flock
 2503:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2504:     my $remoteurl=subscribe($filename);
 2505:     if ($remoteurl =~ /^con_lost by/) {
 2506: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2507:            return 'unavailable';
 2508:     } elsif ($remoteurl eq 'not_found') {
 2509: 	   #&logthis("Subscribe returned not_found: $filename");
 2510: 	   return 'not_found';
 2511:     } elsif ($remoteurl =~ /^rejected by/) {
 2512: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2513:            return 'forbidden';
 2514:     } elsif ($remoteurl eq 'directory') {
 2515:            return 'ok';
 2516:     } else {
 2517:         my $author=$filename;
 2518:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2519:         my ($udom,$uname)=split(/\//,$author);
 2520:         my $home=homeserver($uname,$udom);
 2521:         unless ($home eq $perlvar{'lonHostID'}) {
 2522:            my @parts=split(/\//,$filename);
 2523:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2524:            if ($path ne "$londocroot/res") {
 2525:                &logthis("Malconfiguration for replication: $filename");
 2526: 	       return 'bad_request';
 2527:            }
 2528:            my $count;
 2529:            for ($count=5;$count<$#parts;$count++) {
 2530:                $path.="/$parts[$count]";
 2531:                if ((-e $path)!=1) {
 2532: 		   mkdir($path,0777);
 2533:                }
 2534:            }
 2535:            my $ua=new LWP::UserAgent;
 2536:            my $request=new HTTP::Request('GET',"$remoteurl");
 2537:            my $response=$ua->request($request,$transname);
 2538:            if ($response->is_error()) {
 2539: 	       unlink($transname);
 2540:                my $message=$response->status_line;
 2541:                &logthis("<font color=\"blue\">WARNING:"
 2542:                        ." LWP get: $message: $filename</font>");
 2543:                return 'unavailable';
 2544:            } else {
 2545: 	       if ($remoteurl!~/\.meta$/) {
 2546:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2547:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2548:                   if ($mresponse->is_error()) {
 2549: 		      unlink($filename.'.meta');
 2550:                       &logthis(
 2551:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2552:                   }
 2553: 	       }
 2554:                rename($transname,$filename);
 2555:                return 'ok';
 2556:            }
 2557:        }
 2558:     }
 2559: }
 2560: 
 2561: # ------------------------------------------------ Get server side include body
 2562: sub ssi_body {
 2563:     my ($filelink,%form)=@_;
 2564:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2565:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2566:     }
 2567:     my $output='';
 2568:     my $response;
 2569:     if ($filelink=~/^https?\:/) {
 2570:        ($output,$response)=&externalssi($filelink);
 2571:     } else {
 2572:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2573:        $filelink .= 'inhibitmenu=yes';
 2574:        ($output,$response)=&ssi($filelink,%form);
 2575:     }
 2576:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2577:     $output=~s/^.*?\<body[^\>]*\>//si;
 2578:     $output=~s/\<\/body\s*\>.*?$//si;
 2579:     if (wantarray) {
 2580:         return ($output, $response);
 2581:     } else {
 2582:         return $output;
 2583:     }
 2584: }
 2585: 
 2586: # --------------------------------------------------------- Server Side Include
 2587: 
 2588: sub absolute_url {
 2589:     my ($host_name) = @_;
 2590:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2591:     if ($host_name eq '') {
 2592: 	$host_name = $ENV{'SERVER_NAME'};
 2593:     }
 2594:     return $protocol.$host_name;
 2595: }
 2596: 
 2597: #
 2598: #   Server side include.
 2599: # Parameters:
 2600: #  fn     Possibly encrypted resource name/id.
 2601: #  form   Hash that describes how the rendering should be done
 2602: #         and other things.
 2603: # Returns:
 2604: #   Scalar context: The content of the response.
 2605: #   Array context:  2 element list of the content and the full response object.
 2606: #     
 2607: sub ssi {
 2608: 
 2609:     my ($fn,%form)=@_;
 2610:     my $ua=new LWP::UserAgent;
 2611:     my $request;
 2612: 
 2613:     $form{'no_update_last_known'}=1;
 2614:     &Apache::lonenc::check_encrypt(\$fn);
 2615:     if (%form) {
 2616:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2617:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2618:     } else {
 2619:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2620:     }
 2621: 
 2622:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2623:     my $response= $ua->request($request);
 2624:     my $content = $response->content;
 2625: 
 2626: 
 2627:     if (wantarray) {
 2628: 	return ($content, $response);
 2629:     } else {
 2630: 	return $content;
 2631:     }
 2632: }
 2633: 
 2634: sub externalssi {
 2635:     my ($url)=@_;
 2636:     my $ua=new LWP::UserAgent;
 2637:     my $request=new HTTP::Request('GET',$url);
 2638:     my $response=$ua->request($request);
 2639:     if (wantarray) {
 2640:         return ($response->content, $response);
 2641:     } else {
 2642:         return $response->content;
 2643:     }
 2644: }
 2645: 
 2646: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2647: 
 2648: sub allowuploaded {
 2649:     my ($srcurl,$url)=@_;
 2650:     $url=&clutter(&declutter($url));
 2651:     my $dir=$url;
 2652:     $dir=~s/\/[^\/]+$//;
 2653:     my %httpref=();
 2654:     my $httpurl=&hreflocation('',$url);
 2655:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2656:     &Apache::lonnet::appenv(\%httpref);
 2657: }
 2658: 
 2659: #
 2660: # Determine if the current user should be able to edit a particular resource,
 2661: # when viewing in course context.
 2662: # (a) When viewing resource used to determine if "Edit" item is included in 
 2663: #     Functions.
 2664: # (b) When displaying folder contents in course editor, used to determine if
 2665: #     "Edit" link will be displayed alongside resource.
 2666: #
 2667: #  input: six args -- filename (decluttered), course number, course domain,
 2668: #                   url, symb (if registered) and group (if this is a group
 2669: #                   item -- e.g., bulletin board, group page etc.).
 2670: #  output: array of five scalars -- 
 2671: #          $cfile -- url for file editing if editable on current server
 2672: #          $home -- homeserver of resource (i.e., for author if published,
 2673: #                                           or course if uploaded.).
 2674: #          $switchserver --  1 if server switch will be needed.
 2675: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2676: #          $forceview -- 1 if icon/link should be to go to view mode
 2677: #
 2678: 
 2679: sub can_edit_resource {
 2680:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2681:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2682: #
 2683: # For aboutme pages user can only edit his/her own.
 2684: #
 2685:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2686:         my ($sdom,$sname) = ($1,$2);
 2687:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2688:             $home = $env{'user.home'};
 2689:             $cfile = $resurl;
 2690:             if ($env{'form.forceedit'}) {
 2691:                 $forceview = 1;
 2692:             } else {
 2693:                 $forceedit = 1;
 2694:             }
 2695:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2696:         } else {
 2697:             return;
 2698:         }
 2699:     }
 2700: 
 2701:     if ($env{'request.course.id'}) {
 2702:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2703:         if ($group ne '') {
 2704: # if this is a group homepage or group bulletin board, check group privs
 2705:             my $allowed = 0;
 2706:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2707:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2708:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2709:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2710:                     $allowed = 1;
 2711:                 }
 2712:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2713:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2714:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2715:                     $allowed = 1;
 2716:                 }
 2717:             }
 2718:             if ($allowed) {
 2719:                 $home=&homeserver($cnum,$cdom);
 2720:                 if ($env{'form.forceedit'}) {
 2721:                     $forceview = 1;
 2722:                 } else {
 2723:                     $forceedit = 1;
 2724:                 }
 2725:                 $cfile = $resurl;
 2726:             } else {
 2727:                 return;
 2728:             }
 2729:         } else {
 2730:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2731:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2732:                     return;
 2733:                 }
 2734:             } elsif (!$crsedit) {
 2735: #
 2736: # No edit allowed where CC has switched to student role.
 2737: #
 2738:                 return;
 2739:             }
 2740:         }
 2741:     }
 2742: 
 2743:     if ($file ne '') {
 2744:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2745:             if (&is_course_upload($file,$cnum,$cdom)) {
 2746:                 $uploaded = 1;
 2747:                 $incourse = 1;
 2748:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2749:                     $cfile = &hreflocation('',$file);
 2750:                     if ($env{'form.forceedit'}) {
 2751:                         $forceview = 1;
 2752:                     } else {
 2753:                         $forceedit = 1;
 2754:                     }
 2755:                 }
 2756:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2757:                 $incourse = 1;
 2758:                 if ($env{'form.forceedit'}) {
 2759:                     $forceview = 1;
 2760:                 } else {
 2761:                     $forceedit = 1;
 2762:                 }
 2763:                 $cfile = $resurl;
 2764:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2765:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2766:                     $incourse = 1;
 2767:                     if ($env{'form.forceedit'}) {
 2768:                         $forceview = 1;
 2769:                     } else {
 2770:                         $forceedit = 1;
 2771:                     }
 2772:                     $cfile = $resurl;
 2773:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2774:                     $incourse = 1;
 2775:                     $cfile = $resurl.'/smpedit';
 2776:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2777:                     $incourse = 1;
 2778:                     if ($env{'form.forceedit'}) {
 2779:                         $forceview = 1;
 2780:                     } else {
 2781:                         $forceedit = 1;
 2782:                     }
 2783:                     $cfile = $resurl;
 2784:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2785:                     $incourse = 1;
 2786:                     if ($env{'form.forceedit'}) {
 2787:                         $forceview = 1;
 2788:                     } else {
 2789:                         $forceedit = 1;
 2790:                     }
 2791:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2792:                 }
 2793:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2794:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2795:                 if (&is_on_map($template)) { 
 2796:                     $incourse = 1;
 2797:                     $forceview = 1;
 2798:                     $cfile = $template;
 2799:                 }
 2800:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2801:                     $incourse = 1;
 2802:                     if ($env{'form.forceedit'}) {
 2803:                         $forceview = 1;
 2804:                     } else {
 2805:                         $forceedit = 1;
 2806:                     }
 2807:                     $cfile = $resurl;
 2808:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2809:                 $incourse = 1;
 2810:                 $forceview = 1;
 2811:                 if ($symb) {
 2812:                     my ($map,$id,$res)=&decode_symb($symb);
 2813:                     $env{'request.symb'} = $symb;
 2814:                     $cfile = &clutter($res);
 2815:                 } else {
 2816:                     $cfile = $env{'form.suppurl'};
 2817:                     $cfile =~ s{^http://}{};
 2818:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2819:                 }
 2820:             }
 2821:         }
 2822:         if ($uploaded || $incourse) {
 2823:             $home=&homeserver($cnum,$cdom);
 2824:         } elsif ($file !~ m{/$}) {
 2825:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2826:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2827:             # Check that the user has permission to edit this resource
 2828:             my $setpriv = 1;
 2829:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2830:             if (defined($cfudom)) {
 2831:                 $home=&homeserver($cfuname,$cfudom);
 2832:                 $cfile=$file;
 2833:             }
 2834:         }
 2835:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2836:             (($home ne '') && ($home ne 'no_host'))) {
 2837:             my @ids=&current_machine_ids();
 2838:             unless (grep(/^\Q$home\E$/,@ids)) {
 2839:                 $switchserver=1;
 2840:             }
 2841:         }
 2842:     }
 2843:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2844: }
 2845: 
 2846: sub is_course_upload {
 2847:     my ($file,$cnum,$cdom) = @_;
 2848:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2849:     $uploadpath =~ s{^\/}{};
 2850:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2851:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2852:         return 1;
 2853:     }
 2854:     return;
 2855: }
 2856: 
 2857: sub in_course {
 2858:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2859:     if ($hideprivileged) {
 2860:         my $skipuser;
 2861:         if (&privileged($uname,$udom)) {
 2862:             $skipuser = 1;
 2863:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2864:             if ($coursehash{'nothideprivileged'}) {
 2865:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2866:                     my $user;
 2867:                     if ($item =~ /:/) {
 2868:                         $user = $item;
 2869:                     } else {
 2870:                         $user = join(':',split(/[\@]/,$item));
 2871:                     }
 2872:                     if ($user eq $uname.':'.$udom) {
 2873:                         undef($skipuser);
 2874:                         last;
 2875:                     }
 2876:                 }
 2877:             }
 2878:             if ($skipuser) {
 2879:                 return 0;
 2880:             }
 2881:         }
 2882:     }
 2883:     $type ||= 'any';
 2884:     if (!defined($cdom) || !defined($cnum)) {
 2885:         my $cid  = $env{'request.course.id'};
 2886:         $cdom = $env{'course.'.$cid.'.domain'};
 2887:         $cnum = $env{'course.'.$cid.'.num'};
 2888:     }
 2889:     my $typesref;
 2890:     if (($type eq 'any') || ($type eq 'all')) {
 2891:         $typesref = ['active','previous','future'];
 2892:     } elsif ($type eq 'previous' || $type eq 'future') {
 2893:         $typesref = [$type];
 2894:     }
 2895:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2896:                               $typesref,undef,[$cdom]);
 2897:     my ($tmp) = keys(%roles);
 2898:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2899:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2900:     if (@course_roles > 0) {
 2901:         return 1;
 2902:     }
 2903:     return 0;
 2904: }
 2905: 
 2906: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2907: # input: action, courseID, current domain, intended
 2908: #        path to file, source of file, instruction to parse file for objects,
 2909: #        ref to hash for embedded objects,
 2910: #        ref to hash for codebase of java objects.
 2911: #        reference to scalar to accommodate mime type determined
 2912: #          from File::MMagic if $parser = parse.
 2913: #
 2914: # output: url to file (if action was uploaddoc), 
 2915: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2916: #
 2917: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2918: # course.
 2919: #
 2920: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2921: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2922: #          course's home server.
 2923: #
 2924: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2925: #          be copied from $source (current location) to 
 2926: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2927: #         and will then be copied to
 2928: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2929: #         course's home server.
 2930: #
 2931: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2932: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2933: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2934: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2935: #         in course's home server.
 2936: #
 2937: 
 2938: sub process_coursefile {
 2939:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2940:         $mimetype)=@_;
 2941:     my $fetchresult;
 2942:     my $home=&homeserver($docuname,$docudom);
 2943:     if ($action eq 'propagate') {
 2944:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2945: 			     $home);
 2946:     } else {
 2947:         my $fpath = '';
 2948:         my $fname = $file;
 2949:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2950:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2951:         my $filepath = &build_filepath($fpath);
 2952:         if ($action eq 'copy') {
 2953:             if ($source eq '') {
 2954:                 $fetchresult = 'no source file';
 2955:                 return $fetchresult;
 2956:             } else {
 2957:                 my $destination = $filepath.'/'.$fname;
 2958:                 rename($source,$destination);
 2959:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2960:                                  $home);
 2961:             }
 2962:         } elsif ($action eq 'uploaddoc') {
 2963:             open(my $fh,'>'.$filepath.'/'.$fname);
 2964:             print $fh $env{'form.'.$source};
 2965:             close($fh);
 2966:             if ($parser eq 'parse') {
 2967:                 my $mm = new File::MMagic;
 2968:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2969:                 if ($type eq 'text/html') {
 2970:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2971:                     unless ($parse_result eq 'ok') {
 2972:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2973:                     }
 2974:                 }
 2975:                 if (ref($mimetype)) {
 2976:                     $$mimetype = $type;
 2977:                 } 
 2978:             }
 2979:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2980:                                  $home);
 2981:             if ($fetchresult eq 'ok') {
 2982:                 return '/uploaded/'.$fpath.'/'.$fname;
 2983:             } else {
 2984:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2985:                         ' to host '.$home.': '.$fetchresult);
 2986:                 return '/adm/notfound.html';
 2987:             }
 2988:         }
 2989:     }
 2990:     unless ( $fetchresult eq 'ok') {
 2991:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2992:              ' to host '.$home.': '.$fetchresult);
 2993:     }
 2994:     return $fetchresult;
 2995: }
 2996: 
 2997: sub build_filepath {
 2998:     my ($fpath) = @_;
 2999:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3000:     unless ($fpath eq '') {
 3001:         my @parts=split('/',$fpath);
 3002:         foreach my $part (@parts) {
 3003:             $filepath.= '/'.$part;
 3004:             if ((-e $filepath)!=1) {
 3005:                 mkdir($filepath,0777);
 3006:             }
 3007:         }
 3008:     }
 3009:     return $filepath;
 3010: }
 3011: 
 3012: sub store_edited_file {
 3013:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3014:     my $file = $primary_url;
 3015:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3016:     my $fpath = '';
 3017:     my $fname = $file;
 3018:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3019:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3020:     my $filepath = &build_filepath($fpath);
 3021:     open(my $fh,'>'.$filepath.'/'.$fname);
 3022:     print $fh $content;
 3023:     close($fh);
 3024:     my $home=&homeserver($docuname,$docudom);
 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: sub clean_filename {
 3037:     my ($fname,$args)=@_;
 3038: # Replace Windows backslashes by forward slashes
 3039:     $fname=~s/\\/\//g;
 3040:     if (!$args->{'keep_path'}) {
 3041:         # Get rid of everything but the actual filename
 3042: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3043:     }
 3044: # Replace spaces by underscores
 3045:     $fname=~s/\s+/\_/g;
 3046: # Replace all other weird characters by nothing
 3047:     $fname=~s{[^/\w\.\-]}{}g;
 3048: # Replace all .\d. sequences with _\d. so they no longer look like version
 3049: # numbers
 3050:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3051:     return $fname;
 3052: }
 3053: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3054: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3055: # image with the same aspect ratio as the original, but with dimensions which do 
 3056: # not exceed $resizewidth and $resizeheight.
 3057:  
 3058: sub resizeImage {
 3059:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3060:     my $ima = Image::Magick->new;
 3061:     my $resized;
 3062:     if (-e $img_path) {
 3063:         $ima->Read($img_path);
 3064:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3065:             my $width = $ima->Get('width');
 3066:             my $height = $ima->Get('height');
 3067:             if ($width > $resizewidth) {
 3068: 	        my $factor = $width/$resizewidth;
 3069:                 my $newheight = $height/$factor;
 3070:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3071:                 $resized = 1;
 3072:             }
 3073:         }
 3074:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3075:             my $width = $ima->Get('width');
 3076:             my $height = $ima->Get('height');
 3077:             if ($height > $resizeheight) {
 3078:                 my $factor = $height/$resizeheight;
 3079:                 my $newwidth = $width/$factor;
 3080:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3081:                 $resized = 1;
 3082:             }
 3083:         }
 3084:         if ($resized) {
 3085:             $ima->Write($img_path);
 3086:         }
 3087:     }
 3088:     return;
 3089: }
 3090: 
 3091: # --------------- Take an uploaded file and put it into the userfiles directory
 3092: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3093: #                    the desired filename is in $env{"form.$formname.filename"}
 3094: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3095: #                                    canceloverwrite, or ''. 
 3096: #                   if 'coursedoc': upload to the current course
 3097: #                   if 'existingfile': write file to tmp/overwrites directory 
 3098: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3099: #                   $context is passed as argument to &finishuserfileupload
 3100: #        $subdir - directory in userfile to store the file into
 3101: #        $parser - instruction to parse file for objects ($parser = parse)    
 3102: #        $allfiles - reference to hash for embedded objects
 3103: #        $codebase - reference to hash for codebase of java objects
 3104: #        $desuname - username for permanent storage of uploaded file
 3105: #        $dsetudom - domain for permanaent storage of uploaded file
 3106: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3107: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3108: #        $resizewidth - width (pixels) to which to resize uploaded image
 3109: #        $resizeheight - height (pixels) to which to resize uploaded image
 3110: #        $mimetype - reference to scalar to accommodate mime type determined
 3111: #                    from File::MMagic.
 3112: # 
 3113: # output: url of file in userspace, or error: <message> 
 3114: #             or /adm/notfound.html if failure to upload occurse
 3115: 
 3116: sub userfileupload {
 3117:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3118:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3119:     if (!defined($subdir)) { $subdir='unknown'; }
 3120:     my $fname=$env{'form.'.$formname.'.filename'};
 3121:     $fname=&clean_filename($fname);
 3122:     # See if there is anything left
 3123:     unless ($fname) { return 'error: no uploaded file'; }
 3124:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3125:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3126:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3127:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3128:         my $now = time;
 3129:         my $filepath;
 3130:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3131:              $filepath = 'tmp/helprequests/'.$now;
 3132:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3133:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3134:                          '_'.$env{'user.domain'}.'/pending';
 3135:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3136:             my ($docuname,$docudom);
 3137:             if ($destudom) {
 3138:                 $docudom = $destudom;
 3139:             } else {
 3140:                 $docudom = $env{'user.domain'};
 3141:             }
 3142:             if ($destuname) {
 3143:                 $docuname = $destuname;
 3144:             } else {
 3145:                 $docuname = $env{'user.name'};
 3146:             }
 3147:             if (exists($env{'form.group'})) {
 3148:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3149:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3150:             }
 3151:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3152:             if ($context eq 'canceloverwrite') {
 3153:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3154:                 if (-e  $tempfile) {
 3155:                     my @info = stat($tempfile);
 3156:                     if ($info[9] eq $env{'form.timestamp'}) {
 3157:                         unlink($tempfile);
 3158:                     }
 3159:                 }
 3160:                 return;
 3161:             }
 3162:         }
 3163:         # Create the directory if not present
 3164:         my @parts=split(/\//,$filepath);
 3165:         my $fullpath = $perlvar{'lonDaemons'};
 3166:         for (my $i=0;$i<@parts;$i++) {
 3167:             $fullpath .= '/'.$parts[$i];
 3168:             if ((-e $fullpath)!=1) {
 3169:                 mkdir($fullpath,0777);
 3170:             }
 3171:         }
 3172:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3173:         print $fh $env{'form.'.$formname};
 3174:         close($fh);
 3175:         if ($context eq 'existingfile') {
 3176:             my @info = stat($fullpath.'/'.$fname);
 3177:             return ($fullpath.'/'.$fname,$info[9]);
 3178:         } else {
 3179:             return $fullpath.'/'.$fname;
 3180:         }
 3181:     }
 3182:     if ($subdir eq 'scantron') {
 3183:         $fname = 'scantron_orig_'.$fname;
 3184:     } else {
 3185:         $fname="$subdir/$fname";
 3186:     }
 3187:     if ($context eq 'coursedoc') {
 3188: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3189: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3190:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3191:             return &finishuserfileupload($docuname,$docudom,
 3192: 					 $formname,$fname,$parser,$allfiles,
 3193: 					 $codebase,$thumbwidth,$thumbheight,
 3194:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3195:         } else {
 3196:             $fname=$env{'form.folder'}.'/'.$fname;
 3197:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3198: 				       $fname,$formname,$parser,
 3199: 				       $allfiles,$codebase,$mimetype);
 3200:         }
 3201:     } elsif (defined($destuname)) {
 3202:         my $docuname=$destuname;
 3203:         my $docudom=$destudom;
 3204: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3205: 				     $parser,$allfiles,$codebase,
 3206:                                      $thumbwidth,$thumbheight,
 3207:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3208:     } else {
 3209:         my $docuname=$env{'user.name'};
 3210:         my $docudom=$env{'user.domain'};
 3211:         if (exists($env{'form.group'})) {
 3212:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3213:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3214:         }
 3215: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3216: 				     $parser,$allfiles,$codebase,
 3217:                                      $thumbwidth,$thumbheight,
 3218:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3219:     }
 3220: }
 3221: 
 3222: sub finishuserfileupload {
 3223:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3224:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3225:     my $path=$docudom.'/'.$docuname.'/';
 3226:     my $filepath=$perlvar{'lonDocRoot'};
 3227:   
 3228:     my ($fnamepath,$file,$fetchthumb);
 3229:     $file=$fname;
 3230:     if ($fname=~m|/|) {
 3231:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3232: 	$path.=$fnamepath.'/';
 3233:     }
 3234:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3235:     my $count;
 3236:     for ($count=4;$count<=$#parts;$count++) {
 3237:         $filepath.="/$parts[$count]";
 3238:         if ((-e $filepath)!=1) {
 3239: 	    mkdir($filepath,0777);
 3240:         }
 3241:     }
 3242: 
 3243: # Save the file
 3244:     {
 3245: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3246: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3247: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3248: 	    return '/adm/notfound.html';
 3249: 	}
 3250:         if ($context eq 'overwrite') {
 3251:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3252:             my $target = $filepath.'/'.$file;
 3253:             if (-e $source) {
 3254:                 my @info = stat($source);
 3255:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3256:                     unless (&File::Copy::move($source,$target)) {
 3257:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3258:                         return "Moving from $source failed";
 3259:                     }
 3260:                 } else {
 3261:                     return "Temporary file: $source had unexpected date/time for last modification";
 3262:                 }
 3263:             } else {
 3264:                 return "Temporary file: $source missing";
 3265:             }
 3266:         } elsif (!print FH ($env{'form.'.$formname})) {
 3267: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3268: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3269: 	    return '/adm/notfound.html';
 3270: 	}
 3271: 	close(FH);
 3272:         if ($resizewidth && $resizeheight) {
 3273:             my $mm = new File::MMagic;
 3274:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3275:             if ($mime_type =~ m{^image/}) {
 3276: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3277:             }  
 3278: 	}
 3279:     }
 3280:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3281:         if (ref($mimetype)) {
 3282:             if ($$mimetype eq '') {
 3283:                 my $mm = new File::MMagic;
 3284:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3285:                 $$mimetype = $type;
 3286:             }
 3287:         }
 3288:     }
 3289:     if ($parser eq 'parse') {
 3290:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3291:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3292:                                                        $allfiles,$codebase);
 3293:             unless ($parse_result eq 'ok') {
 3294:                 &logthis('Failed to parse '.$filepath.$file.
 3295: 	   	         ' for embedded media: '.$parse_result); 
 3296:             }
 3297:         }
 3298:     }
 3299:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3300:         my $input = $filepath.'/'.$file;
 3301:         my $output = $filepath.'/'.'tn-'.$file;
 3302:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3303:         system("convert -sample $thumbsize $input $output");
 3304:         if (-e $filepath.'/'.'tn-'.$file) {
 3305:             $fetchthumb  = 1; 
 3306:         }
 3307:     }
 3308:  
 3309: # Notify homeserver to grep it
 3310: #
 3311:     my $docuhome=&homeserver($docuname,$docudom);	
 3312:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3313:     if ($fetchresult eq 'ok') {
 3314:         if ($fetchthumb) {
 3315:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3316:             if ($thumbresult ne 'ok') {
 3317:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3318:                          $docuhome.': '.$thumbresult);
 3319:             }
 3320:         }
 3321: #
 3322: # Return the URL to it
 3323:         return '/uploaded/'.$path.$file;
 3324:     } else {
 3325:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3326: 		 ': '.$fetchresult);
 3327:         return '/adm/notfound.html';
 3328:     }
 3329: }
 3330: 
 3331: sub extract_embedded_items {
 3332:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3333:     my @state = ();
 3334:     my (%lastids,%related,%shockwave,%flashvars);
 3335:     my %javafiles = (
 3336:                       codebase => '',
 3337:                       code => '',
 3338:                       archive => ''
 3339:                     );
 3340:     my %mediafiles = (
 3341:                       src => '',
 3342:                       movie => '',
 3343:                      );
 3344:     my $p;
 3345:     if ($content) {
 3346:         $p = HTML::LCParser->new($content);
 3347:     } else {
 3348:         $p = HTML::LCParser->new($fullpath);
 3349:     }
 3350:     while (my $t=$p->get_token()) {
 3351: 	if ($t->[0] eq 'S') {
 3352: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3353: 	    push(@state, $tagname);
 3354:             if (lc($tagname) eq 'allow') {
 3355:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3356:             }
 3357: 	    if (lc($tagname) eq 'img') {
 3358: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3359: 	    }
 3360: 	    if (lc($tagname) eq 'a') {
 3361: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3362: 	    }
 3363:             if (lc($tagname) eq 'script') {
 3364:                 my $src;
 3365:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3366:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3367:                 } else {
 3368:                     if ($attr->{'src'} ne '') {
 3369:                         $src = $attr->{'src'};
 3370:                         &add_filetype($allfiles,$src,'src');
 3371:                     }
 3372:                 }
 3373:                 my $text = $p->get_trimmed_text();
 3374:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3375:                     my @swfargs = split(/,/,$1);
 3376:                     foreach my $item (@swfargs) {
 3377:                         $item =~ s/["']//g;
 3378:                         $item =~ s/^\s+//;
 3379:                         $item =~ s/\s+$//;
 3380:                     }
 3381:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3382:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3383:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3384:                         } else {
 3385:                             $related{$swfargs[0]} = [$swfargs[2]];
 3386:                         }
 3387:                     }
 3388:                 }
 3389:             }
 3390:             if (lc($tagname) eq 'link') {
 3391:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3392:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3393:                 }
 3394:             }
 3395: 	    if (lc($tagname) eq 'object' ||
 3396: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3397: 		foreach my $item (keys(%javafiles)) {
 3398: 		    $javafiles{$item} = '';
 3399: 		}
 3400:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3401:                     $lastids{lc($tagname)} = $attr->{'id'};
 3402:                 }
 3403: 	    }
 3404: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3405: 		my $name = lc($attr->{'name'});
 3406: 		foreach my $item (keys(%javafiles)) {
 3407: 		    if ($name eq $item) {
 3408: 			$javafiles{$item} = $attr->{'value'};
 3409: 			last;
 3410: 		    }
 3411: 		}
 3412:                 my $pathfrom;
 3413: 		foreach my $item (keys(%mediafiles)) {
 3414: 		    if ($name eq $item) {
 3415:                         $pathfrom = $attr->{'value'};
 3416:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3417: 			&add_filetype($allfiles,$pathfrom,$name);
 3418: 			last;
 3419: 		    }
 3420: 		}
 3421:                 if ($name eq 'flashvars') {
 3422:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3423:                 }
 3424:                 if ($pathfrom ne '') {
 3425:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3426:                                          $pathfrom);
 3427:                 }
 3428: 	    }
 3429: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3430: 		foreach my $item (keys(%javafiles)) {
 3431: 		    if ($attr->{$item}) {
 3432: 			$javafiles{$item} = $attr->{$item};
 3433: 			last;
 3434: 		    }
 3435: 		}
 3436: 		foreach my $item (keys(%mediafiles)) {
 3437: 		    if ($attr->{$item}) {
 3438: 			&add_filetype($allfiles,$attr->{$item},$item);
 3439: 			last;
 3440: 		    }
 3441: 		}
 3442:                 if (lc($tagname) eq 'embed') {
 3443:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3444:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3445:                                              $attr->{'src'});
 3446:                     }
 3447:                 }
 3448: 	    }
 3449:             if ($t->[4] =~ m{/>$}) {
 3450:                 pop(@state);  
 3451:             }
 3452: 	} elsif ($t->[0] eq 'E') {
 3453: 	    my ($tagname) = ($t->[1]);
 3454: 	    if ($javafiles{'codebase'} ne '') {
 3455: 		$javafiles{'codebase'} .= '/';
 3456: 	    }  
 3457: 	    if (lc($tagname) eq 'applet' ||
 3458: 		lc($tagname) eq 'object' ||
 3459: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3460: 		) {
 3461: 		foreach my $item (keys(%javafiles)) {
 3462: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3463: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3464: 			&add_filetype($allfiles,$file,$item);
 3465: 		    }
 3466: 		}
 3467: 	    } 
 3468: 	    pop @state;
 3469: 	}
 3470:     }
 3471:     foreach my $id (sort(keys(%flashvars))) {
 3472:         if ($shockwave{$id} ne '') {
 3473:             my @pairs = split(/\&/,$flashvars{$id});
 3474:             foreach my $pair (@pairs) {
 3475:                 my ($key,$value) = split(/\=/,$pair);
 3476:                 if ($key eq 'thumb') {
 3477:                     &add_filetype($allfiles,$value,$key);
 3478:                 } elsif ($key eq 'content') {
 3479:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3480:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3481:                     if ($ext ne '') {
 3482:                         &add_filetype($allfiles,$path.$value,$ext);
 3483:                     }
 3484:                 }
 3485:             }
 3486:         }
 3487:     }
 3488:     return 'ok';
 3489: }
 3490: 
 3491: sub add_filetype {
 3492:     my ($allfiles,$file,$type)=@_;
 3493:     if (exists($allfiles->{$file})) {
 3494: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3495: 	    push(@{$allfiles->{$file}}, &escape($type));
 3496: 	}
 3497:     } else {
 3498: 	@{$allfiles->{$file}} = (&escape($type));
 3499:     }
 3500: }
 3501: 
 3502: sub embedded_dependency {
 3503:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3504:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3505:         if (($identifier ne '') &&
 3506:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3507:             ($pathfrom ne '')) {
 3508:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3509:             foreach my $dep (@{$related->{$identifier}}) {
 3510:                 &add_filetype($allfiles,$path.$dep,'object');
 3511:             }
 3512:         }
 3513:     }
 3514:     return;
 3515: }
 3516: 
 3517: sub removeuploadedurl {
 3518:     my ($url)=@_;	
 3519:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3520:     return &removeuserfile($uname,$udom,$fname);
 3521: }
 3522: 
 3523: sub removeuserfile {
 3524:     my ($docuname,$docudom,$fname)=@_;
 3525:     my $home=&homeserver($docuname,$docudom);    
 3526:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3527:     if ($result eq 'ok') {	
 3528:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3529:             my $metafile = $fname.'.meta';
 3530:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3531: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3532:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3533:             my $sqlresult = 
 3534:                 &update_portfolio_table($docuname,$docudom,$file,
 3535:                                         'portfolio_metadata',$group,
 3536:                                         'delete');
 3537:         }
 3538:     }
 3539:     return $result;
 3540: }
 3541: 
 3542: sub mkdiruserfile {
 3543:     my ($docuname,$docudom,$dir)=@_;
 3544:     my $home=&homeserver($docuname,$docudom);
 3545:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3546: }
 3547: 
 3548: sub renameuserfile {
 3549:     my ($docuname,$docudom,$old,$new)=@_;
 3550:     my $home=&homeserver($docuname,$docudom);
 3551:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3552:                         &escape("$old").':'.&escape("$new"),$home);
 3553:     if ($result eq 'ok') {
 3554:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3555:             my $oldmeta = $old.'.meta';
 3556:             my $newmeta = $new.'.meta';
 3557:             my $metaresult = 
 3558:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3559: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3560:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3561:             my $sqlresult = 
 3562:                 &update_portfolio_table($docuname,$docudom,$file,
 3563:                                         'portfolio_metadata',$group,
 3564:                                         'delete');
 3565:         }
 3566:     }
 3567:     return $result;
 3568: }
 3569: 
 3570: # ------------------------------------------------------------------------- Log
 3571: 
 3572: sub log {
 3573:     my ($dom,$nam,$hom,$what)=@_;
 3574:     return critical("log:$dom:$nam:$what",$hom);
 3575: }
 3576: 
 3577: # ------------------------------------------------------------------ Course Log
 3578: #
 3579: # This routine flushes several buffers of non-mission-critical nature
 3580: #
 3581: 
 3582: sub flushcourselogs {
 3583:     &logthis('Flushing log buffers');
 3584: #
 3585: # course logs
 3586: # This is a log of all transactions in a course, which can be used
 3587: # for data mining purposes
 3588: #
 3589: # It also collects the courseid database, which lists last transaction
 3590: # times and course titles for all courseids
 3591: #
 3592:     my %courseidbuffer=();
 3593:     foreach my $crsid (keys(%courselogs)) {
 3594:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3595: 		          &escape($courselogs{$crsid}),
 3596: 		          $coursehombuf{$crsid}) eq 'ok') {
 3597: 	    delete $courselogs{$crsid};
 3598:         } else {
 3599:             &logthis('Failed to flush log buffer for '.$crsid);
 3600:             if (length($courselogs{$crsid})>40000) {
 3601:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3602:                         " exceeded maximum size, deleting.</font>");
 3603:                delete $courselogs{$crsid};
 3604:             }
 3605:         }
 3606:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3607:             'description' => $coursedescrbuf{$crsid},
 3608:             'inst_code'    => $courseinstcodebuf{$crsid},
 3609:             'type'        => $coursetypebuf{$crsid},
 3610:             'owner'       => $courseownerbuf{$crsid},
 3611:         };
 3612:     }
 3613: #
 3614: # Write course id database (reverse lookup) to homeserver of courses 
 3615: # Is used in pickcourse
 3616: #
 3617:     foreach my $crs_home (keys(%courseidbuffer)) {
 3618:         my $response = &courseidput(&host_domain($crs_home),
 3619:                                     $courseidbuffer{$crs_home},
 3620:                                     $crs_home,'timeonly');
 3621:     }
 3622: #
 3623: # File accesses
 3624: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3625: #
 3626:     foreach my $entry (keys(%accesshash)) {
 3627:         if ($entry =~ /___count$/) {
 3628:             my ($dom,$name);
 3629:             ($dom,$name,undef)=
 3630: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3631:             if (! defined($dom) || $dom eq '' || 
 3632:                 ! defined($name) || $name eq '') {
 3633:                 my $cid = $env{'request.course.id'};
 3634:                 $dom  = $env{'request.'.$cid.'.domain'};
 3635:                 $name = $env{'request.'.$cid.'.num'};
 3636:             }
 3637:             my $value = $accesshash{$entry};
 3638:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3639:             my %temphash=($url => $value);
 3640:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3641:             if ($result eq 'ok') {
 3642:                 delete $accesshash{$entry};
 3643:             }
 3644:         } else {
 3645:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3646:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3647:             my %temphash=($entry => $accesshash{$entry});
 3648:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3649:                 delete $accesshash{$entry};
 3650:             }
 3651:         }
 3652:     }
 3653: #
 3654: # Roles
 3655: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3656: #
 3657:     foreach my $entry (keys(%userrolehash)) {
 3658:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3659: 	    split(/\:/,$entry);
 3660:         if (&Apache::lonnet::put('nohist_userroles',
 3661:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3662:                 $rudom,$runame) eq 'ok') {
 3663: 	    delete $userrolehash{$entry};
 3664:         }
 3665:     }
 3666: #
 3667: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3668: #
 3669:     my %domrolebuffer = ();
 3670:     foreach my $entry (keys(%domainrolehash)) {
 3671:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3672:         if ($domrolebuffer{$rudom}) {
 3673:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3674:                       '='.&escape($domainrolehash{$entry});
 3675:         } else {
 3676:             $domrolebuffer{$rudom}.=&escape($entry).
 3677:                       '='.&escape($domainrolehash{$entry});
 3678:         }
 3679:         delete $domainrolehash{$entry};
 3680:     }
 3681:     foreach my $dom (keys(%domrolebuffer)) {
 3682: 	my %servers = &get_servers($dom,'library');
 3683: 	foreach my $tryserver (keys(%servers)) {
 3684: 	    unless (&reply('domroleput:'.$dom.':'.
 3685: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3686: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3687: 	    }
 3688:         }
 3689:     }
 3690:     $dumpcount++;
 3691: }
 3692: 
 3693: sub courselog {
 3694:     my $what=shift;
 3695:     $what=time.':'.$what;
 3696:     unless ($env{'request.course.id'}) { return ''; }
 3697:     $coursedombuf{$env{'request.course.id'}}=
 3698:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3699:     $coursenumbuf{$env{'request.course.id'}}=
 3700:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3701:     $coursehombuf{$env{'request.course.id'}}=
 3702:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3703:     $coursedescrbuf{$env{'request.course.id'}}=
 3704:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3705:     $courseinstcodebuf{$env{'request.course.id'}}=
 3706:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3707:     $courseownerbuf{$env{'request.course.id'}}=
 3708:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3709:     $coursetypebuf{$env{'request.course.id'}}=
 3710:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3711:     if (defined $courselogs{$env{'request.course.id'}}) {
 3712: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3713:     } else {
 3714: 	$courselogs{$env{'request.course.id'}}.=$what;
 3715:     }
 3716:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3717: 	&flushcourselogs();
 3718:     }
 3719: }
 3720: 
 3721: sub courseacclog {
 3722:     my $fnsymb=shift;
 3723:     unless ($env{'request.course.id'}) { return ''; }
 3724:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3725:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3726:         $what.=':POST';
 3727:         # FIXME: Probably ought to escape things....
 3728: 	foreach my $key (keys(%env)) {
 3729:             if ($key=~/^form\.(.*)/) {
 3730:                 my $formitem = $1;
 3731:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3732:                     $what.=':'.$formitem.'='.$env{$key};
 3733:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3734:                     $what.=':'.$formitem.'='.$env{$key};
 3735:                 }
 3736:             }
 3737:         }
 3738:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3739:         # FIXME: We should not be depending on a form parameter that someone
 3740:         # editing lonsearchcat.pm might change in the future.
 3741:         if ($env{'form.phase'} eq 'course_search') {
 3742:             $what.= ':POST';
 3743:             # FIXME: Probably ought to escape things....
 3744:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3745:                                  'crsdiscuss') {
 3746:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3747:             }
 3748:         }
 3749:     }
 3750:     &courselog($what);
 3751: }
 3752: 
 3753: sub countacc {
 3754:     my $url=&declutter(shift);
 3755:     return if (! defined($url) || $url eq '');
 3756:     unless ($env{'request.course.id'}) { return ''; }
 3757: #
 3758: # Mark that this url was used in this course
 3759: #
 3760:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3761: #
 3762: # Increase the access count for this resource in this child process
 3763: #
 3764:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3765:     $accesshash{$key}++;
 3766: }
 3767: 
 3768: sub linklog {
 3769:     my ($from,$to)=@_;
 3770:     $from=&declutter($from);
 3771:     $to=&declutter($to);
 3772:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3773:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3774: }
 3775: 
 3776: sub statslog {
 3777:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3778:     if ($users<2) { return; }
 3779:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3780:             'course'       => $env{'request.course.id'},
 3781:             'sections'     => '"all"',
 3782:             'num_students' => $users,
 3783:             'part'         => $part,
 3784:             'symb'         => $symb,
 3785:             'mean_tries'   => $av_attempts,
 3786:             'deg_of_diff'  => $degdiff});
 3787:     foreach my $key (keys(%dynstore)) {
 3788:         $accesshash{$key}=$dynstore{$key};
 3789:     }
 3790: }
 3791:   
 3792: sub userrolelog {
 3793:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3794:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3795:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3796:        $userrolehash
 3797:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3798:                     =$tend.':'.$tstart;
 3799:     }
 3800:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3801:        $userrolehash
 3802:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3803:                     =$tend.':'.$tstart;
 3804:     }
 3805:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3806:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3807:        $domainrolehash
 3808:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3809:                     = $tend.':'.$tstart;
 3810:     }
 3811: }
 3812: 
 3813: sub courserolelog {
 3814:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3815:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3816:         my $cdom = $1;
 3817:         my $cnum = $2;
 3818:         my $sec = $3;
 3819:         my $namespace = 'rolelog';
 3820:         my %storehash = (
 3821:                            role    => $trole,
 3822:                            start   => $tstart,
 3823:                            end     => $tend,
 3824:                            selfenroll => $selfenroll,
 3825:                            context    => $context,
 3826:                         );
 3827:         if ($trole eq 'gr') {
 3828:             $namespace = 'groupslog';
 3829:             $storehash{'group'} = $sec;
 3830:         } else {
 3831:             $storehash{'section'} = $sec;
 3832:         }
 3833:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3834:                    $domain,$cnum,$cdom);
 3835:         if (($trole ne 'st') || ($sec ne '')) {
 3836:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3837:         }
 3838:     }
 3839:     return;
 3840: }
 3841: 
 3842: sub domainrolelog {
 3843:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3844:     if ($area =~ m{^/($match_domain)/$}) {
 3845:         my $cdom = $1;
 3846:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3847:         my $namespace = 'rolelog';
 3848:         my %storehash = (
 3849:                            role    => $trole,
 3850:                            start   => $tstart,
 3851:                            end     => $tend,
 3852:                            context => $context,
 3853:                         );
 3854:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3855:                    $domain,$domconfiguser,$cdom);
 3856:     }
 3857:     return;
 3858: 
 3859: }
 3860: 
 3861: sub coauthorrolelog {
 3862:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3863:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3864:         my $audom = $1;
 3865:         my $auname = $2;
 3866:         my $namespace = 'rolelog';
 3867:         my %storehash = (
 3868:                            role    => $trole,
 3869:                            start   => $tstart,
 3870:                            end     => $tend,
 3871:                            context => $context,
 3872:                         );
 3873:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3874:                    $domain,$auname,$audom);
 3875:     }
 3876:     return;
 3877: }
 3878: 
 3879: sub get_course_adv_roles {
 3880:     my ($cid,$codes) = @_;
 3881:     $cid=$env{'request.course.id'} unless (defined($cid));
 3882:     my %coursehash=&coursedescription($cid);
 3883:     my $crstype = &Apache::loncommon::course_type($cid);
 3884:     my %nothide=();
 3885:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3886:         if ($user !~ /:/) {
 3887: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3888:         } else {
 3889:             $nothide{$user}=1;
 3890:         }
 3891:     }
 3892:     my %returnhash=();
 3893:     my %dumphash=
 3894:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3895:     my $now=time;
 3896:     my %privileged;
 3897:     foreach my $entry (keys(%dumphash)) {
 3898: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3899:         if (($tstart) && ($tstart<0)) { next; }
 3900:         if (($tend) && ($tend<$now)) { next; }
 3901:         if (($tstart) && ($now<$tstart)) { next; }
 3902:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3903: 	if ($username eq '' || $domain eq '') { next; }
 3904:         unless (ref($privileged{$domain}) eq 'HASH') {
 3905:             my %dompersonnel =
 3906:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3907:             $privileged{$domain} = {};
 3908:             foreach my $server (keys(%dompersonnel)) {
 3909:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3910:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3911:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3912:                         $privileged{$udom}{$uname} = 1;
 3913:                     }
 3914:                 }
 3915:             }
 3916:         }
 3917:         if ((exists($privileged{$domain}{$username})) && 
 3918:             (!$nothide{$username.':'.$domain})) { next; }
 3919: 	if ($role eq 'cr') { next; }
 3920:         if ($codes) {
 3921:             if ($section) { $role .= ':'.$section; }
 3922:             if ($returnhash{$role}) {
 3923:                 $returnhash{$role}.=','.$username.':'.$domain;
 3924:             } else {
 3925:                 $returnhash{$role}=$username.':'.$domain;
 3926:             }
 3927:         } else {
 3928:             my $key=&plaintext($role,$crstype);
 3929:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3930:             if ($returnhash{$key}) {
 3931: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3932:             } else {
 3933:                 $returnhash{$key}=$username.':'.$domain;
 3934:             }
 3935:         }
 3936:     }
 3937:     return %returnhash;
 3938: }
 3939: 
 3940: sub get_my_roles {
 3941:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3942:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3943:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3944:     my (%dumphash,%nothide);
 3945:     if ($context eq 'userroles') {
 3946:         %dumphash = &dump('roles',$udom,$uname);
 3947:     } else {
 3948:         %dumphash=
 3949:             &dump('nohist_userroles',$udom,$uname);
 3950:         if ($hidepriv) {
 3951:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3952:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3953:                 if ($user !~ /:/) {
 3954:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3955:                 } else {
 3956:                     $nothide{$user} = 1;
 3957:                 }
 3958:             }
 3959:         }
 3960:     }
 3961:     my %returnhash=();
 3962:     my $now=time;
 3963:     my %privileged;
 3964:     foreach my $entry (keys(%dumphash)) {
 3965:         my ($role,$tend,$tstart);
 3966:         if ($context eq 'userroles') {
 3967:             next if ($entry =~ /^rolesdef/);
 3968: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3969:         } else {
 3970:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3971:         }
 3972:         if (($tstart) && ($tstart<0)) { next; }
 3973:         my $status = 'active';
 3974:         if (($tend) && ($tend<=$now)) {
 3975:             $status = 'previous';
 3976:         } 
 3977:         if (($tstart) && ($now<$tstart)) {
 3978:             $status = 'future';
 3979:         }
 3980:         if (ref($types) eq 'ARRAY') {
 3981:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3982:                 next;
 3983:             } 
 3984:         } else {
 3985:             if ($status ne 'active') {
 3986:                 next;
 3987:             }
 3988:         }
 3989:         my ($rolecode,$username,$domain,$section,$area);
 3990:         if ($context eq 'userroles') {
 3991:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 3992:             (undef,$domain,$username,$section) = split(/\//,$area);
 3993:         } else {
 3994:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3995:         }
 3996:         if (ref($roledoms) eq 'ARRAY') {
 3997:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3998:                 next;
 3999:             }
 4000:         }
 4001:         if (ref($roles) eq 'ARRAY') {
 4002:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4003:                 if ($role =~ /^cr\//) {
 4004:                     if (!grep(/^cr$/,@{$roles})) {
 4005:                         next;
 4006:                     }
 4007:                 } elsif ($role =~ /^gr\//) {
 4008:                     if (!grep(/^gr$/,@{$roles})) {
 4009:                         next;
 4010:                     }
 4011:                 } else {
 4012:                     next;
 4013:                 }
 4014:             }
 4015:         }
 4016:         if ($hidepriv) {
 4017:             if ($context eq 'userroles') {
 4018:                 if ((&privileged($username,$domain)) &&
 4019:                     (!$nothide{$username.':'.$domain})) {
 4020:                     next;
 4021:                 }
 4022:             } else {
 4023:                 unless (ref($privileged{$domain}) eq 'HASH') {
 4024:                     my %dompersonnel =
 4025:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 4026:                     $privileged{$domain} = {};
 4027:                     if (keys(%dompersonnel)) {
 4028:                         foreach my $server (keys(%dompersonnel)) {
 4029:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 4030:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 4031:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 4032:                                     $privileged{$udom}{$uname} = $trole;
 4033:                                 }
 4034:                             }
 4035:                         }
 4036:                     }
 4037:                 }
 4038:                 if (exists($privileged{$domain}{$username})) {
 4039:                     if (!$nothide{$username.':'.$domain}) {
 4040:                         next;
 4041:                     }
 4042:                 }
 4043:             }
 4044:         }
 4045:         if ($withsec) {
 4046:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4047:                 $tstart.':'.$tend;
 4048:         } else {
 4049:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4050:         }
 4051:     }
 4052:     return %returnhash;
 4053: }
 4054: 
 4055: # ----------------------------------------------------- Frontpage Announcements
 4056: #
 4057: #
 4058: 
 4059: sub postannounce {
 4060:     my ($server,$text)=@_;
 4061:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4062:     unless ($text=~/\w/) { $text=''; }
 4063:     return &reply('setannounce:'.&escape($text),$server);
 4064: }
 4065: 
 4066: sub getannounce {
 4067: 
 4068:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4069: 	my $announcement='';
 4070: 	while (my $line = <$fh>) { $announcement .= $line; }
 4071: 	close($fh);
 4072: 	if ($announcement=~/\w/) { 
 4073: 	    return 
 4074:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4075:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4076: 	} else {
 4077: 	    return '';
 4078: 	}
 4079:     } else {
 4080: 	return '';
 4081:     }
 4082: }
 4083: 
 4084: # ---------------------------------------------------------- Course ID routines
 4085: # Deal with domain's nohist_courseid.db files
 4086: #
 4087: 
 4088: sub courseidput {
 4089:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4090:     return unless (ref($storehash) eq 'HASH');
 4091:     my $outcome;
 4092:     if ($caller eq 'timeonly') {
 4093:         my $cids = '';
 4094:         foreach my $item (keys(%$storehash)) {
 4095:             $cids.=&escape($item).'&';
 4096:         }
 4097:         $cids=~s/\&$//;
 4098:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4099:                           $coursehome);       
 4100:     } else {
 4101:         my $items = '';
 4102:         foreach my $item (keys(%$storehash)) {
 4103:             $items.= &escape($item).'='.
 4104:                      &freeze_escape($$storehash{$item}).'&';
 4105:         }
 4106:         $items=~s/\&$//;
 4107:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4108:                           $coursehome);
 4109:     }
 4110:     if ($outcome eq 'unknown_cmd') {
 4111:         my $what;
 4112:         foreach my $cid (keys(%$storehash)) {
 4113:             $what .= &escape($cid).'=';
 4114:             foreach my $item ('description','inst_code','owner','type') {
 4115:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4116:             }
 4117:             $what =~ s/\:$/&/;
 4118:         }
 4119:         $what =~ s/\&$//;  
 4120:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4121:     } else {
 4122:         return $outcome;
 4123:     }
 4124: }
 4125: 
 4126: sub courseiddump {
 4127:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4128:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4129:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4130:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4131:     my $as_hash = 1;
 4132:     my %returnhash;
 4133:     if (!$domfilter) { $domfilter=''; }
 4134:     my %libserv = &all_library();
 4135:     foreach my $tryserver (keys(%libserv)) {
 4136:         if ( (  $hostidflag == 1 
 4137: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4138: 	     || (!defined($hostidflag)) ) {
 4139: 
 4140: 	    if (($domfilter eq '') ||
 4141: 		(&host_domain($tryserver) eq $domfilter)) {
 4142:                 my $rep;
 4143:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4144:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4145:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4146:                                 &escape($descfilter), &escape($instcodefilter), 
 4147:                                 &escape($ownerfilter), &escape($coursefilter),
 4148:                                 &escape($typefilter), &escape($regexp_ok), 
 4149:                                 $as_hash, &escape($selfenrollonly), 
 4150:                                 &escape($catfilter), $showhidden, $caller, 
 4151:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4152:                                 &escape($createdbefore), &escape($createdafter), 
 4153:                                 &escape($creationcontext), $domcloner)));
 4154:                 } else {
 4155:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4156:                              $sincefilter.':'.&escape($descfilter).':'.
 4157:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4158:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4159:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4160:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4161:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4162:                              &escape($cc_clone).':'.$cloneonly.':'.
 4163:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4164:                              &escape($creationcontext).':'.$domcloner,
 4165:                              $tryserver);
 4166:                 }
 4167:                      
 4168:                 my @pairs=split(/\&/,$rep);
 4169:                 foreach my $item (@pairs) {
 4170:                     my ($key,$value)=split(/\=/,$item,2);
 4171:                     $key = &unescape($key);
 4172:                     next if ($key =~ /^error: 2 /);
 4173:                     my $result = &thaw_unescape($value);
 4174:                     if (ref($result) eq 'HASH') {
 4175:                         $returnhash{$key}=$result;
 4176:                     } else {
 4177:                         my @responses = split(/:/,$value);
 4178:                         my @items = ('description','inst_code','owner','type');
 4179:                         for (my $i=0; $i<@responses; $i++) {
 4180:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4181:                         }
 4182:                     }
 4183:                 }
 4184:             }
 4185:         }
 4186:     }
 4187:     return %returnhash;
 4188: }
 4189: 
 4190: sub courselastaccess {
 4191:     my ($cdom,$cnum,$hostidref) = @_;
 4192:     my %returnhash;
 4193:     if ($cdom && $cnum) {
 4194:         my $chome = &homeserver($cnum,$cdom);
 4195:         if ($chome ne 'no_host') {
 4196:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4197:             &extract_lastaccess(\%returnhash,$rep);
 4198:         }
 4199:     } else {
 4200:         if (!$cdom) { $cdom=''; }
 4201:         my %libserv = &all_library();
 4202:         foreach my $tryserver (keys(%libserv)) {
 4203:             if (ref($hostidref) eq 'ARRAY') {
 4204:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4205:             } 
 4206:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4207:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4208:                 &extract_lastaccess(\%returnhash,$rep);
 4209:             }
 4210:         }
 4211:     }
 4212:     return %returnhash;
 4213: }
 4214: 
 4215: sub extract_lastaccess {
 4216:     my ($returnhash,$rep) = @_;
 4217:     if (ref($returnhash) eq 'HASH') {
 4218:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4219:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4220:                  $rep eq '') {
 4221:             my @pairs=split(/\&/,$rep);
 4222:             foreach my $item (@pairs) {
 4223:                 my ($key,$value)=split(/\=/,$item,2);
 4224:                 $key = &unescape($key);
 4225:                 next if ($key =~ /^error: 2 /);
 4226:                 $returnhash->{$key} = &thaw_unescape($value);
 4227:             }
 4228:         }
 4229:     }
 4230:     return;
 4231: }
 4232: 
 4233: # ---------------------------------------------------------- DC e-mail
 4234: 
 4235: sub dcmailput {
 4236:     my ($domain,$msgid,$message,$server)=@_;
 4237:     my $status = &Apache::lonnet::critical(
 4238:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4239:        &escape($message),$server);
 4240:     return $status;
 4241: }
 4242: 
 4243: sub dcmaildump {
 4244:     my ($dom,$startdate,$enddate,$senders) = @_;
 4245:     my %returnhash=();
 4246: 
 4247:     if (defined(&domain($dom,'primary'))) {
 4248:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4249:                                                          &escape($enddate).':';
 4250: 	my @esc_senders=map { &escape($_)} @$senders;
 4251: 	$cmd.=&escape(join('&',@esc_senders));
 4252: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4253:             my ($key,$value) = split(/\=/,$line,2);
 4254:             if (($key) && ($value)) {
 4255:                 $returnhash{&unescape($key)} = &unescape($value);
 4256:             }
 4257:         }
 4258:     }
 4259:     return %returnhash;
 4260: }
 4261: # ---------------------------------------------------------- Domain roles
 4262: 
 4263: sub get_domain_roles {
 4264:     my ($dom,$roles,$startdate,$enddate)=@_;
 4265:     if ((!defined($startdate)) || ($startdate eq '')) {
 4266:         $startdate = '.';
 4267:     }
 4268:     if ((!defined($enddate)) || ($enddate eq '')) {
 4269:         $enddate = '.';
 4270:     }
 4271:     my $rolelist;
 4272:     if (ref($roles) eq 'ARRAY') {
 4273:         $rolelist = join(':',@{$roles});
 4274:     }
 4275:     my %personnel = ();
 4276: 
 4277:     my %servers = &get_servers($dom,'library');
 4278:     foreach my $tryserver (keys(%servers)) {
 4279: 	%{$personnel{$tryserver}}=();
 4280: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4281: 					    &escape($startdate).':'.
 4282: 					    &escape($enddate).':'.
 4283: 					    &escape($rolelist), $tryserver))) {
 4284: 	    my ($key,$value) = split(/\=/,$line,2);
 4285: 	    if (($key) && ($value)) {
 4286: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4287: 	    }
 4288: 	}
 4289:     }
 4290:     return %personnel;
 4291: }
 4292: 
 4293: # ----------------------------------------------------------- Interval timing 
 4294: 
 4295: {
 4296: # Caches needed for speedup of navmaps
 4297: # We don't want to cache this for very long at all (5 seconds at most)
 4298: # 
 4299: # The user for whom we cache
 4300: my $cachedkey='';
 4301: # The cached times for this user
 4302: my %cachedtimes=();
 4303: # When this was last done
 4304: my $cachedtime=();
 4305: 
 4306: sub load_all_first_access {
 4307:     my ($uname,$udom)=@_;
 4308:     if (($cachedkey eq $uname.':'.$udom) &&
 4309:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4310:         return;
 4311:     }
 4312:     $cachedtime=time;
 4313:     $cachedkey=$uname.':'.$udom;
 4314:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4315: }
 4316: 
 4317: sub get_first_access {
 4318:     my ($type,$argsymb,$argmap)=@_;
 4319:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4320:     if ($argsymb) { $symb=$argsymb; }
 4321:     my ($map,$id,$res)=&decode_symb($symb);
 4322:     if ($argmap) { $map = $argmap; }
 4323:     if ($type eq 'course') {
 4324: 	$res='course';
 4325:     } elsif ($type eq 'map') {
 4326: 	$res=&symbread($map);
 4327:     } else {
 4328: 	$res=$symb;
 4329:     }
 4330:     &load_all_first_access($uname,$udom);
 4331:     return $cachedtimes{"$courseid\0$res"};
 4332: }
 4333: 
 4334: sub set_first_access {
 4335:     my ($type,$interval)=@_;
 4336:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4337:     my ($map,$id,$res)=&decode_symb($symb);
 4338:     if ($type eq 'course') {
 4339: 	$res='course';
 4340:     } elsif ($type eq 'map') {
 4341: 	$res=&symbread($map);
 4342:     } else {
 4343: 	$res=$symb;
 4344:     }
 4345:     $cachedkey='';
 4346:     my $firstaccess=&get_first_access($type,$symb,$map);
 4347:     if (!$firstaccess) {
 4348:         my $start = time;
 4349: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4350:                           $udom,$uname);
 4351:         if ($putres eq 'ok') {
 4352:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4353:                  $udom,$uname); 
 4354:             &appenv(
 4355:                      {
 4356:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4357:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4358:                      }
 4359:                   );
 4360:         }
 4361:         return $putres;
 4362:     }
 4363:     return 'already_set';
 4364: }
 4365: }
 4366: # --------------------------------------------- Set Expire Date for Spreadsheet
 4367: 
 4368: sub expirespread {
 4369:     my ($uname,$udom,$stype,$usymb)=@_;
 4370:     my $cid=$env{'request.course.id'}; 
 4371:     if ($cid) {
 4372:        my $now=time;
 4373:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4374:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4375:                             $env{'course.'.$cid.'.num'}.
 4376: 	        	    ':nohist_expirationdates:'.
 4377:                             &escape($key).'='.$now,
 4378:                             $env{'course.'.$cid.'.home'})
 4379:     }
 4380:     return 'ok';
 4381: }
 4382: 
 4383: # ----------------------------------------------------- Devalidate Spreadsheets
 4384: 
 4385: sub devalidate {
 4386:     my ($symb,$uname,$udom)=@_;
 4387:     my $cid=$env{'request.course.id'}; 
 4388:     if ($cid) {
 4389:         # delete the stored spreadsheets for
 4390:         # - the student level sheet of this user in course's homespace
 4391:         # - the assessment level sheet for this resource 
 4392:         #   for this user in user's homespace
 4393: 	# - current conditional state info
 4394: 	my $key=$uname.':'.$udom.':';
 4395:         my $status=
 4396: 	    &del('nohist_calculatedsheets',
 4397: 		 [$key.'studentcalc:'],
 4398: 		 $env{'course.'.$cid.'.domain'},
 4399: 		 $env{'course.'.$cid.'.num'})
 4400: 		.' '.
 4401: 	    &del('nohist_calculatedsheets_'.$cid,
 4402: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4403:         unless ($status eq 'ok ok') {
 4404:            &logthis('Could not devalidate spreadsheet '.
 4405:                     $uname.' at '.$udom.' for '.
 4406: 		    $symb.': '.$status);
 4407:         }
 4408: 	&delenv('user.state.'.$cid);
 4409:     }
 4410: }
 4411: 
 4412: sub get_scalar {
 4413:     my ($string,$end) = @_;
 4414:     my $value;
 4415:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4416: 	$value = $1;
 4417:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4418: 	$value = $1;
 4419:     }
 4420:     return &unescape($value);
 4421: }
 4422: 
 4423: sub array2str {
 4424:   my (@array) = @_;
 4425:   my $result=&arrayref2str(\@array);
 4426:   $result=~s/^__ARRAY_REF__//;
 4427:   $result=~s/__END_ARRAY_REF__$//;
 4428:   return $result;
 4429: }
 4430: 
 4431: sub arrayref2str {
 4432:   my ($arrayref) = @_;
 4433:   my $result='__ARRAY_REF__';
 4434:   foreach my $elem (@$arrayref) {
 4435:     if(ref($elem) eq 'ARRAY') {
 4436:       $result.=&arrayref2str($elem).'&';
 4437:     } elsif(ref($elem) eq 'HASH') {
 4438:       $result.=&hashref2str($elem).'&';
 4439:     } elsif(ref($elem)) {
 4440:       #print("Got a ref of ".(ref($elem))." skipping.");
 4441:     } else {
 4442:       $result.=&escape($elem).'&';
 4443:     }
 4444:   }
 4445:   $result=~s/\&$//;
 4446:   $result .= '__END_ARRAY_REF__';
 4447:   return $result;
 4448: }
 4449: 
 4450: sub hash2str {
 4451:   my (%hash) = @_;
 4452:   my $result=&hashref2str(\%hash);
 4453:   $result=~s/^__HASH_REF__//;
 4454:   $result=~s/__END_HASH_REF__$//;
 4455:   return $result;
 4456: }
 4457: 
 4458: sub hashref2str {
 4459:   my ($hashref)=@_;
 4460:   my $result='__HASH_REF__';
 4461:   foreach my $key (sort(keys(%$hashref))) {
 4462:     if (ref($key) eq 'ARRAY') {
 4463:       $result.=&arrayref2str($key).'=';
 4464:     } elsif (ref($key) eq 'HASH') {
 4465:       $result.=&hashref2str($key).'=';
 4466:     } elsif (ref($key)) {
 4467:       $result.='=';
 4468:       #print("Got a ref of ".(ref($key))." skipping.");
 4469:     } else {
 4470: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4471:     }
 4472: 
 4473:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4474:       $result.=&arrayref2str($hashref->{$key}).'&';
 4475:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4476:       $result.=&hashref2str($hashref->{$key}).'&';
 4477:     } elsif(ref($hashref->{$key})) {
 4478:        $result.='&';
 4479:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4480:     } else {
 4481:       $result.=&escape($hashref->{$key}).'&';
 4482:     }
 4483:   }
 4484:   $result=~s/\&$//;
 4485:   $result .= '__END_HASH_REF__';
 4486:   return $result;
 4487: }
 4488: 
 4489: sub str2hash {
 4490:     my ($string)=@_;
 4491:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4492:     return %$hash;
 4493: }
 4494: 
 4495: sub str2hashref {
 4496:   my ($string) = @_;
 4497: 
 4498:   my %hash;
 4499: 
 4500:   if($string !~ /^__HASH_REF__/) {
 4501:       if (! ($string eq '' || !defined($string))) {
 4502: 	  $hash{'error'}='Not hash reference';
 4503:       }
 4504:       return (\%hash, $string);
 4505:   }
 4506: 
 4507:   $string =~ s/^__HASH_REF__//;
 4508: 
 4509:   while($string !~ /^__END_HASH_REF__/) {
 4510:       #key
 4511:       my $key='';
 4512:       if($string =~ /^__HASH_REF__/) {
 4513:           ($key, $string)=&str2hashref($string);
 4514:           if(defined($key->{'error'})) {
 4515:               $hash{'error'}='Bad data';
 4516:               return (\%hash, $string);
 4517:           }
 4518:       } elsif($string =~ /^__ARRAY_REF__/) {
 4519:           ($key, $string)=&str2arrayref($string);
 4520:           if($key->[0] eq 'Array reference error') {
 4521:               $hash{'error'}='Bad data';
 4522:               return (\%hash, $string);
 4523:           }
 4524:       } else {
 4525:           $string =~ s/^(.*?)=//;
 4526: 	  $key=&unescape($1);
 4527:       }
 4528:       $string =~ s/^=//;
 4529: 
 4530:       #value
 4531:       my $value='';
 4532:       if($string =~ /^__HASH_REF__/) {
 4533:           ($value, $string)=&str2hashref($string);
 4534:           if(defined($value->{'error'})) {
 4535:               $hash{'error'}='Bad data';
 4536:               return (\%hash, $string);
 4537:           }
 4538:       } elsif($string =~ /^__ARRAY_REF__/) {
 4539:           ($value, $string)=&str2arrayref($string);
 4540:           if($value->[0] eq 'Array reference error') {
 4541:               $hash{'error'}='Bad data';
 4542:               return (\%hash, $string);
 4543:           }
 4544:       } else {
 4545: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4546:       }
 4547:       $string =~ s/^&//;
 4548: 
 4549:       $hash{$key}=$value;
 4550:   }
 4551: 
 4552:   $string =~ s/^__END_HASH_REF__//;
 4553: 
 4554:   return (\%hash, $string);
 4555: }
 4556: 
 4557: sub str2array {
 4558:     my ($string)=@_;
 4559:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4560:     return @$array;
 4561: }
 4562: 
 4563: sub str2arrayref {
 4564:   my ($string) = @_;
 4565:   my @array;
 4566: 
 4567:   if($string !~ /^__ARRAY_REF__/) {
 4568:       if (! ($string eq '' || !defined($string))) {
 4569: 	  $array[0]='Array reference error';
 4570:       }
 4571:       return (\@array, $string);
 4572:   }
 4573: 
 4574:   $string =~ s/^__ARRAY_REF__//;
 4575: 
 4576:   while($string !~ /^__END_ARRAY_REF__/) {
 4577:       my $value='';
 4578:       if($string =~ /^__HASH_REF__/) {
 4579:           ($value, $string)=&str2hashref($string);
 4580:           if(defined($value->{'error'})) {
 4581:               $array[0] ='Array reference error';
 4582:               return (\@array, $string);
 4583:           }
 4584:       } elsif($string =~ /^__ARRAY_REF__/) {
 4585:           ($value, $string)=&str2arrayref($string);
 4586:           if($value->[0] eq 'Array reference error') {
 4587:               $array[0] ='Array reference error';
 4588:               return (\@array, $string);
 4589:           }
 4590:       } else {
 4591: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4592:       }
 4593:       $string =~ s/^&//;
 4594: 
 4595:       push(@array, $value);
 4596:   }
 4597: 
 4598:   $string =~ s/^__END_ARRAY_REF__//;
 4599: 
 4600:   return (\@array, $string);
 4601: }
 4602: 
 4603: # -------------------------------------------------------------------Temp Store
 4604: 
 4605: sub tmpreset {
 4606:   my ($symb,$namespace,$domain,$stuname) = @_;
 4607:   if (!$symb) {
 4608:     $symb=&symbread();
 4609:     if (!$symb) { $symb= $env{'request.url'}; }
 4610:   }
 4611:   $symb=escape($symb);
 4612: 
 4613:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4614:   $namespace=~s/\//\_/g;
 4615:   $namespace=~s/\W//g;
 4616: 
 4617:   if (!$domain) { $domain=$env{'user.domain'}; }
 4618:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4619:   if ($domain eq 'public' && $stuname eq 'public') {
 4620:       $stuname=$ENV{'REMOTE_ADDR'};
 4621:   }
 4622:   my $path=LONCAPA::tempdir();
 4623:   my %hash;
 4624:   if (tie(%hash,'GDBM_File',
 4625: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4626: 	  &GDBM_WRCREAT(),0640)) {
 4627:     foreach my $key (keys(%hash)) {
 4628:       if ($key=~ /:$symb/) {
 4629: 	delete($hash{$key});
 4630:       }
 4631:     }
 4632:   }
 4633: }
 4634: 
 4635: sub tmpstore {
 4636:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4637: 
 4638:   if (!$symb) {
 4639:     $symb=&symbread();
 4640:     if (!$symb) { $symb= $env{'request.url'}; }
 4641:   }
 4642:   $symb=escape($symb);
 4643: 
 4644:   if (!$namespace) {
 4645:     # I don't think we would ever want to store this for a course.
 4646:     # it seems this will only be used if we don't have a course.
 4647:     #$namespace=$env{'request.course.id'};
 4648:     #if (!$namespace) {
 4649:       $namespace=$env{'request.state'};
 4650:     #}
 4651:   }
 4652:   $namespace=~s/\//\_/g;
 4653:   $namespace=~s/\W//g;
 4654:   if (!$domain) { $domain=$env{'user.domain'}; }
 4655:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4656:   if ($domain eq 'public' && $stuname eq 'public') {
 4657:       $stuname=$ENV{'REMOTE_ADDR'};
 4658:   }
 4659:   my $now=time;
 4660:   my %hash;
 4661:   my $path=LONCAPA::tempdir();
 4662:   if (tie(%hash,'GDBM_File',
 4663: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4664: 	  &GDBM_WRCREAT(),0640)) {
 4665:     $hash{"version:$symb"}++;
 4666:     my $version=$hash{"version:$symb"};
 4667:     my $allkeys=''; 
 4668:     foreach my $key (keys(%$storehash)) {
 4669:       $allkeys.=$key.':';
 4670:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4671:     }
 4672:     $hash{"$version:$symb:timestamp"}=$now;
 4673:     $allkeys.='timestamp';
 4674:     $hash{"$version:keys:$symb"}=$allkeys;
 4675:     if (untie(%hash)) {
 4676:       return 'ok';
 4677:     } else {
 4678:       return "error:$!";
 4679:     }
 4680:   } else {
 4681:     return "error:$!";
 4682:   }
 4683: }
 4684: 
 4685: # -----------------------------------------------------------------Temp Restore
 4686: 
 4687: sub tmprestore {
 4688:   my ($symb,$namespace,$domain,$stuname) = @_;
 4689: 
 4690:   if (!$symb) {
 4691:     $symb=&symbread();
 4692:     if (!$symb) { $symb= $env{'request.url'}; }
 4693:   }
 4694:   $symb=escape($symb);
 4695: 
 4696:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4697: 
 4698:   if (!$domain) { $domain=$env{'user.domain'}; }
 4699:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4700:   if ($domain eq 'public' && $stuname eq 'public') {
 4701:       $stuname=$ENV{'REMOTE_ADDR'};
 4702:   }
 4703:   my %returnhash;
 4704:   $namespace=~s/\//\_/g;
 4705:   $namespace=~s/\W//g;
 4706:   my %hash;
 4707:   my $path=LONCAPA::tempdir();
 4708:   if (tie(%hash,'GDBM_File',
 4709: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4710: 	  &GDBM_READER(),0640)) {
 4711:     my $version=$hash{"version:$symb"};
 4712:     $returnhash{'version'}=$version;
 4713:     my $scope;
 4714:     for ($scope=1;$scope<=$version;$scope++) {
 4715:       my $vkeys=$hash{"$scope:keys:$symb"};
 4716:       my @keys=split(/:/,$vkeys);
 4717:       my $key;
 4718:       $returnhash{"$scope:keys"}=$vkeys;
 4719:       foreach $key (@keys) {
 4720: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4721: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4722:       }
 4723:     }
 4724:     if (!(untie(%hash))) {
 4725:       return "error:$!";
 4726:     }
 4727:   } else {
 4728:     return "error:$!";
 4729:   }
 4730:   return %returnhash;
 4731: }
 4732: 
 4733: # ----------------------------------------------------------------------- Store
 4734: 
 4735: sub store {
 4736:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4737:     my $home='';
 4738: 
 4739:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4740: 
 4741:     $symb=&symbclean($symb);
 4742:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4743: 
 4744:     if (!$domain) { $domain=$env{'user.domain'}; }
 4745:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4746: 
 4747:     &devalidate($symb,$stuname,$domain);
 4748: 
 4749:     $symb=escape($symb);
 4750:     if (!$namespace) { 
 4751:        unless ($namespace=$env{'request.course.id'}) { 
 4752:           return ''; 
 4753:        } 
 4754:     }
 4755:     if (!$home) { $home=$env{'user.home'}; }
 4756: 
 4757:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4758:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4759: 
 4760:     my $namevalue='';
 4761:     foreach my $key (keys(%$storehash)) {
 4762:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4763:     }
 4764:     $namevalue=~s/\&$//;
 4765:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4766:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4767: }
 4768: 
 4769: # -------------------------------------------------------------- Critical Store
 4770: 
 4771: sub cstore {
 4772:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4773:     my $home='';
 4774: 
 4775:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4776: 
 4777:     $symb=&symbclean($symb);
 4778:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4779: 
 4780:     if (!$domain) { $domain=$env{'user.domain'}; }
 4781:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4782: 
 4783:     &devalidate($symb,$stuname,$domain);
 4784: 
 4785:     $symb=escape($symb);
 4786:     if (!$namespace) { 
 4787:        unless ($namespace=$env{'request.course.id'}) { 
 4788:           return ''; 
 4789:        } 
 4790:     }
 4791:     if (!$home) { $home=$env{'user.home'}; }
 4792: 
 4793:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4794:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4795: 
 4796:     my $namevalue='';
 4797:     foreach my $key (keys(%$storehash)) {
 4798:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4799:     }
 4800:     $namevalue=~s/\&$//;
 4801:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4802:     return critical
 4803:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4804: }
 4805: 
 4806: # --------------------------------------------------------------------- Restore
 4807: 
 4808: sub restore {
 4809:     my ($symb,$namespace,$domain,$stuname) = @_;
 4810:     my $home='';
 4811: 
 4812:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4813: 
 4814:     if (!$symb) {
 4815:       unless ($symb=escape(&symbread())) { return ''; }
 4816:     } else {
 4817:       $symb=&escape(&symbclean($symb));
 4818:     }
 4819:     if (!$namespace) { 
 4820:        unless ($namespace=$env{'request.course.id'}) { 
 4821:           return ''; 
 4822:        } 
 4823:     }
 4824:     if (!$domain) { $domain=$env{'user.domain'}; }
 4825:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4826:     if (!$home) { $home=$env{'user.home'}; }
 4827:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4828: 
 4829:     my %returnhash=();
 4830:     foreach my $line (split(/\&/,$answer)) {
 4831: 	my ($name,$value)=split(/\=/,$line);
 4832:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4833:     }
 4834:     my $version;
 4835:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4836:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4837:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4838:        }
 4839:     }
 4840:     return %returnhash;
 4841: }
 4842: 
 4843: # ---------------------------------------------------------- Course Description
 4844: #
 4845: #  
 4846: 
 4847: sub coursedescription {
 4848:     my ($courseid,$args)=@_;
 4849:     $courseid=~s/^\///;
 4850:     $courseid=~s/\_/\//g;
 4851:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4852:     my $chome=&homeserver($cnum,$cdomain);
 4853:     my $normalid=$cdomain.'_'.$cnum;
 4854:     # need to always cache even if we get errors otherwise we keep 
 4855:     # trying and trying and trying to get the course description.
 4856:     my %envhash=();
 4857:     my %returnhash=();
 4858:     
 4859:     my $expiretime=600;
 4860:     if ($env{'request.course.id'} eq $normalid) {
 4861: 	$expiretime=120;
 4862:     }
 4863: 
 4864:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4865:     if (!$args->{'freshen_cache'}
 4866: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4867: 	foreach my $key (keys(%env)) {
 4868: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4869: 	    my ($setting) = $1;
 4870: 	    $returnhash{$setting} = $env{$key};
 4871: 	}
 4872: 	return %returnhash;
 4873:     }
 4874: 
 4875:     # get the data again
 4876: 
 4877:     if (!$args->{'one_time'}) {
 4878: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4879:     }
 4880: 
 4881:     if ($chome ne 'no_host') {
 4882:        %returnhash=&dump('environment',$cdomain,$cnum);
 4883:        if (!exists($returnhash{'con_lost'})) {
 4884: 	   my $username = $env{'user.name'}; # Defult username
 4885: 	   if(defined $args->{'user'}) {
 4886: 	       $username = $args->{'user'};
 4887: 	   }
 4888:            $returnhash{'home'}= $chome;
 4889: 	   $returnhash{'domain'} = $cdomain;
 4890: 	   $returnhash{'num'} = $cnum;
 4891:            if (!defined($returnhash{'type'})) {
 4892:                $returnhash{'type'} = 'Course';
 4893:            }
 4894:            while (my ($name,$value) = each %returnhash) {
 4895:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4896:            }
 4897:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4898:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4899: 	       $username.'_'.$cdomain.'_'.$cnum;
 4900:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4901:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4902:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4903:        }
 4904:     }
 4905:     if (!$args->{'one_time'}) {
 4906: 	&appenv(\%envhash);
 4907:     }
 4908:     return %returnhash;
 4909: }
 4910: 
 4911: sub update_released_required {
 4912:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4913:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4914:         $cid = $env{'request.course.id'};
 4915:         $cdom = $env{'course.'.$cid.'.domain'};
 4916:         $cnum = $env{'course.'.$cid.'.num'};
 4917:         $chome = $env{'course.'.$cid.'.home'};
 4918:     }
 4919:     if ($needsrelease) {
 4920:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4921:         my $needsupdate;
 4922:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4923:             $needsupdate = 1;
 4924:         } else {
 4925:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4926:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4927:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4928:                 $needsupdate = 1;
 4929:             }
 4930:         }
 4931:         if ($needsupdate) {
 4932:             my %needshash = (
 4933:                              'internal.releaserequired' => $needsrelease,
 4934:                             );
 4935:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4936:             if ($putresult eq 'ok') {
 4937:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4938:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4939:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4940:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4941:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4942:                 }
 4943:             }
 4944:         }
 4945:     }
 4946:     return;
 4947: }
 4948: 
 4949: # -------------------------------------------------See if a user is privileged
 4950: 
 4951: sub privileged {
 4952:     my ($username,$domain)=@_;
 4953: 
 4954:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4955:     my $now = time;
 4956: 
 4957:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4958:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4959:             if (($trole eq 'dc') || ($trole eq 'su')) {
 4960:                 return 1 unless ($tend && $tend < $now) 
 4961:                     or ($tstart && $tstart > $now);
 4962:             }
 4963: 	}
 4964: 
 4965:     return 0;
 4966: }
 4967: 
 4968: # -------------------------------------------------------- Get user privileges
 4969: 
 4970: sub rolesinit {
 4971:     my ($domain, $username) = @_;
 4972:     my %userroles = ('user.login.time' => time);
 4973:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 4974: 
 4975:     # firstaccess and timerinterval are related to timed maps/resources. 
 4976:     # also, blocking can be triggered by an activating timer
 4977:     # it's saved in the user's %env.
 4978:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 4979:     my %timerinterval = &dump('timerinterval', $domain, $username);
 4980:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 4981:         %timerintchk, %timerintenv);
 4982: 
 4983:     foreach my $key (keys(%firstaccess)) {
 4984:         my ($cid, $rest) = split(/\0/, $key);
 4985:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4986:     }
 4987: 
 4988:     foreach my $key (keys(%timerinterval)) {
 4989:         my ($cid,$rest) = split(/\0/,$key);
 4990:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4991:     }
 4992: 
 4993:     my %allroles=();
 4994:     my %allgroups=();
 4995: 
 4996:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 4997:         my $role = $rolesdump{$area};
 4998:         $area =~ s/\_\w\w$//;
 4999: 
 5000:         my ($trole, $tend, $tstart, $group_privs);
 5001: 
 5002:         if ($role =~ /^cr/) {
 5003:         # Custom role, defined by a user 
 5004:         # e.g., user.role.cr/msu/smith/mynewrole
 5005:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5006:                 $trole = $1;
 5007:                 ($tend, $tstart) = split('_', $2);
 5008:             } else {
 5009:                 $trole = $role;
 5010:             }
 5011:         } elsif ($role =~ m|^gr/|) {
 5012:         # Role of member in a group, defined within a course/community
 5013:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5014:             ($trole, $tend, $tstart) = split(/_/, $role);
 5015:             next if $tstart eq '-1';
 5016:             ($trole, $group_privs) = split(/\//, $trole);
 5017:             $group_privs = &unescape($group_privs);
 5018:         } else {
 5019:         # Just a normal role, defined in roles.tab
 5020:             ($trole, $tend, $tstart) = split(/_/,$role);
 5021:         }
 5022: 
 5023:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5024:                  $username);
 5025:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5026: 
 5027:         # role expired or not available yet?
 5028:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5029:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5030: 
 5031:         next if $area eq '' or $trole eq '';
 5032: 
 5033:         my $spec = "$trole.$area";
 5034:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5035: 
 5036:         if ($trole =~ /^cr\//) {
 5037:         # Custom role, defined by a user
 5038:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5039:         } elsif ($trole eq 'gr') {
 5040:         # Role of a member in a group, defined within a course/community
 5041:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5042:             next;
 5043:         } else {
 5044:         # Normal role, defined in roles.tab
 5045:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5046:         }
 5047: 
 5048:         my $cid = $tdomain.'_'.$trest;
 5049:         unless ($firstaccchk{$cid}) {
 5050:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5051:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5052:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5053:                         $coursetimerstarts{$cid}{$item}; 
 5054:                 }
 5055:             }
 5056:             $firstaccchk{$cid} = 1;
 5057:         }
 5058:         unless ($timerintchk{$cid}) {
 5059:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5060:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5061:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5062:                        $coursetimerintervals{$cid}{$item};
 5063:                 }
 5064:             }
 5065:             $timerintchk{$cid} = 1;
 5066:         }
 5067:     }
 5068: 
 5069:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5070:         \%allroles, \%allgroups);
 5071:     $env{'user.adv'} = $userroles{'user.adv'};
 5072: 
 5073:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5074: }
 5075: 
 5076: sub set_arearole {
 5077:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5078:     unless ($nolog) {
 5079: # log the associated role with the area
 5080:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5081:     }
 5082:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5083: }
 5084: 
 5085: sub custom_roleprivs {
 5086:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5087:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5088:     my $homsvr=homeserver($rauthor,$rdomain);
 5089:     if (&hostname($homsvr) ne '') {
 5090:         my ($rdummy,$roledef)=
 5091:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5092:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5093:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5094:             if (defined($syspriv)) {
 5095:                 if ($trest =~ /^$match_community$/) {
 5096:                     $syspriv =~ s/bre\&S//; 
 5097:                 }
 5098:                 $$allroles{'cm./'}.=':'.$syspriv;
 5099:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5100:             }
 5101:             if ($tdomain ne '') {
 5102:                 if (defined($dompriv)) {
 5103:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5104:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5105:                 }
 5106:                 if (($trest ne '') && (defined($coursepriv))) {
 5107:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5108:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5109:                 }
 5110:             }
 5111:         }
 5112:     }
 5113: }
 5114: 
 5115: sub group_roleprivs {
 5116:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5117:     my $access = 1;
 5118:     my $now = time;
 5119:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5120:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5121:     if ($access) {
 5122:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5123:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5124:     }
 5125: }
 5126: 
 5127: sub standard_roleprivs {
 5128:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5129:     if (defined($pr{$trole.':s'})) {
 5130:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5131:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5132:     }
 5133:     if ($tdomain ne '') {
 5134:         if (defined($pr{$trole.':d'})) {
 5135:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5136:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5137:         }
 5138:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5139:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5140:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5141:         }
 5142:     }
 5143: }
 5144: 
 5145: sub set_userprivs {
 5146:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5147:     my $author=0;
 5148:     my $adv=0;
 5149:     my %grouproles = ();
 5150:     if (keys(%{$allgroups}) > 0) {
 5151:         my @groupkeys; 
 5152:         foreach my $role (keys(%{$allroles})) {
 5153:             push(@groupkeys,$role);
 5154:         }
 5155:         if (ref($groups_roles) eq 'HASH') {
 5156:             foreach my $key (keys(%{$groups_roles})) {
 5157:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5158:                     push(@groupkeys,$key);
 5159:                 }
 5160:             }
 5161:         }
 5162:         if (@groupkeys > 0) {
 5163:             foreach my $role (@groupkeys) {
 5164:                 my ($trole,$area,$sec,$extendedarea);
 5165:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5166:                     $trole = $1;
 5167:                     $area = $2;
 5168:                     $sec = $3;
 5169:                     $extendedarea = $area.$sec;
 5170:                     if (exists($$allgroups{$area})) {
 5171:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5172:                             my $spec = $trole.'.'.$extendedarea;
 5173:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5174:                                                 $$allgroups{$area}{$group};
 5175:                         }
 5176:                     }
 5177:                 }
 5178:             }
 5179:         }
 5180:     }
 5181:     foreach my $group (keys(%grouproles)) {
 5182:         $$allroles{$group} = $grouproles{$group};
 5183:     }
 5184:     foreach my $role (keys(%{$allroles})) {
 5185:         my %thesepriv;
 5186:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5187:         foreach my $item (split(/:/,$$allroles{$role})) {
 5188:             if ($item ne '') {
 5189:                 my ($privilege,$restrictions)=split(/&/,$item);
 5190:                 if ($restrictions eq '') {
 5191:                     $thesepriv{$privilege}='F';
 5192:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5193:                     $thesepriv{$privilege}.=$restrictions;
 5194:                 }
 5195:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5196:             }
 5197:         }
 5198:         my $thesestr='';
 5199:         foreach my $priv (sort(keys(%thesepriv))) {
 5200: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5201: 	}
 5202:         $userroles->{'user.priv.'.$role} = $thesestr;
 5203:     }
 5204:     return ($author,$adv);
 5205: }
 5206: 
 5207: sub role_status {
 5208:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5209:     my @pwhere = ();
 5210:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5211:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5212:         unless (!defined($$role) || $$role eq '') {
 5213:             $$where=join('.',@pwhere);
 5214:             $$trolecode=$$role.'.'.$$where;
 5215:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5216:             $$tstatus='is';
 5217:             if ($$tstart && $$tstart>$update) {
 5218:                 $$tstatus='future';
 5219:                 if ($$tstart<$now) {
 5220:                     if ($$tstart && $$tstart>$refresh) {
 5221:                         if (($$where ne '') && ($$role ne '')) {
 5222:                             my (%allroles,%allgroups,$group_privs,
 5223:                                 %groups_roles,@rolecodes);
 5224:                             my %userroles = (
 5225:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5226:                             );
 5227:                             @rolecodes = ('cm'); 
 5228:                             my $spec=$$role.'.'.$$where;
 5229:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5230:                             if ($$role =~ /^cr\//) {
 5231:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5232:                                 push(@rolecodes,'cr');
 5233:                             } elsif ($$role eq 'gr') {
 5234:                                 push(@rolecodes,$$role);
 5235:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5236:                                                     $env{'user.name'});
 5237:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5238:                                 (undef,my $group_privs) = split(/\//,$trole);
 5239:                                 $group_privs = &unescape($group_privs);
 5240:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5241:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5242:                                 &get_groups_roles($tdomain,$trest,
 5243:                                                   \%course_roles,\@rolecodes,
 5244:                                                   \%groups_roles);
 5245:                             } else {
 5246:                                 push(@rolecodes,$$role);
 5247:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5248:                             }
 5249:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5250:                             &appenv(\%userroles,\@rolecodes);
 5251:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5252:                         }
 5253:                     }
 5254:                     $$tstatus = 'is';
 5255:                 }
 5256:             }
 5257:             if ($$tend) {
 5258:                 if ($$tend<$update) {
 5259:                     $$tstatus='expired';
 5260:                 } elsif ($$tend<$now) {
 5261:                     $$tstatus='will_not';
 5262:                 }
 5263:             }
 5264:         }
 5265:     }
 5266: }
 5267: 
 5268: sub get_groups_roles {
 5269:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5270:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5271:                   (ref($rolecodes) eq 'ARRAY') && 
 5272:                   (ref($groups_roles) eq 'HASH')); 
 5273:     if (keys(%{$cdom_courseroles}) > 0) {
 5274:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5275:         if ($cdom ne '' && $cnum ne '') {
 5276:             foreach my $key (keys(%{$cdom_courseroles})) {
 5277:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5278:                     my $crsrole = $1;
 5279:                     my $crssec = $2;
 5280:                     if ($crsrole =~ /^cr/) {
 5281:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5282:                             push(@{$rolecodes},'cr');
 5283:                         }
 5284:                     } else {
 5285:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5286:                             push(@{$rolecodes},$crsrole);
 5287:                         }
 5288:                     }
 5289:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5290:                     if ($crssec ne '') {
 5291:                         $rolekey .= "/$crssec";
 5292:                     }
 5293:                     $rolekey .= './';
 5294:                     $groups_roles->{$rolekey} = $rolecodes;
 5295:                 }
 5296:             }
 5297:         }
 5298:     }
 5299:     return;
 5300: }
 5301: 
 5302: sub delete_env_groupprivs {
 5303:     my ($where,$courseroles,$possroles) = @_;
 5304:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5305:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5306:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5307:         %{$courseroles->{$udom}} =
 5308:             &get_my_roles('','','userroles',['active'],
 5309:                           $possroles,[$udom],1);
 5310:     }
 5311:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5312:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5313:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5314:             my $area = '/'.$cdom.'/'.$cnum;
 5315:             my $privkey = "user.priv.$crsrole.$area";
 5316:             if ($crssec ne '') {
 5317:                 $privkey .= '/'.$crssec;
 5318:             }
 5319:             $privkey .= ".$area/$group";
 5320:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5321:         }
 5322:     }
 5323:     return;
 5324: }
 5325: 
 5326: sub check_adhoc_privs {
 5327:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5328:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5329:     my $setprivs;
 5330:     if ($env{$cckey}) {
 5331:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5332:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5333:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5334:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5335:             $setprivs = 1;
 5336:         }
 5337:     } else {
 5338:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5339:         $setprivs = 1;
 5340:     }
 5341:     return $setprivs;
 5342: }
 5343: 
 5344: sub set_adhoc_privileges {
 5345: # role can be cc or ca
 5346:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5347:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5348:     my $spec = $role.'.'.$area;
 5349:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5350:                                   $env{'user.name'},1);
 5351:     my %ccrole = ();
 5352:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5353:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5354:     &appenv(\%userroles,[$role,'cm']);
 5355:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5356:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5357:         &appenv( {'request.role'        => $spec,
 5358:                   'request.role.domain' => $dcdom,
 5359:                   'request.course.sec'  => ''
 5360:                  }
 5361:                );
 5362:         my $tadv=0;
 5363:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5364:         &appenv({'request.role.adv'    => $tadv});
 5365:     }
 5366: }
 5367: 
 5368: # --------------------------------------------------------------- get interface
 5369: 
 5370: sub get {
 5371:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5372:    my $items='';
 5373:    foreach my $item (@$storearr) {
 5374:        $items.=&escape($item).'&';
 5375:    }
 5376:    $items=~s/\&$//;
 5377:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5378:    if (!$uname) { $uname=$env{'user.name'}; }
 5379:    my $uhome=&homeserver($uname,$udomain);
 5380: 
 5381:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5382:    my @pairs=split(/\&/,$rep);
 5383:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5384:      return @pairs;
 5385:    }
 5386:    my %returnhash=();
 5387:    my $i=0;
 5388:    foreach my $item (@$storearr) {
 5389:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5390:       $i++;
 5391:    }
 5392:    return %returnhash;
 5393: }
 5394: 
 5395: # --------------------------------------------------------------- del interface
 5396: 
 5397: sub del {
 5398:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5399:    my $items='';
 5400:    foreach my $item (@$storearr) {
 5401:        $items.=&escape($item).'&';
 5402:    }
 5403: 
 5404:    $items=~s/\&$//;
 5405:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5406:    if (!$uname) { $uname=$env{'user.name'}; }
 5407:    my $uhome=&homeserver($uname,$udomain);
 5408:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5409: }
 5410: 
 5411: # -------------------------------------------------------------- dump interface
 5412: 
 5413: sub unserialize {
 5414:     my ($rep, $escapedkeys) = @_;
 5415: 
 5416:     return {} if $rep =~ /^error/;
 5417: 
 5418:     my %returnhash=();
 5419: 	foreach my $item (split /\&/, $rep) {
 5420: 	    my ($key, $value) = split(/=/, $item, 2);
 5421: 	    $key = unescape($key) unless $escapedkeys;
 5422: 	    next if $key =~ /^error: 2 /;
 5423: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5424: 	}
 5425:     #return %returnhash;
 5426:     return \%returnhash;
 5427: }        
 5428: 
 5429: # see Lond::dump_with_regexp
 5430: # if $escapedkeys hash keys won't get unescaped.
 5431: sub dump {
 5432:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5433:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5434:     if (!$uname) { $uname=$env{'user.name'}; }
 5435:     my $uhome=&homeserver($uname,$udomain);
 5436: 
 5437:     my $reply;
 5438:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5439:         # user is hosted on this machine
 5440:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5441:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
 5442:         return %{unserialize($reply, $escapedkeys)};
 5443:     }
 5444:     if ($regexp) {
 5445: 	$regexp=&escape($regexp);
 5446:     } else {
 5447: 	$regexp='.';
 5448:     }
 5449:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5450:     my @pairs=split(/\&/,$rep);
 5451:     my %returnhash=();
 5452:     if (!($rep =~ /^error/ )) {
 5453: 	foreach my $item (@pairs) {
 5454: 	    my ($key,$value)=split(/=/,$item,2);
 5455:         $key = unescape($key) unless $escapedkeys;
 5456:         #$key = &unescape($key);
 5457: 	    next if ($key =~ /^error: 2 /);
 5458: 	    $returnhash{$key}=&thaw_unescape($value);
 5459: 	}
 5460:     }
 5461:     return %returnhash;
 5462: }
 5463: 
 5464: 
 5465: # --------------------------------------------------------- dumpstore interface
 5466: 
 5467: sub dumpstore {
 5468:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5469:    # same as dump but keys must be escaped. They may contain colon separated
 5470:    # lists of values that may themself contain colons (e.g. symbs).
 5471:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5472: }
 5473: 
 5474: # -------------------------------------------------------------- keys interface
 5475: 
 5476: sub getkeys {
 5477:    my ($namespace,$udomain,$uname)=@_;
 5478:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5479:    if (!$uname) { $uname=$env{'user.name'}; }
 5480:    my $uhome=&homeserver($uname,$udomain);
 5481:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5482:    my @keyarray=();
 5483:    foreach my $key (split(/\&/,$rep)) {
 5484:       next if ($key =~ /^error: 2 /);
 5485:       push(@keyarray,&unescape($key));
 5486:    }
 5487:    return @keyarray;
 5488: }
 5489: 
 5490: # --------------------------------------------------------------- currentdump
 5491: sub currentdump {
 5492:    my ($courseid,$sdom,$sname)=@_;
 5493:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5494:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5495:    $sname    = $env{'user.name'}         if (! defined($sname));
 5496:    my $uhome = &homeserver($sname,$sdom);
 5497:    my $rep;
 5498: 
 5499:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5500:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5501:                    $courseid)));
 5502:    } else {
 5503:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5504:    }
 5505: 
 5506:    return if ($rep =~ /^(error:|no_such_host)/);
 5507:    #
 5508:    my %returnhash=();
 5509:    #
 5510:    if ($rep eq "unknown_cmd") { 
 5511:        # an old lond will not know currentdump
 5512:        # Do a dump and make it look like a currentdump
 5513:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5514:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5515:        my %hash = @tmp;
 5516:        @tmp=();
 5517:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5518:    } else {
 5519:        my @pairs=split(/\&/,$rep);
 5520:        foreach my $pair (@pairs) {
 5521:            my ($key,$value)=split(/=/,$pair,2);
 5522:            my ($symb,$param) = split(/:/,$key);
 5523:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5524:                                                         &thaw_unescape($value);
 5525:        }
 5526:    }
 5527:    return %returnhash;
 5528: }
 5529: 
 5530: sub convert_dump_to_currentdump{
 5531:     my %hash = %{shift()};
 5532:     my %returnhash;
 5533:     # Code ripped from lond, essentially.  The only difference
 5534:     # here is the unescaping done by lonnet::dump().  Conceivably
 5535:     # we might run in to problems with parameter names =~ /^v\./
 5536:     while (my ($key,$value) = each(%hash)) {
 5537:         my ($v,$symb,$param) = split(/:/,$key);
 5538: 	$symb  = &unescape($symb);
 5539: 	$param = &unescape($param);
 5540:         next if ($v eq 'version' || $symb eq 'keys');
 5541:         next if (exists($returnhash{$symb}) &&
 5542:                  exists($returnhash{$symb}->{$param}) &&
 5543:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5544:         $returnhash{$symb}->{$param}=$value;
 5545:         $returnhash{$symb}->{'v.'.$param}=$v;
 5546:     }
 5547:     #
 5548:     # Remove all of the keys in the hashes which keep track of
 5549:     # the version of the parameter.
 5550:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5551:         # use a foreach because we are going to delete from the hash.
 5552:         foreach my $key (keys(%$param_hash)) {
 5553:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5554:         }
 5555:     }
 5556:     return \%returnhash;
 5557: }
 5558: 
 5559: # ------------------------------------------------------ critical inc interface
 5560: 
 5561: sub cinc {
 5562:     return &inc(@_,'critical');
 5563: }
 5564: 
 5565: # --------------------------------------------------------------- inc interface
 5566: 
 5567: sub inc {
 5568:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5569:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5570:     if (!$uname) { $uname=$env{'user.name'}; }
 5571:     my $uhome=&homeserver($uname,$udomain);
 5572:     my $items='';
 5573:     if (! ref($store)) {
 5574:         # got a single value, so use that instead
 5575:         $items = &escape($store).'=&';
 5576:     } elsif (ref($store) eq 'SCALAR') {
 5577:         $items = &escape($$store).'=&';        
 5578:     } elsif (ref($store) eq 'ARRAY') {
 5579:         $items = join('=&',map {&escape($_);} @{$store});
 5580:     } elsif (ref($store) eq 'HASH') {
 5581:         while (my($key,$value) = each(%{$store})) {
 5582:             $items.= &escape($key).'='.&escape($value).'&';
 5583:         }
 5584:     }
 5585:     $items=~s/\&$//;
 5586:     if ($critical) {
 5587: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5588:     } else {
 5589: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5590:     }
 5591: }
 5592: 
 5593: # --------------------------------------------------------------- put interface
 5594: 
 5595: sub put {
 5596:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5597:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5598:    if (!$uname) { $uname=$env{'user.name'}; }
 5599:    my $uhome=&homeserver($uname,$udomain);
 5600:    my $items='';
 5601:    foreach my $item (keys(%$storehash)) {
 5602:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5603:    }
 5604:    $items=~s/\&$//;
 5605:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5606: }
 5607: 
 5608: # ------------------------------------------------------------ newput interface
 5609: 
 5610: sub newput {
 5611:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5612:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5613:    if (!$uname) { $uname=$env{'user.name'}; }
 5614:    my $uhome=&homeserver($uname,$udomain);
 5615:    my $items='';
 5616:    foreach my $key (keys(%$storehash)) {
 5617:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5618:    }
 5619:    $items=~s/\&$//;
 5620:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5621: }
 5622: 
 5623: # ---------------------------------------------------------  putstore interface
 5624: 
 5625: sub putstore {
 5626:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5627:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5628:    if (!$uname) { $uname=$env{'user.name'}; }
 5629:    my $uhome=&homeserver($uname,$udomain);
 5630:    my $items='';
 5631:    foreach my $key (keys(%$storehash)) {
 5632:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5633:    }
 5634:    $items=~s/\&$//;
 5635:    my $esc_symb=&escape($symb);
 5636:    my $esc_v=&escape($version);
 5637:    my $reply =
 5638:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5639: 	      $uhome);
 5640:    if ($reply eq 'unknown_cmd') {
 5641:        # gfall back to way things use to be done
 5642:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5643: 			    $uname);
 5644:    }
 5645:    return $reply;
 5646: }
 5647: 
 5648: sub old_putstore {
 5649:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5650:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5651:     if (!$uname) { $uname=$env{'user.name'}; }
 5652:     my $uhome=&homeserver($uname,$udomain);
 5653:     my %newstorehash;
 5654:     foreach my $item (keys(%$storehash)) {
 5655: 	my $key = $version.':'.&escape($symb).':'.$item;
 5656: 	$newstorehash{$key} = $storehash->{$item};
 5657:     }
 5658:     my $items='';
 5659:     my %allitems = ();
 5660:     foreach my $item (keys(%newstorehash)) {
 5661: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5662: 	    my $key = $1.':keys:'.$2;
 5663: 	    $allitems{$key} .= $3.':';
 5664: 	}
 5665: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5666:     }
 5667:     foreach my $item (keys(%allitems)) {
 5668: 	$allitems{$item} =~ s/\:$//;
 5669: 	$items.= $item.'='.$allitems{$item}.'&';
 5670:     }
 5671:     $items=~s/\&$//;
 5672:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5673: }
 5674: 
 5675: # ------------------------------------------------------ critical put interface
 5676: 
 5677: sub cput {
 5678:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5679:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5680:    if (!$uname) { $uname=$env{'user.name'}; }
 5681:    my $uhome=&homeserver($uname,$udomain);
 5682:    my $items='';
 5683:    foreach my $item (keys(%$storehash)) {
 5684:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5685:    }
 5686:    $items=~s/\&$//;
 5687:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5688: }
 5689: 
 5690: # -------------------------------------------------------------- eget interface
 5691: 
 5692: sub eget {
 5693:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5694:    my $items='';
 5695:    foreach my $item (@$storearr) {
 5696:        $items.=&escape($item).'&';
 5697:    }
 5698:    $items=~s/\&$//;
 5699:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5700:    if (!$uname) { $uname=$env{'user.name'}; }
 5701:    my $uhome=&homeserver($uname,$udomain);
 5702:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5703:    my @pairs=split(/\&/,$rep);
 5704:    my %returnhash=();
 5705:    my $i=0;
 5706:    foreach my $item (@$storearr) {
 5707:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5708:       $i++;
 5709:    }
 5710:    return %returnhash;
 5711: }
 5712: 
 5713: # ------------------------------------------------------------ tmpput interface
 5714: sub tmpput {
 5715:     my ($storehash,$server,$context)=@_;
 5716:     my $items='';
 5717:     foreach my $item (keys(%$storehash)) {
 5718: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5719:     }
 5720:     $items=~s/\&$//;
 5721:     if (defined($context)) {
 5722:         $items .= ':'.&escape($context);
 5723:     }
 5724:     return &reply("tmpput:$items",$server);
 5725: }
 5726: 
 5727: # ------------------------------------------------------------ tmpget interface
 5728: sub tmpget {
 5729:     my ($token,$server)=@_;
 5730:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5731:     my $rep=&reply("tmpget:$token",$server);
 5732:     my %returnhash;
 5733:     foreach my $item (split(/\&/,$rep)) {
 5734: 	my ($key,$value)=split(/=/,$item);
 5735:         next if ($key =~ /^error: 2 /);
 5736: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5737:     }
 5738:     return %returnhash;
 5739: }
 5740: 
 5741: # ------------------------------------------------------------ tmpdel interface
 5742: sub tmpdel {
 5743:     my ($token,$server)=@_;
 5744:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5745:     return &reply("tmpdel:$token",$server);
 5746: }
 5747: 
 5748: # ------------------------------------------------------------ get_timebased_id 
 5749: 
 5750: sub get_timebased_id {
 5751:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5752:         $maxtries) = @_;
 5753:     my ($newid,$error,$dellock);
 5754:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5755:         return ('','ok','invalid call to get suffix');
 5756:     }
 5757: 
 5758: # set defaults for any optional args for which values were not supplied
 5759:     if ($who eq '') {
 5760:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5761:     }
 5762:     if (!$locktries) {
 5763:         $locktries = 3;
 5764:     }
 5765:     if (!$maxtries) {
 5766:         $maxtries = 10;
 5767:     }
 5768:     
 5769:     if (($cdom eq '') || ($cnum eq '')) {
 5770:         if ($env{'request.course.id'}) {
 5771:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5772:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5773:         }
 5774:         if (($cdom eq '') || ($cnum eq '')) {
 5775:             return ('','ok','call to get suffix not in course context');
 5776:         }
 5777:     }
 5778: 
 5779: # construct locking item
 5780:     my $lockhash = {
 5781:                       $prefix."\0".'locked_'.$keyid => $who,
 5782:                    };
 5783:     my $tries = 0;
 5784: 
 5785: # attempt to get lock on nohist_$namespace file
 5786:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5787:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5788:         $tries ++;
 5789:         sleep 1;
 5790:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5791:     }
 5792: 
 5793: # attempt to get unique identifier, based on current timestamp
 5794:     if ($gotlock eq 'ok') {
 5795:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5796:         my $id = time;
 5797:         $newid = $id;
 5798:         my $idtries = 0;
 5799:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5800:             if ($idtype eq 'concat') {
 5801:                 $newid = $id.$idtries;
 5802:             } else {
 5803:                 $newid ++;
 5804:             }
 5805:             $idtries ++;
 5806:         }
 5807:         if (!exists($inuse{$prefix."\0".$newid})) {
 5808:             my %new_item =  (
 5809:                               $prefix."\0".$newid => $who,
 5810:                             );
 5811:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5812:                                                  $cdom,$cnum);
 5813:             if ($putresult ne 'ok') {
 5814:                 undef($newid);
 5815:                 $error = 'error saving new item: '.$putresult;
 5816:             }
 5817:         } else {
 5818:              $error = ('error: no unique suffix available for the new item ');
 5819:         }
 5820: #  remove lock
 5821:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5822:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5823:     } else {
 5824:         $error = "error: could not obtain lockfile\n";
 5825:         $dellock = 'ok';
 5826:     }
 5827:     return ($newid,$dellock,$error);
 5828: }
 5829: 
 5830: # -------------------------------------------------- portfolio access checking
 5831: 
 5832: sub portfolio_access {
 5833:     my ($requrl) = @_;
 5834:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5835:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5836:     if ($result) {
 5837:         my %setters;
 5838:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5839:             my ($startblock,$endblock) =
 5840:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5841:             if ($startblock && $endblock) {
 5842:                 return 'B';
 5843:             }
 5844:         } else {
 5845:             my ($startblock,$endblock) =
 5846:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5847:             if ($startblock && $endblock) {
 5848:                 return 'B';
 5849:             }
 5850:         }
 5851:     }
 5852:     if ($result eq 'ok') {
 5853:        return 'F';
 5854:     } elsif ($result =~ /^[^:]+:guest_/) {
 5855:        return 'A';
 5856:     }
 5857:     return '';
 5858: }
 5859: 
 5860: sub get_portfolio_access {
 5861:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5862: 
 5863:     if (!ref($access_hash)) {
 5864: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5865: 	my %access_controls = &get_access_controls($current_perms,$group,
 5866: 						   $file_name);
 5867: 	$access_hash = $access_controls{$file_name};
 5868:     }
 5869: 
 5870:     my ($public,$guest,@domains,@users,@courses,@groups);
 5871:     my $now = time;
 5872:     if (ref($access_hash) eq 'HASH') {
 5873:         foreach my $key (keys(%{$access_hash})) {
 5874:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5875:             if ($start > $now) {
 5876:                 next;
 5877:             }
 5878:             if ($end && $end<$now) {
 5879:                 next;
 5880:             }
 5881:             if ($scope eq 'public') {
 5882:                 $public = $key;
 5883:                 last;
 5884:             } elsif ($scope eq 'guest') {
 5885:                 $guest = $key;
 5886:             } elsif ($scope eq 'domains') {
 5887:                 push(@domains,$key);
 5888:             } elsif ($scope eq 'users') {
 5889:                 push(@users,$key);
 5890:             } elsif ($scope eq 'course') {
 5891:                 push(@courses,$key);
 5892:             } elsif ($scope eq 'group') {
 5893:                 push(@groups,$key);
 5894:             }
 5895:         }
 5896:         if ($public) {
 5897:             return 'ok';
 5898:         }
 5899:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5900:             if ($guest) {
 5901:                 return $guest;
 5902:             }
 5903:         } else {
 5904:             if (@domains > 0) {
 5905:                 foreach my $domkey (@domains) {
 5906:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5907:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5908:                             return 'ok';
 5909:                         }
 5910:                     }
 5911:                 }
 5912:             }
 5913:             if (@users > 0) {
 5914:                 foreach my $userkey (@users) {
 5915:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5916:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5917:                             if (ref($item) eq 'HASH') {
 5918:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5919:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5920:                                     return 'ok';
 5921:                                 }
 5922:                             }
 5923:                         }
 5924:                     } 
 5925:                 }
 5926:             }
 5927:             my %roleshash;
 5928:             my @courses_and_groups = @courses;
 5929:             push(@courses_and_groups,@groups); 
 5930:             if (@courses_and_groups > 0) {
 5931:                 my (%allgroups,%allroles); 
 5932:                 my ($start,$end,$role,$sec,$group);
 5933:                 foreach my $envkey (%env) {
 5934:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5935:                         my $cid = $2.'_'.$3; 
 5936:                         if ($1 eq 'gr') {
 5937:                             $group = $4;
 5938:                             $allgroups{$cid}{$group} = $env{$envkey};
 5939:                         } else {
 5940:                             if ($4 eq '') {
 5941:                                 $sec = 'none';
 5942:                             } else {
 5943:                                 $sec = $4;
 5944:                             }
 5945:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5946:                         }
 5947:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5948:                         my $cid = $2.'_'.$3;
 5949:                         if ($4 eq '') {
 5950:                             $sec = 'none';
 5951:                         } else {
 5952:                             $sec = $4;
 5953:                         }
 5954:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5955:                     }
 5956:                 }
 5957:                 if (keys(%allroles) == 0) {
 5958:                     return;
 5959:                 }
 5960:                 foreach my $key (@courses_and_groups) {
 5961:                     my %content = %{$$access_hash{$key}};
 5962:                     my $cnum = $content{'number'};
 5963:                     my $cdom = $content{'domain'};
 5964:                     my $cid = $cdom.'_'.$cnum;
 5965:                     if (!exists($allroles{$cid})) {
 5966:                         next;
 5967:                     }    
 5968:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5969:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5970:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5971:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5972:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5973:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5974:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5975:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5976:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5977:                                         if (grep/^all$/,@sections) {
 5978:                                             return 'ok';
 5979:                                         } else {
 5980:                                             if (grep/^$sec$/,@sections) {
 5981:                                                 return 'ok';
 5982:                                             }
 5983:                                         }
 5984:                                     }
 5985:                                 }
 5986:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5987:                                     if (grep/^none$/,@groups) {
 5988:                                         return 'ok';
 5989:                                     }
 5990:                                 } else {
 5991:                                     if (grep/^all$/,@groups) {
 5992:                                         return 'ok';
 5993:                                     } 
 5994:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5995:                                         if (grep/^$group$/,@groups) {
 5996:                                             return 'ok';
 5997:                                         }
 5998:                                     }
 5999:                                 } 
 6000:                             }
 6001:                         }
 6002:                     }
 6003:                 }
 6004:             }
 6005:             if ($guest) {
 6006:                 return $guest;
 6007:             }
 6008:         }
 6009:     }
 6010:     return;
 6011: }
 6012: 
 6013: sub course_group_datechecker {
 6014:     my ($dates,$now,$status) = @_;
 6015:     my ($start,$end) = split(/\./,$dates);
 6016:     if (!$start && !$end) {
 6017:         return 'ok';
 6018:     }
 6019:     if (grep/^active$/,@{$status}) {
 6020:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6021:             return 'ok';
 6022:         }
 6023:     }
 6024:     if (grep/^previous$/,@{$status}) {
 6025:         if ($end > $now ) {
 6026:             return 'ok';
 6027:         }
 6028:     }
 6029:     if (grep/^future$/,@{$status}) {
 6030:         if ($start > $now) {
 6031:             return 'ok';
 6032:         }
 6033:     }
 6034:     return; 
 6035: }
 6036: 
 6037: sub parse_portfolio_url {
 6038:     my ($url) = @_;
 6039: 
 6040:     my ($type,$udom,$unum,$group,$file_name);
 6041:     
 6042:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6043: 	$type = 1;
 6044:         $udom = $1;
 6045:         $unum = $2;
 6046:         $file_name = $3;
 6047:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6048: 	$type = 2;
 6049:         $udom = $1;
 6050:         $unum = $2;
 6051:         $group = $3;
 6052:         $file_name = $3.'/'.$4;
 6053:     }
 6054:     if (wantarray) {
 6055: 	return ($type,$udom,$unum,$file_name,$group);
 6056:     }
 6057:     return $type;
 6058: }
 6059: 
 6060: sub is_portfolio_url {
 6061:     my ($url) = @_;
 6062:     return scalar(&parse_portfolio_url($url));
 6063: }
 6064: 
 6065: sub is_portfolio_file {
 6066:     my ($file) = @_;
 6067:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6068:         return 1;
 6069:     }
 6070:     return;
 6071: }
 6072: 
 6073: sub usertools_access {
 6074:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6075:     my ($access,%tools);
 6076:     if ($context eq '') {
 6077:         $context = 'tools';
 6078:     }
 6079:     if ($context eq 'requestcourses') {
 6080:         %tools = (
 6081:                       official   => 1,
 6082:                       unofficial => 1,
 6083:                       community  => 1,
 6084:                  );
 6085:     } elsif ($context eq 'requestauthor') {
 6086:         %tools = (
 6087:                       requestauthor => 1,
 6088:                  );
 6089:     } else {
 6090:         %tools = (
 6091:                       aboutme   => 1,
 6092:                       blog      => 1,
 6093:                       webdav    => 1,
 6094:                       portfolio => 1,
 6095:                  );
 6096:     }
 6097:     return if (!defined($tools{$tool}));
 6098: 
 6099:     if ((!defined($udom)) || (!defined($uname))) {
 6100:         $udom = $env{'user.domain'};
 6101:         $uname = $env{'user.name'};
 6102:     }
 6103: 
 6104:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6105:         if ($action ne 'reload') {
 6106:             if ($context eq 'requestcourses') {
 6107:                 return $env{'environment.canrequest.'.$tool};
 6108:             } elsif ($context eq 'requestauthor') {
 6109:                 return $env{'environment.canrequest.author'};
 6110:             } else {
 6111:                 return $env{'environment.availabletools.'.$tool};
 6112:             }
 6113:         }
 6114:     }
 6115: 
 6116:     my ($toolstatus,$inststatus,$envkey);
 6117:     if ($context eq 'requestauthor') {
 6118:         $envkey = $context; 
 6119:     } else {
 6120:         $envkey = $context.'.'.$tool;
 6121:     }
 6122: 
 6123:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6124:          ($action ne 'reload')) {
 6125:         $toolstatus = $env{'environment.'.$envkey};
 6126:         $inststatus = $env{'environment.inststatus'};
 6127:     } else {
 6128:         if (ref($userenvref) eq 'HASH') {
 6129:             $toolstatus = $userenvref->{$envkey};
 6130:             $inststatus = $userenvref->{'inststatus'};
 6131:         } else {
 6132:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6133:             $toolstatus = $userenv{$envkey};
 6134:             $inststatus = $userenv{'inststatus'};
 6135:         }
 6136:     }
 6137: 
 6138:     if ($toolstatus ne '') {
 6139:         if ($toolstatus) {
 6140:             $access = 1;
 6141:         } else {
 6142:             $access = 0;
 6143:         }
 6144:         return $access;
 6145:     }
 6146: 
 6147:     my ($is_adv,%domdef);
 6148:     if (ref($is_advref) eq 'HASH') {
 6149:         $is_adv = $is_advref->{'is_adv'};
 6150:     } else {
 6151:         $is_adv = &is_advanced_user($udom,$uname);
 6152:     }
 6153:     if (ref($domdefref) eq 'HASH') {
 6154:         %domdef = %{$domdefref};
 6155:     } else {
 6156:         %domdef = &get_domain_defaults($udom);
 6157:     }
 6158:     if (ref($domdef{$tool}) eq 'HASH') {
 6159:         if ($is_adv) {
 6160:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6161:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6162:                     $access = 1;
 6163:                 } else {
 6164:                     $access = 0;
 6165:                 }
 6166:                 return $access;
 6167:             }
 6168:         }
 6169:         if ($inststatus ne '') {
 6170:             my ($hasaccess,$hasnoaccess);
 6171:             foreach my $affiliation (split(/:/,$inststatus)) {
 6172:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6173:                     if ($domdef{$tool}{$affiliation}) {
 6174:                         $hasaccess = 1;
 6175:                     } else {
 6176:                         $hasnoaccess = 1;
 6177:                     }
 6178:                 }
 6179:             }
 6180:             if ($hasaccess || $hasnoaccess) {
 6181:                 if ($hasaccess) {
 6182:                     $access = 1;
 6183:                 } elsif ($hasnoaccess) {
 6184:                     $access = 0; 
 6185:                 }
 6186:                 return $access;
 6187:             }
 6188:         } else {
 6189:             if ($domdef{$tool}{'default'} ne '') {
 6190:                 if ($domdef{$tool}{'default'}) {
 6191:                     $access = 1;
 6192:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6193:                     $access = 0;
 6194:                 }
 6195:                 return $access;
 6196:             }
 6197:         }
 6198:     } else {
 6199:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6200:             $access = 1;
 6201:         } else {
 6202:             $access = 0;
 6203:         }
 6204:         return $access;
 6205:     }
 6206: }
 6207: 
 6208: sub is_course_owner {
 6209:     my ($cdom,$cnum,$udom,$uname) = @_;
 6210:     if (($udom eq '') || ($uname eq '')) {
 6211:         $udom = $env{'user.domain'};
 6212:         $uname = $env{'user.name'};
 6213:     }
 6214:     unless (($udom eq '') || ($uname eq '')) {
 6215:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6216:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6217:                 return 1;
 6218:             } else {
 6219:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6220:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6221:                     return 1;
 6222:                 }
 6223:             }
 6224:         }
 6225:     }
 6226:     return;
 6227: }
 6228: 
 6229: sub is_advanced_user {
 6230:     my ($udom,$uname) = @_;
 6231:     if ($udom ne '' && $uname ne '') {
 6232:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6233:             if (wantarray) {
 6234:                 return ($env{'user.adv'},$env{'user.author'});
 6235:             } else {
 6236:                 return $env{'user.adv'};
 6237:             }
 6238:         }
 6239:     }
 6240:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6241:     my %allroles;
 6242:     my ($is_adv,$is_author);
 6243:     foreach my $role (keys(%roleshash)) {
 6244:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6245:         my $area = '/'.$tdomain.'/'.$trest;
 6246:         if ($sec ne '') {
 6247:             $area .= '/'.$sec;
 6248:         }
 6249:         if (($area ne '') && ($trole ne '')) {
 6250:             my $spec=$trole.'.'.$area;
 6251:             if ($trole =~ /^cr\//) {
 6252:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6253:             } elsif ($trole ne 'gr') {
 6254:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6255:             }
 6256:             if ($trole eq 'au') {
 6257:                 $is_author = 1;
 6258:             }
 6259:         }
 6260:     }
 6261:     foreach my $role (keys(%allroles)) {
 6262:         last if ($is_adv);
 6263:         foreach my $item (split(/:/,$allroles{$role})) {
 6264:             if ($item ne '') {
 6265:                 my ($privilege,$restrictions)=split(/&/,$item);
 6266:                 if ($privilege eq 'adv') {
 6267:                     $is_adv = 1;
 6268:                     last;
 6269:                 }
 6270:             }
 6271:         }
 6272:     }
 6273:     if (wantarray) {
 6274:         return ($is_adv,$is_author);
 6275:     }
 6276:     return $is_adv;
 6277: }
 6278: 
 6279: sub check_can_request {
 6280:     my ($dom,$can_request,$request_domains) = @_;
 6281:     my $canreq = 0;
 6282:     my ($types,$typename) = &Apache::loncommon::course_types();
 6283:     my @options = ('approval','validate','autolimit');
 6284:     my $optregex = join('|',@options);
 6285:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6286:         foreach my $type (@{$types}) {
 6287:             if (&usertools_access($env{'user.name'},
 6288:                                   $env{'user.domain'},
 6289:                                   $type,undef,'requestcourses')) {
 6290:                 $canreq ++;
 6291:                 if (ref($request_domains) eq 'HASH') {
 6292:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6293:                 }
 6294:                 if ($dom eq $env{'user.domain'}) {
 6295:                     $can_request->{$type} = 1;
 6296:                 }
 6297:             }
 6298:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6299:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6300:                 if (@curr > 0) {
 6301:                     foreach my $item (@curr) {
 6302:                         if (ref($request_domains) eq 'HASH') {
 6303:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6304:                             if ($otherdom ne '') {
 6305:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6306:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6307:                                         push(@{$request_domains->{$type}},$otherdom);
 6308:                                     }
 6309:                                 } else {
 6310:                                     push(@{$request_domains->{$type}},$otherdom);
 6311:                                 }
 6312:                             }
 6313:                         }
 6314:                     }
 6315:                     unless($dom eq $env{'user.domain'}) {
 6316:                         $canreq ++;
 6317:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6318:                             $can_request->{$type} = 1;
 6319:                         }
 6320:                     }
 6321:                 }
 6322:             }
 6323:         }
 6324:     }
 6325:     return $canreq;
 6326: }
 6327: 
 6328: # ---------------------------------------------- Custom access rule evaluation
 6329: 
 6330: sub customaccess {
 6331:     my ($priv,$uri)=@_;
 6332:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6333:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6334:     $udom = &LONCAPA::clean_domain($udom);
 6335:     $ucrs = &LONCAPA::clean_username($ucrs);
 6336:     my $access=0;
 6337:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6338: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6339: 	if ($type eq 'user') {
 6340: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6341: 		my ($tdom,$tuname)=split(m{/},$scope);
 6342: 		if ($tdom) {
 6343: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6344: 		}
 6345: 		if ($tuname) {
 6346: 		    if ($tuname ne $env{'user.name'}) { next; }
 6347: 		}
 6348: 		$access=($effect eq 'allow');
 6349: 		last;
 6350: 	    }
 6351: 	} else {
 6352: 	    if ($role) {
 6353: 		if ($role ne $urole) { next; }
 6354: 	    }
 6355: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6356: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6357: 		if ($tdom) {
 6358: 		    if ($tdom ne $udom) { next; }
 6359: 		}
 6360: 		if ($tcrs) {
 6361: 		    if ($tcrs ne $ucrs) { next; }
 6362: 		}
 6363: 		if ($tsec) {
 6364: 		    if ($tsec ne $usec) { next; }
 6365: 		}
 6366: 		$access=($effect eq 'allow');
 6367: 		last;
 6368: 	    }
 6369: 	    if ($realm eq '' && $role eq '') {
 6370: 		$access=($effect eq 'allow');
 6371: 	    }
 6372: 	}
 6373:     }
 6374:     return $access;
 6375: }
 6376: 
 6377: # ------------------------------------------------- Check for a user privilege
 6378: 
 6379: sub allowed {
 6380:     my ($priv,$uri,$symb,$role)=@_;
 6381:     my $ver_orguri=$uri;
 6382:     $uri=&deversion($uri);
 6383:     my $orguri=$uri;
 6384:     $uri=&declutter($uri);
 6385: 
 6386:     if ($priv eq 'evb') {
 6387: # Evade communication block restrictions for specified role in a course
 6388:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6389:             return $1;
 6390:         } else {
 6391:             return;
 6392:         }
 6393:     }
 6394: 
 6395:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6396: # Free bre access to adm and meta resources
 6397:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6398: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6399: 	&& ($priv eq 'bre')) {
 6400: 	return 'F';
 6401:     }
 6402: 
 6403: # Free bre access to user's own portfolio contents
 6404:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6405:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6406: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6407:         my %setters;
 6408:         my ($startblock,$endblock) = 
 6409:             &Apache::loncommon::blockcheck(\%setters,'port');
 6410:         if ($startblock && $endblock) {
 6411:             return 'B';
 6412:         } else {
 6413:             return 'F';
 6414:         }
 6415:     }
 6416: 
 6417: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6418:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6419:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6420:         if (exists($env{'request.course.id'})) {
 6421:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6422:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6423:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6424:                 my $courseprivid=$env{'request.course.id'};
 6425:                 $courseprivid=~s/\_/\//;
 6426:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6427:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6428:                     return $1; 
 6429:                 } else {
 6430:                     if ($env{'request.course.sec'}) {
 6431:                         $courseprivid.='/'.$env{'request.course.sec'};
 6432:                     }
 6433:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6434:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6435:                         return $2;
 6436:                     }
 6437:                 }
 6438:             }
 6439:         }
 6440:     }
 6441: 
 6442: # Free bre to public access
 6443: 
 6444:     if ($priv eq 'bre') {
 6445:         my $copyright=&metadata($uri,'copyright');
 6446: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6447:            return 'F'; 
 6448:         }
 6449:         if ($copyright eq 'priv') {
 6450:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6451: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6452: 		return '';
 6453:             }
 6454:         }
 6455:         if ($copyright eq 'domain') {
 6456:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6457: 	    unless (($env{'user.domain'} eq $1) ||
 6458:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6459: 		return '';
 6460:             }
 6461:         }
 6462:         if ($env{'request.role'}=~ /li\.\//) {
 6463:             # Library role, so allow browsing of resources in this domain.
 6464:             return 'F';
 6465:         }
 6466:         if ($copyright eq 'custom') {
 6467: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6468:         }
 6469:     }
 6470:     # Domain coordinator is trying to create a course
 6471:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6472:         # uri is the requested domain in this case.
 6473:         # comparison to 'request.role.domain' shows if the user has selected
 6474:         # a role of dc for the domain in question.
 6475:         return 'F' if ($uri eq $env{'request.role.domain'});
 6476:     }
 6477: 
 6478:     my $thisallowed='';
 6479:     my $statecond=0;
 6480:     my $courseprivid='';
 6481: 
 6482:     my $ownaccess;
 6483:     # Community Coordinator or Assistant Co-author browsing resource space.
 6484:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6485:         if ($uri eq '') {
 6486:             $ownaccess = 1;
 6487:         } else {
 6488:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6489:                 my $udom = $env{'user.domain'};
 6490:                 my $uname = $env{'user.name'};
 6491:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6492:                     $ownaccess = 1;
 6493:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6494:                     unless ($uri =~ m{\.\./}) {
 6495:                         $ownaccess = 1;
 6496:                     }
 6497:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6498:                     my $now = time;
 6499:                     if ($uri =~ m{^([^/]+)/?$}) {
 6500:                         my $adom = $1;
 6501:                         foreach my $key (keys(%env)) {
 6502:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6503:                                 my ($start,$end) = split('.',$env{$key});
 6504:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6505:                                     $ownaccess = 1;
 6506:                                     last;
 6507:                                 }
 6508:                             }
 6509:                         }
 6510:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6511:                         my $adom = $1;
 6512:                         my $aname = $2;
 6513:                         foreach my $role ('ca','aa') { 
 6514:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6515:                                 my ($start,$end) =
 6516:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6517:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6518:                                     $ownaccess = 1;
 6519:                                     last;
 6520:                                 }
 6521:                             }
 6522:                         }
 6523:                     }
 6524:                 }
 6525:             }
 6526:         }
 6527:     }
 6528: 
 6529: # Course
 6530: 
 6531:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6532:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6533:             $thisallowed.=$1;
 6534:         }
 6535:     }
 6536: 
 6537: # Domain
 6538: 
 6539:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6540:        =~/\Q$priv\E\&([^\:]*)/) {
 6541:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6542:             $thisallowed.=$1;
 6543:         }
 6544:     }
 6545: 
 6546: # User who is not author or co-author might still be able to edit
 6547: # resource of an author in the domain (e.g., if Domain Coordinator).
 6548:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6549:         (&allowed('mdc',$env{'request.course.id'}))) {
 6550:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6551:             $thisallowed.=$1;
 6552:         }
 6553:     }
 6554: 
 6555: # Course: uri itself is a course
 6556:     my $courseuri=$uri;
 6557:     $courseuri=~s/\_(\d)/\/$1/;
 6558:     $courseuri=~s/^([^\/])/\/$1/;
 6559: 
 6560:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6561:        =~/\Q$priv\E\&([^\:]*)/) {
 6562:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6563:             $thisallowed.=$1;
 6564:         }
 6565:     }
 6566: 
 6567: # URI is an uploaded document for this course, default permissions don't matter
 6568: # not allowing 'edit' access (editupload) to uploaded course docs
 6569:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6570: 	$thisallowed='';
 6571:         my ($match)=&is_on_map($uri);
 6572:         if ($match) {
 6573:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6574:                   =~/\Q$priv\E\&([^\:]*)/) {
 6575:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6576:                 if (@blockers > 0) {
 6577:                     $thisallowed = 'B';
 6578:                 } else {
 6579:                     $thisallowed.=$1;
 6580:                 }
 6581:             }
 6582:         } else {
 6583:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6584:             if ($refuri) {
 6585:                 if ($refuri =~ m|^/adm/|) {
 6586:                     $thisallowed='F';
 6587:                 } else {
 6588:                     $refuri=&declutter($refuri);
 6589:                     my ($match) = &is_on_map($refuri);
 6590:                     if ($match) {
 6591:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6592:                         if (@blockers > 0) {
 6593:                             $thisallowed = 'B';
 6594:                         } else {
 6595:                             $thisallowed='F';
 6596:                         }
 6597:                     }
 6598:                 }
 6599:             }
 6600:         }
 6601:     }
 6602: 
 6603:     if ($priv eq 'bre'
 6604: 	&& $thisallowed ne 'F' 
 6605: 	&& $thisallowed ne '2'
 6606: 	&& &is_portfolio_url($uri)) {
 6607: 	$thisallowed = &portfolio_access($uri);
 6608:     }
 6609:     
 6610: # Full access at system, domain or course-wide level? Exit.
 6611:     if ($thisallowed=~/F/) {
 6612: 	return 'F';
 6613:     }
 6614: 
 6615: # If this is generating or modifying users, exit with special codes
 6616: 
 6617:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6618: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6619: 	    my ($audom,$auname)=split('/',$uri);
 6620: # no author name given, so this just checks on the general right to make a co-author in this domain
 6621: 	    unless ($auname) { return $thisallowed; }
 6622: # an author name is given, so we are about to actually make a co-author for a certain account
 6623: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6624: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6625: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6626: 	}
 6627: 	return $thisallowed;
 6628:     }
 6629: #
 6630: # Gathered so far: system, domain and course wide privileges
 6631: #
 6632: # Course: See if uri or referer is an individual resource that is part of 
 6633: # the course
 6634: 
 6635:     if ($env{'request.course.id'}) {
 6636: 
 6637:        $courseprivid=$env{'request.course.id'};
 6638:        if ($env{'request.course.sec'}) {
 6639:           $courseprivid.='/'.$env{'request.course.sec'};
 6640:        }
 6641:        $courseprivid=~s/\_/\//;
 6642:        my $checkreferer=1;
 6643:        my ($match,$cond)=&is_on_map($uri);
 6644:        if ($match) {
 6645:            $statecond=$cond;
 6646:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6647:                =~/\Q$priv\E\&([^\:]*)/) {
 6648:                my $value = $1;
 6649:                if ($priv eq 'bre') {
 6650:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6651:                    if (@blockers > 0) {
 6652:                        $thisallowed = 'B';
 6653:                    } else {
 6654:                        $thisallowed.=$value;
 6655:                    }
 6656:                } else {
 6657:                    $thisallowed.=$value;
 6658:                }
 6659:                $checkreferer=0;
 6660:            }
 6661:        }
 6662:        
 6663:        if ($checkreferer) {
 6664: 	  my $refuri=$env{'httpref.'.$orguri};
 6665:             unless ($refuri) {
 6666:                 foreach my $key (keys(%env)) {
 6667: 		    if ($key=~/^httpref\..*\*/) {
 6668: 			my $pattern=$key;
 6669:                         $pattern=~s/^httpref\.\/res\///;
 6670:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6671:                         $pattern=~s/\//\\\//g;
 6672:                         if ($orguri=~/$pattern/) {
 6673: 			    $refuri=$env{$key};
 6674:                         }
 6675:                     }
 6676:                 }
 6677:             }
 6678: 
 6679:          if ($refuri) { 
 6680: 	  $refuri=&declutter($refuri);
 6681:           my ($match,$cond)=&is_on_map($refuri);
 6682:             if ($match) {
 6683:               my $refstatecond=$cond;
 6684:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6685:                   =~/\Q$priv\E\&([^\:]*)/) {
 6686:                   my $value = $1;
 6687:                   if ($priv eq 'bre') {
 6688:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6689:                       if (@blockers > 0) {
 6690:                           $thisallowed = 'B';
 6691:                       } else {
 6692:                           $thisallowed.=$value;
 6693:                       }
 6694:                   } else {
 6695:                       $thisallowed.=$value;
 6696:                   }
 6697:                   $uri=$refuri;
 6698:                   $statecond=$refstatecond;
 6699:               }
 6700:           }
 6701:         }
 6702:        }
 6703:    }
 6704: 
 6705: #
 6706: # Gathered now: all privileges that could apply, and condition number
 6707: # 
 6708: #
 6709: # Full or no access?
 6710: #
 6711: 
 6712:     if ($thisallowed=~/F/) {
 6713: 	return 'F';
 6714:     }
 6715: 
 6716:     unless ($thisallowed) {
 6717:         return '';
 6718:     }
 6719: 
 6720: # Restrictions exist, deal with them
 6721: #
 6722: #   C:according to course preferences
 6723: #   R:according to resource settings
 6724: #   L:unless locked
 6725: #   X:according to user session state
 6726: #
 6727: 
 6728: # Possibly locked functionality, check all courses
 6729: # Locks might take effect only after 10 minutes cache expiration for other
 6730: # courses, and 2 minutes for current course
 6731: 
 6732:     my $envkey;
 6733:     if ($thisallowed=~/L/) {
 6734:         foreach $envkey (keys(%env)) {
 6735:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6736:                my $courseid=$2;
 6737:                my $roleid=$1.'.'.$2;
 6738:                $courseid=~s/^\///;
 6739:                my $expiretime=600;
 6740:                if ($env{'request.role'} eq $roleid) {
 6741: 		  $expiretime=120;
 6742:                }
 6743: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6744:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6745:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6746: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6747:                }
 6748:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6749:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6750: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6751:                        &log($env{'user.domain'},$env{'user.name'},
 6752:                             $env{'user.home'},
 6753:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6754:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6755:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6756: 		       return '';
 6757:                    }
 6758:                }
 6759:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6760:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6761: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6762:                        &log($env{'user.domain'},$env{'user.name'},
 6763:                             $env{'user.home'},
 6764:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6765:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6766:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6767: 		       return '';
 6768:                    }
 6769:                }
 6770: 	   }
 6771:        }
 6772:     }
 6773:    
 6774: #
 6775: # Rest of the restrictions depend on selected course
 6776: #
 6777: 
 6778:     unless ($env{'request.course.id'}) {
 6779: 	if ($thisallowed eq 'A') {
 6780: 	    return 'A';
 6781:         } elsif ($thisallowed eq 'B') {
 6782:             return 'B';
 6783: 	} else {
 6784: 	    return '1';
 6785: 	}
 6786:     }
 6787: 
 6788: #
 6789: # Now user is definitely in a course
 6790: #
 6791: 
 6792: 
 6793: # Course preferences
 6794: 
 6795:    if ($thisallowed=~/C/) {
 6796:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6797:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6798:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6799: 	   =~/\Q$rolecode\E/) {
 6800: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6801: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6802: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6803: 			$env{'request.course.id'});
 6804: 	   }
 6805:            return '';
 6806:        }
 6807: 
 6808:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6809: 	   =~/\Q$unamedom\E/) {
 6810: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6811: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6812: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6813: 			$env{'request.course.id'});
 6814: 	   }
 6815:            return '';
 6816:        }
 6817:    }
 6818: 
 6819: # Resource preferences
 6820: 
 6821:    if ($thisallowed=~/R/) {
 6822:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6823:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6824: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6825: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6826: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6827: 	   }
 6828: 	   return '';
 6829:        }
 6830:    }
 6831: 
 6832: # Restricted by state or randomout?
 6833: 
 6834:    if ($thisallowed=~/X/) {
 6835:       if ($env{'acc.randomout'}) {
 6836: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6837:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6838:             return ''; 
 6839:          }
 6840:       }
 6841:       if (&condval($statecond)) {
 6842: 	 return '2';
 6843:       } else {
 6844:          return '';
 6845:       }
 6846:    }
 6847: 
 6848:     if ($thisallowed eq 'A') {
 6849: 	return 'A';
 6850:     } elsif ($thisallowed eq 'B') {
 6851:         return 'B';
 6852:     }
 6853:    return 'F';
 6854: }
 6855: 
 6856: # ------------------------------------------- Check construction space access
 6857: 
 6858: sub constructaccess {
 6859:     my ($url,$setpriv)=@_;
 6860: 
 6861: # We do not allow editing of previous versions of files
 6862:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6863: 
 6864: # Get username and domain from URL
 6865:     my ($ownername,$ownerdomain,$ownerhome);
 6866: 
 6867:     ($ownerdomain,$ownername) =
 6868:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6869: 
 6870: # The URL does not really point to any authorspace, forget it
 6871:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6872: 
 6873: # Now we need to see if the user has access to the authorspace of
 6874: # $ownername at $ownerdomain
 6875: 
 6876:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6877: # Real author for this?
 6878:        $ownerhome = $env{'user.home'};
 6879:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6880:           return ($ownername,$ownerdomain,$ownerhome);
 6881:        }
 6882:     } else {
 6883: # Co-author for this?
 6884:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6885:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6886:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6887:             return ($ownername,$ownerdomain,$ownerhome);
 6888:         }
 6889:     }
 6890: 
 6891: # We don't have any access right now. If we are not possibly going to do anything about this,
 6892: # we might as well leave
 6893:    unless ($setpriv) { return ''; }
 6894: 
 6895: # Backdoor access?
 6896:     my $allowed=&allowed('eco',$ownerdomain);
 6897: # Nope
 6898:     unless ($allowed) { return ''; }
 6899: # Looks like we may have access, but could be locked by the owner of the construction space
 6900:     if ($allowed eq 'U') {
 6901:         my %blocked=&get('environment',['domcoord.author'],
 6902:                          $ownerdomain,$ownername);
 6903: # Is blocked by owner
 6904:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 6905:     }
 6906:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 6907: # Grant temporary access
 6908:         my $then=$env{'user.login.time'};
 6909:         my $update=$env{'user.update.time'};
 6910:         if (!$update) { $update = $then; }
 6911:         my $refresh=$env{'user.refresh.time'};
 6912:         if (!$refresh) { $refresh = $update; }
 6913:         my $now = time;
 6914:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 6915:                            $now,'ca','constructaccess');
 6916:         $ownerhome = &homeserver($ownername,$ownerdomain);
 6917:         return($ownername,$ownerdomain,$ownerhome);
 6918:     }
 6919: # No business here
 6920:     return '';
 6921: }
 6922: 
 6923: sub get_comm_blocks {
 6924:     my ($cdom,$cnum) = @_;
 6925:     if ($cdom eq '' || $cnum eq '') {
 6926:         return unless ($env{'request.course.id'});
 6927:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6928:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6929:     }
 6930:     my %commblocks;
 6931:     my $hashid=$cdom.'_'.$cnum;
 6932:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6933:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6934:         %commblocks = %{$blocksref};
 6935:     } else {
 6936:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6937:         my $cachetime = 600;
 6938:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6939:     }
 6940:     return %commblocks;
 6941: }
 6942: 
 6943: sub has_comm_blocking {
 6944:     my ($priv,$symb,$uri,$blocks) = @_;
 6945:     return unless ($env{'request.course.id'});
 6946:     return unless ($priv eq 'bre');
 6947:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6948:     my %commblocks;
 6949:     if (ref($blocks) eq 'HASH') {
 6950:         %commblocks = %{$blocks};
 6951:     } else {
 6952:         %commblocks = &get_comm_blocks();
 6953:     }
 6954:     return unless (keys(%commblocks) > 0);
 6955:     if (!$symb) { $symb=&symbread($uri,1); }
 6956:     my ($map,$resid,undef)=&decode_symb($symb);
 6957:     my %tocheck = (
 6958:                     maps      => $map,
 6959:                     resources => $symb,
 6960:                   );
 6961:     my @blockers;
 6962:     my $now = time;
 6963:     my $navmap = Apache::lonnavmaps::navmap->new();
 6964:     foreach my $block (keys(%commblocks)) {
 6965:         if ($block =~ /^(\d+)____(\d+)$/) {
 6966:             my ($start,$end) = ($1,$2);
 6967:             if ($start <= $now && $end >= $now) {
 6968:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6969:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6970:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6971:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6972:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6973:                                     push(@blockers,$block);
 6974:                                 }
 6975:                             }
 6976:                         }
 6977:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6978:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6979:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6980:                                     push(@blockers,$block);
 6981:                                 }
 6982:                             }
 6983:                         }
 6984:                     }
 6985:                 }
 6986:             }
 6987:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6988:             my $item = $1;
 6989:             my @to_test;
 6990:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6991:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6992:                     my $check_interval;
 6993:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6994:                         my @interval;
 6995:                         my $type = 'map';
 6996:                         if ($item eq 'course') {
 6997:                             $type = 'course';
 6998:                             @interval=&EXT("resource.0.interval");
 6999:                         } else {
 7000:                             if ($item =~ /___\d+___/) {
 7001:                                 $type = 'resource';
 7002:                                 @interval=&EXT("resource.0.interval",$item);
 7003:                                 if (ref($navmap)) {                        
 7004:                                     my $res = $navmap->getBySymb($item); 
 7005:                                     push(@to_test,$res);
 7006:                                 }
 7007:                             } else {
 7008:                                 my $mapsymb = &symbread($item,1);
 7009:                                 if ($mapsymb) {
 7010:                                     if (ref($navmap)) {
 7011:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7012:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7013:                                         foreach my $res (@to_test) {
 7014:                                             my $symb = $res->symb();
 7015:                                             next if ($symb eq $mapsymb);
 7016:                                             if ($symb ne '') {
 7017:                                                 @interval=&EXT("resource.0.interval",$symb);
 7018:                                                 last;
 7019:                                             }
 7020:                                         }
 7021:                                     }
 7022:                                 }
 7023:                             }
 7024:                         }
 7025:                         if ($interval[0] =~ /\d+/) {
 7026:                             my $first_access;
 7027:                             if ($type eq 'resource') {
 7028:                                 $first_access=&get_first_access($interval[1],$item);
 7029:                             } elsif ($type eq 'map') {
 7030:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7031:                             } else {
 7032:                                 $first_access=&get_first_access($interval[1]);
 7033:                             }
 7034:                             if ($first_access) {
 7035:                                 my $timesup = $first_access+$interval[0];
 7036:                                 if ($timesup > $now) {
 7037:                                     foreach my $res (@to_test) {
 7038:                                         if ($res->is_problem()) {
 7039:                                             if ($res->completable()) {
 7040:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7041:                                                     push(@blockers,$block);
 7042:                                                 }
 7043:                                                 last;
 7044:                                             }
 7045:                                         }
 7046:                                     }
 7047:                                 }
 7048:                             }
 7049:                         }
 7050:                     }
 7051:                 }
 7052:             }
 7053:         }
 7054:     }
 7055:     return @blockers;
 7056: }
 7057: 
 7058: sub check_docs_block {
 7059:     my ($docsblock,$tocheck) =@_;
 7060:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7061:         return;
 7062:     }
 7063:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7064:         if ($tocheck->{'maps'}) {
 7065:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7066:                 return 1;
 7067:             }
 7068:         }
 7069:     }
 7070:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7071:         if ($tocheck->{'resources'}) {
 7072:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7073:                 return 1;
 7074:             }
 7075:         }
 7076:     }
 7077:     return;
 7078: }
 7079: 
 7080: #
 7081: #   Removes the versino from a URI and
 7082: #   splits it in to its filename and path to the filename.
 7083: #   Seems like File::Basename could have done this more clearly.
 7084: #   Parameters:
 7085: #      $uri   - input URI
 7086: #   Returns:
 7087: #     Two element list consisting of 
 7088: #     $pathname  - the URI up to and excluding the trailing /
 7089: #     $filename  - The part of the URI following the last /
 7090: #  NOTE:
 7091: #    Another realization of this is simply:
 7092: #    use File::Basename;
 7093: #    ...
 7094: #    $uri = shift;
 7095: #    $filename = basename($uri);
 7096: #    $path     = dirname($uri);
 7097: #    return ($filename, $path);
 7098: #
 7099: #     The implementation below is probably faster however.
 7100: #
 7101: sub split_uri_for_cond {
 7102:     my $uri=&deversion(&declutter(shift));
 7103:     my @uriparts=split(/\//,$uri);
 7104:     my $filename=pop(@uriparts);
 7105:     my $pathname=join('/',@uriparts);
 7106:     return ($pathname,$filename);
 7107: }
 7108: # --------------------------------------------------- Is a resource on the map?
 7109: 
 7110: sub is_on_map {
 7111:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7112:     #Trying to find the conditional for the file
 7113:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7114: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7115:     if ($match) {
 7116: 	return (1,$1);
 7117:     } else {
 7118: 	return (0,0);
 7119:     }
 7120: }
 7121: 
 7122: # --------------------------------------------------------- Get symb from alias
 7123: 
 7124: sub get_symb_from_alias {
 7125:     my $symb=shift;
 7126:     my ($map,$resid,$url)=&decode_symb($symb);
 7127: # Already is a symb
 7128:     if ($url) { return $symb; }
 7129: # Must be an alias
 7130:     my $aliassymb='';
 7131:     my %bighash;
 7132:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7133:                             &GDBM_READER(),0640)) {
 7134:         my $rid=$bighash{'mapalias_'.$symb};
 7135: 	if ($rid) {
 7136: 	    my ($mapid,$resid)=split(/\./,$rid);
 7137: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7138: 				    $resid,$bighash{'src_'.$rid});
 7139: 	}
 7140:         untie %bighash;
 7141:     }
 7142:     return $aliassymb;
 7143: }
 7144: 
 7145: # ----------------------------------------------------------------- Define Role
 7146: 
 7147: sub definerole {
 7148:   if (allowed('mcr','/')) {
 7149:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7150:     foreach my $role (split(':',$sysrole)) {
 7151: 	my ($crole,$cqual)=split(/\&/,$role);
 7152:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7153:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7154: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7155:                return "refused:s:$crole&$cqual"; 
 7156:             }
 7157:         }
 7158:     }
 7159:     foreach my $role (split(':',$domrole)) {
 7160: 	my ($crole,$cqual)=split(/\&/,$role);
 7161:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7162:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7163: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7164:                return "refused:d:$crole&$cqual"; 
 7165:             }
 7166:         }
 7167:     }
 7168:     foreach my $role (split(':',$courole)) {
 7169: 	my ($crole,$cqual)=split(/\&/,$role);
 7170:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7171:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7172: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7173:                return "refused:c:$crole&$cqual"; 
 7174:             }
 7175:         }
 7176:     }
 7177:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7178:                 "$env{'user.domain'}:$env{'user.name'}:".
 7179: 	        "rolesdef_$rolename=".
 7180:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7181:     return reply($command,$env{'user.home'});
 7182:   } else {
 7183:     return 'refused';
 7184:   }
 7185: }
 7186: 
 7187: # ---------------- Make a metadata query against the network of library servers
 7188: 
 7189: sub metadata_query {
 7190:     my ($query,$custom,$customshow,$server_array)=@_;
 7191:     my %rhash;
 7192:     my %libserv = &all_library();
 7193:     my @server_list = (defined($server_array) ? @$server_array
 7194:                                               : keys(%libserv) );
 7195:     for my $server (@server_list) {
 7196: 	unless ($custom or $customshow) {
 7197: 	    my $reply=&reply("querysend:".&escape($query),$server);
 7198: 	    $rhash{$server}=$reply;
 7199: 	}
 7200: 	else {
 7201: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7202: 			     &escape($custom).':'.&escape($customshow),
 7203: 			     $server);
 7204: 	    $rhash{$server}=$reply;
 7205: 	}
 7206:     }
 7207:     return \%rhash;
 7208: }
 7209: 
 7210: # ----------------------------------------- Send log queries and wait for reply
 7211: 
 7212: sub log_query {
 7213:     my ($uname,$udom,$query,%filters)=@_;
 7214:     my $uhome=&homeserver($uname,$udom);
 7215:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7216:     my $uhost=&hostname($uhome);
 7217:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7218:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7219:                        $uhome);
 7220:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7221:     return get_query_reply($queryid);
 7222: }
 7223: 
 7224: # -------------------------- Update MySQL table for portfolio file
 7225: 
 7226: sub update_portfolio_table {
 7227:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7228:     if ($group ne '') {
 7229:         $file_name =~s /^\Q$group\E//;
 7230:     }
 7231:     my $homeserver = &homeserver($uname,$udom);
 7232:     my $queryid=
 7233:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7234:                ':'.&escape($file_name).':'.$action,$homeserver);
 7235:     my $reply = &get_query_reply($queryid);
 7236:     return $reply;
 7237: }
 7238: 
 7239: # -------------------------- Update MySQL allusers table
 7240: 
 7241: sub update_allusers_table {
 7242:     my ($uname,$udom,$names) = @_;
 7243:     my $homeserver = &homeserver($uname,$udom);
 7244:     my $queryid=
 7245:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7246:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7247:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7248:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7249:                'generation='.&escape($names->{'generation'}).'%%'.
 7250:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7251:                'id='.&escape($names->{'id'}),$homeserver);
 7252:     return;
 7253: }
 7254: 
 7255: # ------- Request retrieval of institutional classlists for course(s)
 7256: 
 7257: sub fetch_enrollment_query {
 7258:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7259:     my $homeserver;
 7260:     my $maxtries = 1;
 7261:     if ($context eq 'automated') {
 7262:         $homeserver = $perlvar{'lonHostID'};
 7263:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7264:     } else {
 7265:         $homeserver = &homeserver($cnum,$dom);
 7266:     }
 7267:     my $host=&hostname($homeserver);
 7268:     my $cmd = '';
 7269:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7270:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7271:     }
 7272:     $cmd =~ s/%%$//;
 7273:     $cmd = &escape($cmd);
 7274:     my $query = 'fetchenrollment';
 7275:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7276:     unless ($queryid=~/^\Q$host\E\_/) { 
 7277:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7278:         return 'error: '.$queryid;
 7279:     }
 7280:     my $reply = &get_query_reply($queryid);
 7281:     my $tries = 1;
 7282:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7283:         $reply = &get_query_reply($queryid);
 7284:         $tries ++;
 7285:     }
 7286:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7287:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7288:     } else {
 7289:         my @responses = split(/:/,$reply);
 7290:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7291:             foreach my $line (@responses) {
 7292:                 my ($key,$value) = split(/=/,$line,2);
 7293:                 $$replyref{$key} = $value;
 7294:             }
 7295:         } else {
 7296:             my $pathname = LONCAPA::tempdir();
 7297:             foreach my $line (@responses) {
 7298:                 my ($key,$value) = split(/=/,$line);
 7299:                 $$replyref{$key} = $value;
 7300:                 if ($value > 0) {
 7301:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7302:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7303:                         my $destname = $pathname.'/'.$filename;
 7304:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7305:                         if ($xml_classlist =~ /^error/) {
 7306:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7307:                         } else {
 7308:                             if ( open(FILE,">$destname") ) {
 7309:                                 print FILE &unescape($xml_classlist);
 7310:                                 close(FILE);
 7311:                             } else {
 7312:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7313:                             }
 7314:                         }
 7315:                     }
 7316:                 }
 7317:             }
 7318:         }
 7319:         return 'ok';
 7320:     }
 7321:     return 'error';
 7322: }
 7323: 
 7324: sub get_query_reply {
 7325:     my $queryid=shift;
 7326:     my $replyfile=LONCAPA::tempdir().$queryid;
 7327:     my $reply='';
 7328:     for (1..100) {
 7329: 	sleep 2;
 7330:         if (-e $replyfile.'.end') {
 7331: 	    if (open(my $fh,$replyfile)) {
 7332: 		$reply = join('',<$fh>);
 7333: 		close($fh);
 7334: 	   } else { return 'error: reply_file_error'; }
 7335:            return &unescape($reply);
 7336: 	}
 7337:     }
 7338:     return 'timeout:'.$queryid;
 7339: }
 7340: 
 7341: sub courselog_query {
 7342: #
 7343: # possible filters:
 7344: # url: url or symb
 7345: # username
 7346: # domain
 7347: # action: view, submit, grade
 7348: # start: timestamp
 7349: # end: timestamp
 7350: #
 7351:     my (%filters)=@_;
 7352:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7353:     if ($filters{'url'}) {
 7354: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7355:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7356:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7357:     }
 7358:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7359:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7360:     return &log_query($cname,$cdom,'courselog',%filters);
 7361: }
 7362: 
 7363: sub userlog_query {
 7364: #
 7365: # possible filters:
 7366: # action: log check role
 7367: # start: timestamp
 7368: # end: timestamp
 7369: #
 7370:     my ($uname,$udom,%filters)=@_;
 7371:     return &log_query($uname,$udom,'userlog',%filters);
 7372: }
 7373: 
 7374: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7375: 
 7376: sub auto_run {
 7377:     my ($cnum,$cdom) = @_;
 7378:     my $response = 0;
 7379:     my $settings;
 7380:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7381:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7382:         $settings = $domconfig{'autoenroll'};
 7383:         if ($settings->{'run'} eq '1') {
 7384:             $response = 1;
 7385:         }
 7386:     } else {
 7387:         my $homeserver;
 7388:         if (&is_course($cdom,$cnum)) {
 7389:             $homeserver = &homeserver($cnum,$cdom);
 7390:         } else {
 7391:             $homeserver = &domain($cdom,'primary');
 7392:         }
 7393:         if ($homeserver ne 'no_host') {
 7394:             $response = &reply('autorun:'.$cdom,$homeserver);
 7395:         }
 7396:     }
 7397:     return $response;
 7398: }
 7399: 
 7400: sub auto_get_sections {
 7401:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7402:     my $homeserver;
 7403:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7404:         $homeserver = &homeserver($cnum,$cdom);
 7405:     }
 7406:     if (!defined($homeserver)) { 
 7407:         if ($cdom =~ /^$match_domain$/) {
 7408:             $homeserver = &domain($cdom,'primary');
 7409:         }
 7410:     }
 7411:     my @secs;
 7412:     if (defined($homeserver)) {
 7413:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7414:         unless ($response eq 'refused') {
 7415:             @secs = split(/:/,$response);
 7416:         }
 7417:     }
 7418:     return @secs;
 7419: }
 7420: 
 7421: sub auto_new_course {
 7422:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7423:     my $homeserver = &homeserver($cnum,$cdom);
 7424:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7425:     return $response;
 7426: }
 7427: 
 7428: sub auto_validate_courseID {
 7429:     my ($cnum,$cdom,$inst_course_id) = @_;
 7430:     my $homeserver = &homeserver($cnum,$cdom);
 7431:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7432:     return $response;
 7433: }
 7434: 
 7435: sub auto_validate_instcode {
 7436:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7437:     my ($homeserver,$response);
 7438:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7439:         $homeserver = &homeserver($cnum,$cdom);
 7440:     }
 7441:     if (!defined($homeserver)) {
 7442:         if ($cdom =~ /^$match_domain$/) {
 7443:             $homeserver = &domain($cdom,'primary');
 7444:         }
 7445:     }
 7446:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7447:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7448:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7449:     return ($outcome,$description,$defaultcredits);
 7450: }
 7451: 
 7452: sub auto_create_password {
 7453:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7454:     my ($homeserver,$response);
 7455:     my $create_passwd = 0;
 7456:     my $authchk = '';
 7457:     if ($udom =~ /^$match_domain$/) {
 7458:         $homeserver = &domain($udom,'primary');
 7459:     }
 7460:     if ($homeserver eq '') {
 7461:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7462:             $homeserver = &homeserver($cnum,$cdom);
 7463:         }
 7464:     }
 7465:     if ($homeserver eq '') {
 7466:         $authchk = 'nodomain';
 7467:     } else {
 7468:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7469:         if ($response eq 'refused') {
 7470:             $authchk = 'refused';
 7471:         } else {
 7472:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7473:         }
 7474:     }
 7475:     return ($authparam,$create_passwd,$authchk);
 7476: }
 7477: 
 7478: sub auto_photo_permission {
 7479:     my ($cnum,$cdom,$students) = @_;
 7480:     my $homeserver = &homeserver($cnum,$cdom);
 7481:     my ($outcome,$perm_reqd,$conditions) = 
 7482: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7483:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7484: 	return (undef,undef);
 7485:     }
 7486:     return ($outcome,$perm_reqd,$conditions);
 7487: }
 7488: 
 7489: sub auto_checkphotos {
 7490:     my ($uname,$udom,$pid) = @_;
 7491:     my $homeserver = &homeserver($uname,$udom);
 7492:     my ($result,$resulttype);
 7493:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7494: 				   &escape($uname).':'.&escape($pid),
 7495: 				   $homeserver));
 7496:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7497: 	return (undef,undef);
 7498:     }
 7499:     if ($outcome) {
 7500:         ($result,$resulttype) = split(/:/,$outcome);
 7501:     } 
 7502:     return ($result,$resulttype);
 7503: }
 7504: 
 7505: sub auto_photochoice {
 7506:     my ($cnum,$cdom) = @_;
 7507:     my $homeserver = &homeserver($cnum,$cdom);
 7508:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7509: 						       &escape($cdom),
 7510: 						       $homeserver)));
 7511:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7512: 	return (undef,undef);
 7513:     }
 7514:     return ($update,$comment);
 7515: }
 7516: 
 7517: sub auto_photoupdate {
 7518:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7519:     my $homeserver = &homeserver($cnum,$dom);
 7520:     my $host=&hostname($homeserver);
 7521:     my $cmd = '';
 7522:     my $maxtries = 1;
 7523:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7524:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7525:     }
 7526:     $cmd =~ s/%%$//;
 7527:     $cmd = &escape($cmd);
 7528:     my $query = 'institutionalphotos';
 7529:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7530:     unless ($queryid=~/^\Q$host\E\_/) {
 7531:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7532:         return 'error: '.$queryid;
 7533:     }
 7534:     my $reply = &get_query_reply($queryid);
 7535:     my $tries = 1;
 7536:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7537:         $reply = &get_query_reply($queryid);
 7538:         $tries ++;
 7539:     }
 7540:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7541:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7542:     } else {
 7543:         my @responses = split(/:/,$reply);
 7544:         my $outcome = shift(@responses); 
 7545:         foreach my $item (@responses) {
 7546:             my ($key,$value) = split(/=/,$item);
 7547:             $$photo{$key} = $value;
 7548:         }
 7549:         return $outcome;
 7550:     }
 7551:     return 'error';
 7552: }
 7553: 
 7554: sub auto_instcode_format {
 7555:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7556: 	$cat_order) = @_;
 7557:     my $courses = '';
 7558:     my @homeservers;
 7559:     if ($caller eq 'global') {
 7560: 	my %servers = &get_servers($codedom,'library');
 7561: 	foreach my $tryserver (keys(%servers)) {
 7562: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7563: 		push(@homeservers,$tryserver);
 7564: 	    }
 7565:         }
 7566:     } elsif ($caller eq 'requests') {
 7567:         if ($codedom =~ /^$match_domain$/) {
 7568:             my $chome = &domain($codedom,'primary');
 7569:             unless ($chome eq 'no_host') {
 7570:                 push(@homeservers,$chome);
 7571:             }
 7572:         }
 7573:     } else {
 7574:         push(@homeservers,&homeserver($caller,$codedom));
 7575:     }
 7576:     foreach my $code (keys(%{$instcodes})) {
 7577:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7578:     }
 7579:     chop($courses);
 7580:     my $ok_response = 0;
 7581:     my $response;
 7582:     while (@homeservers > 0 && $ok_response == 0) {
 7583:         my $server = shift(@homeservers); 
 7584:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7585:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7586:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7587: 		split(/:/,$response);
 7588:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7589:             push(@{$codetitles},&str2array($codetitles_str));
 7590:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7591:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7592:             $ok_response = 1;
 7593:         }
 7594:     }
 7595:     if ($ok_response) {
 7596:         return 'ok';
 7597:     } else {
 7598:         return $response;
 7599:     }
 7600: }
 7601: 
 7602: sub auto_instcode_defaults {
 7603:     my ($domain,$returnhash,$code_order) = @_;
 7604:     my @homeservers;
 7605: 
 7606:     my %servers = &get_servers($domain,'library');
 7607:     foreach my $tryserver (keys(%servers)) {
 7608: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7609: 	    push(@homeservers,$tryserver);
 7610: 	}
 7611:     }
 7612: 
 7613:     my $response;
 7614:     foreach my $server (@homeservers) {
 7615:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7616:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7617: 	
 7618: 	foreach my $pair (split(/\&/,$response)) {
 7619: 	    my ($name,$value)=split(/\=/,$pair);
 7620: 	    if ($name eq 'code_order') {
 7621: 		@{$code_order} = split(/\&/,&unescape($value));
 7622: 	    } else {
 7623: 		$returnhash->{&unescape($name)}=&unescape($value);
 7624: 	    }
 7625: 	}
 7626: 	return 'ok';
 7627:     }
 7628: 
 7629:     return $response;
 7630: }
 7631: 
 7632: sub auto_possible_instcodes {
 7633:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7634:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7635:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7636:         return;
 7637:     }
 7638:     my (@homeservers,$uhome);
 7639:     if (defined(&domain($domain,'primary'))) {
 7640:         $uhome=&domain($domain,'primary');
 7641:         push(@homeservers,&domain($domain,'primary'));
 7642:     } else {
 7643:         my %servers = &get_servers($domain,'library');
 7644:         foreach my $tryserver (keys(%servers)) {
 7645:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7646:                 push(@homeservers,$tryserver);
 7647:             }
 7648:         }
 7649:     }
 7650:     my $response;
 7651:     foreach my $server (@homeservers) {
 7652:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7653:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7654:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7655:             split(':',$response);
 7656:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7657:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7658:         foreach my $item (split('&',$cat_title)) {   
 7659:             my ($name,$value)=split('=',$item);
 7660:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7661:         }
 7662:         foreach my $item (split('&',$cat_order)) {
 7663:             my ($name,$value)=split('=',$item);
 7664:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7665:         }
 7666:         return 'ok';
 7667:     }
 7668:     return $response;
 7669: }
 7670: 
 7671: sub auto_courserequest_checks {
 7672:     my ($dom) = @_;
 7673:     my ($homeserver,%validations);
 7674:     if ($dom =~ /^$match_domain$/) {
 7675:         $homeserver = &domain($dom,'primary');
 7676:     }
 7677:     unless ($homeserver eq 'no_host') {
 7678:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7679:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7680:             my @items = split(/&/,$response);
 7681:             foreach my $item (@items) {
 7682:                 my ($key,$value) = split('=',$item);
 7683:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7684:             }
 7685:         }
 7686:     }
 7687:     return %validations; 
 7688: }
 7689: 
 7690: sub auto_courserequest_validation {
 7691:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7692:     my ($homeserver,$response);
 7693:     if ($dom =~ /^$match_domain$/) {
 7694:         $homeserver = &domain($dom,'primary');
 7695:     }
 7696:     unless ($homeserver eq 'no_host') {  
 7697:           
 7698:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7699:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7700:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7701:                                     $homeserver));
 7702:     }
 7703:     return $response;
 7704: }
 7705: 
 7706: sub auto_validate_class_sec {
 7707:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7708:     my $homeserver = &homeserver($cnum,$cdom);
 7709:     my $ownerlist;
 7710:     if (ref($owners) eq 'ARRAY') {
 7711:         $ownerlist = join(',',@{$owners});
 7712:     } else {
 7713:         $ownerlist = $owners;
 7714:     }
 7715:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7716:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7717:     return $response;
 7718: }
 7719: 
 7720: # ------------------------------------------------------- Course Group routines
 7721: 
 7722: sub get_coursegroups {
 7723:     my ($cdom,$cnum,$group,$namespace) = @_;
 7724:     return(&dump($namespace,$cdom,$cnum,$group));
 7725: }
 7726: 
 7727: sub modify_coursegroup {
 7728:     my ($cdom,$cnum,$groupsettings) = @_;
 7729:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7730: }
 7731: 
 7732: sub toggle_coursegroup_status {
 7733:     my ($cdom,$cnum,$group,$action) = @_;
 7734:     my ($from_namespace,$to_namespace);
 7735:     if ($action eq 'delete') {
 7736:         $from_namespace = 'coursegroups';
 7737:         $to_namespace = 'deleted_groups';
 7738:     } else {
 7739:         $from_namespace = 'deleted_groups';
 7740:         $to_namespace = 'coursegroups';
 7741:     }
 7742:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7743:     if (my $tmp = &error(%curr_group)) {
 7744:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7745:         return ('read error',$tmp);
 7746:     } else {
 7747:         my %savedsettings = %curr_group; 
 7748:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7749:         my $deloutcome;
 7750:         if ($result eq 'ok') {
 7751:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7752:         } else {
 7753:             return ('write error',$result);
 7754:         }
 7755:         if ($deloutcome eq 'ok') {
 7756:             return 'ok';
 7757:         } else {
 7758:             return ('delete error',$deloutcome);
 7759:         }
 7760:     }
 7761: }
 7762: 
 7763: sub modify_group_roles {
 7764:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7765:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7766:     my $role = 'gr/'.&escape($userprivs);
 7767:     my ($uname,$udom) = split(/:/,$user);
 7768:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7769:     if ($result eq 'ok') {
 7770:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7771:     }
 7772:     return $result;
 7773: }
 7774: 
 7775: sub modify_coursegroup_membership {
 7776:     my ($cdom,$cnum,$membership) = @_;
 7777:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7778:     return $result;
 7779: }
 7780: 
 7781: sub get_active_groups {
 7782:     my ($udom,$uname,$cdom,$cnum) = @_;
 7783:     my $now = time;
 7784:     my %groups = ();
 7785:     foreach my $key (keys(%env)) {
 7786:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7787:             my ($start,$end) = split(/\./,$env{$key});
 7788:             if (($end!=0) && ($end<$now)) { next; }
 7789:             if (($start!=0) && ($start>$now)) { next; }
 7790:             if ($1 eq $cdom && $2 eq $cnum) {
 7791:                 $groups{$3} = $env{$key} ;
 7792:             }
 7793:         }
 7794:     }
 7795:     return %groups;
 7796: }
 7797: 
 7798: sub get_group_membership {
 7799:     my ($cdom,$cnum,$group) = @_;
 7800:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7801: }
 7802: 
 7803: sub get_users_groups {
 7804:     my ($udom,$uname,$courseid) = @_;
 7805:     my @usersgroups;
 7806:     my $cachetime=1800;
 7807: 
 7808:     my $hashid="$udom:$uname:$courseid";
 7809:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7810:     if (defined($cached)) {
 7811:         @usersgroups = split(/:/,$grouplist);
 7812:     } else {  
 7813:         $grouplist = '';
 7814:         my $courseurl = &courseid_to_courseurl($courseid);
 7815:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7816:         my $access_end = $env{'course.'.$courseid.
 7817:                               '.default_enrollment_end_date'};
 7818:         my $now = time;
 7819:         foreach my $key (keys(%roleshash)) {
 7820:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7821:                 my $group = $1;
 7822:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7823:                     my $start = $2;
 7824:                     my $end = $1;
 7825:                     if ($start == -1) { next; } # deleted from group
 7826:                     if (($start!=0) && ($start>$now)) { next; }
 7827:                     if (($end!=0) && ($end<$now)) {
 7828:                         if ($access_end && $access_end < $now) {
 7829:                             if ($access_end - $end < 86400) {
 7830:                                 push(@usersgroups,$group);
 7831:                             }
 7832:                         }
 7833:                         next;
 7834:                     }
 7835:                     push(@usersgroups,$group);
 7836:                 }
 7837:             }
 7838:         }
 7839:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7840:         $grouplist = join(':',@usersgroups);
 7841:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7842:     }
 7843:     return @usersgroups;
 7844: }
 7845: 
 7846: sub devalidate_getgroups_cache {
 7847:     my ($udom,$uname,$cdom,$cnum)=@_;
 7848:     my $courseid = $cdom.'_'.$cnum;
 7849: 
 7850:     my $hashid="$udom:$uname:$courseid";
 7851:     &devalidate_cache_new('getgroups',$hashid);
 7852: }
 7853: 
 7854: # ------------------------------------------------------------------ Plain Text
 7855: 
 7856: sub plaintext {
 7857:     my ($short,$type,$cid,$forcedefault) = @_;
 7858:     if ($short =~ m{^cr/}) {
 7859: 	return (split('/',$short))[-1];
 7860:     }
 7861:     if (!defined($cid)) {
 7862:         $cid = $env{'request.course.id'};
 7863:     }
 7864:     my %rolenames = (
 7865:                       Course    => 'std',
 7866:                       Community => 'alt1',
 7867:                     );
 7868:     if ($cid ne '') {
 7869:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7870:             unless ($forcedefault) {
 7871:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7872:                 &Apache::lonlocal::mt_escape(\$roletext);
 7873:                 return &Apache::lonlocal::mt($roletext);
 7874:             }
 7875:         }
 7876:     }
 7877:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7878:         (defined($rolenames{$type})) && 
 7879:         (defined($prp{$short}{$rolenames{$type}}))) {
 7880:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7881:     } elsif ($cid ne '') {
 7882:         my $crstype = $env{'course.'.$cid.'.type'};
 7883:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7884:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7885:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7886:         }
 7887:     }
 7888:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7889: }
 7890: 
 7891: # ----------------------------------------------------------------- Assign Role
 7892: 
 7893: sub assignrole {
 7894:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7895:         $context)=@_;
 7896:     my $mrole;
 7897:     if ($role =~ /^cr\//) {
 7898:         my $cwosec=$url;
 7899:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7900: 	unless (&allowed('ccr',$cwosec)) {
 7901:            my $refused = 1;
 7902:            if ($context eq 'requestcourses') {
 7903:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7904:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7905:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7906:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7907:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7908:                            if ($crsenv{'internal.courseowner'} eq
 7909:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7910:                                $refused = '';
 7911:                            }
 7912:                        }
 7913:                    }
 7914:                }
 7915:            }
 7916:            if ($refused) {
 7917:                &logthis('Refused custom assignrole: '.
 7918:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7919:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7920:                return 'refused';
 7921:            }
 7922:         }
 7923:         $mrole='cr';
 7924:     } elsif ($role =~ /^gr\//) {
 7925:         my $cwogrp=$url;
 7926:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7927:         unless (&allowed('mdg',$cwogrp)) {
 7928:             &logthis('Refused group assignrole: '.
 7929:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7930:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7931:             return 'refused';
 7932:         }
 7933:         $mrole='gr';
 7934:     } else {
 7935:         my $cwosec=$url;
 7936:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7937:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7938:             my $refused;
 7939:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7940:                 if (!(&allowed('c'.$role,$url))) {
 7941:                     $refused = 1;
 7942:                 }
 7943:             } else {
 7944:                 $refused = 1;
 7945:             }
 7946:             if ($refused) {
 7947:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7948:                 if (!$selfenroll && $context eq 'course') {
 7949:                     my %crsenv;
 7950:                     if ($role eq 'cc' || $role eq 'co') {
 7951:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7952:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7953:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7954:                                 if ($crsenv{'internal.courseowner'} eq 
 7955:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7956:                                     $refused = '';
 7957:                                 }
 7958:                             }
 7959:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7960:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7961:                                 if ($crsenv{'internal.courseowner'} eq 
 7962:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7963:                                     $refused = '';
 7964:                                 }
 7965:                             }
 7966:                         }
 7967:                     }
 7968:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7969:                     $refused = '';
 7970:                 } elsif ($context eq 'requestcourses') {
 7971:                     my @possroles = ('st','ta','ep','in','cc','co');
 7972:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7973:                         my $wrongcc;
 7974:                         if ($cnum =~ /^$match_community$/) {
 7975:                             $wrongcc = 1 if ($role eq 'cc');
 7976:                         } else {
 7977:                             $wrongcc = 1 if ($role eq 'co');
 7978:                         }
 7979:                         unless ($wrongcc) {
 7980:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7981:                             if ($crsenv{'internal.courseowner'} eq 
 7982:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7983:                                 $refused = '';
 7984:                             }
 7985:                         }
 7986:                     }
 7987:                 } elsif ($context eq 'requestauthor') {
 7988:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 7989:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 7990:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 7991:                             $refused = '';
 7992:                         } else {
 7993:                             my %domdefaults = &get_domain_defaults($udom);
 7994:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 7995:                                 my $checkbystatus;
 7996:                                 if ($env{'user.adv'}) { 
 7997:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 7998:                                     if ($disposition eq 'automatic') {
 7999:                                         $refused = '';
 8000:                                     } elsif ($disposition eq '') {
 8001:                                         $checkbystatus = 1;
 8002:                                     } 
 8003:                                 } else {
 8004:                                     $checkbystatus = 1;
 8005:                                 }
 8006:                                 if ($checkbystatus) {
 8007:                                     if ($env{'environment.inststatus'}) {
 8008:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8009:                                         foreach my $type (@inststatuses) {
 8010:                                             if (($type ne '') &&
 8011:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8012:                                                 $refused = '';
 8013:                                             }
 8014:                                         }
 8015:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8016:                                         $refused = '';
 8017:                                     }
 8018:                                 }
 8019:                             }
 8020:                         }
 8021:                     }
 8022:                 }
 8023:                 if ($refused) {
 8024:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8025:                              ' '.$role.' '.$end.' '.$start.' by '.
 8026: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8027:                     return 'refused';
 8028:                 }
 8029:             }
 8030:         } elsif ($role eq 'au') {
 8031:             if ($url ne '/'.$udom.'/') {
 8032:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8033:                          ' to assign author role for '.$uname.':'.$udom.
 8034:                          ' in domain: '.$url.' refused (wrong domain).');
 8035:                 return 'refused';
 8036:             }
 8037:         }
 8038:         $mrole=$role;
 8039:     }
 8040:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8041:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8042:     if ($end) { $command.='_'.$end; }
 8043:     if ($start) {
 8044: 	if ($end) { 
 8045:            $command.='_'.$start; 
 8046:         } else {
 8047:            $command.='_0_'.$start;
 8048:         }
 8049:     }
 8050:     my $origstart = $start;
 8051:     my $origend = $end;
 8052:     my $delflag;
 8053: # actually delete
 8054:     if ($deleteflag) {
 8055: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8056: # modify command to delete the role
 8057:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8058:                 "$udom:$uname:$url".'_'."$mrole";
 8059: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8060: # set start and finish to negative values for userrolelog
 8061:            $start=-1;
 8062:            $end=-1;
 8063:            $delflag = 1;
 8064:         }
 8065:     }
 8066: # send command
 8067:     my $answer=&reply($command,&homeserver($uname,$udom));
 8068: # log new user role if status is ok
 8069:     if ($answer eq 'ok') {
 8070: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8071:         if (($role eq 'cc') || ($role eq 'in') ||
 8072:             ($role eq 'ep') || ($role eq 'ad') ||
 8073:             ($role eq 'ta') || ($role eq 'st') ||
 8074:             ($role=~/^cr/) || ($role eq 'gr') ||
 8075:             ($role eq 'co')) {
 8076: # for course roles, perform group memberships changes triggered by role change.
 8077:             unless ($role =~ /^gr/) {
 8078:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8079:                                                  $origstart,$selfenroll,$context);
 8080:             }
 8081:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8082:                            $selfenroll,$context);
 8083:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8084:                  ($role eq 'au') || ($role eq 'dc')) {
 8085:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8086:                            $context);
 8087:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8088:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8089:                              $context); 
 8090:         }
 8091:         if ($role eq 'cc') {
 8092:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8093:         }
 8094:     }
 8095:     return $answer;
 8096: }
 8097: 
 8098: sub autoupdate_coowners {
 8099:     my ($url,$end,$start,$uname,$udom) = @_;
 8100:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8101:     if (($cdom ne '') && ($cnum ne '')) {
 8102:         my $now = time;
 8103:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8104:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8105:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8106:             my $instcode = $coursehash{'internal.coursecode'};
 8107:             if ($instcode ne '') {
 8108:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8109:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8110:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8111:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8112:                         if ($result eq 'valid') {
 8113:                             if ($coursehash{'internal.co-owners'}) {
 8114:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8115:                                     push(@newcoowners,$coowner);
 8116:                                 }
 8117:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8118:                                     push(@newcoowners,$uname.':'.$udom);
 8119:                                 }
 8120:                                 @newcoowners = sort(@newcoowners);
 8121:                             } else {
 8122:                                 push(@newcoowners,$uname.':'.$udom);
 8123:                             }
 8124:                         } else {
 8125:                             if ($coursehash{'internal.co-owners'}) {
 8126:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8127:                                     unless ($coowner eq $uname.':'.$udom) {
 8128:                                         push(@newcoowners,$coowner);
 8129:                                     }
 8130:                                 }
 8131:                                 unless (@newcoowners > 0) {
 8132:                                     $delcoowners = 1;
 8133:                                     $coowners = '';
 8134:                                 }
 8135:                             }
 8136:                         }
 8137:                         if (@newcoowners || $delcoowners) {
 8138:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8139:                                             $delcoowners,@newcoowners);
 8140:                         }
 8141:                     }
 8142:                 }
 8143:             }
 8144:         }
 8145:     }
 8146: }
 8147: 
 8148: sub store_coowners {
 8149:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8150:     my $cid = $cdom.'_'.$cnum;
 8151:     my ($coowners,$delresult,$putresult);
 8152:     if (@newcoowners) {
 8153:         $coowners = join(',',@newcoowners);
 8154:         my %coownershash = (
 8155:                             'internal.co-owners' => $coowners,
 8156:                            );
 8157:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8158:         if ($putresult eq 'ok') {
 8159:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8160:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8161:             }
 8162:         }
 8163:     }
 8164:     if ($delcoowners) {
 8165:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8166:         if ($delresult eq 'ok') {
 8167:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8168:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8169:             }
 8170:         }
 8171:     }
 8172:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8173:         my %crsinfo =
 8174:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8175:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8176:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8177:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8178:         }
 8179:     }
 8180: }
 8181: 
 8182: # -------------------------------------------------- Modify user authentication
 8183: # Overrides without validation
 8184: 
 8185: sub modifyuserauth {
 8186:     my ($udom,$uname,$umode,$upass)=@_;
 8187:     my $uhome=&homeserver($uname,$udom);
 8188:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8189:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8190:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8191:              ' in domain '.$env{'request.role.domain'});  
 8192:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8193: 		     &escape($upass),$uhome);
 8194:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8195:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8196:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8197:     &log($udom,,$uname,$uhome,
 8198:         'Authentication changed by '.$env{'user.domain'}.', '.
 8199:                                      $env{'user.name'}.', '.$umode.
 8200:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8201:     unless ($reply eq 'ok') {
 8202:         &logthis('Authentication mode error: '.$reply);
 8203: 	return 'error: '.$reply;
 8204:     }   
 8205:     return 'ok';
 8206: }
 8207: 
 8208: # --------------------------------------------------------------- Modify a user
 8209: 
 8210: sub modifyuser {
 8211:     my ($udom,    $uname, $uid,
 8212:         $umode,   $upass, $first,
 8213:         $middle,  $last,  $gene,
 8214:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8215:     $udom= &LONCAPA::clean_domain($udom);
 8216:     $uname=&LONCAPA::clean_username($uname);
 8217:     my $showcandelete = 'none';
 8218:     if (ref($candelete) eq 'ARRAY') {
 8219:         if (@{$candelete} > 0) {
 8220:             $showcandelete = join(', ',@{$candelete});
 8221:         }
 8222:     }
 8223:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8224:              $umode.', '.$first.', '.$middle.', '.
 8225: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8226:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8227:                                      ' desiredhome not specified'). 
 8228:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8229:              ' in domain '.$env{'request.role.domain'});
 8230:     my $uhome=&homeserver($uname,$udom,'true');
 8231:     my $newuser;
 8232:     if ($uhome eq 'no_host') {
 8233:         $newuser = 1;
 8234:     }
 8235: # ----------------------------------------------------------------- Create User
 8236:     if (($uhome eq 'no_host') && 
 8237: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8238:         my $unhome='';
 8239:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8240:             $unhome = $desiredhome;
 8241: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8242: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8243:         } else { # load balancing routine for determining $unhome
 8244:             my $loadm=10000000;
 8245: 	    my %servers = &get_servers($udom,'library');
 8246: 	    foreach my $tryserver (keys(%servers)) {
 8247: 		my $answer=reply('load',$tryserver);
 8248: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8249: 		    $loadm=$answer;
 8250: 		    $unhome=$tryserver;
 8251: 		}
 8252: 	    }
 8253:         }
 8254:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8255: 	    return 'error: unable to find a home server for '.$uname.
 8256:                    ' in domain '.$udom;
 8257:         }
 8258:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8259:                          &escape($upass),$unhome);
 8260: 	unless ($reply eq 'ok') {
 8261:             return 'error: '.$reply;
 8262:         }   
 8263:         $uhome=&homeserver($uname,$udom,'true');
 8264:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8265: 	    return 'error: unable verify users home machine.';
 8266:         }
 8267:     }   # End of creation of new user
 8268: # ---------------------------------------------------------------------- Add ID
 8269:     if ($uid) {
 8270:        $uid=~tr/A-Z/a-z/;
 8271:        my %uidhash=&idrget($udom,$uname);
 8272:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8273:          && (!$forceid)) {
 8274: 	  unless ($uid eq $uidhash{$uname}) {
 8275: 	      return 'error: user id "'.$uid.'" does not match '.
 8276:                   'current user id "'.$uidhash{$uname}.'".';
 8277:           }
 8278:        } else {
 8279: 	  &idput($udom,($uname => $uid));
 8280:        }
 8281:     }
 8282: # -------------------------------------------------------------- Add names, etc
 8283:     my @tmp=&get('environment',
 8284: 		   ['firstname','middlename','lastname','generation','id',
 8285:                     'permanentemail','inststatus'],
 8286: 		   $udom,$uname);
 8287:     my (%names,%oldnames);
 8288:     if ($tmp[0] =~ m/^error:.*/) { 
 8289:         %names=(); 
 8290:     } else {
 8291:         %names = @tmp;
 8292:         %oldnames = %names;
 8293:     }
 8294: #
 8295: # If name, email and/or uid are blank (e.g., because an uploaded file
 8296: # of users did not contain them), do not overwrite existing values
 8297: # unless field is in $candelete array ref.  
 8298: #
 8299: 
 8300:     my @fields = ('firstname','middlename','lastname','generation',
 8301:                   'permanentemail','id');
 8302:     my %newvalues;
 8303:     if (ref($candelete) eq 'ARRAY') {
 8304:         foreach my $field (@fields) {
 8305:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8306:                 if ($field eq 'firstname') {
 8307:                     $names{$field} = $first;
 8308:                 } elsif ($field eq 'middlename') {
 8309:                     $names{$field} = $middle;
 8310:                 } elsif ($field eq 'lastname') {
 8311:                     $names{$field} = $last;
 8312:                 } elsif ($field eq 'generation') { 
 8313:                     $names{$field} = $gene;
 8314:                 } elsif ($field eq 'permanentemail') {
 8315:                     $names{$field} = $email;
 8316:                 } elsif ($field eq 'id') {
 8317:                     $names{$field}  = $uid;
 8318:                 }
 8319:             }
 8320:         }
 8321:     }
 8322:     if ($first)  { $names{'firstname'}  = $first; }
 8323:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8324:     if ($last)   { $names{'lastname'}   = $last; }
 8325:     if (defined($gene))   { $names{'generation'} = $gene; }
 8326:     if ($email) {
 8327:        $email=~s/[^\w\@\.\-\,]//gs;
 8328:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8329:     }
 8330:     if ($uid) { $names{'id'}  = $uid; }
 8331:     if (defined($inststatus)) {
 8332:         $names{'inststatus'} = '';
 8333:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8334:         if (ref($usertypes) eq 'HASH') {
 8335:             my @okstatuses; 
 8336:             foreach my $item (split(/:/,$inststatus)) {
 8337:                 if (defined($usertypes->{$item})) {
 8338:                     push(@okstatuses,$item);  
 8339:                 }
 8340:             }
 8341:             if (@okstatuses) {
 8342:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8343:             }
 8344:         }
 8345:     }
 8346:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8347:                  $umode.', '.$first.', '.$middle.', '.
 8348:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8349:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8350:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8351:     } else {
 8352:         $logmsg .= ' during self creation';
 8353:     }
 8354:     my $changed;
 8355:     if ($newuser) {
 8356:         $changed = 1;
 8357:     } else {
 8358:         foreach my $field (@fields) {
 8359:             if ($names{$field} ne $oldnames{$field}) {
 8360:                 $changed = 1;
 8361:                 last;
 8362:             }
 8363:         }
 8364:     }
 8365:     unless ($changed) {
 8366:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8367:         &logthis($logmsg);
 8368:         return 'ok';
 8369:     }
 8370:     my $reply = &put('environment', \%names, $udom,$uname);
 8371:     if ($reply ne 'ok') { 
 8372:         return 'error: '.$reply;
 8373:     }
 8374:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8375:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8376:     }
 8377:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8378:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8379:     $logmsg = 'Success modifying user '.$logmsg;
 8380:     &logthis($logmsg);
 8381:     return 'ok';
 8382: }
 8383: 
 8384: # -------------------------------------------------------------- Modify student
 8385: 
 8386: sub modifystudent {
 8387:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8388:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8389:         $selfenroll,$context,$inststatus,$credits)=@_;
 8390:     if (!$cid) {
 8391: 	unless ($cid=$env{'request.course.id'}) {
 8392: 	    return 'not_in_class';
 8393: 	}
 8394:     }
 8395: # --------------------------------------------------------------- Make the user
 8396:     my $reply=&modifyuser
 8397: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8398:          $desiredhome,$email,$inststatus);
 8399:     unless ($reply eq 'ok') { return $reply; }
 8400:     # This will cause &modify_student_enrollment to get the uid from the
 8401:     # students environment
 8402:     $uid = undef if (!$forceid);
 8403:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8404:                                         $gene,$usec,$end,$start,$type,$locktype,
 8405:                                         $cid,$selfenroll,$context,$credits);
 8406:     return $reply;
 8407: }
 8408: 
 8409: sub modify_student_enrollment {
 8410:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8411:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8412:     my ($cdom,$cnum,$chome);
 8413:     if (!$cid) {
 8414: 	unless ($cid=$env{'request.course.id'}) {
 8415: 	    return 'not_in_class';
 8416: 	}
 8417: 	$cdom=$env{'course.'.$cid.'.domain'};
 8418: 	$cnum=$env{'course.'.$cid.'.num'};
 8419:     } else {
 8420: 	($cdom,$cnum)=split(/_/,$cid);
 8421:     }
 8422:     $chome=$env{'course.'.$cid.'.home'};
 8423:     if (!$chome) {
 8424: 	$chome=&homeserver($cnum,$cdom);
 8425:     }
 8426:     if (!$chome) { return 'unknown_course'; }
 8427:     # Make sure the user exists
 8428:     my $uhome=&homeserver($uname,$udom);
 8429:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8430: 	return 'error: no such user';
 8431:     }
 8432:     # Get student data if we were not given enough information
 8433:     if (!defined($first)  || $first  eq '' || 
 8434:         !defined($last)   || $last   eq '' || 
 8435:         !defined($uid)    || $uid    eq '' || 
 8436:         !defined($middle) || $middle eq '' || 
 8437:         !defined($gene)   || $gene   eq '') {
 8438:         # They did not supply us with enough data to enroll the student, so
 8439:         # we need to pick up more information.
 8440:         my %tmp = &get('environment',
 8441:                        ['firstname','middlename','lastname', 'generation','id']
 8442:                        ,$udom,$uname);
 8443: 
 8444:         #foreach my $key (keys(%tmp)) {
 8445:         #    &logthis("key $key = ".$tmp{$key});
 8446:         #}
 8447:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8448:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8449:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8450:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8451:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8452:     }
 8453:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8454:     my $user = "$uname:$udom";
 8455:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8456:     my $reply=cput('classlist',
 8457: 		   {$user => 
 8458: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8459: 		   $cdom,$cnum);
 8460:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8461:         &devalidate_getsection_cache($udom,$uname,$cid);
 8462:     } else { 
 8463: 	return 'error: '.$reply;
 8464:     }
 8465:     # Add student role to user
 8466:     my $uurl='/'.$cid;
 8467:     $uurl=~s/\_/\//g;
 8468:     if ($usec) {
 8469: 	$uurl.='/'.$usec;
 8470:     }
 8471:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8472:                              $selfenroll,$context);
 8473:     if ($result ne 'ok') {
 8474:         if ($old_entry{$user} ne '') {
 8475:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8476:         } else {
 8477:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8478:         }
 8479:     }
 8480:     return $result; 
 8481: }
 8482: 
 8483: sub format_name {
 8484:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8485:     my $name;
 8486:     if ($first ne 'lastname') {
 8487: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8488:     } else {
 8489: 	if ($lastname=~/\S/) {
 8490: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8491: 	    $name=~s/\s+,/,/;
 8492: 	} else {
 8493: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8494: 	}
 8495:     }
 8496:     $name=~s/^\s+//;
 8497:     $name=~s/\s+$//;
 8498:     $name=~s/\s+/ /g;
 8499:     return $name;
 8500: }
 8501: 
 8502: # ------------------------------------------------- Write to course preferences
 8503: 
 8504: sub writecoursepref {
 8505:     my ($courseid,%prefs)=@_;
 8506:     $courseid=~s/^\///;
 8507:     $courseid=~s/\_/\//g;
 8508:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8509:     my $chome=homeserver($cnum,$cdomain);
 8510:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8511: 	return 'error: no such course';
 8512:     }
 8513:     my $cstring='';
 8514:     foreach my $pref (keys(%prefs)) {
 8515: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8516:     }
 8517:     $cstring=~s/\&$//;
 8518:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8519: }
 8520: 
 8521: # ---------------------------------------------------------- Make/modify course
 8522: 
 8523: sub createcourse {
 8524:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8525:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8526:     $url=&declutter($url);
 8527:     my $cid='';
 8528:     if ($context eq 'requestcourses') {
 8529:         my $can_create = 0;
 8530:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8531:         if ($udom eq $ownerdom) {
 8532:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8533:                                   $context)) {
 8534:                 $can_create = 1;
 8535:             }
 8536:         } else {
 8537:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8538:                                            $category);
 8539:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8540:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8541:                 if (@curr > 0) {
 8542:                     my @options = qw(approval validate autolimit);
 8543:                     my $optregex = join('|',@options);
 8544:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8545:                         $can_create = 1;
 8546:                     }
 8547:                 }
 8548:             }
 8549:         }
 8550:         if ($can_create) {
 8551:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8552:                 unless (&allowed('ccc',$udom)) {
 8553:                     return 'refused'; 
 8554:                 }
 8555:             }
 8556:         } else {
 8557:             return 'refused';
 8558:         }
 8559:     } elsif (!&allowed('ccc',$udom)) {
 8560:         return 'refused';
 8561:     }
 8562: # --------------------------------------------------------------- Get Unique ID
 8563:     my $uname;
 8564:     if ($cnum =~ /^$match_courseid$/) {
 8565:         my $chome=&homeserver($cnum,$udom,'true');
 8566:         if (($chome eq '') || ($chome eq 'no_host')) {
 8567:             $uname = $cnum;
 8568:         } else {
 8569:             $uname = &generate_coursenum($udom,$crstype);
 8570:         }
 8571:     } else {
 8572:         $uname = &generate_coursenum($udom,$crstype);
 8573:     }
 8574:     return $uname if ($uname =~ /^error/);
 8575: # -------------------------------------------------- Check supplied server name
 8576:     if (!defined($course_server)) {
 8577:         if (defined(&domain($udom,'primary'))) {
 8578:             $course_server = &domain($udom,'primary');
 8579:         } else {
 8580:             $course_server = $env{'user.home'}; 
 8581:         }
 8582:     }
 8583:     my %host_servers =
 8584:         &Apache::lonnet::get_servers($udom,'library');
 8585:     unless ($host_servers{$course_server}) {
 8586:         return 'error: invalid home server for course: '.$course_server;
 8587:     }
 8588: # ------------------------------------------------------------- Make the course
 8589:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8590:                       $course_server);
 8591:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8592:     my $uhome=&homeserver($uname,$udom,'true');
 8593:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8594: 	return 'error: no such course';
 8595:     }
 8596: # ----------------------------------------------------------------- Course made
 8597: # log existence
 8598:     my $now = time;
 8599:     my $newcourse = {
 8600:                     $udom.'_'.$uname => {
 8601:                                      description => $description,
 8602:                                      inst_code   => $inst_code,
 8603:                                      owner       => $course_owner,
 8604:                                      type        => $crstype,
 8605:                                      creator     => $env{'user.name'}.':'.
 8606:                                                     $env{'user.domain'},
 8607:                                      created     => $now,
 8608:                                      context     => $context,
 8609:                                                 },
 8610:                     };
 8611:     &courseidput($udom,$newcourse,$uhome,'notime');
 8612: # set toplevel url
 8613:     my $topurl=$url;
 8614:     unless ($nonstandard) {
 8615: # ------------------------------------------ For standard courses, make top url
 8616:         my $mapurl=&clutter($url);
 8617:         if ($mapurl eq '/res/') { $mapurl=''; }
 8618:         $env{'form.initmap'}=(<<ENDINITMAP);
 8619: <map>
 8620: <resource id="1" type="start"></resource>
 8621: <resource id="2" src="$mapurl"></resource>
 8622: <resource id="3" type="finish"></resource>
 8623: <link index="1" from="1" to="2"></link>
 8624: <link index="2" from="2" to="3"></link>
 8625: </map>
 8626: ENDINITMAP
 8627:         $topurl=&declutter(
 8628:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8629:                           );
 8630:     }
 8631: # ----------------------------------------------------------- Write preferences
 8632:     &writecoursepref($udom.'_'.$uname,
 8633:                      ('description'              => $description,
 8634:                       'url'                      => $topurl,
 8635:                       'internal.creator'         => $env{'user.name'}.':'.
 8636:                                                     $env{'user.domain'},
 8637:                       'internal.created'         => $now,
 8638:                       'internal.creationcontext' => $context)
 8639:                     );
 8640:     return '/'.$udom.'/'.$uname;
 8641: }
 8642: 
 8643: # ------------------------------------------------------------------- Create ID
 8644: sub generate_coursenum {
 8645:     my ($udom,$crstype) = @_;
 8646:     my $domdesc = &domain($udom);
 8647:     return 'error: invalid domain' if ($domdesc eq '');
 8648:     my $first;
 8649:     if ($crstype eq 'Community') {
 8650:         $first = '0';
 8651:     } else {
 8652:         $first = int(1+rand(9)); 
 8653:     } 
 8654:     my $uname=$first.
 8655:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8656:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8657:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8658: # ----------------------------------------------- Make sure that does not exist
 8659:     my $uhome=&homeserver($uname,$udom,'true');
 8660:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8661:         if ($crstype eq 'Community') {
 8662:             $first = '0';
 8663:         } else {
 8664:             $first = int(1+rand(9));
 8665:         }
 8666:         $uname=$first.
 8667:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8668:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8669:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8670:         $uhome=&homeserver($uname,$udom,'true');
 8671:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8672:             return 'error: unable to generate unique course-ID';
 8673:         }
 8674:     }
 8675:     return $uname;
 8676: }
 8677: 
 8678: sub is_course {
 8679:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8680:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8681: 
 8682:     return unless $cdom and $cnum;
 8683: 
 8684:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8685:         '.');
 8686: 
 8687:     return unless exists($courses{$cdom.'_'.$cnum});
 8688:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8689: }
 8690: 
 8691: sub store_userdata {
 8692:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8693:     my $result;
 8694:     if ($datakey ne '') {
 8695:         if (ref($storehash) eq 'HASH') {
 8696:             if ($udom eq '' || $uname eq '') {
 8697:                 $udom = $env{'user.domain'};
 8698:                 $uname = $env{'user.name'};
 8699:             }
 8700:             my $uhome=&homeserver($uname,$udom);
 8701:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8702:                 $result = 'error: no_host';
 8703:             } else {
 8704:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8705:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8706: 
 8707:                 my $namevalue='';
 8708:                 foreach my $key (keys(%{$storehash})) {
 8709:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8710:                 }
 8711:                 $namevalue=~s/\&$//;
 8712:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8713:                                   $namevalue,$uhome);
 8714:             }
 8715:         } else {
 8716:             $result = 'error: data to store was not a hash reference'; 
 8717:         }
 8718:     } else {
 8719:         $result= 'error: invalid requestkey'; 
 8720:     }
 8721:     return $result;
 8722: }
 8723: 
 8724: # ---------------------------------------------------------- Assign Custom Role
 8725: 
 8726: sub assigncustomrole {
 8727:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8728:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8729:                        $end,$start,$deleteflag,$selfenroll,$context);
 8730: }
 8731: 
 8732: # ----------------------------------------------------------------- Revoke Role
 8733: 
 8734: sub revokerole {
 8735:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8736:     my $now=time;
 8737:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8738: }
 8739: 
 8740: # ---------------------------------------------------------- Revoke Custom Role
 8741: 
 8742: sub revokecustomrole {
 8743:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8744:     my $now=time;
 8745:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8746:            $deleteflag,$selfenroll,$context);
 8747: }
 8748: 
 8749: # ------------------------------------------------------------ Disk usage
 8750: sub diskusage {
 8751:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8752:     $directorypath =~ s/\/$//;
 8753:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8754:                        .&escape($getpropath).':'.&escape($uname).':'
 8755:                        .&escape($udom),homeserver($uname,$udom));
 8756:     if ($listing eq 'unknown_cmd') {
 8757:         if ($getpropath) {
 8758:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8759:         }
 8760:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8761:     }
 8762:     return $listing;
 8763: }
 8764: 
 8765: sub is_locked {
 8766:     my ($file_name, $domain, $user, $which) = @_;
 8767:     my @check;
 8768:     my $is_locked;
 8769:     push (@check,$file_name);
 8770:     my %locked = &get('file_permissions',\@check,
 8771: 		      $env{'user.domain'},$env{'user.name'});
 8772:     my ($tmp)=keys(%locked);
 8773:     if ($tmp=~/^error:/) { undef(%locked); }
 8774:     
 8775:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8776:         $is_locked = 'false';
 8777:         foreach my $entry (@{$locked{$file_name}}) {
 8778:            if (ref($entry) eq 'ARRAY') {
 8779:                $is_locked = 'true';
 8780:                if (ref($which) eq 'ARRAY') {
 8781:                    push(@{$which},$entry);
 8782:                } else {
 8783:                    last;
 8784:                }
 8785:            }
 8786:        }
 8787:     } else {
 8788:         $is_locked = 'false';
 8789:     }
 8790:     return $is_locked;
 8791: }
 8792: 
 8793: sub declutter_portfile {
 8794:     my ($file) = @_;
 8795:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8796:     return $file;
 8797: }
 8798: 
 8799: # ------------------------------------------------------------- Mark as Read Only
 8800: 
 8801: sub mark_as_readonly {
 8802:     my ($domain,$user,$files,$what) = @_;
 8803:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8804:     my ($tmp)=keys(%current_permissions);
 8805:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8806:     foreach my $file (@{$files}) {
 8807: 	$file = &declutter_portfile($file);
 8808:         push(@{$current_permissions{$file}},$what);
 8809:     }
 8810:     &put('file_permissions',\%current_permissions,$domain,$user);
 8811:     return;
 8812: }
 8813: 
 8814: # ------------------------------------------------------------Save Selected Files
 8815: 
 8816: sub save_selected_files {
 8817:     my ($user, $path, @files) = @_;
 8818:     my $filename = $user."savedfiles";
 8819:     my @other_files = &files_not_in_path($user, $path);
 8820:     open (OUT, '>'.$tmpdir.$filename);
 8821:     foreach my $file (@files) {
 8822:         print (OUT $env{'form.currentpath'}.$file."\n");
 8823:     }
 8824:     foreach my $file (@other_files) {
 8825:         print (OUT $file."\n");
 8826:     }
 8827:     close (OUT);
 8828:     return 'ok';
 8829: }
 8830: 
 8831: sub clear_selected_files {
 8832:     my ($user) = @_;
 8833:     my $filename = $user."savedfiles";
 8834:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8835:     print (OUT undef);
 8836:     close (OUT);
 8837:     return ("ok");    
 8838: }
 8839: 
 8840: sub files_in_path {
 8841:     my ($user, $path) = @_;
 8842:     my $filename = $user."savedfiles";
 8843:     my %return_files;
 8844:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8845:     while (my $line_in = <IN>) {
 8846:         chomp ($line_in);
 8847:         my @paths_and_file = split (m!/!, $line_in);
 8848:         my $file_part = pop (@paths_and_file);
 8849:         my $path_part = join ('/', @paths_and_file);
 8850:         $path_part.='/';
 8851:         my $path_and_file = $path_part.$file_part;
 8852:         if ($path_part eq $path) {
 8853:             $return_files{$file_part}= 'selected';
 8854:         }
 8855:     }
 8856:     close (IN);
 8857:     return (\%return_files);
 8858: }
 8859: 
 8860: # called in portfolio select mode, to show files selected NOT in current directory
 8861: sub files_not_in_path {
 8862:     my ($user, $path) = @_;
 8863:     my $filename = $user."savedfiles";
 8864:     my @return_files;
 8865:     my $path_part;
 8866:     open(IN, '<'.LONCAPA::.$filename);
 8867:     while (my $line = <IN>) {
 8868:         #ok, I know it's clunky, but I want it to work
 8869:         my @paths_and_file = split(m|/|, $line);
 8870:         my $file_part = pop(@paths_and_file);
 8871:         chomp($file_part);
 8872:         my $path_part = join('/', @paths_and_file);
 8873:         $path_part .= '/';
 8874:         my $path_and_file = $path_part.$file_part;
 8875:         if ($path_part ne $path) {
 8876:             push(@return_files, ($path_and_file));
 8877:         }
 8878:     }
 8879:     close(OUT);
 8880:     return (@return_files);
 8881: }
 8882: 
 8883: #----------------------------------------------Get portfolio file permissions
 8884: 
 8885: sub get_portfile_permissions {
 8886:     my ($domain,$user) = @_;
 8887:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8888:     my ($tmp)=keys(%current_permissions);
 8889:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8890:     return \%current_permissions;
 8891: }
 8892: 
 8893: #---------------------------------------------Get portfolio file access controls
 8894: 
 8895: sub get_access_controls {
 8896:     my ($current_permissions,$group,$file) = @_;
 8897:     my %access;
 8898:     my $real_file = $file;
 8899:     $file =~ s/\.meta$//;
 8900:     if (defined($file)) {
 8901:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8902:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8903:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8904:             }
 8905:         }
 8906:     } else {
 8907:         foreach my $key (keys(%{$current_permissions})) {
 8908:             if ($key =~ /\0accesscontrol$/) {
 8909:                 if (defined($group)) {
 8910:                     if ($key !~ m-^\Q$group\E/-) {
 8911:                         next;
 8912:                     }
 8913:                 }
 8914:                 my ($fullpath) = split(/\0/,$key);
 8915:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8916:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8917:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8918:                     }
 8919:                 }
 8920:             }
 8921:         }
 8922:     }
 8923:     return %access;
 8924: }
 8925: 
 8926: sub modify_access_controls {
 8927:     my ($file_name,$changes,$domain,$user)=@_;
 8928:     my ($outcome,$deloutcome);
 8929:     my %store_permissions;
 8930:     my %new_values;
 8931:     my %new_control;
 8932:     my %translation;
 8933:     my @deletions = ();
 8934:     my $now = time;
 8935:     if (exists($$changes{'activate'})) {
 8936:         if (ref($$changes{'activate'}) eq 'HASH') {
 8937:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8938:             my $numnew = scalar(@newitems);
 8939:             for (my $i=0; $i<$numnew; $i++) {
 8940:                 my $newkey = $newitems[$i];
 8941:                 my $newid = &Apache::loncommon::get_cgi_id();
 8942:                 if ($newkey =~ /^\d+:/) { 
 8943:                     $newkey =~ s/^(\d+)/$newid/;
 8944:                     $translation{$1} = $newid;
 8945:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8946:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8947:                     $translation{$1} = $newid;
 8948:                 }
 8949:                 $new_values{$file_name."\0".$newkey} = 
 8950:                                           $$changes{'activate'}{$newitems[$i]};
 8951:                 $new_control{$newkey} = $now;
 8952:             }
 8953:         }
 8954:     }
 8955:     my %todelete;
 8956:     my %changed_items;
 8957:     foreach my $action ('delete','update') {
 8958:         if (exists($$changes{$action})) {
 8959:             if (ref($$changes{$action}) eq 'HASH') {
 8960:                 foreach my $key (keys(%{$$changes{$action}})) {
 8961:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8962:                     if ($action eq 'delete') { 
 8963:                         $todelete{$itemnum} = 1;
 8964:                     } else {
 8965:                         $changed_items{$itemnum} = $key;
 8966:                     }
 8967:                 }
 8968:             }
 8969:         }
 8970:     }
 8971:     # get lock on access controls for file.
 8972:     my $lockhash = {
 8973:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8974:                                                        ':'.$env{'user.domain'},
 8975:                    }; 
 8976:     my $tries = 0;
 8977:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8978:    
 8979:     while (($gotlock ne 'ok') && $tries <3) {
 8980:         $tries ++;
 8981:         sleep 1;
 8982:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8983:     }
 8984:     if ($gotlock eq 'ok') {
 8985:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8986:         my ($tmp)=keys(%curr_permissions);
 8987:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8988:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8989:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8990:             if (ref($curr_controls) eq 'HASH') {
 8991:                 foreach my $control_item (keys(%{$curr_controls})) {
 8992:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8993:                     if (defined($todelete{$itemnum})) {
 8994:                         push(@deletions,$file_name."\0".$control_item);
 8995:                     } else {
 8996:                         if (defined($changed_items{$itemnum})) {
 8997:                             $new_control{$changed_items{$itemnum}} = $now;
 8998:                             push(@deletions,$file_name."\0".$control_item);
 8999:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9000:                         } else {
 9001:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9002:                         }
 9003:                     }
 9004:                 }
 9005:             }
 9006:         }
 9007:         my ($group);
 9008:         if (&is_course($domain,$user)) {
 9009:             ($group,my $file) = split(/\//,$file_name,2);
 9010:         }
 9011:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9012:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9013:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9014:         #  remove lock
 9015:         my @del_lock = ($file_name."\0".'locked_access_records');
 9016:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9017:         my $sqlresult =
 9018:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9019:                                     $group);
 9020:     } else {
 9021:         $outcome = "error: could not obtain lockfile\n";  
 9022:     }
 9023:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9024: }
 9025: 
 9026: sub make_public_indefinitely {
 9027:     my ($requrl) = @_;
 9028:     my $now = time;
 9029:     my $action = 'activate';
 9030:     my $aclnum = 0;
 9031:     if (&is_portfolio_url($requrl)) {
 9032:         my (undef,$udom,$unum,$file_name,$group) =
 9033:             &parse_portfolio_url($requrl);
 9034:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9035:         my %access_controls = &get_access_controls($current_perms,
 9036:                                                    $group,$file_name);
 9037:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9038:             my ($num,$scope,$end,$start) = 
 9039:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9040:             if ($scope eq 'public') {
 9041:                 if ($start <= $now && $end == 0) {
 9042:                     $action = 'none';
 9043:                 } else {
 9044:                     $action = 'update';
 9045:                     $aclnum = $num;
 9046:                 }
 9047:                 last;
 9048:             }
 9049:         }
 9050:         if ($action eq 'none') {
 9051:              return 'ok';
 9052:         } else {
 9053:             my %changes;
 9054:             my $newend = 0;
 9055:             my $newstart = $now;
 9056:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9057:             $changes{$action}{$newkey} = {
 9058:                 type => 'public',
 9059:                 time => {
 9060:                     start => $newstart,
 9061:                     end   => $newend,
 9062:                 },
 9063:             };
 9064:             my ($outcome,$deloutcome,$new_values,$translation) =
 9065:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9066:             return $outcome;
 9067:         }
 9068:     } else {
 9069:         return 'invalid';
 9070:     }
 9071: }
 9072: 
 9073: #------------------------------------------------------Get Marked as Read Only
 9074: 
 9075: sub get_marked_as_readonly {
 9076:     my ($domain,$user,$what,$group) = @_;
 9077:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9078:     my @readonly_files;
 9079:     my $cmp1=$what;
 9080:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9081:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9082:         if (defined($group)) {
 9083:             if ($file_name !~ m-^\Q$group\E/-) {
 9084:                 next;
 9085:             }
 9086:         }
 9087:         if (ref($value) eq "ARRAY"){
 9088:             foreach my $stored_what (@{$value}) {
 9089:                 my $cmp2=$stored_what;
 9090:                 if (ref($stored_what) eq 'ARRAY') {
 9091:                     $cmp2=join('',@{$stored_what});
 9092:                 }
 9093:                 if ($cmp1 eq $cmp2) {
 9094:                     push(@readonly_files, $file_name);
 9095:                     last;
 9096:                 } elsif (!defined($what)) {
 9097:                     push(@readonly_files, $file_name);
 9098:                     last;
 9099:                 }
 9100:             }
 9101:         }
 9102:     }
 9103:     return @readonly_files;
 9104: }
 9105: #-----------------------------------------------------------Get Marked as Read Only Hash
 9106: 
 9107: sub get_marked_as_readonly_hash {
 9108:     my ($current_permissions,$group,$what) = @_;
 9109:     my %readonly_files;
 9110:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9111:         if (defined($group)) {
 9112:             if ($file_name !~ m-^\Q$group\E/-) {
 9113:                 next;
 9114:             }
 9115:         }
 9116:         if (ref($value) eq "ARRAY"){
 9117:             foreach my $stored_what (@{$value}) {
 9118:                 if (ref($stored_what) eq 'ARRAY') {
 9119:                     foreach my $lock_descriptor(@{$stored_what}) {
 9120:                         if ($lock_descriptor eq 'graded') {
 9121:                             $readonly_files{$file_name} = 'graded';
 9122:                         } elsif ($lock_descriptor eq 'handback') {
 9123:                             $readonly_files{$file_name} = 'handback';
 9124:                         } else {
 9125:                             if (!exists($readonly_files{$file_name})) {
 9126:                                 $readonly_files{$file_name} = 'locked';
 9127:                             }
 9128:                         }
 9129:                     }
 9130:                 } 
 9131:             }
 9132:         } 
 9133:     }
 9134:     return %readonly_files;
 9135: }
 9136: # ------------------------------------------------------------ Unmark as Read Only
 9137: 
 9138: sub unmark_as_readonly {
 9139:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9140:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9141:     my ($domain,$user,$what,$file_name,$group) = @_;
 9142:     $file_name = &declutter_portfile($file_name);
 9143:     my $symb_crs = $what;
 9144:     if (ref($what)) { $symb_crs=join('',@$what); }
 9145:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9146:     my ($tmp)=keys(%current_permissions);
 9147:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9148:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9149:     foreach my $file (@readonly_files) {
 9150: 	my $clean_file = &declutter_portfile($file);
 9151: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9152: 	my $current_locks = $current_permissions{$file};
 9153:         my @new_locks;
 9154:         my @del_keys;
 9155:         if (ref($current_locks) eq "ARRAY"){
 9156:             foreach my $locker (@{$current_locks}) {
 9157:                 my $compare=$locker;
 9158:                 if (ref($locker) eq 'ARRAY') {
 9159:                     $compare=join('',@{$locker});
 9160:                     if ($compare ne $symb_crs) {
 9161:                         push(@new_locks, $locker);
 9162:                     }
 9163:                 }
 9164:             }
 9165:             if (scalar(@new_locks) > 0) {
 9166:                 $current_permissions{$file} = \@new_locks;
 9167:             } else {
 9168:                 push(@del_keys, $file);
 9169:                 &del('file_permissions',\@del_keys, $domain, $user);
 9170:                 delete($current_permissions{$file});
 9171:             }
 9172:         }
 9173:     }
 9174:     &put('file_permissions',\%current_permissions,$domain,$user);
 9175:     return;
 9176: }
 9177: 
 9178: # ------------------------------------------------------------ Directory lister
 9179: 
 9180: sub dirlist {
 9181:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9182:     $uri=~s/^\///;
 9183:     $uri=~s/\/$//;
 9184:     my ($udom, $uname);
 9185:     if ($getuserdir) {
 9186:         $udom = $userdomain;
 9187:         $uname = $username;
 9188:     } else {
 9189:         (undef,$udom,$uname)=split(/\//,$uri);
 9190:         if(defined($userdomain)) {
 9191:             $udom = $userdomain;
 9192:         }
 9193:         if(defined($username)) {
 9194:             $uname = $username;
 9195:         }
 9196:     }
 9197:     my ($dirRoot,$listing,@listing_results);
 9198: 
 9199:     $dirRoot = $perlvar{'lonDocRoot'};
 9200:     if (defined($getpropath)) {
 9201:         $dirRoot = &propath($udom,$uname);
 9202:         $dirRoot =~ s/\/$//;
 9203:     } elsif (defined($getuserdir)) {
 9204:         my $subdir=$uname.'__';
 9205:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9206:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9207:                    ."/$udom/$subdir/$uname";
 9208:     } elsif (defined($alternateRoot)) {
 9209:         $dirRoot = $alternateRoot;
 9210:     }
 9211: 
 9212:     if($udom) {
 9213:         if($uname) {
 9214:             my $uhome = &homeserver($uname,$udom);
 9215:             if ($uhome eq 'no_host') {
 9216:                 return ([],'no_host');
 9217:             }
 9218:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9219:                               .$getuserdir.':'.&escape($dirRoot)
 9220:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9221:             if ($listing eq 'unknown_cmd') {
 9222:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9223:             } else {
 9224:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9225:             }
 9226:             if ($listing eq 'unknown_cmd') {
 9227:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9228:                 @listing_results = split(/:/,$listing);
 9229:             } else {
 9230:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9231:             }
 9232:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9233:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9234:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9235:                 return ([],$listing);
 9236:             } else {
 9237:                 return (\@listing_results);
 9238:             }
 9239:         } elsif(!$alternateRoot) {
 9240:             my (%allusers,%listerror);
 9241: 	    my %servers = &get_servers($udom,'library');
 9242:  	    foreach my $tryserver (keys(%servers)) {
 9243:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9244:                                   &escape($udom),$tryserver);
 9245:                 if ($listing eq 'unknown_cmd') {
 9246: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9247: 				      $udom, $tryserver);
 9248:                 } else {
 9249:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9250:                 }
 9251: 		if ($listing eq 'unknown_cmd') {
 9252: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9253: 				      $udom, $tryserver);
 9254: 		    @listing_results = split(/:/,$listing);
 9255: 		} else {
 9256: 		    @listing_results =
 9257: 			map { &unescape($_); } split(/:/,$listing);
 9258: 		}
 9259:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9260:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9261:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9262:                     $listerror{$tryserver} = $listing;
 9263:                 } else {
 9264: 		    foreach my $line (@listing_results) {
 9265: 			my ($entry) = split(/&/,$line,2);
 9266: 			$allusers{$entry} = 1;
 9267: 		    }
 9268: 		}
 9269:             }
 9270:             my @alluserslist=();
 9271:             foreach my $user (sort(keys(%allusers))) {
 9272:                 push(@alluserslist,$user.'&user');
 9273:             }
 9274:             return (\@alluserslist);
 9275:         } else {
 9276:             return ([],'missing username');
 9277:         }
 9278:     } elsif(!defined($getpropath)) {
 9279:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9280:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9281:         return (\@all_domains);
 9282:     } else {
 9283:         return ([],'missing domain');
 9284:     }
 9285: }
 9286: 
 9287: # --------------------------------------------- GetFileTimestamp
 9288: # This function utilizes dirlist and returns the date stamp for
 9289: # when it was last modified.  It will also return an error of -1
 9290: # if an error occurs
 9291: 
 9292: sub GetFileTimestamp {
 9293:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9294:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9295:     $studentName   = &LONCAPA::clean_username($studentName);
 9296:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9297:                                     undef,$getuserdir);
 9298:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9299:         return -1;
 9300:     }
 9301:     if (ref($fileref) eq 'ARRAY') {
 9302:         my @stats = split('&',$fileref->[0]);
 9303:         # @stats contains first the filename, then the stat output
 9304:         return $stats[10]; # so this is 10 instead of 9.
 9305:     } else {
 9306:         return -1;
 9307:     }
 9308: }
 9309: 
 9310: sub stat_file {
 9311:     my ($uri) = @_;
 9312:     $uri = &clutter_with_no_wrapper($uri);
 9313: 
 9314:     my ($udom,$uname,$file);
 9315:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9316: 	($udom,$uname,$file) =
 9317: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9318: 	$file = 'userfiles/'.$file;
 9319:     }
 9320:     if ($uri =~ m-^/res/-) {
 9321: 	($udom,$uname) = 
 9322: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9323: 	$file = $uri;
 9324:     }
 9325: 
 9326:     if (!$udom || !$uname || !$file) {
 9327: 	# unable to handle the uri
 9328: 	return ();
 9329:     }
 9330:     my $getpropath;
 9331:     if ($file =~ /^userfiles\//) {
 9332:         $getpropath = 1;
 9333:     }
 9334:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9335:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9336:         return ();
 9337:     } else {
 9338:         if (ref($listref) eq 'ARRAY') {
 9339:             my @stats = split('&',$listref->[0]);
 9340: 	    shift(@stats); #filename is first
 9341: 	    return @stats;
 9342:         }
 9343:     }
 9344:     return ();
 9345: }
 9346: 
 9347: # -------------------------------------------------------- Value of a Condition
 9348: 
 9349: # gets the value of a specific preevaluated condition
 9350: #    stored in the string  $env{user.state.<cid>}
 9351: # or looks up a condition reference in the bighash and if if hasn't
 9352: # already been evaluated recurses into docondval to get the value of
 9353: # the condition, then memoizing it to 
 9354: #   $env{user.state.<cid>.<condition>}
 9355: sub directcondval {
 9356:     my $number=shift;
 9357:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9358: 	&Apache::lonuserstate::evalstate();
 9359:     }
 9360:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9361: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9362:     } elsif ($number =~ /^_/) {
 9363: 	my $sub_condition;
 9364: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9365: 		&GDBM_READER(),0640)) {
 9366: 	    $sub_condition=$bighash{'conditions'.$number};
 9367: 	    untie(%bighash);
 9368: 	}
 9369: 	my $value = &docondval($sub_condition);
 9370: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9371: 	return $value;
 9372:     }
 9373:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9374:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9375:     } else {
 9376:        return 2;
 9377:     }
 9378: }
 9379: 
 9380: # get the collection of conditions for this resource
 9381: sub condval {
 9382:     my $condidx=shift;
 9383:     my $allpathcond='';
 9384:     foreach my $cond (split(/\|/,$condidx)) {
 9385: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9386: 	    $allpathcond.=
 9387: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9388: 	}
 9389:     }
 9390:     $allpathcond=~s/\|$//;
 9391:     return &docondval($allpathcond);
 9392: }
 9393: 
 9394: #evaluates an expression of conditions
 9395: sub docondval {
 9396:     my ($allpathcond) = @_;
 9397:     my $result=0;
 9398:     if ($env{'request.course.id'}
 9399: 	&& defined($allpathcond)) {
 9400: 	my $operand='|';
 9401: 	my @stack;
 9402: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9403: 	    if ($chunk eq '(') {
 9404: 		push @stack,($operand,$result);
 9405: 	    } elsif ($chunk eq ')') {
 9406: 		my $before=pop @stack;
 9407: 		if (pop @stack eq '&') {
 9408: 		    $result=$result>$before?$before:$result;
 9409: 		} else {
 9410: 		    $result=$result>$before?$result:$before;
 9411: 		}
 9412: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9413: 		$operand=$chunk;
 9414: 	    } else {
 9415: 		my $new=directcondval($chunk);
 9416: 		if ($operand eq '&') {
 9417: 		    $result=$result>$new?$new:$result;
 9418: 		} else {
 9419: 		    $result=$result>$new?$result:$new;
 9420: 		}
 9421: 	    }
 9422: 	}
 9423:     }
 9424:     return $result;
 9425: }
 9426: 
 9427: # ---------------------------------------------------- Devalidate courseresdata
 9428: 
 9429: sub devalidatecourseresdata {
 9430:     my ($coursenum,$coursedomain)=@_;
 9431:     my $hashid=$coursenum.':'.$coursedomain;
 9432:     &devalidate_cache_new('courseres',$hashid);
 9433: }
 9434: 
 9435: 
 9436: # --------------------------------------------------- Course Resourcedata Query
 9437: #
 9438: #  Parameters:
 9439: #      $coursenum    - Number of the course.
 9440: #      $coursedomain - Domain at which the course was created.
 9441: #  Returns:
 9442: #     A hash of the course parameters along (I think) with timestamps
 9443: #     and version info.
 9444: 
 9445: sub get_courseresdata {
 9446:     my ($coursenum,$coursedomain)=@_;
 9447:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9448:     my $hashid=$coursenum.':'.$coursedomain;
 9449:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9450:     my %dumpreply;
 9451:     unless (defined($cached)) {
 9452: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9453: 	$result=\%dumpreply;
 9454: 	my ($tmp) = keys(%dumpreply);
 9455: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9456: 	    &do_cache_new('courseres',$hashid,$result,600);
 9457: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9458: 	    return $tmp;
 9459: 	} elsif ($tmp =~ /^(error)/) {
 9460: 	    $result=undef;
 9461: 	    &do_cache_new('courseres',$hashid,$result,600);
 9462: 	}
 9463:     }
 9464:     return $result;
 9465: }
 9466: 
 9467: sub devalidateuserresdata {
 9468:     my ($uname,$udom)=@_;
 9469:     my $hashid="$udom:$uname";
 9470:     &devalidate_cache_new('userres',$hashid);
 9471: }
 9472: 
 9473: sub get_userresdata {
 9474:     my ($uname,$udom)=@_;
 9475:     #most student don\'t have any data set, check if there is some data
 9476:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9477: 
 9478:     my $hashid="$udom:$uname";
 9479:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9480:     if (!defined($cached)) {
 9481: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9482: 	$result=\%resourcedata;
 9483: 	&do_cache_new('userres',$hashid,$result,600);
 9484:     }
 9485:     my ($tmp)=keys(%$result);
 9486:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9487: 	return $result;
 9488:     }
 9489:     #error 2 occurs when the .db doesn't exist
 9490:     if ($tmp!~/error: 2 /) {
 9491: 	&logthis("<font color=\"blue\">WARNING:".
 9492: 		 " Trying to get resource data for ".
 9493: 		 $uname." at ".$udom.": ".
 9494: 		 $tmp."</font>");
 9495:     } elsif ($tmp=~/error: 2 /) {
 9496: 	#&EXT_cache_set($udom,$uname);
 9497: 	&do_cache_new('userres',$hashid,undef,600);
 9498: 	undef($tmp); # not really an error so don't send it back
 9499:     }
 9500:     return $tmp;
 9501: }
 9502: #----------------------------------------------- resdata - return resource data
 9503: #  Purpose:
 9504: #    Return resource data for either users or for a course.
 9505: #  Parameters:
 9506: #     $name      - Course/user name.
 9507: #     $domain    - Name of the domain the user/course is registered on.
 9508: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9509: #     @which     - Array of names of resources desired.
 9510: #  Returns:
 9511: #     The value of the first reasource in @which that is found in the
 9512: #     resource hash.
 9513: #  Exceptional Conditions:
 9514: #     If the $type passed in is not valid (not the string 'course' or 
 9515: #     'user', an undefined  reference is returned.
 9516: #     If none of the resources are found, an undef is returned
 9517: sub resdata {
 9518:     my ($name,$domain,$type,@which)=@_;
 9519:     my $result;
 9520:     if ($type eq 'course') {
 9521: 	$result=&get_courseresdata($name,$domain);
 9522:     } elsif ($type eq 'user') {
 9523: 	$result=&get_userresdata($name,$domain);
 9524:     }
 9525:     if (!ref($result)) { return $result; }    
 9526:     foreach my $item (@which) {
 9527: 	if (defined($result->{$item->[0]})) {
 9528: 	    return [$result->{$item->[0]},$item->[1]];
 9529: 	}
 9530:     }
 9531:     return undef;
 9532: }
 9533: 
 9534: #
 9535: # EXT resource caching routines
 9536: #
 9537: 
 9538: sub clear_EXT_cache_status {
 9539:     &delenv('cache.EXT.');
 9540: }
 9541: 
 9542: sub EXT_cache_status {
 9543:     my ($target_domain,$target_user) = @_;
 9544:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9545:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9546:         # We know already the user has no data
 9547:         return 1;
 9548:     } else {
 9549:         return 0;
 9550:     }
 9551: }
 9552: 
 9553: sub EXT_cache_set {
 9554:     my ($target_domain,$target_user) = @_;
 9555:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9556:     #&appenv({$cachename => time});
 9557: }
 9558: 
 9559: # --------------------------------------------------------- Value of a Variable
 9560: sub EXT {
 9561: 
 9562:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 9563:     unless ($varname) { return ''; }
 9564:     #get real user name/domain, courseid and symb
 9565:     my $courseid;
 9566:     my $publicuser;
 9567:     if ($symbparm) {
 9568: 	$symbparm=&get_symb_from_alias($symbparm);
 9569:     }
 9570:     if (!($uname && $udom)) {
 9571:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9572:       if (!$symbparm) {	$symbparm=$cursymb; }
 9573:     } else {
 9574: 	$courseid=$env{'request.course.id'};
 9575:     }
 9576:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9577:     my $rest;
 9578:     if (defined($therest[0])) {
 9579:        $rest=join('.',@therest);
 9580:     } else {
 9581:        $rest='';
 9582:     }
 9583: 
 9584:     my $qualifierrest=$qualifier;
 9585:     if ($rest) { $qualifierrest.='.'.$rest; }
 9586:     my $spacequalifierrest=$space;
 9587:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9588:     if ($realm eq 'user') {
 9589: # --------------------------------------------------------------- user.resource
 9590: 	if ($space eq 'resource') {
 9591: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9592: 		  || defined($Apache::lonhomework::parsing_a_task))
 9593: 		 &&
 9594: 		 ($symbparm eq &symbread()) ) {	
 9595: 		# if we are in the middle of processing the resource the
 9596: 		# get the value we are planning on committing
 9597:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9598:                     return $Apache::lonhomework::results{$qualifierrest};
 9599:                 } else {
 9600:                     return $Apache::lonhomework::history{$qualifierrest};
 9601:                 }
 9602: 	    } else {
 9603: 		my %restored;
 9604: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9605: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9606: 		} else {
 9607: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9608: 		}
 9609: 		return $restored{$qualifierrest};
 9610: 	    }
 9611: # ----------------------------------------------------------------- user.access
 9612:         } elsif ($space eq 'access') {
 9613: 	    # FIXME - not supporting calls for a specific user
 9614:             return &allowed($qualifier,$rest);
 9615: # ------------------------------------------ user.preferences, user.environment
 9616:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9617: 	    if (($uname eq $env{'user.name'}) &&
 9618: 		($udom eq $env{'user.domain'})) {
 9619: 		return $env{join('.',('environment',$qualifierrest))};
 9620: 	    } else {
 9621: 		my %returnhash;
 9622: 		if (!$publicuser) {
 9623: 		    %returnhash=&userenvironment($udom,$uname,
 9624: 						 $qualifierrest);
 9625: 		}
 9626: 		return $returnhash{$qualifierrest};
 9627: 	    }
 9628: # ----------------------------------------------------------------- user.course
 9629:         } elsif ($space eq 'course') {
 9630: 	    # FIXME - not supporting calls for a specific user
 9631:             return $env{join('.',('request.course',$qualifier))};
 9632: # ------------------------------------------------------------------- user.role
 9633:         } elsif ($space eq 'role') {
 9634: 	    # FIXME - not supporting calls for a specific user
 9635:             my ($role,$where)=split(/\./,$env{'request.role'});
 9636:             if ($qualifier eq 'value') {
 9637: 		return $role;
 9638:             } elsif ($qualifier eq 'extent') {
 9639:                 return $where;
 9640:             }
 9641: # ----------------------------------------------------------------- user.domain
 9642:         } elsif ($space eq 'domain') {
 9643:             return $udom;
 9644: # ------------------------------------------------------------------- user.name
 9645:         } elsif ($space eq 'name') {
 9646:             return $uname;
 9647: # ---------------------------------------------------- Any other user namespace
 9648:         } else {
 9649: 	    my %reply;
 9650: 	    if (!$publicuser) {
 9651: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9652: 	    }
 9653: 	    return $reply{$qualifierrest};
 9654:         }
 9655:     } elsif ($realm eq 'query') {
 9656: # ---------------------------------------------- pull stuff out of query string
 9657:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9658: 						[$spacequalifierrest]);
 9659: 	return $env{'form.'.$spacequalifierrest}; 
 9660:    } elsif ($realm eq 'request') {
 9661: # ------------------------------------------------------------- request.browser
 9662:         if ($space eq 'browser') {
 9663:             return $env{'browser.'.$qualifier};
 9664: # ------------------------------------------------------------ request.filename
 9665:         } else {
 9666:             return $env{'request.'.$spacequalifierrest};
 9667:         }
 9668:     } elsif ($realm eq 'course') {
 9669: # ---------------------------------------------------------- course.description
 9670:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9671:     } elsif ($realm eq 'resource') {
 9672: 
 9673: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9674: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9675: 	}
 9676: 
 9677: 	if ($space eq 'title') {
 9678: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9679: 	    return &gettitle($symbparm);
 9680: 	}
 9681: 	
 9682: 	if ($space eq 'map') {
 9683: 	    my ($map) = &decode_symb($symbparm);
 9684: 	    return &symbread($map);
 9685: 	}
 9686: 	if ($space eq 'filename') {
 9687: 	    if ($symbparm) {
 9688: 		return &clutter((&decode_symb($symbparm))[2]);
 9689: 	    }
 9690: 	    return &hreflocation('',$env{'request.filename'});
 9691: 	}
 9692: 
 9693: 	my ($section, $group, @groups);
 9694: 	my ($courselevelm,$courselevel);
 9695: 	if ($symbparm && defined($courseid) && 
 9696: 	    $courseid eq $env{'request.course.id'}) {
 9697: 
 9698: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9699: 
 9700: # ----------------------------------------------------- Cascading lookup scheme
 9701: 	    my $symbp=$symbparm;
 9702: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9703: 
 9704: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9705: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9706: 
 9707: 	    if (($env{'user.name'} eq $uname) &&
 9708: 		($env{'user.domain'} eq $udom)) {
 9709: 		$section=$env{'request.course.sec'};
 9710:                 @groups = split(/:/,$env{'request.course.groups'});  
 9711:                 @groups=&sort_course_groups($courseid,@groups); 
 9712: 	    } else {
 9713: 		if (! defined($usection)) {
 9714: 		    $section=&getsection($udom,$uname,$courseid);
 9715: 		} else {
 9716: 		    $section = $usection;
 9717: 		}
 9718:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9719: 	    }
 9720: 
 9721: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9722: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9723: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9724: 
 9725: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9726: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9727: 	    $courselevelm=$courseid.'.'.$mapparm;
 9728: 
 9729: # ----------------------------------------------------------- first, check user
 9730: 
 9731: 	    my $userreply=&resdata($uname,$udom,'user',
 9732: 				       ([$courselevelr,'resource'],
 9733: 					[$courselevelm,'map'     ],
 9734: 					[$courselevel, 'course'  ]));
 9735: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9736: 
 9737: # ------------------------------------------------ second, check some of course
 9738:             my $coursereply;
 9739:             if (@groups > 0) {
 9740:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9741:                                        $mapparm,$spacequalifierrest);
 9742:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9743:             }
 9744: 
 9745: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9746: 				  $env{'course.'.$courseid.'.domain'},
 9747: 				  'course',
 9748: 				  ([$seclevelr,   'resource'],
 9749: 				   [$seclevelm,   'map'     ],
 9750: 				   [$seclevel,    'course'  ],
 9751: 				   [$courselevelr,'resource']));
 9752: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9753: 
 9754: # ------------------------------------------------------ third, check map parms
 9755: 	    my %parmhash=();
 9756: 	    my $thisparm='';
 9757: 	    if (tie(%parmhash,'GDBM_File',
 9758: 		    $env{'request.course.fn'}.'_parms.db',
 9759: 		    &GDBM_READER(),0640)) {
 9760: 		$thisparm=$parmhash{$symbparm};
 9761: 		untie(%parmhash);
 9762: 	    }
 9763: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9764: 	}
 9765: # ------------------------------------------ fourth, look in resource metadata
 9766: 
 9767: 	$spacequalifierrest=~s/\./\_/;
 9768: 	my $filename;
 9769: 	if (!$symbparm) { $symbparm=&symbread(); }
 9770: 	if ($symbparm) {
 9771: 	    $filename=(&decode_symb($symbparm))[2];
 9772: 	} else {
 9773: 	    $filename=$env{'request.filename'};
 9774: 	}
 9775: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9776: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9777: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9778: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9779: 
 9780: # ---------------------------------------------- fourth, look in rest of course
 9781: 	if ($symbparm && defined($courseid) && 
 9782: 	    $courseid eq $env{'request.course.id'}) {
 9783: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9784: 				     $env{'course.'.$courseid.'.domain'},
 9785: 				     'course',
 9786: 				     ([$courselevelm,'map'   ],
 9787: 				      [$courselevel, 'course']));
 9788: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9789: 	}
 9790: # ------------------------------------------------------------------ Cascade up
 9791: 	unless ($space eq '0') {
 9792: 	    my @parts=split(/_/,$space);
 9793: 	    my $id=pop(@parts);
 9794: 	    my $part=join('_',@parts);
 9795: 	    if ($part eq '') { $part='0'; }
 9796: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9797: 				 $symbparm,$udom,$uname,$section,1);
 9798: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9799: 	}
 9800: 	if ($recurse) { return undef; }
 9801: 	my $pack_def=&packages_tab_default($filename,$varname);
 9802: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9803: # ---------------------------------------------------- Any other user namespace
 9804:     } elsif ($realm eq 'environment') {
 9805: # ----------------------------------------------------------------- environment
 9806: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9807: 	    return $env{'environment.'.$spacequalifierrest};
 9808: 	} else {
 9809: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9810: 		return '';
 9811: 	    }
 9812: 	    my %returnhash=&userenvironment($udom,$uname,
 9813: 					    $spacequalifierrest);
 9814: 	    return $returnhash{$spacequalifierrest};
 9815: 	}
 9816:     } elsif ($realm eq 'system') {
 9817: # ----------------------------------------------------------------- system.time
 9818: 	if ($space eq 'time') {
 9819: 	    return time;
 9820:         }
 9821:     } elsif ($realm eq 'server') {
 9822: # ----------------------------------------------------------------- system.time
 9823: 	if ($space eq 'name') {
 9824: 	    return $ENV{'SERVER_NAME'};
 9825:         }
 9826:     }
 9827:     return '';
 9828: }
 9829: 
 9830: sub get_reply {
 9831:     my ($reply_value) = @_;
 9832:     if (ref($reply_value) eq 'ARRAY') {
 9833:         if (wantarray) {
 9834: 	    return @$reply_value;
 9835:         }
 9836:         return $reply_value->[0];
 9837:     } else {
 9838:         return $reply_value;
 9839:     }
 9840: }
 9841: 
 9842: sub check_group_parms {
 9843:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9844:     my @groupitems = ();
 9845:     my $resultitem;
 9846:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9847:     foreach my $group (@{$groups}) {
 9848:         foreach my $level (@levels) {
 9849:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9850:              push(@groupitems,[$item,$level->[1]]);
 9851:         }
 9852:     }
 9853:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9854:                             $env{'course.'.$courseid.'.domain'},
 9855:                                      'course',@groupitems);
 9856:     return $coursereply;
 9857: }
 9858: 
 9859: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9860:     my ($courseid,@groups) = @_;
 9861:     @groups = sort(@groups);
 9862:     return @groups;
 9863: }
 9864: 
 9865: sub packages_tab_default {
 9866:     my ($uri,$varname)=@_;
 9867:     my (undef,$part,$name)=split(/\./,$varname);
 9868: 
 9869:     my (@extension,@specifics,$do_default);
 9870:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9871: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9872: 	if ($pack_type eq 'default') {
 9873: 	    $do_default=1;
 9874: 	} elsif ($pack_type eq 'extension') {
 9875: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9876: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9877: 	    # only look at packages defaults for packages that this id is
 9878: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9879: 	}
 9880:     }
 9881:     # first look for a package that matches the requested part id
 9882:     foreach my $package (@specifics) {
 9883: 	my (undef,$pack_type,$pack_part)=@{$package};
 9884: 	next if ($pack_part ne $part);
 9885: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9886: 	    return $packagetab{"$pack_type&$name&default"};
 9887: 	}
 9888:     }
 9889:     # look for any possible matching non extension_ package
 9890:     foreach my $package (@specifics) {
 9891: 	my (undef,$pack_type,$pack_part)=@{$package};
 9892: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9893: 	    return $packagetab{"$pack_type&$name&default"};
 9894: 	}
 9895: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9896: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9897: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9898: 	}
 9899:     }
 9900:     # look for any posible extension_ match
 9901:     foreach my $package (@extension) {
 9902: 	my ($package,$pack_type)=@{$package};
 9903: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9904: 	    return $packagetab{"$pack_type&$name&default"};
 9905: 	}
 9906: 	if (defined($packagetab{$package."&$name&default"})) {
 9907: 	    return $packagetab{$package."&$name&default"};
 9908: 	}
 9909:     }
 9910:     # look for a global default setting
 9911:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9912: 	return $packagetab{"default&$name&default"};
 9913:     }
 9914:     return undef;
 9915: }
 9916: 
 9917: sub add_prefix_and_part {
 9918:     my ($prefix,$part)=@_;
 9919:     my $keyroot;
 9920:     if (defined($prefix) && $prefix !~ /^__/) {
 9921: 	# prefix that has a part already
 9922: 	$keyroot=$prefix;
 9923:     } elsif (defined($prefix)) {
 9924: 	# prefix that is missing a part
 9925: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9926:     } else {
 9927: 	# no prefix at all
 9928: 	if (defined($part)) { $keyroot='_'.$part; }
 9929:     }
 9930:     return $keyroot;
 9931: }
 9932: 
 9933: # ---------------------------------------------------------------- Get metadata
 9934: 
 9935: my %metaentry;
 9936: my %importedpartids;
 9937: sub metadata {
 9938:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9939:     $uri=&declutter($uri);
 9940:     # if it is a non metadata possible uri return quickly
 9941:     if (($uri eq '') || 
 9942: 	(($uri =~ m|^/*adm/|) && 
 9943: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9944:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9945: 	return undef;
 9946:     }
 9947:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9948: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9949: 	return undef;
 9950:     }
 9951:     my $filename=$uri;
 9952:     $uri=~s/\.meta$//;
 9953: #
 9954: # Is the metadata already cached?
 9955: # Look at timestamp of caching
 9956: # Everything is cached by the main uri, libraries are never directly cached
 9957: #
 9958:     if (!defined($liburi)) {
 9959: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9960: 	if (defined($cached)) { return $result->{':'.$what}; }
 9961:     }
 9962:     {
 9963: # Imported parts would go here
 9964:         my %importedids=();
 9965:         my @origfileimportpartids=();
 9966:         my $importedparts=0;
 9967: #
 9968: # Is this a recursive call for a library?
 9969: #
 9970: #	if (! exists($metacache{$uri})) {
 9971: #	    $metacache{$uri}={};
 9972: #	}
 9973: 	my $cachetime = 60*60;
 9974:         if ($liburi) {
 9975: 	    $liburi=&declutter($liburi);
 9976:             $filename=$liburi;
 9977:         } else {
 9978: 	    &devalidate_cache_new('meta',$uri);
 9979: 	    undef(%metaentry);
 9980: 	}
 9981:         my %metathesekeys=();
 9982:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9983: 	my $metastring;
 9984: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9985: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9986: 	    $metastring = 
 9987: 		&Apache::lonnet::ssi_body($which,
 9988: 					  ('grade_target' => 'meta'));
 9989: 	    $cachetime = 1; # only want this cached in the child not long term
 9990: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9991:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9992: 	    my $file=&filelocation('',&clutter($filename));
 9993: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9994: 	    $metastring=&getfile($file);
 9995: 	}
 9996:         my $parser=HTML::LCParser->new(\$metastring);
 9997:         my $token;
 9998:         undef %metathesekeys;
 9999:         while ($token=$parser->get_token) {
10000: 	    if ($token->[0] eq 'S') {
10001: 		if (defined($token->[2]->{'package'})) {
10002: #
10003: # This is a package - get package info
10004: #
10005: 		    my $package=$token->[2]->{'package'};
10006: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10007: 		    if (defined($token->[2]->{'id'})) { 
10008: 			$keyroot.='_'.$token->[2]->{'id'}; 
10009: 		    }
10010: 		    if ($metaentry{':packages'}) {
10011: 			$metaentry{':packages'}.=','.$package.$keyroot;
10012: 		    } else {
10013: 			$metaentry{':packages'}=$package.$keyroot;
10014: 		    }
10015: 		    foreach my $pack_entry (keys(%packagetab)) {
10016: 			my $part=$keyroot;
10017: 			$part=~s/^\_//;
10018: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10019: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10020: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10021: 			    # ignore package.tab specified default values
10022:                             # here &package_tab_default() will fetch those
10023: 			    if ($subp eq 'default') { next; }
10024: 			    my $value=$packagetab{$pack_entry};
10025: 			    my $unikey;
10026: 			    if ($pack =~ /_0$/) {
10027: 				$unikey='parameter_0_'.$name;
10028: 				$part=0;
10029: 			    } else {
10030: 				$unikey='parameter'.$keyroot.'_'.$name;
10031: 			    }
10032: 			    if ($subp eq 'display') {
10033: 				$value.=' [Part: '.$part.']';
10034: 			    }
10035: 			    $metaentry{':'.$unikey.'.part'}=$part;
10036: 			    $metathesekeys{$unikey}=1;
10037: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10038: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10039: 			    }
10040: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10041: 				$metaentry{':'.$unikey}=
10042: 				    $metaentry{':'.$unikey.'.default'};
10043: 			    }
10044: 			}
10045: 		    }
10046: 		} else {
10047: #
10048: # This is not a package - some other kind of start tag
10049: #
10050: 		    my $entry=$token->[1];
10051: 		    my $unikey='';
10052: 
10053: 		    if ($entry eq 'import') {
10054: #
10055: # Importing a library here
10056: #
10057:                         my $location=$parser->get_text('/import');
10058:                         my $dir=$filename;
10059:                         $dir=~s|[^/]*$||;
10060:                         $location=&filelocation($dir,$location);
10061:                        
10062:                         my $importmode=$token->[2]->{'importmode'};
10063:                         if ($importmode eq 'problem') {
10064: # Import as problem/response
10065:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10066:                         } elsif ($importmode eq 'part') {
10067: # Import as part(s)
10068:                            $importedparts=1;
10069: # We need to get the original file and the imported file to get the part order correct
10070: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10071: # Load and inspect original file
10072:                            if ($#origfileimportpartids<0) {
10073:                               undef(%importedpartids);
10074:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10075:                               my $origfile=&getfile($origfilelocation);
10076:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10077:                            }
10078: 
10079: # Load and inspect imported file
10080:                            my $impfile=&getfile($location);
10081:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10082:                            if ($#impfilepartids>=0) {
10083: # This problem had parts
10084:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10085:                            } else {
10086: # Importing by turning a single problem into a problem part
10087: # It gets the import-tags ID as part-ID
10088:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10089:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10090:                            }
10091:                         } else {
10092: # Normal import
10093:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10094:                            if (defined($token->[2]->{'id'})) {
10095:                               $unikey.='_'.$token->[2]->{'id'};
10096:                            }
10097:                         }
10098: 
10099: 			if ($depthcount<20) {
10100: 			    my $metadata = 
10101: 				&metadata($uri,'keys', $location,$unikey,
10102: 					  $depthcount+1);
10103: 			    foreach my $meta (split(',',$metadata)) {
10104: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10105: 				$metathesekeys{$meta}=1;
10106: 			    }
10107: 			
10108:                         }
10109: 		    } else {
10110: #
10111: # Not importing, some other kind of non-package, non-library start tag
10112: # 
10113:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10114:                         if (defined($token->[2]->{'id'})) {
10115:                             $unikey.='_'.$token->[2]->{'id'};
10116:                         }
10117: 			if (defined($token->[2]->{'name'})) { 
10118: 			    $unikey.='_'.$token->[2]->{'name'}; 
10119: 			}
10120: 			$metathesekeys{$unikey}=1;
10121: 			foreach my $param (@{$token->[3]}) {
10122: 			    $metaentry{':'.$unikey.'.'.$param} =
10123: 				$token->[2]->{$param};
10124: 			}
10125: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10126: 			my $default=$metaentry{':'.$unikey.'.default'};
10127: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10128: 		 # only ws inside the tag, and not in default, so use default
10129: 		 # as value
10130: 			    $metaentry{':'.$unikey}=$default;
10131: 			} elsif ( $internaltext =~ /\S/ ) {
10132: 		  # something interesting inside the tag
10133: 			    $metaentry{':'.$unikey}=$internaltext;
10134: 			} else {
10135: 		  # no interesting values, don't set a default
10136: 			}
10137: # end of not-a-package not-a-library import
10138: 		    }
10139: # end of not-a-package start tag
10140: 		}
10141: # the next is the end of "start tag"
10142: 	    }
10143: 	}
10144: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10145: 	$extension = lc($extension);
10146: 	if ($extension eq 'htm') { $extension='html'; }
10147: 
10148: 	foreach my $key (keys(%packagetab)) {
10149: 	    #no specific packages #how's our extension
10150: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10151: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10152: 					 \%metathesekeys);
10153: 	}
10154: 
10155: 	if (!exists($metaentry{':packages'})
10156: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10157: 	    foreach my $key (keys(%packagetab)) {
10158: 		#no specific packages well let's get default then
10159: 		if ($key!~/^default&/) { next; }
10160: 		&metadata_create_package_def($uri,$key,'default',
10161: 					     \%metathesekeys);
10162: 	    }
10163: 	}
10164: # are there custom rights to evaluate
10165: 	if ($metaentry{':copyright'} eq 'custom') {
10166: 
10167:     #
10168:     # Importing a rights file here
10169:     #
10170: 	    unless ($depthcount) {
10171: 		my $location=$metaentry{':customdistributionfile'};
10172: 		my $dir=$filename;
10173: 		$dir=~s|[^/]*$||;
10174: 		$location=&filelocation($dir,$location);
10175: 		my $rights_metadata =
10176: 		    &metadata($uri,'keys',$location,'_rights',
10177: 			      $depthcount+1);
10178: 		foreach my $rights (split(',',$rights_metadata)) {
10179: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10180: 		    $metathesekeys{$rights}=1;
10181: 		}
10182: 	    }
10183: 	}
10184: 	# uniqifiy package listing
10185: 	my %seen;
10186: 	my @uniq_packages =
10187: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10188: 	$metaentry{':packages'} = join(',',@uniq_packages);
10189: 
10190:         if ($importedparts) {
10191: # We had imported parts and need to rebuild partorder
10192:            $metaentry{':partorder'}='';
10193:            $metathesekeys{'partorder'}=1;
10194:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10195:                if ($origfileimportpartids[$index] eq 'part') {
10196: # original part, part of the problem
10197:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10198:                } else {
10199: # we have imported parts at this position
10200:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10201:                }
10202:            }
10203:            $metaentry{':partorder'}=~s/^\,//;
10204:         }
10205: 
10206: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10207: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10208: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10209: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10210: # this is the end of "was not already recently cached
10211:     }
10212:     return $metaentry{':'.$what};
10213: }
10214: 
10215: sub metadata_create_package_def {
10216:     my ($uri,$key,$package,$metathesekeys)=@_;
10217:     my ($pack,$name,$subp)=split(/\&/,$key);
10218:     if ($subp eq 'default') { next; }
10219:     
10220:     if (defined($metaentry{':packages'})) {
10221: 	$metaentry{':packages'}.=','.$package;
10222:     } else {
10223: 	$metaentry{':packages'}=$package;
10224:     }
10225:     my $value=$packagetab{$key};
10226:     my $unikey;
10227:     $unikey='parameter_0_'.$name;
10228:     $metaentry{':'.$unikey.'.part'}=0;
10229:     $$metathesekeys{$unikey}=1;
10230:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10231: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10232:     }
10233:     if (defined($metaentry{':'.$unikey.'.default'})) {
10234: 	$metaentry{':'.$unikey}=
10235: 	    $metaentry{':'.$unikey.'.default'};
10236:     }
10237: }
10238: 
10239: sub metadata_generate_part0 {
10240:     my ($metadata,$metacache,$uri) = @_;
10241:     my %allnames;
10242:     foreach my $metakey (keys(%$metadata)) {
10243: 	if ($metakey=~/^parameter\_(.*)/) {
10244: 	  my $part=$$metacache{':'.$metakey.'.part'};
10245: 	  my $name=$$metacache{':'.$metakey.'.name'};
10246: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10247: 	    $allnames{$name}=$part;
10248: 	  }
10249: 	}
10250:     }
10251:     foreach my $name (keys(%allnames)) {
10252:       $$metadata{"parameter_0_$name"}=1;
10253:       my $key=":parameter_0_$name";
10254:       $$metacache{"$key.part"}='0';
10255:       $$metacache{"$key.name"}=$name;
10256:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10257: 					   $allnames{$name}.'_'.$name.
10258: 					   '.type'};
10259:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10260: 			     '.display'};
10261:       my $expr='[Part: '.$allnames{$name}.']';
10262:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10263:       $$metacache{"$key.display"}=$olddis;
10264:     }
10265: }
10266: 
10267: # ------------------------------------------------------ Devalidate title cache
10268: 
10269: sub devalidate_title_cache {
10270:     my ($url)=@_;
10271:     if (!$env{'request.course.id'}) { return; }
10272:     my $symb=&symbread($url);
10273:     if (!$symb) { return; }
10274:     my $key=$env{'request.course.id'}."\0".$symb;
10275:     &devalidate_cache_new('title',$key);
10276: }
10277: 
10278: # ------------------------------------------------- Get the title of a course
10279: 
10280: sub current_course_title {
10281:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10282: }
10283: # ------------------------------------------------- Get the title of a resource
10284: 
10285: sub gettitle {
10286:     my $urlsymb=shift;
10287:     my $symb=&symbread($urlsymb);
10288:     if ($symb) {
10289: 	my $key=$env{'request.course.id'}."\0".$symb;
10290: 	my ($result,$cached)=&is_cached_new('title',$key);
10291: 	if (defined($cached)) { 
10292: 	    return $result;
10293: 	}
10294: 	my ($map,$resid,$url)=&decode_symb($symb);
10295: 	my $title='';
10296: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10297: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10298: 	} else {
10299: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10300: 		    &GDBM_READER(),0640)) {
10301: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10302: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10303: 		untie(%bighash);
10304: 	    }
10305: 	}
10306: 	$title=~s/\&colon\;/\:/gs;
10307: 	if ($title) {
10308: # Remember both $symb and $title for dynamic metadata
10309:             $accesshash{$symb.'___crstitle'}=$title;
10310:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10311: # Cache this title and then return it
10312: 	    return &do_cache_new('title',$key,$title,600);
10313: 	}
10314: 	$urlsymb=$url;
10315:     }
10316:     my $title=&metadata($urlsymb,'title');
10317:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10318:     return $title;
10319: }
10320: 
10321: sub getdocspath {
10322:     my ($symb) = @_;
10323:     my $path;
10324:     if ($symb) {
10325:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
10326:         if ($resurl=~/\.(sequence|page)$/) {
10327:             $mapurl=$resurl;
10328:         } elsif ($resurl eq 'adm/navmaps') {
10329:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
10330:         }
10331:         my $mapresobj;
10332:         my $navmap = Apache::lonnavmaps::navmap->new();
10333:         if (ref($navmap)) {
10334:             $mapresobj = $navmap->getResourceByUrl($mapurl);
10335:         }
10336:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
10337:         my $type=$2;
10338:         if (ref($mapresobj)) {
10339:             my $pcslist = $mapresobj->map_hierarchy();
10340:             if ($pcslist ne '') {
10341:                 foreach my $pc (split(/,/,$pcslist)) {
10342:                     next if ($pc <= 1);
10343:                     my $res = $navmap->getByMapPc($pc);
10344:                     if (ref($res)) {
10345:                         my $thisurl = $res->src();
10346:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
10347:                         my $thistitle = $res->title();
10348:                         $path .= '&'.
10349:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
10350:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
10351:                                  ':'.$res->randompick().
10352:                                  ':'.$res->randomout().
10353:                                  ':'.$res->encrypted().
10354:                                  ':'.$res->randomorder().
10355:                                  ':'.$res->is_page();
10356:                     }
10357:                 }
10358:             }
10359:             $path =~ s/^\&//;
10360:             my $maptitle = $mapresobj->title();
10361:             if ($mapurl eq 'default') {
10362:                 $maptitle = 'Main Course Documents';
10363:             }
10364:             $path .= ($path ne '')? '&' : ''.
10365:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10366:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
10367:                     ':'.$mapresobj->randompick().
10368:                     ':'.$mapresobj->randomout().
10369:                     ':'.$mapresobj->encrypted().
10370:                     ':'.$mapresobj->randomorder().
10371:                     ':'.$mapresobj->is_page();
10372:         } else {
10373:             my $maptitle = &gettitle($mapurl);
10374:             my $ispage;
10375:             if ($mapurl =~ /\.page$/) {
10376:                 $ispage = 1;
10377:             }
10378:             if ($mapurl eq 'default') {
10379:                 $maptitle = 'Main Course Documents';
10380:             }
10381:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10382:                     &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
10383:         }
10384:         unless ($mapurl eq 'default') {
10385:             $path = 'default&'.
10386:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
10387:                     ':::::&'.$path;
10388:         }
10389:     }
10390:     return $path;
10391: }
10392: 
10393: sub get_slot {
10394:     my ($which,$cnum,$cdom)=@_;
10395:     if (!$cnum || !$cdom) {
10396: 	(undef,my $courseid)=&whichuser();
10397: 	$cdom=$env{'course.'.$courseid.'.domain'};
10398: 	$cnum=$env{'course.'.$courseid.'.num'};
10399:     }
10400:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10401:     my %slotinfo;
10402:     if (exists($remembered{$key})) {
10403: 	$slotinfo{$which} = $remembered{$key};
10404:     } else {
10405: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10406: 	&Apache::lonhomework::showhash(%slotinfo);
10407: 	my ($tmp)=keys(%slotinfo);
10408: 	if ($tmp=~/^error:/) { return (); }
10409: 	$remembered{$key} = $slotinfo{$which};
10410:     }
10411:     if (ref($slotinfo{$which}) eq 'HASH') {
10412: 	return %{$slotinfo{$which}};
10413:     }
10414:     return $slotinfo{$which};
10415: }
10416: 
10417: sub get_reservable_slots {
10418:     my ($cnum,$cdom,$uname,$udom) = @_;
10419:     my $now = time;
10420:     my $reservable_info;
10421:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10422:     if (exists($remembered{$key})) {
10423:         $reservable_info = $remembered{$key};
10424:     } else {
10425:         my %resv;
10426:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10427:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10428:         $reservable_info = \%resv;
10429:         $remembered{$key} = $reservable_info;
10430:     }
10431:     return $reservable_info;
10432: }
10433: 
10434: sub get_course_slots {
10435:     my ($cnum,$cdom) = @_;
10436:     my $hashid=$cnum.':'.$cdom;
10437:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10438:     if (defined($cached)) {
10439:         if (ref($result) eq 'HASH') {
10440:             return %{$result};
10441:         }
10442:     } else {
10443:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10444:         my ($tmp) = keys(%slots);
10445:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10446:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
10447:             return %slots;
10448:         }
10449:     }
10450:     return;
10451: }
10452: 
10453: sub devalidate_slots_cache {
10454:     my ($cnum,$cdom)=@_;
10455:     my $hashid=$cnum.':'.$cdom;
10456:     &devalidate_cache_new('allslots',$hashid);
10457: }
10458: 
10459: sub get_coursechange {
10460:     my ($cdom,$cnum) = @_;
10461:     if ($cdom eq '' || $cnum eq '') {
10462:         return unless ($env{'request.course.id'});
10463:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10464:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10465:     }
10466:     my $hashid=$cdom.'_'.$cnum;
10467:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10468:     if ((defined($cached)) && ($change ne '')) {
10469:         return $change;
10470:     } else {
10471:         my %crshash;
10472:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10473:         if ($crshash{'internal.contentchange'} eq '') {
10474:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10475:             if ($change eq '') {
10476:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10477:                 $change = $crshash{'internal.created'};
10478:             }
10479:         } else {
10480:             $change = $crshash{'internal.contentchange'};
10481:         }
10482:         my $cachetime = 600;
10483:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10484:     }
10485:     return $change;
10486: }
10487: 
10488: sub devalidate_coursechange_cache {
10489:     my ($cnum,$cdom)=@_;
10490:     my $hashid=$cnum.':'.$cdom;
10491:     &devalidate_cache_new('crschange',$hashid);
10492: }
10493: 
10494: # ------------------------------------------------- Update symbolic store links
10495: 
10496: sub symblist {
10497:     my ($mapname,%newhash)=@_;
10498:     $mapname=&deversion(&declutter($mapname));
10499:     my %hash;
10500:     if (($env{'request.course.fn'}) && (%newhash)) {
10501:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10502:                       &GDBM_WRCREAT(),0640)) {
10503: 	    foreach my $url (keys(%newhash)) {
10504: 		next if ($url eq 'last_known'
10505: 			 && $env{'form.no_update_last_known'});
10506: 		$hash{declutter($url)}=&encode_symb($mapname,
10507: 						    $newhash{$url}->[1],
10508: 						    $newhash{$url}->[0]);
10509:             }
10510:             if (untie(%hash)) {
10511: 		return 'ok';
10512:             }
10513:         }
10514:     }
10515:     return 'error';
10516: }
10517: 
10518: # --------------------------------------------------------------- Verify a symb
10519: 
10520: sub symbverify {
10521:     my ($symb,$thisurl,$encstate)=@_;
10522:     my $thisfn=$thisurl;
10523:     $thisfn=&declutter($thisfn);
10524: # direct jump to resource in page or to a sequence - will construct own symbs
10525:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10526: # check URL part
10527:     my ($map,$resid,$url)=&decode_symb($symb);
10528: 
10529:     unless ($url eq $thisfn) { return 0; }
10530: 
10531:     $symb=&symbclean($symb);
10532:     $thisurl=&deversion($thisurl);
10533:     $thisfn=&deversion($thisfn);
10534: 
10535:     my %bighash;
10536:     my $okay=0;
10537: 
10538:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10539:                             &GDBM_READER(),0640)) {
10540:         my $noclutter;
10541:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10542:             $thisurl =~ s/\?.+$//;
10543:             if ($map =~ m{^uploaded/.+\.page$}) {
10544:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10545:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10546:                 $noclutter = 1;
10547:             }
10548:         }
10549:         my $ids;
10550:         if ($noclutter) {
10551:             $ids=$bighash{'ids_'.$thisurl};
10552:         } else {
10553:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10554:         }
10555:         unless ($ids) {
10556:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10557:             $ids=$bighash{$idkey};
10558:         }
10559:         if ($ids) {
10560: # ------------------------------------------------------------------- Has ID(s)
10561:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10562:                 $symb =~ s/\?.+$//;
10563:             }
10564: 	    foreach my $id (split(/\,/,$ids)) {
10565: 	       my ($mapid,$resid)=split(/\./,$id);
10566:                if (
10567:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10568:    eq $symb) {
10569:                    if (ref($encstate)) {
10570:                        $$encstate = $bighash{'encrypted_'.$id};
10571:                    }
10572: 		   if (($env{'request.role.adv'}) ||
10573: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10574:                        ($thisurl eq '/adm/navmaps')) {
10575: 		       $okay=1;
10576:                        last;
10577: 		   }
10578: 	       }
10579: 	   }
10580:         }
10581: 	untie(%bighash);
10582:     }
10583:     return $okay;
10584: }
10585: 
10586: # --------------------------------------------------------------- Clean-up symb
10587: 
10588: sub symbclean {
10589:     my $symb=shift;
10590:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10591: # remove version from map
10592:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10593: 
10594: # remove version from URL
10595:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10596: 
10597: # remove wrapper
10598: 
10599:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10600:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10601:     return $symb;
10602: }
10603: 
10604: # ---------------------------------------------- Split symb to find map and url
10605: 
10606: sub encode_symb {
10607:     my ($map,$resid,$url)=@_;
10608:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10609: }
10610: 
10611: sub decode_symb {
10612:     my $symb=shift;
10613:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10614:     my ($map,$resid,$url)=split(/___/,$symb);
10615:     return (&fixversion($map),$resid,&fixversion($url));
10616: }
10617: 
10618: sub fixversion {
10619:     my $fn=shift;
10620:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10621:     my %bighash;
10622:     my $uri=&clutter($fn);
10623:     my $key=$env{'request.course.id'}.'_'.$uri;
10624: # is this cached?
10625:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10626:     if (defined($cached)) { return $result; }
10627: # unfortunately not cached, or expired
10628:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10629: 	    &GDBM_READER(),0640)) {
10630:  	if ($bighash{'version_'.$uri}) {
10631:  	    my $version=$bighash{'version_'.$uri};
10632:  	    unless (($version eq 'mostrecent') || 
10633: 		    ($version==&getversion($uri))) {
10634:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10635:  	    }
10636:  	}
10637:  	untie %bighash;
10638:     }
10639:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10640: }
10641: 
10642: sub deversion {
10643:     my $url=shift;
10644:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10645:     return $url;
10646: }
10647: 
10648: # ------------------------------------------------------ Return symb list entry
10649: 
10650: sub symbread {
10651:     my ($thisfn,$donotrecurse)=@_;
10652:     my $cache_str;
10653:     if ($thisfn ne '') {
10654:         $cache_str='request.symbread.cached.'.$thisfn;
10655:         if ($env{$cache_str} ne '') {
10656:             return $env{$cache_str};
10657:         }
10658:     } else {
10659: # no filename provided? try from environment
10660:         if ($env{'request.symb'}) {
10661: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10662: 	}
10663: 	$thisfn=$env{'request.filename'};
10664:     }
10665:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10666: # is that filename actually a symb? Verify, clean, and return
10667:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10668: 	if (&symbverify($thisfn,$1)) {
10669: 	    return $env{$cache_str}=&symbclean($thisfn);
10670: 	}
10671:     }
10672:     $thisfn=declutter($thisfn);
10673:     my %hash;
10674:     my %bighash;
10675:     my $syval='';
10676:     if (($env{'request.course.fn'}) && ($thisfn)) {
10677:         my $targetfn = $thisfn;
10678:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10679:             $targetfn = 'adm/wrapper/'.$thisfn;
10680:         }
10681: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10682: 	    $targetfn=$1;
10683: 	}
10684:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10685:                       &GDBM_READER(),0640)) {
10686: 	    $syval=$hash{$targetfn};
10687:             untie(%hash);
10688:         }
10689: # ---------------------------------------------------------- There was an entry
10690:         if ($syval) {
10691: 	    #unless ($syval=~/\_\d+$/) {
10692: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10693: 		    #&appenv({'request.ambiguous' => $thisfn});
10694: 		    #return $env{$cache_str}='';
10695: 		#}    
10696: 		#$syval.=$1;
10697: 	    #}
10698:         } else {
10699: # ------------------------------------------------------- Was not in symb table
10700:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10701:                             &GDBM_READER(),0640)) {
10702: # ---------------------------------------------- Get ID(s) for current resource
10703:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10704:               unless ($ids) { 
10705:                  $ids=$bighash{'ids_/'.$thisfn};
10706:               }
10707:               unless ($ids) {
10708: # alias?
10709: 		  $ids=$bighash{'mapalias_'.$thisfn};
10710:               }
10711:               if ($ids) {
10712: # ------------------------------------------------------------------- Has ID(s)
10713:                  my @possibilities=split(/\,/,$ids);
10714:                  if ($#possibilities==0) {
10715: # ----------------------------------------------- There is only one possibility
10716: 		     my ($mapid,$resid)=split(/\./,$ids);
10717: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10718: 						    $resid,$thisfn);
10719:                  } elsif (!$donotrecurse) {
10720: # ------------------------------------------ There is more than one possibility
10721:                      my $realpossible=0;
10722:                      foreach my $id (@possibilities) {
10723: 			 my $file=$bighash{'src_'.$id};
10724:                          if (&allowed('bre',$file)) {
10725:          		    my ($mapid,$resid)=split(/\./,$id);
10726:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10727: 				$realpossible++;
10728:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10729: 						    $resid,$thisfn);
10730:                             }
10731: 			 }
10732:                      }
10733: 		     if ($realpossible!=1) { $syval=''; }
10734:                  } else {
10735:                      $syval='';
10736:                  }
10737: 	      }
10738:               untie(%bighash)
10739:            }
10740:         }
10741:         if ($syval) {
10742: 	    return $env{$cache_str}=$syval;
10743:         }
10744:     }
10745:     &appenv({'request.ambiguous' => $thisfn});
10746:     return $env{$cache_str}='';
10747: }
10748: 
10749: # ---------------------------------------------------------- Return random seed
10750: 
10751: sub numval {
10752:     my $txt=shift;
10753:     $txt=~tr/A-J/0-9/;
10754:     $txt=~tr/a-j/0-9/;
10755:     $txt=~tr/K-T/0-9/;
10756:     $txt=~tr/k-t/0-9/;
10757:     $txt=~tr/U-Z/0-5/;
10758:     $txt=~tr/u-z/0-5/;
10759:     $txt=~s/\D//g;
10760:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10761:     return int($txt);
10762: }
10763: 
10764: sub numval2 {
10765:     my $txt=shift;
10766:     $txt=~tr/A-J/0-9/;
10767:     $txt=~tr/a-j/0-9/;
10768:     $txt=~tr/K-T/0-9/;
10769:     $txt=~tr/k-t/0-9/;
10770:     $txt=~tr/U-Z/0-5/;
10771:     $txt=~tr/u-z/0-5/;
10772:     $txt=~s/\D//g;
10773:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10774:     my $total;
10775:     foreach my $val (@txts) { $total+=$val; }
10776:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10777:     return int($total);
10778: }
10779: 
10780: sub numval3 {
10781:     use integer;
10782:     my $txt=shift;
10783:     $txt=~tr/A-J/0-9/;
10784:     $txt=~tr/a-j/0-9/;
10785:     $txt=~tr/K-T/0-9/;
10786:     $txt=~tr/k-t/0-9/;
10787:     $txt=~tr/U-Z/0-5/;
10788:     $txt=~tr/u-z/0-5/;
10789:     $txt=~s/\D//g;
10790:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10791:     my $total;
10792:     foreach my $val (@txts) { $total+=$val; }
10793:     if ($_64bit) { $total=(($total<<32)>>32); }
10794:     return $total;
10795: }
10796: 
10797: sub digest {
10798:     my ($data)=@_;
10799:     my $digest=&Digest::MD5::md5($data);
10800:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10801:     my ($e,$f);
10802:     {
10803:         use integer;
10804:         $e=($a+$b);
10805:         $f=($c+$d);
10806:         if ($_64bit) {
10807:             $e=(($e<<32)>>32);
10808:             $f=(($f<<32)>>32);
10809:         }
10810:     }
10811:     if (wantarray) {
10812: 	return ($e,$f);
10813:     } else {
10814: 	my $g;
10815: 	{
10816: 	    use integer;
10817: 	    $g=($e+$f);
10818: 	    if ($_64bit) {
10819: 		$g=(($g<<32)>>32);
10820: 	    }
10821: 	}
10822: 	return $g;
10823:     }
10824: }
10825: 
10826: sub latest_rnd_algorithm_id {
10827:     return '64bit5';
10828: }
10829: 
10830: sub get_rand_alg {
10831:     my ($courseid)=@_;
10832:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10833:     if ($courseid) {
10834: 	return $env{"course.$courseid.rndseed"};
10835:     }
10836:     return &latest_rnd_algorithm_id();
10837: }
10838: 
10839: sub validCODE {
10840:     my ($CODE)=@_;
10841:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10842:     return 0;
10843: }
10844: 
10845: sub getCODE {
10846:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10847:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10848: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10849: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10850: 	return $Apache::lonhomework::history{'resource.CODE'};
10851:     }
10852:     return undef;
10853: }
10854: #
10855: #  Determines the random seed for a specific context:
10856: #
10857: # parameters:
10858: #   symb      - in course context the symb for the seed.
10859: #   course_id - The course id of the form domain_coursenum.
10860: #   domain    - Domain for the user.
10861: #   course    - Course for the user.
10862: #   cenv      - environment of the course.
10863: #
10864: # NOTE:
10865: #   All parameters are picked out of the environment if missing
10866: #   or not defined.
10867: #   If a symb cannot be determined the current time is used instead.
10868: #
10869: #  For a given well defined symb, courside, domain, username,
10870: #  and course environment, the seed is reproducible.
10871: #
10872: sub rndseed {
10873:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10874:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10875:     if (!defined($symb)) {
10876: 	unless ($symb=$wsymb) { return time; }
10877:     }
10878:     if (!defined $courseid) { 
10879: 	$courseid=$wcourseid; 
10880:     }
10881:     if (!defined $domain) { $domain=$wdomain; }
10882:     if (!defined $username) { $username=$wusername }
10883: 
10884:     my $which;
10885:     if (defined($cenv->{'rndseed'})) {
10886: 	$which = $cenv->{'rndseed'};
10887:     } else {
10888: 	$which =&get_rand_alg($courseid);
10889:     }
10890:     if (defined(&getCODE())) {
10891: 
10892: 	if ($which eq '64bit5') {
10893: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10894: 	} elsif ($which eq '64bit4') {
10895: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10896: 	} else {
10897: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10898: 	}
10899:     } elsif ($which eq '64bit5') {
10900: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10901:     } elsif ($which eq '64bit4') {
10902: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10903:     } elsif ($which eq '64bit3') {
10904: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10905:     } elsif ($which eq '64bit2') {
10906: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10907:     } elsif ($which eq '64bit') {
10908: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10909:     }
10910:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10911: }
10912: 
10913: sub rndseed_32bit {
10914:     my ($symb,$courseid,$domain,$username)=@_;
10915:     {
10916: 	use integer;
10917: 	my $symbchck=unpack("%32C*",$symb) << 27;
10918: 	my $symbseed=numval($symb) << 22;
10919: 	my $namechck=unpack("%32C*",$username) << 17;
10920: 	my $nameseed=numval($username) << 12;
10921: 	my $domainseed=unpack("%32C*",$domain) << 7;
10922: 	my $courseseed=unpack("%32C*",$courseid);
10923: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10924: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10925: 	#&logthis("rndseed :$num:$symb");
10926: 	if ($_64bit) { $num=(($num<<32)>>32); }
10927: 	return $num;
10928:     }
10929: }
10930: 
10931: sub rndseed_64bit {
10932:     my ($symb,$courseid,$domain,$username)=@_;
10933:     {
10934: 	use integer;
10935: 	my $symbchck=unpack("%32S*",$symb) << 21;
10936: 	my $symbseed=numval($symb) << 10;
10937: 	my $namechck=unpack("%32S*",$username);
10938: 	
10939: 	my $nameseed=numval($username) << 21;
10940: 	my $domainseed=unpack("%32S*",$domain) << 10;
10941: 	my $courseseed=unpack("%32S*",$courseid);
10942: 	
10943: 	my $num1=$symbchck+$symbseed+$namechck;
10944: 	my $num2=$nameseed+$domainseed+$courseseed;
10945: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10946: 	#&logthis("rndseed :$num:$symb");
10947: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10948: 	return "$num1,$num2";
10949:     }
10950: }
10951: 
10952: sub rndseed_64bit2 {
10953:     my ($symb,$courseid,$domain,$username)=@_;
10954:     {
10955: 	use integer;
10956: 	# strings need to be an even # of cahracters long, it it is odd the
10957:         # last characters gets thrown away
10958: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10959: 	my $symbseed=numval($symb) << 10;
10960: 	my $namechck=unpack("%32S*",$username.' ');
10961: 	
10962: 	my $nameseed=numval($username) << 21;
10963: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10964: 	my $courseseed=unpack("%32S*",$courseid.' ');
10965: 	
10966: 	my $num1=$symbchck+$symbseed+$namechck;
10967: 	my $num2=$nameseed+$domainseed+$courseseed;
10968: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10969: 	#&logthis("rndseed :$num:$symb");
10970: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10971: 	return "$num1,$num2";
10972:     }
10973: }
10974: 
10975: sub rndseed_64bit3 {
10976:     my ($symb,$courseid,$domain,$username)=@_;
10977:     {
10978: 	use integer;
10979: 	# strings need to be an even # of cahracters long, it it is odd the
10980:         # last characters gets thrown away
10981: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10982: 	my $symbseed=numval2($symb) << 10;
10983: 	my $namechck=unpack("%32S*",$username.' ');
10984: 	
10985: 	my $nameseed=numval2($username) << 21;
10986: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10987: 	my $courseseed=unpack("%32S*",$courseid.' ');
10988: 	
10989: 	my $num1=$symbchck+$symbseed+$namechck;
10990: 	my $num2=$nameseed+$domainseed+$courseseed;
10991: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10992: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10993: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10994: 	
10995: 	return "$num1:$num2";
10996:     }
10997: }
10998: 
10999: sub rndseed_64bit4 {
11000:     my ($symb,$courseid,$domain,$username)=@_;
11001:     {
11002: 	use integer;
11003: 	# strings need to be an even # of cahracters long, it it is odd the
11004:         # last characters gets thrown away
11005: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11006: 	my $symbseed=numval3($symb) << 10;
11007: 	my $namechck=unpack("%32S*",$username.' ');
11008: 	
11009: 	my $nameseed=numval3($username) << 21;
11010: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11011: 	my $courseseed=unpack("%32S*",$courseid.' ');
11012: 	
11013: 	my $num1=$symbchck+$symbseed+$namechck;
11014: 	my $num2=$nameseed+$domainseed+$courseseed;
11015: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11016: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11017: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11018: 	
11019: 	return "$num1:$num2";
11020:     }
11021: }
11022: 
11023: sub rndseed_64bit5 {
11024:     my ($symb,$courseid,$domain,$username)=@_;
11025:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11026:     return "$num1:$num2";
11027: }
11028: 
11029: sub rndseed_CODE_64bit {
11030:     my ($symb,$courseid,$domain,$username)=@_;
11031:     {
11032: 	use integer;
11033: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11034: 	my $symbseed=numval2($symb);
11035: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11036: 	my $CODEseed=numval(&getCODE());
11037: 	my $courseseed=unpack("%32S*",$courseid.' ');
11038: 	my $num1=$symbseed+$CODEchck;
11039: 	my $num2=$CODEseed+$courseseed+$symbchck;
11040: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11041: 	#&logthis("rndseed :$num1:$num2:$symb");
11042: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11043: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11044: 	return "$num1:$num2";
11045:     }
11046: }
11047: 
11048: sub rndseed_CODE_64bit4 {
11049:     my ($symb,$courseid,$domain,$username)=@_;
11050:     {
11051: 	use integer;
11052: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11053: 	my $symbseed=numval3($symb);
11054: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11055: 	my $CODEseed=numval3(&getCODE());
11056: 	my $courseseed=unpack("%32S*",$courseid.' ');
11057: 	my $num1=$symbseed+$CODEchck;
11058: 	my $num2=$CODEseed+$courseseed+$symbchck;
11059: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11060: 	#&logthis("rndseed :$num1:$num2:$symb");
11061: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11062: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11063: 	return "$num1:$num2";
11064:     }
11065: }
11066: 
11067: sub rndseed_CODE_64bit5 {
11068:     my ($symb,$courseid,$domain,$username)=@_;
11069:     my $code = &getCODE();
11070:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11071:     return "$num1:$num2";
11072: }
11073: 
11074: sub setup_random_from_rndseed {
11075:     my ($rndseed)=@_;
11076:     if ($rndseed =~/([,:])/) {
11077: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11078: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11079:     } else {
11080: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11081:     }
11082: }
11083: 
11084: sub latest_receipt_algorithm_id {
11085:     return 'receipt3';
11086: }
11087: 
11088: sub recunique {
11089:     my $fucourseid=shift;
11090:     my $unique;
11091:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11092: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11093: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11094:     } else {
11095: 	$unique=$perlvar{'lonReceipt'};
11096:     }
11097:     return unpack("%32C*",$unique);
11098: }
11099: 
11100: sub recprefix {
11101:     my $fucourseid=shift;
11102:     my $prefix;
11103:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11104: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11105: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11106:     } else {
11107: 	$prefix=$perlvar{'lonHostID'};
11108:     }
11109:     return unpack("%32C*",$prefix);
11110: }
11111: 
11112: sub ireceipt {
11113:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11114: 
11115:     my $return =&recprefix($fucourseid).'-';
11116: 
11117:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11118: 	$env{'request.state'} eq 'construct') {
11119: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11120: 	return $return;
11121:     }
11122: 
11123:     my $cuname=unpack("%32C*",$funame);
11124:     my $cudom=unpack("%32C*",$fudom);
11125:     my $cucourseid=unpack("%32C*",$fucourseid);
11126:     my $cusymb=unpack("%32C*",$fusymb);
11127:     my $cunique=&recunique($fucourseid);
11128:     my $cpart=unpack("%32S*",$part);
11129:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11130: 
11131: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11132: 			       
11133: 	$return.= ($cunique%$cuname+
11134: 		   $cunique%$cudom+
11135: 		   $cusymb%$cuname+
11136: 		   $cusymb%$cudom+
11137: 		   $cucourseid%$cuname+
11138: 		   $cucourseid%$cudom+
11139: 		   $cpart%$cuname+
11140: 		   $cpart%$cudom);
11141:     } else {
11142: 	$return.= ($cunique%$cuname+
11143: 		   $cunique%$cudom+
11144: 		   $cusymb%$cuname+
11145: 		   $cusymb%$cudom+
11146: 		   $cucourseid%$cuname+
11147: 		   $cucourseid%$cudom);
11148:     }
11149:     return $return;
11150: }
11151: 
11152: sub receipt {
11153:     my ($part)=@_;
11154:     my ($symb,$courseid,$domain,$name) = &whichuser();
11155:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11156: }
11157: 
11158: sub whichuser {
11159:     my ($passedsymb)=@_;
11160:     my ($symb,$courseid,$domain,$name,$publicuser);
11161:     if (defined($env{'form.grade_symb'})) {
11162: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11163: 	my $allowed=&allowed('vgr',$tmp_courseid);
11164: 	if (!$allowed &&
11165: 	    exists($env{'request.course.sec'}) &&
11166: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11167: 	    $allowed=&allowed('vgr',$tmp_courseid.
11168: 			      '/'.$env{'request.course.sec'});
11169: 	}
11170: 	if ($allowed) {
11171: 	    ($symb)=&get_env_multiple('form.grade_symb');
11172: 	    $courseid=$tmp_courseid;
11173: 	    ($domain)=&get_env_multiple('form.grade_domain');
11174: 	    ($name)=&get_env_multiple('form.grade_username');
11175: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11176: 	}
11177:     }
11178:     if (!$passedsymb) {
11179: 	$symb=&symbread();
11180:     } else {
11181: 	$symb=$passedsymb;
11182:     }
11183:     $courseid=$env{'request.course.id'};
11184:     $domain=$env{'user.domain'};
11185:     $name=$env{'user.name'};
11186:     if ($name eq 'public' && $domain eq 'public') {
11187: 	if (!defined($env{'form.username'})) {
11188: 	    $env{'form.username'}.=time.rand(10000000);
11189: 	}
11190: 	$name.=$env{'form.username'};
11191:     }
11192:     return ($symb,$courseid,$domain,$name,$publicuser);
11193: 
11194: }
11195: 
11196: # ------------------------------------------------------------ Serves up a file
11197: # returns either the contents of the file or 
11198: # -1 if the file doesn't exist
11199: #
11200: # if the target is a file that was uploaded via DOCS, 
11201: # a check will be made to see if a current copy exists on the local server,
11202: # if it does this will be served, otherwise a copy will be retrieved from
11203: # the home server for the course and stored in /home/httpd/html/userfiles on
11204: # the local server.   
11205: 
11206: sub getfile {
11207:     my ($file) = @_;
11208:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11209:     &repcopy($file);
11210:     return &readfile($file);
11211: }
11212: 
11213: sub repcopy_userfile {
11214:     my ($file)=@_;
11215:     my $londocroot = $perlvar{'lonDocRoot'};
11216:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11217:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11218:     my ($cdom,$cnum,$filename) = 
11219: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11220:     my $uri="/uploaded/$cdom/$cnum/$filename";
11221:     if (-e "$file") {
11222: # we already have a local copy, check it out
11223: 	my @fileinfo = stat($file);
11224: 	my $rtncode;
11225: 	my $info;
11226: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11227: 	if ($lwpresp ne 'ok') {
11228: # there is no such file anymore, even though we had a local copy
11229: 	    if ($rtncode eq '404') {
11230: 		unlink($file);
11231: 	    }
11232: 	    return -1;
11233: 	}
11234: 	if ($info < $fileinfo[9]) {
11235: # nice, the file we have is up-to-date, just say okay
11236: 	    return 'ok';
11237: 	} else {
11238: # the file is outdated, get rid of it
11239: 	    unlink($file);
11240: 	}
11241:     }
11242: # one way or the other, at this point, we don't have the file
11243: # construct the correct path for the file
11244:     my @parts = ($cdom,$cnum); 
11245:     if ($filename =~ m|^(.+)/[^/]+$|) {
11246: 	push @parts, split(/\//,$1);
11247:     }
11248:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11249:     foreach my $part (@parts) {
11250: 	$path .= '/'.$part;
11251: 	if (!-e $path) {
11252: 	    mkdir($path,0770);
11253: 	}
11254:     }
11255: # now the path exists for sure
11256: # get a user agent
11257:     my $ua=new LWP::UserAgent;
11258:     my $transferfile=$file.'.in.transfer';
11259: # FIXME: this should flock
11260:     if (-e $transferfile) { return 'ok'; }
11261:     my $request;
11262:     $uri=~s/^\///;
11263:     my $homeserver = &homeserver($cnum,$cdom);
11264:     my $protocol = $protocol{$homeserver};
11265:     $protocol = 'http' if ($protocol ne 'https');
11266:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11267:     my $response=$ua->request($request,$transferfile);
11268: # did it work?
11269:     if ($response->is_error()) {
11270: 	unlink($transferfile);
11271: 	&logthis("Userfile repcopy failed for $uri");
11272: 	return -1;
11273:     }
11274: # worked, rename the transfer file
11275:     rename($transferfile,$file);
11276:     return 'ok';
11277: }
11278: 
11279: sub tokenwrapper {
11280:     my $uri=shift;
11281:     $uri=~s|^https?\://([^/]+)||;
11282:     $uri=~s|^/||;
11283:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11284:     my $token=$1;
11285:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11286:     if ($udom && $uname && $file) {
11287: 	$file=~s|(\?\.*)*$||;
11288:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11289:         my $homeserver = &homeserver($uname,$udom);
11290:         my $protocol = $protocol{$homeserver};
11291:         $protocol = 'http' if ($protocol ne 'https');
11292:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11293:                (($uri=~/\?/)?'&':'?').'token='.$token.
11294:                                '&tokenissued='.$perlvar{'lonHostID'};
11295:     } else {
11296:         return '/adm/notfound.html';
11297:     }
11298: }
11299: 
11300: # call with reqtype HEAD: get last modification time
11301: # call with reqtype GET: get the file contents
11302: # Do not call this with reqtype GET for large files! It loads everything into memory
11303: #
11304: sub getuploaded {
11305:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11306:     $uri=~s/^\///;
11307:     my $homeserver = &homeserver($cnum,$cdom);
11308:     my $protocol = $protocol{$homeserver};
11309:     $protocol = 'http' if ($protocol ne 'https');
11310:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11311:     my $ua=new LWP::UserAgent;
11312:     my $request=new HTTP::Request($reqtype,$uri);
11313:     my $response=$ua->request($request);
11314:     $$rtncode = $response->code;
11315:     if (! $response->is_success()) {
11316: 	return 'failed';
11317:     }      
11318:     if ($reqtype eq 'HEAD') {
11319: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11320:     } elsif ($reqtype eq 'GET') {
11321: 	$$info = $response->content;
11322:     }
11323:     return 'ok';
11324: }
11325: 
11326: sub readfile {
11327:     my $file = shift;
11328:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11329:     my $fh;
11330:     open($fh,"<$file");
11331:     my $a='';
11332:     while (my $line = <$fh>) { $a .= $line; }
11333:     return $a;
11334: }
11335: 
11336: sub filelocation {
11337:     my ($dir,$file) = @_;
11338:     my $location;
11339:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11340: 
11341:     if ($file =~ m-^/adm/-) {
11342: 	$file=~s-^/adm/wrapper/-/-;
11343: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11344:     }
11345: 
11346:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11347:         $location = $file;
11348:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11349:         my ($udom,$uname,$filename)=
11350:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11351:         my $home=&homeserver($uname,$udom);
11352:         my $is_me=0;
11353:         my @ids=&current_machine_ids();
11354:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11355:         if ($is_me) {
11356:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11357:         } else {
11358:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11359:   	      $udom.'/'.$uname.'/'.$filename;
11360:         }
11361:     } elsif ($file =~ m-^/adm/-) {
11362: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11363:     } else {
11364:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11365:         $file=~s:^/(res|priv)/:/:;
11366:         my $space=$1;
11367:         if ( !( $file =~ m:^/:) ) {
11368:             $location = $dir. '/'.$file;
11369:         } else {
11370:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11371:         }
11372:     }
11373:     $location=~s://+:/:g; # remove duplicate /
11374:     while ($location=~m{/\.\./}) {
11375: 	if ($location =~ m{/[^/]+/\.\./}) {
11376: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11377: 	} else {
11378: 	    $location=~ s{/\.\./}{/}g;
11379: 	}
11380:     } #remove dir/..
11381:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11382:     return $location;
11383: }
11384: 
11385: sub hreflocation {
11386:     my ($dir,$file)=@_;
11387:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11388: 	$file=filelocation($dir,$file);
11389:     } elsif ($file=~m-^/adm/-) {
11390: 	$file=~s-^/adm/wrapper/-/-;
11391: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11392:     }
11393:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11394: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11395:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11396: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11397: 	        {/uploaded/$1/$2/}x;
11398:     }
11399:     if ($file=~ m{^/userfiles/}) {
11400: 	$file =~ s{^/userfiles/}{/uploaded/};
11401:     }
11402:     return $file;
11403: }
11404: 
11405: 
11406: 
11407: 
11408: 
11409: sub current_machine_domains {
11410:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11411: }
11412: 
11413: sub machine_domains {
11414:     my ($hostname) = @_;
11415:     my @domains;
11416:     my %hostname = &all_hostnames();
11417:     while( my($id, $name) = each(%hostname)) {
11418: #	&logthis("-$id-$name-$hostname-");
11419: 	if ($hostname eq $name) {
11420: 	    push(@domains,&host_domain($id));
11421: 	}
11422:     }
11423:     return @domains;
11424: }
11425: 
11426: sub current_machine_ids {
11427:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11428: }
11429: 
11430: sub machine_ids {
11431:     my ($hostname) = @_;
11432:     $hostname ||= &hostname($perlvar{'lonHostID'});
11433:     my @ids;
11434:     my %name_to_host = &all_names();
11435:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11436: 	return @{ $name_to_host{$hostname} };
11437:     }
11438:     return;
11439: }
11440: 
11441: sub additional_machine_domains {
11442:     my @domains;
11443:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11444:     while( my $line = <$fh>) {
11445:         $line =~ s/\s//g;
11446:         push(@domains,$line);
11447:     }
11448:     return @domains;
11449: }
11450: 
11451: sub default_login_domain {
11452:     my $domain = $perlvar{'lonDefDomain'};
11453:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11454:     foreach my $posdom (&current_machine_domains(),
11455:                         &additional_machine_domains()) {
11456:         if (lc($posdom) eq lc($testdomain)) {
11457:             $domain=$posdom;
11458:             last;
11459:         }
11460:     }
11461:     return $domain;
11462: }
11463: 
11464: # ------------------------------------------------------------- Declutters URLs
11465: 
11466: sub declutter {
11467:     my $thisfn=shift;
11468:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11469:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11470:     $thisfn=~s/^\///;
11471:     $thisfn=~s|^adm/wrapper/||;
11472:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11473:     $thisfn=~s/^res\///;
11474:     $thisfn=~s/^priv\///;
11475:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11476:         $thisfn=~s/\?.+$//;
11477:     }
11478:     return $thisfn;
11479: }
11480: 
11481: # ------------------------------------------------------------- Clutter up URLs
11482: 
11483: sub clutter {
11484:     my $thisfn='/'.&declutter(shift);
11485:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11486: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11487:        $thisfn='/res'.$thisfn; 
11488:     }
11489:     if ($thisfn !~m|^/adm|) {
11490: 	if ($thisfn =~ m|^/ext/|) {
11491: 	    $thisfn='/adm/wrapper'.$thisfn;
11492: 	} else {
11493: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11494: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11495: 	    if ($embstyle eq 'ssi'
11496: 		|| ($embstyle eq 'hdn')
11497: 		|| ($embstyle eq 'rat')
11498: 		|| ($embstyle eq 'prv')
11499: 		|| ($embstyle eq 'ign')) {
11500: 		#do nothing with these
11501: 	    } elsif (($embstyle eq 'img') 
11502: 		|| ($embstyle eq 'emb')
11503: 		|| ($embstyle eq 'wrp')) {
11504: 		$thisfn='/adm/wrapper'.$thisfn;
11505: 	    } elsif ($embstyle eq 'unk'
11506: 		     && $thisfn!~/\.(sequence|page)$/) {
11507: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11508: 	    } else {
11509: #		&logthis("Got a blank emb style");
11510: 	    }
11511: 	}
11512:     }
11513:     return $thisfn;
11514: }
11515: 
11516: sub clutter_with_no_wrapper {
11517:     my $uri = &clutter(shift);
11518:     if ($uri =~ m-^/adm/-) {
11519: 	$uri =~ s-^/adm/wrapper/-/-;
11520: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11521:     }
11522:     return $uri;
11523: }
11524: 
11525: sub freeze_escape {
11526:     my ($value)=@_;
11527:     if (ref($value)) {
11528: 	$value=&nfreeze($value);
11529: 	return '__FROZEN__'.&escape($value);
11530:     }
11531:     return &escape($value);
11532: }
11533: 
11534: 
11535: sub thaw_unescape {
11536:     my ($value)=@_;
11537:     if ($value =~ /^__FROZEN__/) {
11538: 	substr($value,0,10,undef);
11539: 	$value=&unescape($value);
11540: 	return &thaw($value);
11541:     }
11542:     return &unescape($value);
11543: }
11544: 
11545: sub correct_line_ends {
11546:     my ($result)=@_;
11547:     $$result =~s/\r\n/\n/mg;
11548:     $$result =~s/\r/\n/mg;
11549: }
11550: # ================================================================ Main Program
11551: 
11552: sub goodbye {
11553:    &logthis("Starting Shut down");
11554: #not converted to using infrastruture and probably shouldn't be
11555:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11556: #converted
11557: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11558:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11559: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11560: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11561: #1.1 only
11562: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11563: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11564: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11565: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11566:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11567:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11568:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11569:    &flushcourselogs();
11570:    &logthis("Shutting down");
11571: }
11572: 
11573: sub get_dns {
11574:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11575:     if (!$ignore_cache) {
11576: 	my ($content,$cached)=
11577: 	    &Apache::lonnet::is_cached_new('dns',$url);
11578: 	if ($cached) {
11579: 	    &$func($content,$hashref);
11580: 	    return;
11581: 	}
11582:     }
11583: 
11584:     my %alldns;
11585:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11586:     foreach my $dns (<$config>) {
11587: 	next if ($dns !~ /^\^(\S*)/x);
11588:         my $line = $1;
11589:         my ($host,$protocol) = split(/:/,$line);
11590:         if ($protocol ne 'https') {
11591:             $protocol = 'http';
11592:         }
11593: 	$alldns{$host} = $protocol;
11594:     }
11595:     while (%alldns) {
11596: 	my ($dns) = keys(%alldns);
11597: 	my $ua=new LWP::UserAgent;
11598:         $ua->timeout(30);
11599: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11600: 	my $response=$ua->request($request);
11601:         delete($alldns{$dns});
11602: 	next if ($response->is_error());
11603: 	my @content = split("\n",$response->content);
11604: 	unless ($nocache) {
11605: 	    &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
11606: 	}
11607: 	&$func(\@content,$hashref);
11608: 	return;
11609:     }
11610:     close($config);
11611:     my $which = (split('/',$url))[3];
11612:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11613:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11614:     my @content = <$config>;
11615:     &$func(\@content,$hashref);
11616:     return;
11617: }
11618: 
11619: # ------------------------------------------------------Get DNS checksums file
11620: sub parse_dns_checksums_tab {
11621:     my ($lines,$hashref) = @_;
11622:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11623:     my $loncaparev = &get_server_loncaparev($machine_dom);
11624:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11625:     my (%chksum,%revnum);
11626:     if (ref($lines) eq 'ARRAY') {
11627:         chomp(@{$lines});
11628:         my $versions = shift(@{$lines});
11629:         my %supported;
11630:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
11631:             my $releaseslist = $1;
11632:             if ($releaseslist =~ /,/) {
11633:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
11634:             } elsif ($releaseslist) {
11635:                 $supported{$releaseslist} = 1;
11636:             }
11637:         }
11638:         if ($supported{$release}) {  
11639:             my $matchthis = 0;
11640:             foreach my $line (@{$lines}) {
11641:                 if ($line =~ /^(\d[\w\.]+)$/) {
11642:                     if ($matchthis) {
11643:                         last;
11644:                     } elsif ($1 eq $release) {
11645:                         $matchthis = 1;
11646:                     }
11647:                 } elsif ($matchthis) {
11648:                     my ($file,$version,$shasum) = split(/,/,$line);
11649:                     $chksum{$file} = $shasum;
11650:                     $revnum{$file} = $version;
11651:                 }
11652:             }
11653:             if (ref($hashref) eq 'HASH') {
11654:                 %{$hashref} = (
11655:                                 sums     => \%chksum,
11656:                                 versions => \%revnum,
11657:                               );
11658:             }
11659:         }
11660:     }
11661:     return;
11662: }
11663: 
11664: sub fetch_dns_checksums {
11665:     my %checksums; 
11666:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
11667:              \%checksums);
11668:     return \%checksums;
11669: }
11670: 
11671: # ------------------------------------------------------------ Read domain file
11672: {
11673:     my $loaded;
11674:     my %domain;
11675: 
11676:     sub parse_domain_tab {
11677: 	my ($lines) = @_;
11678: 	foreach my $line (@$lines) {
11679: 	    next if ($line =~ /^(\#|\s*$ )/x);
11680: 
11681: 	    chomp($line);
11682: 	    my ($name,@elements) = split(/:/,$line,9);
11683: 	    my %this_domain;
11684: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11685: 			       'lang_def', 'city', 'longi', 'lati',
11686: 			       'primary') {
11687: 		$this_domain{$field} = shift(@elements);
11688: 	    }
11689: 	    $domain{$name} = \%this_domain;
11690: 	}
11691:     }
11692: 
11693:     sub reset_domain_info {
11694: 	undef($loaded);
11695: 	undef(%domain);
11696:     }
11697: 
11698:     sub load_domain_tab {
11699: 	my ($ignore_cache) = @_;
11700: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11701: 	my $fh;
11702: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11703: 	    my @lines = <$fh>;
11704: 	    &parse_domain_tab(\@lines);
11705: 	}
11706: 	close($fh);
11707: 	$loaded = 1;
11708:     }
11709: 
11710:     sub domain {
11711: 	&load_domain_tab() if (!$loaded);
11712: 
11713: 	my ($name,$what) = @_;
11714: 	return if ( !exists($domain{$name}) );
11715: 
11716: 	if (!$what) {
11717: 	    return $domain{$name}{'description'};
11718: 	}
11719: 	return $domain{$name}{$what};
11720:     }
11721: 
11722:     sub domain_info {
11723:         &load_domain_tab() if (!$loaded);
11724:         return %domain;
11725:     }
11726: 
11727: }
11728: 
11729: 
11730: # ------------------------------------------------------------- Read hosts file
11731: {
11732:     my %hostname;
11733:     my %hostdom;
11734:     my %libserv;
11735:     my $loaded;
11736:     my %name_to_host;
11737:     my %internetdom;
11738:     my %LC_dns_serv;
11739: 
11740:     sub parse_hosts_tab {
11741: 	my ($file) = @_;
11742: 	foreach my $configline (@$file) {
11743: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11744:             chomp($configline);
11745: 	    if ($configline =~ /^\^/) {
11746:                 if ($configline =~ /^\^([\w.\-]+)/) {
11747:                     $LC_dns_serv{$1} = 1;
11748:                 }
11749:                 next;
11750:             }
11751: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11752: 	    $name=~s/\s//g;
11753: 	    if ($id && $domain && $role && $name) {
11754: 		$hostname{$id}=$name;
11755: 		push(@{$name_to_host{$name}}, $id);
11756: 		$hostdom{$id}=$domain;
11757: 		if ($role eq 'library') { $libserv{$id}=$name; }
11758:                 if (defined($protocol)) {
11759:                     if ($protocol eq 'https') {
11760:                         $protocol{$id} = $protocol;
11761:                     } else {
11762:                         $protocol{$id} = 'http'; 
11763:                     }
11764:                 } else {
11765:                     $protocol{$id} = 'http';
11766:                 }
11767:                 if (defined($intdom)) {
11768:                     $internetdom{$id} = $intdom;
11769:                 }
11770: 	    }
11771: 	}
11772:     }
11773:     
11774:     sub reset_hosts_info {
11775: 	&purge_remembered();
11776: 	&reset_domain_info();
11777: 	&reset_hosts_ip_info();
11778: 	undef(%name_to_host);
11779: 	undef(%hostname);
11780: 	undef(%hostdom);
11781: 	undef(%libserv);
11782: 	undef($loaded);
11783:     }
11784: 
11785:     sub load_hosts_tab {
11786: 	my ($ignore_cache) = @_;
11787: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11788: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11789: 	my @config = <$config>;
11790: 	&parse_hosts_tab(\@config);
11791: 	close($config);
11792: 	$loaded=1;
11793:     }
11794: 
11795:     sub hostname {
11796: 	&load_hosts_tab() if (!$loaded);
11797: 
11798: 	my ($lonid) = @_;
11799: 	return $hostname{$lonid};
11800:     }
11801: 
11802:     sub all_hostnames {
11803: 	&load_hosts_tab() if (!$loaded);
11804: 
11805: 	return %hostname;
11806:     }
11807: 
11808:     sub all_names {
11809: 	&load_hosts_tab() if (!$loaded);
11810: 
11811: 	return %name_to_host;
11812:     }
11813: 
11814:     sub all_host_domain {
11815:         &load_hosts_tab() if (!$loaded);
11816:         return %hostdom;
11817:     }
11818: 
11819:     sub is_library {
11820: 	&load_hosts_tab() if (!$loaded);
11821: 
11822: 	return exists($libserv{$_[0]});
11823:     }
11824: 
11825:     sub all_library {
11826: 	&load_hosts_tab() if (!$loaded);
11827: 
11828: 	return %libserv;
11829:     }
11830: 
11831:     sub unique_library {
11832: 	#2x reverse removes all hostnames that appear more than once
11833:         my %unique = reverse &all_library();
11834:         return reverse %unique;
11835:     }
11836: 
11837:     sub get_servers {
11838: 	&load_hosts_tab() if (!$loaded);
11839: 
11840: 	my ($domain,$type) = @_;
11841: 	my %possible_hosts = ($type eq 'library') ? %libserv
11842: 	                                          : %hostname;
11843: 	my %result;
11844: 	if (ref($domain) eq 'ARRAY') {
11845: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11846: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11847: 		    $result{$host} = $hostname;
11848: 		}
11849: 	    }
11850: 	} else {
11851: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11852: 		if ($hostdom{$host} eq $domain) {
11853: 		    $result{$host} = $hostname;
11854: 		}
11855: 	    }
11856: 	}
11857: 	return %result;
11858:     }
11859: 
11860:     sub get_unique_servers {
11861:         my %unique = reverse &get_servers(@_);
11862: 	return reverse %unique;
11863:     }
11864: 
11865:     sub host_domain {
11866: 	&load_hosts_tab() if (!$loaded);
11867: 
11868: 	my ($lonid) = @_;
11869: 	return $hostdom{$lonid};
11870:     }
11871: 
11872:     sub all_domains {
11873: 	&load_hosts_tab() if (!$loaded);
11874: 
11875: 	my %seen;
11876: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11877: 	return @uniq;
11878:     }
11879: 
11880:     sub internet_dom {
11881:         &load_hosts_tab() if (!$loaded);
11882: 
11883:         my ($lonid) = @_;
11884:         return $internetdom{$lonid};
11885:     }
11886: 
11887:     sub is_LC_dns {
11888:         &load_hosts_tab() if (!$loaded);
11889: 
11890:         my ($hostname) = @_;
11891:         return exists($LC_dns_serv{$hostname});
11892:     }
11893: 
11894: }
11895: 
11896: { 
11897:     my %iphost;
11898:     my %name_to_ip;
11899:     my %lonid_to_ip;
11900: 
11901:     sub get_hosts_from_ip {
11902: 	my ($ip) = @_;
11903: 	my %iphosts = &get_iphost();
11904: 	if (ref($iphosts{$ip})) {
11905: 	    return @{$iphosts{$ip}};
11906: 	}
11907: 	return;
11908:     }
11909:     
11910:     sub reset_hosts_ip_info {
11911: 	undef(%iphost);
11912: 	undef(%name_to_ip);
11913: 	undef(%lonid_to_ip);
11914:     }
11915: 
11916:     sub get_host_ip {
11917: 	my ($lonid) = @_;
11918: 	if (exists($lonid_to_ip{$lonid})) {
11919: 	    return $lonid_to_ip{$lonid};
11920: 	}
11921: 	my $name=&hostname($lonid);
11922:    	my $ip = gethostbyname($name);
11923: 	return if (!$ip || length($ip) ne 4);
11924: 	$ip=inet_ntoa($ip);
11925: 	$name_to_ip{$name}   = $ip;
11926: 	$lonid_to_ip{$lonid} = $ip;
11927: 	return $ip;
11928:     }
11929:     
11930:     sub get_iphost {
11931: 	my ($ignore_cache) = @_;
11932: 
11933: 	if (!$ignore_cache) {
11934: 	    if (%iphost) {
11935: 		return %iphost;
11936: 	    }
11937: 	    my ($ip_info,$cached)=
11938: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11939: 	    if ($cached) {
11940: 		%iphost      = %{$ip_info->[0]};
11941: 		%name_to_ip  = %{$ip_info->[1]};
11942: 		%lonid_to_ip = %{$ip_info->[2]};
11943: 		return %iphost;
11944: 	    }
11945: 	}
11946: 
11947: 	# get yesterday's info for fallback
11948: 	my %old_name_to_ip;
11949: 	my ($ip_info,$cached)=
11950: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11951: 	if ($cached) {
11952: 	    %old_name_to_ip = %{$ip_info->[1]};
11953: 	}
11954: 
11955: 	my %name_to_host = &all_names();
11956: 	foreach my $name (keys(%name_to_host)) {
11957: 	    my $ip;
11958: 	    if (!exists($name_to_ip{$name})) {
11959: 		$ip = gethostbyname($name);
11960: 		if (!$ip || length($ip) ne 4) {
11961: 		    if (defined($old_name_to_ip{$name})) {
11962: 			$ip = $old_name_to_ip{$name};
11963: 			&logthis("Can't find $name defaulting to old $ip");
11964: 		    } else {
11965: 			&logthis("Name $name no IP found");
11966: 			next;
11967: 		    }
11968: 		} else {
11969: 		    $ip=inet_ntoa($ip);
11970: 		}
11971: 		$name_to_ip{$name} = $ip;
11972: 	    } else {
11973: 		$ip = $name_to_ip{$name};
11974: 	    }
11975: 	    foreach my $id (@{ $name_to_host{$name} }) {
11976: 		$lonid_to_ip{$id} = $ip;
11977: 	    }
11978: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11979: 	}
11980: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11981: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11982: 				      48*60*60);
11983: 
11984: 	return %iphost;
11985:     }
11986: 
11987:     #
11988:     #  Given a DNS returns the loncapa host name for that DNS 
11989:     # 
11990:     sub host_from_dns {
11991:         my ($dns) = @_;
11992:         my @hosts;
11993:         my $ip;
11994: 
11995:         if (exists($name_to_ip{$dns})) {
11996:             $ip = $name_to_ip{$dns};
11997:         }
11998:         if (!$ip) {
11999:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12000:             if (length($ip) == 4) { 
12001: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12002:             }
12003:         }
12004:         if ($ip) {
12005: 	    @hosts = get_hosts_from_ip($ip);
12006: 	    return $hosts[0];
12007:         }
12008:         return undef;
12009:     }
12010: 
12011:     sub get_internet_names {
12012:         my ($lonid) = @_;
12013:         return if ($lonid eq '');
12014:         my ($idnref,$cached)=
12015:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12016:         if ($cached) {
12017:             return $idnref;
12018:         }
12019:         my $ip = &get_host_ip($lonid);
12020:         my @hosts = &get_hosts_from_ip($ip);
12021:         my %iphost = &get_iphost();
12022:         my (@idns,%seen);
12023:         foreach my $id (@hosts) {
12024:             my $dom = &host_domain($id);
12025:             my $prim_id = &domain($dom,'primary');
12026:             my $prim_ip = &get_host_ip($prim_id);
12027:             next if ($seen{$prim_ip});
12028:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12029:                 foreach my $id (@{$iphost{$prim_ip}}) {
12030:                     my $intdom = &internet_dom($id);
12031:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12032:                         push(@idns,$intdom);
12033:                     }
12034:                 }
12035:             }
12036:             $seen{$prim_ip} = 1;
12037:         }
12038:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12039:     }
12040: 
12041: }
12042: 
12043: sub all_loncaparevs {
12044:     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);
12045: }
12046: 
12047: BEGIN {
12048: 
12049: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12050:     unless ($readit) {
12051: {
12052:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12053:     %perlvar = (%perlvar,%{$configvars});
12054: }
12055: 
12056: 
12057: # ------------------------------------------------------ Read spare server file
12058: {
12059:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12060: 
12061:     while (my $configline=<$config>) {
12062:        chomp($configline);
12063:        if ($configline) {
12064: 	   my ($host,$type) = split(':',$configline,2);
12065: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12066: 	   push(@{ $spareid{$type} }, $host);
12067:        }
12068:     }
12069:     close($config);
12070: }
12071: # ------------------------------------------------------------ Read permissions
12072: {
12073:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12074: 
12075:     while (my $configline=<$config>) {
12076: 	chomp($configline);
12077: 	if ($configline) {
12078: 	    my ($role,$perm)=split(/ /,$configline);
12079: 	    if ($perm ne '') { $pr{$role}=$perm; }
12080: 	}
12081:     }
12082:     close($config);
12083: }
12084: 
12085: # -------------------------------------------- Read plain texts for permissions
12086: {
12087:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12088: 
12089:     while (my $configline=<$config>) {
12090: 	chomp($configline);
12091: 	if ($configline) {
12092: 	    my ($short,@plain)=split(/:/,$configline);
12093:             %{$prp{$short}} = ();
12094: 	    if (@plain > 0) {
12095:                 $prp{$short}{'std'} = $plain[0];
12096:                 for (my $i=1; $i<@plain; $i++) {
12097:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12098:                 }
12099:             }
12100: 	}
12101:     }
12102:     close($config);
12103: }
12104: 
12105: # ---------------------------------------------------------- Read package table
12106: {
12107:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12108: 
12109:     while (my $configline=<$config>) {
12110: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12111: 	chomp($configline);
12112: 	my ($short,$plain)=split(/:/,$configline);
12113: 	my ($pack,$name)=split(/\&/,$short);
12114: 	if ($plain ne '') {
12115: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12116: 	    $packagetab{$short}=$plain; 
12117: 	}
12118:     }
12119:     close($config);
12120: }
12121: 
12122: # ---------------------------------------------------------- Read loncaparev table
12123: {
12124:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12125:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12126:             while (my $configline=<$config>) {
12127:                 chomp($configline);
12128:                 my ($hostid,$loncaparev)=split(/:/,$configline);
12129:                 $loncaparevs{$hostid}=$loncaparev;
12130:             }
12131:             close($config);
12132:         }
12133:     }
12134: }
12135: 
12136: # ---------------------------------------------------------- Read serverhostID table
12137: {
12138:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12139:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12140:             while (my $configline=<$config>) {
12141:                 chomp($configline);
12142:                 my ($name,$id)=split(/:/,$configline);
12143:                 $serverhomeIDs{$name}=$id;
12144:             }
12145:             close($config);
12146:         }
12147:     }
12148: }
12149: 
12150: {
12151:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12152:     if (-e $file) {
12153:         my $parser = HTML::LCParser->new($file);
12154:         while (my $token = $parser->get_token()) {
12155:             if ($token->[0] eq 'S') {
12156:                 my $item = $token->[1];
12157:                 my $name = $token->[2]{'name'};
12158:                 my $value = $token->[2]{'value'};
12159:                 if ($item ne '' && $name ne '' && $value ne '') {
12160:                     my $release = $parser->get_text();
12161:                     $release =~ s/(^\s*|\s*$ )//gx;
12162:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12163:                 }
12164:             }
12165:         }
12166:     }
12167: }
12168: 
12169: # ---------------------------------------------------------- Read managers table
12170: {
12171:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12172:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12173:             while (my $configline=<$config>) {
12174:                 chomp($configline);
12175:                 next if ($configline =~ /^\#/);
12176:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12177:                     $managerstab{$configline} = 1;
12178:                 }
12179:             }
12180:             close($config);
12181:         }
12182:     }
12183: }
12184: 
12185: # ------------- set up temporary directory
12186: {
12187:     $tmpdir = LONCAPA::tempdir();
12188: 
12189: }
12190: 
12191: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12192: 				'compress_threshold'=> 20_000,
12193:  			        });
12194: 
12195: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12196: $dumpcount=0;
12197: $locknum=0;
12198: 
12199: &logtouch();
12200: &logthis('<font color="yellow">INFO: Read configuration</font>');
12201: $readit=1;
12202:     {
12203: 	use integer;
12204: 	my $test=(2**32)+1;
12205: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12206: 	&logthis(" Detected 64bit platform ($_64bit)");
12207:     }
12208: 
12209:     {
12210:         eval {
12211:             ($apache) =
12212:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12213:         };
12214:         if ($@) {
12215:            $apache = 1.3;
12216:         }
12217:     }
12218: 
12219: }
12220: }
12221: 
12222: 1;
12223: __END__
12224: 
12225: =pod
12226: 
12227: =head1 NAME
12228: 
12229: Apache::lonnet - Subroutines to ask questions about things in the network.
12230: 
12231: =head1 SYNOPSIS
12232: 
12233: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12234: 
12235:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12236: 
12237: Common parameters:
12238: 
12239: =over 4
12240: 
12241: =item *
12242: 
12243: $uname : an internal username (if $cname expecting a course Id specifically)
12244: 
12245: =item *
12246: 
12247: $udom : a domain (if $cdom expecting a course's domain specifically)
12248: 
12249: =item *
12250: 
12251: $symb : a resource instance identifier
12252: 
12253: =item *
12254: 
12255: $namespace : the name of a .db file that contains the data needed or
12256: being set.
12257: 
12258: =back
12259: 
12260: =head1 OVERVIEW
12261: 
12262: lonnet provides subroutines which interact with the
12263: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12264: about classes, users, and resources.
12265: 
12266: For many of these objects you can also use this to store data about
12267: them or modify them in various ways.
12268: 
12269: =head2 Symbs
12270: 
12271: To identify a specific instance of a resource, LON-CAPA uses symbols
12272: or "symbs"X<symb>. These identifiers are built from the URL of the
12273: map, the resource number of the resource in the map, and the URL of
12274: the resource itself. The latter is somewhat redundant, but might help
12275: if maps change.
12276: 
12277: An example is
12278: 
12279:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12280: 
12281: The respective map entry is
12282: 
12283:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12284:   title="Problem 2">
12285:  </resource>
12286: 
12287: Symbs are used by the random number generator, as well as to store and
12288: restore data specific to a certain instance of for example a problem.
12289: 
12290: =head2 Storing And Retrieving Data
12291: 
12292: X<store()>X<cstore()>X<restore()>Three of the most important functions
12293: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12294: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12295: is is the non-critical message twin of cstore. These functions are for
12296: handlers to store a perl hash to a user's permanent data space in an
12297: easy manner, and to retrieve it again on another call. It is expected
12298: that a handler would use this once at the beginning to retrieve data,
12299: and then again once at the end to send only the new data back.
12300: 
12301: The data is stored in the user's data directory on the user's
12302: homeserver under the ID of the course.
12303: 
12304: The hash that is returned by restore will have all of the previous
12305: value for all of the elements of the hash.
12306: 
12307: Example:
12308: 
12309:  #creating a hash
12310:  my %hash;
12311:  $hash{'foo'}='bar';
12312: 
12313:  #storing it
12314:  &Apache::lonnet::cstore(\%hash);
12315: 
12316:  #changing a value
12317:  $hash{'foo'}='notbar';
12318: 
12319:  #adding a new value
12320:  $hash{'bar'}='foo';
12321:  &Apache::lonnet::cstore(\%hash);
12322: 
12323:  #retrieving the hash
12324:  my %history=&Apache::lonnet::restore();
12325: 
12326:  #print the hash
12327:  foreach my $key (sort(keys(%history))) {
12328:    print("\%history{$key} = $history{$key}");
12329:  }
12330: 
12331: Will print out:
12332: 
12333:  %history{1:foo} = bar
12334:  %history{1:keys} = foo:timestamp
12335:  %history{1:timestamp} = 990455579
12336:  %history{2:bar} = foo
12337:  %history{2:foo} = notbar
12338:  %history{2:keys} = foo:bar:timestamp
12339:  %history{2:timestamp} = 990455580
12340:  %history{bar} = foo
12341:  %history{foo} = notbar
12342:  %history{timestamp} = 990455580
12343:  %history{version} = 2
12344: 
12345: Note that the special hash entries C<keys>, C<version> and
12346: C<timestamp> were added to the hash. C<version> will be equal to the
12347: total number of versions of the data that have been stored. The
12348: C<timestamp> attribute will be the UNIX time the hash was
12349: stored. C<keys> is available in every historical section to list which
12350: keys were added or changed at a specific historical revision of a
12351: hash.
12352: 
12353: B<Warning>: do not store the hash that restore returns directly. This
12354: will cause a mess since it will restore the historical keys as if the
12355: were new keys. I.E. 1:foo will become 1:1:foo etc.
12356: 
12357: Calling convention:
12358: 
12359:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
12360:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
12361: 
12362: For more detailed information, see lonnet specific documentation.
12363: 
12364: =head1 RETURN MESSAGES
12365: 
12366: =over 4
12367: 
12368: =item * B<con_lost>: unable to contact remote host
12369: 
12370: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12371: when the connection is brought back up
12372: 
12373: =item * B<con_failed>: unable to contact remote host and unable to save message
12374: for later delivery
12375: 
12376: =item * B<error:>: an error a occurred, a description of the error follows the :
12377: 
12378: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12379: that was requested
12380: 
12381: =back
12382: 
12383: =head1 PUBLIC SUBROUTINES
12384: 
12385: =head2 Session Environment Functions
12386: 
12387: =over 4
12388: 
12389: =item * 
12390: X<appenv()>
12391: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12392: the user envirnoment file, and will be restored for each access this
12393: user makes during this session, also modifies the %env for the current
12394: process. Optional rolesarrayref - if defined contains a reference to an array
12395: of roles which are exempt from the restriction on modifying user.role entries 
12396: in the user's environment.db and in %env.    
12397: 
12398: =item *
12399: X<delenv()>
12400: B<delenv($delthis,$regexp)>: removes all items from the session
12401: environment file that begin with $delthis. If the 
12402: optional second arg - $regexp - is true, $delthis is treated as a 
12403: regular expression, otherwise \Q$delthis\E is used. 
12404: The values are also deleted from the current processes %env.
12405: 
12406: =item * get_env_multiple($name) 
12407: 
12408: gets $name from the %env hash, it seemlessly handles the cases where multiple
12409: values may be defined and end up as an array ref.
12410: 
12411: returns an array of values
12412: 
12413: =back
12414: 
12415: =head2 User Information
12416: 
12417: =over 4
12418: 
12419: =item *
12420: X<queryauthenticate()>
12421: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12422: authentication scheme
12423: 
12424: =item *
12425: X<authenticate()>
12426: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12427: authenticate user from domain's lib servers (first use the current
12428: one). C<$upass> should be the users password.
12429: $checkdefauth is optional (value is 1 if a check should be made to
12430:    authenticate user using default authentication method, and allow
12431:    account creation if username does not have account in the domain).
12432: $clientcancheckhost is optional (value is 1 if checking whether the
12433:    server can host will occur on the client side in lonauth.pm).   
12434: 
12435: =item *
12436: X<homeserver()>
12437: B<homeserver($uname,$udom)>: find the server which has
12438: the user's directory and files (there must be only one), this caches
12439: the answer, and also caches if there is a borken connection.
12440: 
12441: =item *
12442: X<idget()>
12443: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12444: (IDs are a unique resource in a domain, there must be only 1 ID per
12445: username, and only 1 username per ID in a specific domain) (returns
12446: hash: id=>name,id=>name)
12447: 
12448: =item *
12449: X<idrget()>
12450: B<idrget($udom,@unames)>: find the IDs behind a list of
12451: usernames (returns hash: name=>id,name=>id)
12452: 
12453: =item *
12454: X<idput()>
12455: B<idput($udom,%ids)>: store away a list of names and associated IDs
12456: 
12457: =item *
12458: X<rolesinit()>
12459: B<rolesinit($udom,$username)>: get user privileges.
12460: returns user role, first access and timer interval hashes
12461: 
12462: =item *
12463: X<privileged()>
12464: B<privileged($username,$domain)>: returns a true if user has a
12465: privileged and active role (i.e. su or dc), false otherwise.
12466: 
12467: =item *
12468: X<getsection()>
12469: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12470: course $cname, return section name/number or '' for "not in course"
12471: and '-1' for "no section"
12472: 
12473: =item *
12474: X<userenvironment()>
12475: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12476: passed in @what from the requested user's environment, returns a hash
12477: 
12478: =item * 
12479: X<userlog_query()>
12480: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12481: activity.log file. %filters defines filters applied when parsing the
12482: log file. These can be start or end timestamps, or the type of action
12483: - log to look for Login or Logout events, check for Checkin or
12484: Checkout, role for role selection. The response is in the form
12485: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12486: escaped strings of the action recorded in the activity.log file.
12487: 
12488: =back
12489: 
12490: =head2 User Roles
12491: 
12492: =over 4
12493: 
12494: =item *
12495: 
12496: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12497:  F: full access
12498:  U,I,K: authentication modes (cxx only)
12499:  '': forbidden
12500:  1: user needs to choose course
12501:  2: browse allowed
12502:  A: passphrase authentication needed
12503: 
12504: =item *
12505: 
12506: constructaccess($url,$setpriv) : check for access to construction space URL
12507: 
12508: See if the owner domain and name in the URL match those in the
12509: expected environment.  If so, return three element list
12510: ($ownername,$ownerdomain,$ownerhome).
12511: 
12512: Otherwise return the null string.
12513: 
12514: If second argument 'setpriv' is true, it assigns the privileges,
12515: and returns the same three element list, unless the owner has
12516: blocked "ad hoc" Domain Coordinator access to the Author Space,
12517: in which case the null string is returned.
12518: 
12519: =item *
12520: 
12521: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12522: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12523: and course level
12524: 
12525: =item *
12526: 
12527: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12528: (rolesplain.tab); plain text explanation of a user role term.
12529: $type is Course (default) or Community.
12530: If $forcedefault evaluates to true, text returned will be default 
12531: text for $type. Otherwise, if this is a course, the text returned 
12532: will be a custom name for the role (if defined in the course's 
12533: environment).  If no custom name is defined the default is returned.
12534:    
12535: =item *
12536: 
12537: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
12538: All arguments are optional. Returns a hash of a roles, either for
12539: co-author/assistant author roles for a user's Construction Space
12540: (default), or if $context is 'userroles', roles for the user himself,
12541: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12542: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12543: For each key, value is set to colon-separated start and end times for
12544: the role.  If no username and domain are specified, will default to
12545: current user/domain. Types, roles, and roledoms are references to arrays
12546: of role statuses (active, future or previous), roles 
12547: (e.g., cc,in, st etc.) and domains of the roles which can be used
12548: to restrict the list of roles reported. If no array ref is 
12549: provided for types, will default to return only active roles.
12550: 
12551: =item *
12552: 
12553: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12554: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12555: 
12556: Additional optional arguments are: $type (if role checking is to be restricted 
12557: to certain user status types -- previous (expired roles), active (currently
12558: available roles) or future (roles available in the future), and
12559: $hideprivileged -- if true will not report course roles for users who
12560: have active Domain Coordinator or Super User roles.
12561: 
12562: =back
12563: 
12564: =head2 User Modification
12565: 
12566: =over 4
12567: 
12568: =item *
12569: 
12570: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12571: user for the level given by URL.  Optional start and end dates (leave empty
12572: string or zero for "no date")
12573: 
12574: =item *
12575: 
12576: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12577: change a users, password, possible return values are: ok,
12578: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12579: refused
12580: 
12581: =item *
12582: 
12583: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12584: 
12585: =item *
12586: 
12587: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12588:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12589: 
12590: will update user information (firstname,middlename,lastname,generation,
12591: permanentemail), and if forceid is true, student/employee ID also.
12592: A user's institutional affiliation(s) can also be updated.
12593: User information fields will not be overwritten with empty entries 
12594: unless the field is included in the $candelete array reference.
12595: This array is included when a single user is modified via "Manage Users",
12596: or when Autoupdate.pl is run by cron in a domain.
12597: 
12598: =item *
12599: 
12600: modifystudent
12601: 
12602: modify a student's enrollment and identification information.
12603: The course id is resolved based on the current users environment.  
12604: This means the envoking user must be a course coordinator or otherwise
12605: associated with a course.
12606: 
12607: This call is essentially a wrapper for lonnet::modifyuser and
12608: lonnet::modify_student_enrollment
12609: 
12610: Inputs: 
12611: 
12612: =over 4
12613: 
12614: =item B<$udom> Student's loncapa domain
12615: 
12616: =item B<$uname> Student's loncapa login name
12617: 
12618: =item B<$uid> Student/Employee ID
12619: 
12620: =item B<$umode> Student's authentication mode
12621: 
12622: =item B<$upass> Student's password
12623: 
12624: =item B<$first> Student's first name
12625: 
12626: =item B<$middle> Student's middle name
12627: 
12628: =item B<$last> Student's last name
12629: 
12630: =item B<$gene> Student's generation
12631: 
12632: =item B<$usec> Student's section in course
12633: 
12634: =item B<$end> Unix time of the roles expiration
12635: 
12636: =item B<$start> Unix time of the roles start date
12637: 
12638: =item B<$forceid> If defined, allow $uid to be changed
12639: 
12640: =item B<$desiredhome> server to use as home server for student
12641: 
12642: =item B<$email> Student's permanent e-mail address
12643: 
12644: =item B<$type> Type of enrollment (auto or manual)
12645: 
12646: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12647: 
12648: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12649: 
12650: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12651: 
12652: =item B<$context> role change context (shown in User Management Logs display in a course)
12653: 
12654: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12655: 
12656: =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.
12657: 
12658: =back
12659: 
12660: =item *
12661: 
12662: modify_student_enrollment
12663: 
12664: Change a students enrollment status in a class.  The environment variable
12665: 'role.request.course' must be defined for this function to proceed.
12666: 
12667: Inputs:
12668: 
12669: =over 4
12670: 
12671: =item $udom, students domain
12672: 
12673: =item $uname, students name
12674: 
12675: =item $uid, students user id
12676: 
12677: =item $first, students first name
12678: 
12679: =item $middle
12680: 
12681: =item $last
12682: 
12683: =item $gene
12684: 
12685: =item $usec
12686: 
12687: =item $end
12688: 
12689: =item $start
12690: 
12691: =item $type
12692: 
12693: =item $locktype
12694: 
12695: =item $cid
12696: 
12697: =item $selfenroll
12698: 
12699: =item $context
12700: 
12701: =item $credits, number of credits student will earn from this class
12702: 
12703: =back
12704: 
12705: 
12706: =item *
12707: 
12708: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12709: custom role; give a custom role to a user for the level given by URL.  Specify
12710: name and domain of role author, and role name
12711: 
12712: =item *
12713: 
12714: revokerole($udom,$uname,$url,$role) : revoke a role for url
12715: 
12716: =item *
12717: 
12718: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12719: 
12720: =back
12721: 
12722: =head2 Course Infomation
12723: 
12724: =over 4
12725: 
12726: =item *
12727: 
12728: coursedescription($courseid,$options) : returns a hash of information about the
12729: specified course id, including all environment settings for the
12730: course, the description of the course will be in the hash under the
12731: key 'description'
12732: 
12733: $options is an optional parameter that if supplied is a hash reference that controls
12734: what how this function works.  It has the following key/values:
12735: 
12736: =over 4
12737: 
12738: =item freshen_cache
12739: 
12740: If defined, and the environment cache for the course is valid, it is 
12741: returned in the returned hash.
12742: 
12743: =item one_time
12744: 
12745: If defined, the last cache time is set to _now_
12746: 
12747: =item user
12748: 
12749: If defined, the supplied username is used instead of the current user.
12750: 
12751: 
12752: =back
12753: 
12754: =item *
12755: 
12756: resdata($name,$domain,$type,@which) : request for current parameter
12757: setting for a specific $type, where $type is either 'course' or 'user',
12758: @what should be a list of parameters to ask about. This routine caches
12759: answers for 5 minutes.
12760: 
12761: =item *
12762: 
12763: get_courseresdata($courseid, $domain) : dump the entire course resource
12764: data base, returning a hash that is keyed by the resource name and has
12765: values that are the resource value.  I believe that the timestamps and
12766: versions are also returned.
12767: 
12768: =back
12769: 
12770: =head2 Course Modification
12771: 
12772: =over 4
12773: 
12774: =item *
12775: 
12776: writecoursepref($courseid,%prefs) : write preferences (environment
12777: database) for a course
12778: 
12779: =item *
12780: 
12781: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12782: 
12783: =item *
12784: 
12785: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12786: 
12787: =item *
12788: 
12789: is_course($courseid), is_course($cdom, $cnum)
12790: 
12791: Accepts either a combined $courseid (in the form of domain_courseid) or the
12792: two component version $cdom, $cnum. It checks if the specified course exists.
12793: 
12794: Returns:
12795:     undef if the course doesn't exist, otherwise
12796:     in scalar context the combined courseid.
12797:     in list context the two components of the course identifier, domain and 
12798:     courseid.    
12799: 
12800: =back
12801: 
12802: =head2 Resource Subroutines
12803: 
12804: =over 4
12805: 
12806: =item *
12807: 
12808: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12809: 
12810: =item *
12811: 
12812: repcopy($filename) : subscribes to the requested file, and attempts to
12813: replicate from the owning library server, Might return
12814: 'unavailable', 'not_found', 'forbidden', 'ok', or
12815: 'bad_request', also attempts to grab the metadata for the
12816: resource. Expects the local filesystem pathname
12817: (/home/httpd/html/res/....)
12818: 
12819: =back
12820: 
12821: =head2 Resource Information
12822: 
12823: =over 4
12824: 
12825: =item *
12826: 
12827: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12828: a vairety of different possible values, $varname should be a request
12829: string, and the other parameters can be used to specify who and what
12830: one is asking about.
12831: 
12832: Possible values for $varname are environment.lastname (or other item
12833: from the envirnment hash), user.name (or someother aspect about the
12834: user), resource.0.maxtries (or some other part and parameter of a
12835: resource)
12836: 
12837: =item *
12838: 
12839: directcondval($number) : get current value of a condition; reads from a state
12840: string
12841: 
12842: =item *
12843: 
12844: condval($condidx) : value of condition index based on state
12845: 
12846: =item *
12847: 
12848: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12849: resource's metadata, $what should be either a specific key, or either
12850: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12851: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12852: 
12853: this function automatically caches all requests
12854: 
12855: =item *
12856: 
12857: metadata_query($query,$custom,$customshow) : make a metadata query against the
12858: network of library servers; returns file handle of where SQL and regex results
12859: will be stored for query
12860: 
12861: =item *
12862: 
12863: symbread($filename) : return symbolic list entry (filename argument optional);
12864: returns the data handle
12865: 
12866: =item *
12867: 
12868: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12869: and is a possible symb for the URL in $thisfn, and if is an encrypted
12870: resource that the user accessed using /enc/ returns a 1 on success, 0
12871: on failure, user must be in a course, as it assumes the existence of
12872: the course initial hash, and uses $env('request.course.id'}.  The third
12873: arg is an optional reference to a scalar.  If this arg is passed in the 
12874: call to symbverify, it will be set to 1 if the symb has been set to be 
12875: encrypted; otherwise it will be null.  
12876: 
12877: =item *
12878: 
12879: symbclean($symb) : removes versions numbers from a symb, returns the
12880: cleaned symb
12881: 
12882: =item *
12883: 
12884: is_on_map($uri) : checks if the $uri is somewhere on the current
12885: course map, user must be in a course for it to work.
12886: 
12887: =item *
12888: 
12889: numval($salt) : return random seed value (addend for rndseed)
12890: 
12891: =item *
12892: 
12893: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12894: a random seed, all arguments are optional, if they aren't sent it uses the
12895: environment to derive them. Note: if symb isn't sent and it can't get one
12896: from &symbread it will use the current time as its return value
12897: 
12898: =item *
12899: 
12900: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12901: unfakeable, receipt
12902: 
12903: =item *
12904: 
12905: receipt() : API to ireceipt working off of env values; given out to users
12906: 
12907: =item *
12908: 
12909: countacc($url) : count the number of accesses to a given URL
12910: 
12911: =item *
12912: 
12913: 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
12914: 
12915: =item *
12916: 
12917: 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)
12918: 
12919: =item *
12920: 
12921: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12922: 
12923: =item *
12924: 
12925: devalidate($symb) : devalidate temporary spreadsheet calculations,
12926: forcing spreadsheet to reevaluate the resource scores next time.
12927: 
12928: =item * 
12929: 
12930: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
12931: when viewing in course context.
12932: 
12933:  input: six args -- filename (decluttered), course number, course domain,
12934:                     url, symb (if registered) and group (if this is a 
12935:                     group item -- e.g., bulletin board, group page etc.).
12936: 
12937:  output: array of five scalars --
12938:          $cfile -- url for file editing if editable on current server
12939:          $home -- homeserver of resource (i.e., for author if published,
12940:                                           or course if uploaded.).
12941:          $switchserver --  1 if server switch will be needed.
12942:          $forceedit -- 1 if icon/link should be to go to edit mode 
12943:          $forceview -- 1 if icon/link should be to go to view mode
12944: 
12945: =item *
12946: 
12947: is_course_upload($file,$cnum,$cdom)
12948: 
12949: Used in course context to determine if current file was uploaded to 
12950: the course (i.e., would be found in /userfiles/docs on the course's 
12951: homeserver.
12952: 
12953:   input: 3 args -- filename (decluttered), course number and course domain.
12954:   output: boolean -- 1 if file was uploaded.
12955: 
12956: =back
12957: 
12958: =head2 Storing/Retreiving Data
12959: 
12960: =over 4
12961: 
12962: =item *
12963: 
12964: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12965: for this url; hashref needs to be given and should be a \%hashname; the
12966: remaining args aren't required and if they aren't passed or are '' they will
12967: be derived from the env
12968: 
12969: =item *
12970: 
12971: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12972: uses critical subroutine
12973: 
12974: =item *
12975: 
12976: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12977: all args are optional
12978: 
12979: =item *
12980: 
12981: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12982: dumps the complete (or key matching regexp) namespace into a hash
12983: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12984: normally &store()ed into
12985: 
12986: $range should be either an integer '100' (give me the first 100
12987:                                            matching records)
12988:               or be  two integers sperated by a - with no spaces
12989:                  '30-50' (give me the 30th through the 50th matching
12990:                           records)
12991: 
12992: 
12993: =item *
12994: 
12995: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12996: replaces a &store() version of data with a replacement set of data
12997: for a particular resource in a namespace passed in the $storehash hash 
12998: reference
12999: 
13000: =item *
13001: 
13002: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13003: works very similar to store/cstore, but all data is stored in a
13004: temporary location and can be reset using tmpreset, $storehash should
13005: be a hash reference, returns nothing on success
13006: 
13007: =item *
13008: 
13009: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13010: similar to restore, but all data is stored in a temporary location and
13011: can be reset using tmpreset. Returns a hash of values on success,
13012: error string otherwise.
13013: 
13014: =item *
13015: 
13016: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13017: deltes all keys for $symb form the temporary storage hash.
13018: 
13019: =item *
13020: 
13021: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13022: reference filled in from namesp ($udom and $uname are optional)
13023: 
13024: =item *
13025: 
13026: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13027: namesp ($udom and $uname are optional)
13028: 
13029: =item *
13030: 
13031: dump($namespace,$udom,$uname,$regexp,$range) : 
13032: dumps the complete (or key matching regexp) namespace into a hash
13033: ($udom, $uname, $regexp, $range are optional)
13034: 
13035: $range should be either an integer '100' (give me the first 100
13036:                                            matching records)
13037:               or be  two integers sperated by a - with no spaces
13038:                  '30-50' (give me the 30th through the 50th matching
13039:                           records)
13040: =item *
13041: 
13042: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13043: $store can be a scalar, an array reference, or if the amount to be 
13044: incremented is > 1, a hash reference.
13045: 
13046: ($udom and $uname are optional)
13047: 
13048: =item *
13049: 
13050: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13051: ($udom and $uname are optional)
13052: 
13053: =item *
13054: 
13055: cput($namespace,$storehash,$udom,$uname) : critical put
13056: ($udom and $uname are optional)
13057: 
13058: =item *
13059: 
13060: newput($namespace,$storehash,$udom,$uname) :
13061: 
13062: Attempts to store the items in the $storehash, but only if they don't
13063: currently exist, if this succeeds you can be certain that you have 
13064: successfully created a new key value pair in the $namespace db.
13065: 
13066: 
13067: Args:
13068:  $namespace: name of database to store values to
13069:  $storehash: hashref to store to the db
13070:  $udom: (optional) domain of user containing the db
13071:  $uname: (optional) name of user caontaining the db
13072: 
13073: Returns:
13074:  'ok' -> succeeded in storing all keys of $storehash
13075:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13076:                         least <key> already existed in the db (other
13077:                         requested keys may also already exist)
13078:  'error: <msg>' -> unable to tie the DB or other error occurred
13079:  'con_lost' -> unable to contact request server
13080:  'refused' -> action was not allowed by remote machine
13081: 
13082: 
13083: =item *
13084: 
13085: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13086: reference filled in from namesp (encrypts the return communication)
13087: ($udom and $uname are optional)
13088: 
13089: =item *
13090: 
13091: log($udom,$name,$home,$message) : write to permanent log for user; use
13092: critical subroutine
13093: 
13094: =item *
13095: 
13096: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13097: array reference filled in from namespace found in domain level on either
13098: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13099: 
13100: =item *
13101: 
13102: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13103: domain level either on specified domain server ($uhome) or primary domain 
13104: server ($udom and $uhome are optional)
13105: 
13106: =item * 
13107: 
13108: get_domain_defaults($target_domain) : returns hash with defaults for
13109: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
13110: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
13111: or localauth), initial password or a kerberos realm, language (e.g., en-us).
13112: Values are retrieved from cache (if current), or from domain's configuration.db
13113: (if available), or lastly from values in lonTabs/dns_domain,tab, 
13114: or lonTabs/domain.tab. 
13115: 
13116: %domdefaults = &get_auth_defaults($target_domain);
13117: 
13118: =back
13119: 
13120: =head2 Network Status Functions
13121: 
13122: =over 4
13123: 
13124: =item *
13125: 
13126: dirlist() : return directory list based on URI (first arg).
13127: 
13128: Inputs: 1 required, 5 optional.
13129: 
13130: =over
13131: 
13132: =item 
13133: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13134: 
13135: =item
13136: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13137: 
13138: =item
13139: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13140: 
13141: =item
13142: $getpropath - boolean: 1 if prepend path using &propath(). 
13143: 
13144: =item
13145: $getuserdir - boolean: 1 if prepend path for "userfiles".
13146: 
13147: =item 
13148: $alternateRoot - path to prepend in place of path from $uri.
13149: 
13150: =back
13151: 
13152: Returns: Array of up to two items.
13153: 
13154: =over
13155: 
13156: a reference to an array of files/subdirectories
13157: 
13158: =over
13159: 
13160: Each element in the array of files/subdirectories is a & separated list of
13161: item name and the result of running stat on the item.  If dirlist was requested
13162: for a file instead of a directory, the item name will be ''. For a directory 
13163: listing, if the item is a metadata file, the element will end &N&M 
13164: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13165: default copyright set (1).  
13166: 
13167: =back
13168: 
13169: a scalar containing error condition (if encountered).
13170: 
13171: =over
13172: 
13173: =item 
13174: no_host (no homeserver identified for $username:$domain).
13175: 
13176: =item 
13177: no_such_host (server contacted for listing not identified as valid host).
13178: 
13179: =item 
13180: con_lost (connection to remote server failed).
13181: 
13182: =item 
13183: refused (invalid $username:$domain received on lond side).
13184: 
13185: =item 
13186: no_such_dir (directory at specified path on lond side does not exist). 
13187: 
13188: =item 
13189: empty (directory at specified path on lond side is empty).
13190: 
13191: =over
13192: 
13193: This is currently not encountered because the &ls3, &ls2, 
13194: &ls (_handler) routines on the lond side do not filter out
13195: . and .. from a directory listing. 
13196: 
13197: =back
13198: 
13199: =back
13200: 
13201: =back
13202: 
13203: =item *
13204: 
13205: spareserver() : find server with least workload from spare.tab
13206: 
13207: 
13208: =item *
13209: 
13210: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13211: if there is no corresponding loncapa host.
13212: 
13213: =back
13214: 
13215: 
13216: =head2 Apache Request
13217: 
13218: =over 4
13219: 
13220: =item *
13221: 
13222: ssi($url,%hash) : server side include, does a complete request cycle on url to
13223: localhost, posts hash
13224: 
13225: =back
13226: 
13227: =head2 Data to String to Data
13228: 
13229: =over 4
13230: 
13231: =item *
13232: 
13233: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13234: and '&' separators, supports elements that are arrayrefs and hashrefs
13235: 
13236: =item *
13237: 
13238: hashref2str($hashref) : convert a hashref into a string complete with
13239: escaping and '=' and '&' separators, supports elements that are
13240: arrayrefs and hashrefs
13241: 
13242: =item *
13243: 
13244: arrayref2str($arrayref) : convert an arrayref into a string complete
13245: with escaping and '&' separators, supports elements that are arrayrefs
13246: and hashrefs
13247: 
13248: =item *
13249: 
13250: str2hash($string) : convert string to hash using unescaping and
13251: splitting on '=' and '&', supports elements that are arrayrefs and
13252: hashrefs
13253: 
13254: =item *
13255: 
13256: str2array($string) : convert string to hash using unescaping and
13257: splitting on '&', supports elements that are arrayrefs and hashrefs
13258: 
13259: =back
13260: 
13261: =head2 Logging Routines
13262: 
13263: 
13264: These routines allow one to make log messages in the lonnet.log and
13265: lonnet.perm logfiles.
13266: 
13267: =over 4
13268: 
13269: =item *
13270: 
13271: logtouch() : make sure the logfile, lonnet.log, exists
13272: 
13273: =item *
13274: 
13275: logthis() : append message to the normal lonnet.log file, it gets
13276: preiodically rolled over and deleted.
13277: 
13278: =item *
13279: 
13280: logperm() : append a permanent message to lonnet.perm.log, this log
13281: file never gets deleted by any automated portion of the system, only
13282: messages of critical importance should go in here.
13283: 
13284: 
13285: =back
13286: 
13287: =head2 General File Helper Routines
13288: 
13289: =over 4
13290: 
13291: =item *
13292: 
13293: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13294: (a) files in /uploaded
13295:   (i) If a local copy of the file exists - 
13296:       compares modification date of local copy with last-modified date for 
13297:       definitive version stored on home server for course. If local copy is 
13298:       stale, requests a new version from the home server and stores it. 
13299:       If the original has been removed from the home server, then local copy 
13300:       is unlinked.
13301:   (ii) If local copy does not exist -
13302:       requests the file from the home server and stores it. 
13303:   
13304:   If $caller is 'uploadrep':  
13305:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13306:     for request for files originally uploaded via DOCS. 
13307:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13308:   
13309:   Otherwise:
13310:      This indicates a call from the content generation phase of the request.
13311:      -  returns the entire contents of the file or -1.
13312:      
13313: (b) files in /res
13314:    - returns the entire contents of a file or -1; 
13315:    it properly subscribes to and replicates the file if neccessary.
13316: 
13317: 
13318: =item *
13319: 
13320: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13321:                   reference
13322: 
13323: returns either a stat() list of data about the file or an empty list
13324: if the file doesn't exist or couldn't find out about it (connection
13325: problems or user unknown)
13326: 
13327: =item *
13328: 
13329: filelocation($dir,$file) : returns file system location of a file
13330: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13331: directory that relative $file lookups are to looked in ($dir of /a/dir
13332: and a file of ../bob will become /a/bob)
13333: 
13334: =item *
13335: 
13336: hreflocation($dir,$file) : returns file system location or a URL; same as
13337: filelocation except for hrefs
13338: 
13339: =item *
13340: 
13341: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13342: 
13343: =back
13344: 
13345: =head2 Usererfile file routines (/uploaded*)
13346: 
13347: =over 4
13348: 
13349: =item *
13350: 
13351: userfileupload(): main rotine for putting a file in a user or course's
13352:                   filespace, arguments are,
13353: 
13354:  formname - required - this is the name of the element in $env where the
13355:            filename, and the contents of the file to create/modifed exist
13356:            the filename is in $env{'form.'.$formname.'.filename'} and the
13357:            contents of the file is located in $env{'form.'.$formname}
13358:  context - if coursedoc, store the file in the course of the active role
13359:              of the current user; 
13360:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13361:            if 'canceloverwrite': delete file in tmp/overwrites directory
13362:  subdir - required - subdirectory to put the file in under ../userfiles/
13363:          if undefined, it will be placed in "unknown"
13364: 
13365:  (This routine calls clean_filename() to remove any dangerous
13366:  characters from the filename, and then calls finuserfileupload() to
13367:  complete the transaction)
13368: 
13369:  returns either the url of the uploaded file (/uploaded/....) if successful
13370:  and /adm/notfound.html if unsuccessful
13371: 
13372: =item *
13373: 
13374: clean_filename(): routine for cleaing a filename up for storage in
13375:                  userfile space, argument is:
13376: 
13377:  filename - proposed filename
13378: 
13379: returns: the new clean filename
13380: 
13381: =item *
13382: 
13383: finishuserfileupload(): routine that creates and sends the file to
13384: userspace, probably shouldn't be called directly
13385: 
13386:   docuname: username or courseid of destination for the file
13387:   docudom: domain of user/course of destination for the file
13388:   formname: same as for userfileupload()
13389:   fname: filename (including subdirectories) for the file
13390:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13391:   allfiles: reference to hash used to store objects found by parser
13392:   codebase: reference to hash used for codebases of java objects found by parser
13393:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13394:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13395:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13396:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13397:   context: if 'overwrite', will move the uploaded file from its temporary location to
13398:             userfiles to facilitate overwriting a previously uploaded file with same name.
13399:   mimetype: reference to scalar to accommodate mime type determined
13400:             from File::MMagic if $parser = parse.
13401: 
13402:  returns either the url of the uploaded file (/uploaded/....) if successful
13403:  and /adm/notfound.html if unsuccessful (or an error message if context 
13404:  was 'overwrite').
13405:  
13406: 
13407: =item *
13408: 
13409: renameuserfile(): renames an existing userfile to a new name
13410: 
13411:   Args:
13412:    docuname: username or courseid of destination for the file
13413:    docudom: domain of user/course of destination for the file
13414:    old: current file name (including any subdirs under userfiles)
13415:    new: desired file name (including any subdirs under userfiles)
13416: 
13417: =item *
13418: 
13419: mkdiruserfile(): creates a directory is a userfiles dir
13420: 
13421:   Args:
13422:    docuname: username or courseid of destination for the file
13423:    docudom: domain of user/course of destination for the file
13424:    dir: dir to create (including any subdirs under userfiles)
13425: 
13426: =item *
13427: 
13428: removeuserfile(): removes a file that exists in userfiles
13429: 
13430:   Args:
13431:    docuname: username or courseid of destination for the file
13432:    docudom: domain of user/course of destination for the file
13433:    fname: filname to delete (including any subdirs under userfiles)
13434: 
13435: =item *
13436: 
13437: removeuploadedurl(): convience function for removeuserfile()
13438: 
13439:   Args:
13440:    url:  a full /uploaded/... url to delete
13441: 
13442: =item * 
13443: 
13444: get_portfile_permissions():
13445:   Args:
13446:     domain: domain of user or course contain the portfolio files
13447:     user: name of user or num of course contain the portfolio files
13448:   Returns:
13449:     hashref of a dump of the proper file_permissions.db
13450:    
13451: 
13452: =item * 
13453: 
13454: get_access_controls():
13455: 
13456: Args:
13457:   current_permissions: the hash ref returned from get_portfile_permissions()
13458:   group: (optional) the group you want the files associated with
13459:   file: (optional) the file you want access info on
13460: 
13461: Returns:
13462:     a hash (keys are file names) of hashes containing
13463:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13464:         values are XML containing access control settings (see below) 
13465: 
13466: Internal notes:
13467: 
13468:  access controls are stored in file_permissions.db as key=value pairs.
13469:     key -> path to file/file_name\0uniqueID:scope_end_start
13470:         where scope -> public,guest,course,group,domains or users.
13471:               end -> UNIX time for end of access (0 -> no end date)
13472:               start -> UNIX time for start of access
13473: 
13474:     value -> XML description of access control
13475:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13476:             <start></start>
13477:             <end></end>
13478: 
13479:             <password></password>  for scope type = guest
13480: 
13481:             <domain></domain>     for scope type = course or group
13482:             <number></number>
13483:             <roles id="">
13484:              <role></role>
13485:              <access></access>
13486:              <section></section>
13487:              <group></group>
13488:             </roles>
13489: 
13490:             <dom></dom>         for scope type = domains
13491: 
13492:             <users>             for scope type = users
13493:              <user>
13494:               <uname></uname>
13495:               <udom></udom>
13496:              </user>
13497:             </users>
13498:            </scope> 
13499:               
13500:  Access data is also aggregated for each file in an additional key=value pair:
13501:  key -> path to file/file_name\0accesscontrol 
13502:  value -> reference to hash
13503:           hash contains key = value pairs
13504:           where key = uniqueID:scope_end_start
13505:                 value = UNIX time record was last updated
13506: 
13507:           Used to improve speed of look-ups of access controls for each file.  
13508:  
13509:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13510: 
13511: =item *
13512: 
13513: modify_access_controls():
13514: 
13515: Modifies access controls for a portfolio file
13516: Args
13517: 1. file name
13518: 2. reference to hash of required changes,
13519: 3. domain
13520: 4. username
13521:   where domain,username are the domain of the portfolio owner 
13522:   (either a user or a course) 
13523: 
13524: Returns:
13525: 1. result of additions or updates ('ok' or 'error', with error message). 
13526: 2. result of deletions ('ok' or 'error', with error message).
13527: 3. reference to hash of any new or updated access controls.
13528: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13529:    key = integer (inbound ID)
13530:    value = uniqueID
13531: 
13532: =item *
13533: 
13534: get_timebased_id():
13535: 
13536: Attempts to get a unique timestamp-based suffix for use with items added to a 
13537: course via the Course Editor (e.g., folders, composite pages, 
13538: group bulletin boards).
13539: 
13540: Args: (first three required; six others optional)
13541: 
13542: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13543:    docssequence, or name of group
13544: 
13545: 2. keyid (alphanumeric): name of temporary locking key in hash,
13546:    e.g., num, boardids
13547: 
13548: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13549:    file will be named nohist_namespace.db
13550: 
13551: 4. cdom: domain of course; default is current course domain from %env
13552: 
13553: 5. cnum: course number; default is current course number from %env
13554: 
13555: 6. idtype: set to concat if an additional digit is to be appended to the 
13556:    unix timestamp to form the suffix, if the plain timestamp is already
13557:    in use.  Default is to not do this, but simply increment the unix 
13558:    timestamp by 1 until a unique key is obtained.
13559: 
13560: 7. who: holder of locking key; defaults to user:domain for user.
13561: 
13562: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13563:    retrying); default is 3.
13564: 
13565: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13566: 
13567: Returns:
13568: 
13569: 1. suffix obtained (numeric)
13570: 
13571: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13572: 
13573: 3. error: contains (localized) error message if an error occurred.
13574: 
13575: 
13576: =back
13577: 
13578: =head2 HTTP Helper Routines
13579: 
13580: =over 4
13581: 
13582: =item *
13583: 
13584: escape() : unpack non-word characters into CGI-compatible hex codes
13585: 
13586: =item *
13587: 
13588: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13589: 
13590: =back
13591: 
13592: =head1 PRIVATE SUBROUTINES
13593: 
13594: =head2 Underlying communication routines (Shouldn't call)
13595: 
13596: =over 4
13597: 
13598: =item *
13599: 
13600: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13601: 
13602: =item *
13603: 
13604: reply() : uses subreply to send a message to remote machine, logs all failures
13605: 
13606: =item *
13607: 
13608: critical() : passes a critical message to another server; if cannot
13609: get through then place message in connection buffer directory and
13610: returns con_delayed, if incapable of saving message, returns
13611: con_failed
13612: 
13613: =item *
13614: 
13615: reconlonc() : tries to reconnect lonc client processes.
13616: 
13617: =back
13618: 
13619: =head2 Resource Access Logging
13620: 
13621: =over 4
13622: 
13623: =item *
13624: 
13625: flushcourselogs() : flush (save) buffer logs and access logs
13626: 
13627: =item *
13628: 
13629: courselog($what) : save message for course in hash
13630: 
13631: =item *
13632: 
13633: courseacclog($what) : save message for course using &courselog().  Perform
13634: special processing for specific resource types (problems, exams, quizzes, etc).
13635: 
13636: =item *
13637: 
13638: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13639: as a PerlChildExitHandler
13640: 
13641: =back
13642: 
13643: =head2 Other
13644: 
13645: =over 4
13646: 
13647: =item *
13648: 
13649: symblist($mapname,%newhash) : update symbolic storage links
13650: 
13651: =back
13652: 
13653: =cut
13654: 

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