File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1279: download - view: text, annotated - select for diffs
Wed Apr 1 23:22:13 2015 UTC (9 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6771
  Domain configuration to switch active users from a server in the domain.
  - When the page has loaded on the session hosting server, javascript will
    cause display of an alert and will switch user's session to another server
    in the domain, after 5s. Submit buttons for homewrk problems disabled for
    those 5s.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1279 2015/04/01 23:22:13 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$cachekeys) = @_;
  360:     my $items;
  361:     return unless (ref($cachekeys) eq 'ARRAY');
  362:     my $cachestr = join('&',@{$cachekeys});
  363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  364:     return $response;
  365: }
  366: 
  367: # -------------------------------------------------- Non-critical communication
  368: sub subreply {
  369:     my ($cmd,$server)=@_;
  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  371:     #
  372:     #  With loncnew process trimming, there's a timing hole between lonc server
  373:     #  process exit and the master server picking up the listen on the AF_UNIX
  374:     #  socket.  In that time interval, a lock file will exist:
  375: 
  376:     my $lockfile=$peerfile.".lock";
  377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  378: 	sleep(1);
  379:     }
  380:     # At this point, either a loncnew parent is listening or an old lonc
  381:     # or loncnew child is listening so we can connect or everything's dead.
  382:     #
  383:     #   We'll give the connection a few tries before abandoning it.  If
  384:     #   connection is not possible, we'll con_lost back to the client.
  385:     #   
  386:     my $client;
  387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  389: 				      Type    => SOCK_STREAM,
  390: 				      Timeout => 10);
  391: 	if ($client) {
  392: 	    last;		# Connected!
  393: 	} else {
  394: 	    &create_connection(&hostname($server),$server);
  395: 	}
  396:         sleep(1);		# Try again later if failed connection.
  397:     }
  398:     my $answer;
  399:     if ($client) {
  400: 	print $client "sethost:$server:$cmd\n";
  401: 	$answer=<$client>;
  402: 	if (!$answer) { $answer="con_lost"; }
  403: 	chomp($answer);
  404:     } else {
  405: 	$answer = 'con_lost';	# Failed connection.
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: sub reply {
  411:     my ($cmd,$server)=@_;
  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  413:     my $answer=subreply($cmd,$server);
  414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  415:        &logthis("<font color=\"blue\">WARNING:".
  416:                 " $cmd to $server returned $answer</font>");
  417:     }
  418:     return $answer;
  419: }
  420: 
  421: # ----------------------------------------------------------- Send USR1 to lonc
  422: 
  423: sub reconlonc {
  424:     my ($lonid) = @_;
  425:     my $hostname = &hostname($lonid);
  426:     if ($lonid) {
  427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  428: 	if ($hostname && -e $peerfile) {
  429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  431: 					     Type    => SOCK_STREAM,
  432: 					     Timeout => 10);
  433: 	    if ($client) {
  434: 		print $client ("reset_retries\n");
  435: 		my $answer=<$client>;
  436: 		#reset just this one.
  437: 	    }
  438: 	}
  439: 	return;
  440:     }
  441: 
  442:     &logthis("Trying to reconnect lonc");
  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  444:     if (open(my $fh,"<$loncfile")) {
  445: 	my $loncpid=<$fh>;
  446:         chomp($loncpid);
  447:         if (kill 0 => $loncpid) {
  448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  449:             kill USR1 => $loncpid;
  450:             sleep 1;
  451:          } else {
  452: 	    &logthis(
  453:                "<font color=\"blue\">WARNING:".
  454:                " lonc at pid $loncpid not responding, giving up</font>");
  455:         }
  456:     } else {
  457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  458:     }
  459: }
  460: 
  461: # ------------------------------------------------------ Critical communication
  462: 
  463: sub critical {
  464:     my ($cmd,$server)=@_;
  465:     unless (&hostname($server)) {
  466:         &logthis("<font color=\"blue\">WARNING:".
  467:                " Critical message to unknown server ($server)</font>");
  468:         return 'no_such_host';
  469:     }
  470:     my $answer=reply($cmd,$server);
  471:     if ($answer eq 'con_lost') {
  472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  473: 	my $answer=reply($cmd,$server);
  474:         if ($answer eq 'con_lost') {
  475:             my $now=time;
  476:             my $middlename=$cmd;
  477:             $middlename=substr($middlename,0,16);
  478:             $middlename=~s/\W//g;
  479:             my $dfilename=
  480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  481:             $dumpcount++;
  482:             {
  483: 		my $dfh;
  484: 		if (open($dfh,">$dfilename")) {
  485: 		    print $dfh "$cmd\n"; 
  486: 		    close($dfh);
  487: 		}
  488:             }
  489:             sleep 2;
  490:             my $wcmd='';
  491:             {
  492: 		my $dfh;
  493: 		if (open($dfh,"<$dfilename")) {
  494: 		    $wcmd=<$dfh>; 
  495: 		    close($dfh);
  496: 		}
  497:             }
  498:             chomp($wcmd);
  499:             if ($wcmd eq $cmd) {
  500: 		&logthis("<font color=\"blue\">WARNING: ".
  501:                          "Connection buffer $dfilename: $cmd</font>");
  502:                 &logperm("D:$server:$cmd");
  503: 	        return 'con_delayed';
  504:             } else {
  505:                 &logthis("<font color=\"red\">CRITICAL:"
  506:                         ." Critical connection failed: $server $cmd</font>");
  507:                 &logperm("F:$server:$cmd");
  508:                 return 'con_failed';
  509:             }
  510:         }
  511:     }
  512:     return $answer;
  513: }
  514: 
  515: # ------------------------------------------- check if return value is an error
  516: 
  517: sub error {
  518:     my ($result) = @_;
  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  520: 	if ($2 == 2) { return undef; }
  521: 	return $1;
  522:     }
  523:     return undef;
  524: }
  525: 
  526: sub convert_and_load_session_env {
  527:     my ($lonidsdir,$handle)=@_;
  528:     my @profile;
  529:     {
  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  531: 	if (!$opened) {
  532: 	    return 0;
  533: 	}
  534: 	flock($idf,LOCK_SH);
  535: 	@profile=<$idf>;
  536: 	close($idf);
  537:     }
  538:     my %temp_env;
  539:     foreach my $line (@profile) {
  540: 	if ($line !~ m/=/) {
  541: 	    return 0;
  542: 	}
  543: 	chomp($line);
  544: 	my ($envname,$envvalue)=split(/=/,$line,2);
  545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  546:     }
  547:     unlink("$lonidsdir/$handle.id");
  548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  549: 	    0640)) {
  550: 	%disk_env = %temp_env;
  551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  552: 	untie(%disk_env);
  553:     }
  554:     return 1;
  555: }
  556: 
  557: # ------------------------------------------- Transfer profile into environment
  558: my $env_loaded;
  559: sub transfer_profile_to_env {
  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
  561:     if (!$force_transfer && $env_loaded) { return; } 
  562: 
  563:     if (!defined($lonidsdir)) {
  564: 	$lonidsdir = $perlvar{'lonIDsDir'};
  565:     }
  566:     if (!defined($handle)) {
  567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  568:     }
  569: 
  570:     my $convert;
  571:     {
  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  573: 	if (!$opened) {
  574: 	    return;
  575: 	}
  576: 	flock($idf,LOCK_SH);
  577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  578: 		&GDBM_READER(),0640)) {
  579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  580: 	    untie(%disk_env);
  581: 	} else {
  582: 	    $convert = 1;
  583: 	}
  584:     }
  585:     if ($convert) {
  586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  587: 	    &logthis("Failed to load session, or convert session.");
  588: 	}
  589:     }
  590: 
  591:     my %remove;
  592:     while ( my $envname = each(%env) ) {
  593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  594:             if ($time < time-300) {
  595:                 $remove{$key}++;
  596:             }
  597:         }
  598:     }
  599: 
  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  601:     $env_loaded=1;
  602:     foreach my $expired_key (keys(%remove)) {
  603:         &delenv($expired_key);
  604:     }
  605: }
  606: 
  607: # ---------------------------------------------------- Check for valid session 
  608: sub check_for_valid_session {
  609:     my ($r,$name,$userhashref) = @_;
  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  611:     if ($name eq '') {
  612:         $name = 'lonID';
  613:     }
  614:     my $lonid=$cookies{$name};
  615:     return undef if (!$lonid);
  616: 
  617:     my $handle=&LONCAPA::clean_handle($lonid->value);
  618:     my $lonidsdir;
  619:     if ($name eq 'lonDAV') {
  620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  621:     } else {
  622:         $lonidsdir=$r->dir_config('lonIDsDir');
  623:     }
  624:     return undef if (!-e "$lonidsdir/$handle.id");
  625: 
  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  627:     return undef if (!$opened);
  628: 
  629:     flock($idf,LOCK_SH);
  630:     my %disk_env;
  631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  632: 	    &GDBM_READER(),0640)) {
  633: 	return undef;	
  634:     }
  635: 
  636:     if (!defined($disk_env{'user.name'})
  637: 	|| !defined($disk_env{'user.domain'})) {
  638: 	return undef;
  639:     }
  640: 
  641:     if (ref($userhashref) eq 'HASH') {
  642:         $userhashref->{'name'} = $disk_env{'user.name'};
  643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  644:     }
  645: 
  646:     return $handle;
  647: }
  648: 
  649: sub timed_flock {
  650:     my ($file,$lock_type) = @_;
  651:     my $failed=0;
  652:     eval {
  653: 	local $SIG{__DIE__}='DEFAULT';
  654: 	local $SIG{ALRM}=sub {
  655: 	    $failed=1;
  656: 	    die("failed lock");
  657: 	};
  658: 	alarm(13);
  659: 	flock($file,$lock_type);
  660: 	alarm(0);
  661:     };
  662:     if ($failed) {
  663: 	return undef;
  664:     } else {
  665: 	return 1;
  666:     }
  667: }
  668: 
  669: # ---------------------------------------------------------- Append Environment
  670: 
  671: sub appenv {
  672:     my ($newenv,$roles) = @_;
  673:     if (ref($newenv) eq 'HASH') {
  674:         foreach my $key (keys(%{$newenv})) {
  675:             my $refused = 0;
  676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  677:                 $refused = 1;
  678:                 if (ref($roles) eq 'ARRAY') {
  679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  681:                         $refused = 0;
  682:                     }
  683:                 }
  684:             }
  685:             if ($refused) {
  686:                 &logthis("<font color=\"blue\">WARNING: ".
  687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  688:                          .'</font>');
  689: 	        delete($newenv->{$key});
  690:             } else {
  691:                 $env{$key}=$newenv->{$key};
  692:             }
  693:         }
  694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  695:         if ($opened
  696: 	    && &timed_flock($env_file,LOCK_EX)
  697: 	    &&
  698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  700: 	    while (my ($key,$value) = each(%{$newenv})) {
  701: 	        $disk_env{$key} = $value;
  702: 	    }
  703: 	    untie(%disk_env);
  704:         }
  705:     }
  706:     return 'ok';
  707: }
  708: # ----------------------------------------------------- Delete from Environment
  709: 
  710: sub delenv {
  711:     my ($delthis,$regexp,$roles) = @_;
  712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  713:         my $refused = 1;
  714:         if (ref($roles) eq 'ARRAY') {
  715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  716:             if (grep(/^\Q$role\E$/,@{$roles})) {
  717:                 $refused = 0;
  718:             }
  719:         }
  720:         if ($refused) {
  721:             &logthis("<font color=\"blue\">WARNING: ".
  722:                      "Attempt to delete from environment ".$delthis);
  723:             return 'error';
  724:         }
  725:     }
  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  727:     if ($opened
  728: 	&& &timed_flock($env_file,LOCK_EX)
  729: 	&&
  730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  732: 	foreach my $key (keys(%disk_env)) {
  733: 	    if ($regexp) {
  734:                 if ($key=~/^$delthis/) {
  735:                     delete($env{$key});
  736:                     delete($disk_env{$key});
  737:                 } 
  738:             } else {
  739:                 if ($key=~/^\Q$delthis\E/) {
  740: 		    delete($env{$key});
  741: 		    delete($disk_env{$key});
  742: 	        }
  743:             }
  744: 	}
  745: 	untie(%disk_env);
  746:     }
  747:     return 'ok';
  748: }
  749: 
  750: sub get_env_multiple {
  751:     my ($name) = @_;
  752:     my @values;
  753:     if (defined($env{$name})) {
  754:         # exists is it an array
  755:         if (ref($env{$name})) {
  756:             @values=@{ $env{$name} };
  757:         } else {
  758:             $values[0]=$env{$name};
  759:         }
  760:     }
  761:     return(@values);
  762: }
  763: 
  764: # ------------------------------------------------------------------- Locking
  765: 
  766: sub set_lock {
  767:     my ($text)=@_;
  768:     $locknum++;
  769:     my $id=$$.'-'.$locknum;
  770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  771:              'session.lock.'.$id => $text});
  772:     return $id;
  773: }
  774: 
  775: sub get_locks {
  776:     my $num=0;
  777:     my %texts=();
  778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  779:        if ($lock=~/\w/) {
  780:           $num++;
  781:           $texts{$lock}=$env{'session.lock.'.$lock};
  782:        }
  783:    }
  784:    return ($num,%texts);
  785: }
  786: 
  787: sub remove_lock {
  788:     my ($id)=@_;
  789:     my $newlocks='';
  790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  791:        if (($lock=~/\w/) && ($lock ne $id)) {
  792:           $newlocks.=','.$lock;
  793:        }
  794:     }
  795:     &appenv({'session.locks' => $newlocks});
  796:     &delenv('session.lock.'.$id);
  797: }
  798: 
  799: sub remove_all_locks {
  800:     my $activelocks=$env{'session.locks'};
  801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  802:        if ($lock=~/\w/) {
  803:           &remove_lock($lock);
  804:        }
  805:     }
  806: }
  807: 
  808: 
  809: # ------------------------------------------ Find out current server userload
  810: sub userload {
  811:     my $numusers=0;
  812:     {
  813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  814: 	my $filename;
  815: 	my $curtime=time;
  816: 	while ($filename=readdir(LONIDS)) {
  817: 	    next if ($filename eq '.' || $filename eq '..');
  818: 	    next if ($filename =~ /publicuser_\d+\.id/);
  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  821: 	}
  822: 	closedir(LONIDS);
  823:     }
  824:     my $userloadpercent=0;
  825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  826:     if ($maxuserload) {
  827: 	$userloadpercent=100*$numusers/$maxuserload;
  828:     }
  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  830:     return $userloadpercent;
  831: }
  832: 
  833: # ------------------------------ Find server with least workload from spare.tab
  834: 
  835: sub spareserver {
  836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  837:     my $spare_server;
  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  840:                                                      :  $userloadpercent;
  841:     my ($uint_dom,$remotesessions);
  842:     if (($udom ne '') && (&domain($udom) ne '')) {
  843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  846:         $remotesessions = $udomdefaults{'remotesessions'};
  847:     }
  848:     my $spareshash = &this_host_spares($udom);
  849:     if (ref($spareshash) eq 'HASH') {
  850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  852:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  853:                                              $try_server));
  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:                     next unless (&spare_can_host($udom,$uint_dom,
  865:                                                  $remotesessions,$try_server));
  866: 	            ($spare_server, $lowest_load) =
  867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  868:                 }
  869: 	    }
  870:         }
  871:     }
  872: 
  873:     if (!$want_server_name) {
  874:         my $protocol = 'http';
  875:         if ($protocol{$spare_server} eq 'https') {
  876:             $protocol = $protocol{$spare_server};
  877:         }
  878:         if (defined($spare_server)) {
  879:             my $hostname = &hostname($spare_server);
  880:             if (defined($hostname)) {
  881: 	        $spare_server = $protocol.'://'.$hostname;
  882:             }
  883:         }
  884:     }
  885:     return $spare_server;
  886: }
  887: 
  888: sub compare_server_load {
  889:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  890: 
  891:     if ($required) {
  892:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  893:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  894:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  895:         if (($major eq '' && $minor eq '') ||
  896:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  897:             return ($spare_server,$lowest_load);
  898:         }
  899:     }
  900: 
  901:     my $loadans     = &reply('load',    $try_server);
  902:     my $userloadans = &reply('userload',$try_server);
  903: 
  904:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  905: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  906:     }
  907: 
  908:     my $load;
  909:     if ($loadans =~ /\d/) {
  910: 	if ($userloadans =~ /\d/) {
  911: 	    #both are numbers, pick the bigger one
  912: 	    $load = ($loadans > $userloadans) ? $loadans 
  913: 		                              : $userloadans;
  914: 	} else {
  915: 	    $load = $loadans;
  916: 	}
  917:     } else {
  918: 	$load = $userloadans;
  919:     }
  920: 
  921:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  922: 	$spare_server = $try_server;
  923: 	$lowest_load  = $load;
  924:     }
  925:     return ($spare_server,$lowest_load);
  926: }
  927: 
  928: # --------------------------- ask offload servers if user already has a session
  929: sub find_existing_session {
  930:     my ($udom,$uname) = @_;
  931:     my $spareshash = &this_host_spares($udom);
  932:     if (ref($spareshash) eq 'HASH') {
  933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  936:             }
  937:         }
  938:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  939:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  940:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  941:             }
  942:         }
  943:     }
  944:     return;
  945: }
  946: 
  947: # -------------------------------- ask if server already has a session for user
  948: sub has_user_session {
  949:     my ($lonid,$udom,$uname) = @_;
  950:     my $result = &reply(join(':','userhassession',
  951: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  952:     return 1 if ($result eq 'ok');
  953: 
  954:     return 0;
  955: }
  956: 
  957: # --------- determine least loaded server in a user's domain which allows login
  958: 
  959: sub choose_server {
  960:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
  961:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  962:     my %servers = &get_servers($udom);
  963:     my $lowest_load = 30000;
  964:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
  965:     if ($skiploadbal) {
  966:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
  967:         unless (defined($cached)) {
  968:             my $cachetime = 60*60*24;
  969:             my %domconfig =
  970:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
  971:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  972:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
  973:                                            $cachetime);
  974:             }
  975:         }
  976:     }
  977:     foreach my $lonhost (keys(%servers)) {
  978:         if ($skiploadbal) {
  979:             if (ref($balancers) eq 'HASH') {
  980:                 next if (exists($balancers->{$lonhost}));
  981:             }
  982:         }   
  983:         my $loginvia;
  984:         if ($checkloginvia) {
  985:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  986:             if ($loginvia) {
  987:                 my ($server,$path) = split(/:/,$loginvia);
  988:                 ($login_host, $lowest_load) =
  989:                     &compare_server_load($server, $login_host, $lowest_load, $required);
  990:                 if ($login_host eq $server) {
  991:                     $portal_path = $path;
  992:                     $isredirect = 1;
  993:                 }
  994:             } else {
  995:                 ($login_host, $lowest_load) =
  996:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
  997:                 if ($login_host eq $lonhost) {
  998:                     $portal_path = '';
  999:                     $isredirect = ''; 
 1000:                 }
 1001:             }
 1002:         } else {
 1003:             ($login_host, $lowest_load) =
 1004:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1005:         }
 1006:     }
 1007:     if ($login_host ne '') {
 1008:         $hostname = &hostname($login_host);
 1009:     }
 1010:     return ($login_host,$hostname,$portal_path,$isredirect);
 1011: }
 1012: 
 1013: # --------------------------------------------- Try to change a user's password
 1014: 
 1015: sub changepass {
 1016:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1017:     $currentpass = &escape($currentpass);
 1018:     $newpass     = &escape($newpass);
 1019:     my $lonhost = $perlvar{'lonHostID'};
 1020:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1021: 		       $server);
 1022:     if (! $answer) {
 1023: 	&logthis("No reply on password change request to $server ".
 1024: 		 "by $uname in domain $udom.");
 1025:     } elsif ($answer =~ "^ok") {
 1026:         &logthis("$uname in $udom successfully changed their password ".
 1027: 		 "on $server.");
 1028:     } elsif ($answer =~ "^pwchange_failure") {
 1029: 	&logthis("$uname in $udom was unable to change their password ".
 1030: 		 "on $server.  The action was blocked by either lcpasswd ".
 1031: 		 "or pwchange");
 1032:     } elsif ($answer =~ "^non_authorized") {
 1033:         &logthis("$uname in $udom did not get their password correct when ".
 1034: 		 "attempting to change it on $server.");
 1035:     } elsif ($answer =~ "^auth_mode_error") {
 1036:         &logthis("$uname in $udom attempted to change their password despite ".
 1037: 		 "not being locally or internally authenticated on $server.");
 1038:     } elsif ($answer =~ "^unknown_user") {
 1039:         &logthis("$uname in $udom attempted to change their password ".
 1040: 		 "on $server but were unable to because $server is not ".
 1041: 		 "their home server.");
 1042:     } elsif ($answer =~ "^refused") {
 1043: 	&logthis("$server refused to change $uname in $udom password because ".
 1044: 		 "it was sent an unencrypted request to change the password.");
 1045:     } elsif ($answer =~ "invalid_client") {
 1046:         &logthis("$server refused to change $uname in $udom password because ".
 1047:                  "it was a reset by e-mail originating from an invalid server.");
 1048:     }
 1049:     return $answer;
 1050: }
 1051: 
 1052: # ----------------------- Try to determine user's current authentication scheme
 1053: 
 1054: sub queryauthenticate {
 1055:     my ($uname,$udom)=@_;
 1056:     my $uhome=&homeserver($uname,$udom);
 1057:     if (!$uhome) {
 1058: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1059: 	return 'no_host';
 1060:     }
 1061:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1062:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1063: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1064:     }
 1065:     return $answer;
 1066: }
 1067: 
 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
 1069: 
 1070: sub authenticate {
 1071:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1072:     $upass=&escape($upass);
 1073:     $uname= &LONCAPA::clean_username($uname);
 1074:     my $uhome=&homeserver($uname,$udom,1);
 1075:     my $newhome;
 1076:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1077: # Maybe the machine was offline and only re-appeared again recently?
 1078:         &reconlonc();
 1079: # One more
 1080: 	$uhome=&homeserver($uname,$udom,1);
 1081:         if (($uhome eq 'no_host') && $checkdefauth) {
 1082:             if (defined(&domain($udom,'primary'))) {
 1083:                 $newhome=&domain($udom,'primary');
 1084:             }
 1085:             if ($newhome ne '') {
 1086:                 $uhome = $newhome;
 1087:             }
 1088:         }
 1089: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1090: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1091: 	    return 'no_host';
 1092:         }
 1093:     }
 1094:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1095:     if ($answer eq 'authorized') {
 1096:         if ($newhome) {
 1097:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1098:             return 'no_account_on_host'; 
 1099:         } else {
 1100:             &logthis("User $uname at $udom authorized by $uhome");
 1101:             return $uhome;
 1102:         }
 1103:     }
 1104:     if ($answer eq 'non_authorized') {
 1105: 	&logthis("User $uname at $udom rejected by $uhome");
 1106: 	return 'no_host'; 
 1107:     }
 1108:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1109:     return 'no_host';
 1110: }
 1111: 
 1112: sub can_host_session {
 1113:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1114:     my $canhost = 1;
 1115:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1116:     if (ref($remotesessions) eq 'HASH') {
 1117:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1118:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1119:                 $canhost = 0;
 1120:             } else {
 1121:                 $canhost = 1;
 1122:             }
 1123:         }
 1124:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1126:                 $canhost = 1;
 1127:             } else {
 1128:                 $canhost = 0;
 1129:             }
 1130:         }
 1131:         if ($canhost) {
 1132:             if ($remotesessions->{'version'} ne '') {
 1133:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1134:                 if ($reqmajor ne '' && $reqminor ne '') {
 1135:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1136:                         my $major = $1;
 1137:                         my $minor = $2;
 1138:                         if (($major < $reqmajor ) ||
 1139:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1140:                             $canhost = 0;
 1141:                         }
 1142:                     } else {
 1143:                         $canhost = 0;
 1144:                     }
 1145:                 }
 1146:             }
 1147:         }
 1148:     }
 1149:     if ($canhost) {
 1150:         if (ref($hostedsessions) eq 'HASH') {
 1151:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1152:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1153:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1154:                 if (($uint_dom ne '') && 
 1155:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1156:                     $canhost = 0;
 1157:                 } else {
 1158:                     $canhost = 1;
 1159:                 }
 1160:             }
 1161:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1162:                 if (($uint_dom ne '') && 
 1163:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1164:                     $canhost = 1;
 1165:                 } else {
 1166:                     $canhost = 0;
 1167:                 }
 1168:             }
 1169:         }
 1170:     }
 1171:     return $canhost;
 1172: }
 1173: 
 1174: sub spare_can_host {
 1175:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1176:     my $canhost=1;
 1177:     my $try_server_hostname = &hostname($try_server);
 1178:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1179:     my $serverhomedom = &host_domain($serverhomeID);
 1180:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1181:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1182:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1183:             $canhost = 0;
 1184:         }
 1185:     }
 1186:     if (($canhost) && ($uint_dom)) {
 1187:         my @intdoms;
 1188:         my $internet_names = &get_internet_names($try_server);
 1189:         if (ref($internet_names) eq 'ARRAY') {
 1190:             @intdoms = @{$internet_names};
 1191:         }
 1192:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1193:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1194:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1195:                                          $remotesessions,
 1196:                                          $defdomdefaults{'hostedsessions'});
 1197:         }
 1198:     }
 1199:     return $canhost;
 1200: }
 1201: 
 1202: sub this_host_spares {
 1203:     my ($dom) = @_;
 1204:     my ($dom_in_use,$lonhost_in_use,$result);
 1205:     my @hosts = &current_machine_ids();
 1206:     foreach my $lonhost (@hosts) {
 1207:         if (&host_domain($lonhost) eq $dom) {
 1208:             $dom_in_use = $dom;
 1209:             $lonhost_in_use = $lonhost;
 1210:             last;
 1211:         }
 1212:     }
 1213:     if ($dom_in_use ne '') {
 1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1215:     }
 1216:     if (ref($result) ne 'HASH') {
 1217:         $lonhost_in_use = $perlvar{'lonHostID'};
 1218:         $dom_in_use = &host_domain($lonhost_in_use);
 1219:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1220:         if (ref($result) ne 'HASH') {
 1221:             $result = \%spareid;
 1222:         }
 1223:     }
 1224:     return $result;
 1225: }
 1226: 
 1227: sub spares_for_offload  {
 1228:     my ($dom_in_use,$lonhost_in_use) = @_;
 1229:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1230:     if (defined($cached)) {
 1231:         return $result;
 1232:     } else {
 1233:         my $cachetime = 60*60*24;
 1234:         my %domconfig =
 1235:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1236:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1237:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1238:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1239:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1240:                 }
 1241:             }
 1242:         }
 1243:     }
 1244:     return;
 1245: }
 1246: 
 1247: sub get_lonbalancer_config {
 1248:     my ($servers) = @_;
 1249:     my ($currbalancer,$currtargets);
 1250:     if (ref($servers) eq 'HASH') {
 1251:         foreach my $server (keys(%{$servers})) {
 1252:             my %what = (
 1253:                          spareid => 1,
 1254:                          perlvar => 1,
 1255:                        );
 1256:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1257:             if ($result eq 'ok') {
 1258:                 if (ref($returnhash) eq 'HASH') {
 1259:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1260:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1261:                             $currbalancer = $server;
 1262:                             $currtargets = {};
 1263:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1264:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1265:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1266:                                 }
 1267:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1268:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1269:                                 }
 1270:                             }
 1271:                             last;
 1272:                         }
 1273:                     }
 1274:                 }
 1275:             }
 1276:         }
 1277:     }
 1278:     return ($currbalancer,$currtargets);
 1279: }
 1280: 
 1281: sub check_loadbalancing {
 1282:     my ($uname,$udom) = @_;
 1283:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1284:         $rule_in_effect,$offloadto,$otherserver);
 1285:     my $lonhost = $perlvar{'lonHostID'};
 1286:     my @hosts = &current_machine_ids();
 1287:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1288:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1289:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1290:     my $serverhomedom = &host_domain($lonhost);
 1291: 
 1292:     my $cachetime = 60*60*24;
 1293: 
 1294:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1295:         $dom_in_use = $udom;
 1296:         $homeintdom = 1;
 1297:     } else {
 1298:         $dom_in_use = $serverhomedom;
 1299:     }
 1300:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1301:     unless (defined($cached)) {
 1302:         my %domconfig =
 1303:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1304:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1305:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1306:         }
 1307:     }
 1308:     if (ref($result) eq 'HASH') {
 1309:         ($is_balancer,$currtargets,$currrules) = 
 1310:             &check_balancer_result($result,@hosts);
 1311:         if ($is_balancer) {
 1312:             if (ref($currrules) eq 'HASH') {
 1313:                 if ($homeintdom) {
 1314:                     if ($uname ne '') {
 1315:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1316:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1317:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1318:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1319:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1320:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1321:                             }
 1322:                         }
 1323:                         if ($rule_in_effect eq '') {
 1324:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1325:                             if ($userenv{'inststatus'} ne '') {
 1326:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1327:                                 my ($othertitle,$usertypes,$types) =
 1328:                                     &Apache::loncommon::sorted_inst_types($udom);
 1329:                                 if (ref($types) eq 'ARRAY') {
 1330:                                     foreach my $type (@{$types}) {
 1331:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1332:                                             if (exists($currrules->{$type})) {
 1333:                                                 $rule_in_effect = $currrules->{$type};
 1334:                                             }
 1335:                                         }
 1336:                                     }
 1337:                                 }
 1338:                             } else {
 1339:                                 if (exists($currrules->{'default'})) {
 1340:                                     $rule_in_effect = $currrules->{'default'};
 1341:                                 }
 1342:                             }
 1343:                         }
 1344:                     } else {
 1345:                         if (exists($currrules->{'default'})) {
 1346:                             $rule_in_effect = $currrules->{'default'};
 1347:                         }
 1348:                     }
 1349:                 } else {
 1350:                     if ($currrules->{'_LC_external'} ne '') {
 1351:                         $rule_in_effect = $currrules->{'_LC_external'};
 1352:                     }
 1353:                 }
 1354:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1355:                                                        $uname,$udom);
 1356:             }
 1357:         }
 1358:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1359:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1360:         unless (defined($cached)) {
 1361:             my %domconfig =
 1362:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1363:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1364:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1365:             }
 1366:         }
 1367:         if (ref($result) eq 'HASH') {
 1368:             ($is_balancer,$currtargets,$currrules) = 
 1369:                 &check_balancer_result($result,@hosts);
 1370:             if ($is_balancer) {
 1371:                 if (ref($currrules) eq 'HASH') {
 1372:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1373:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1374:                     }
 1375:                 }
 1376:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1377:                                                        $uname,$udom);
 1378:             }
 1379:         } else {
 1380:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1381:                 $is_balancer = 1;
 1382:                 $offloadto = &this_host_spares($dom_in_use);
 1383:             }
 1384:         }
 1385:     } else {
 1386:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1387:             $is_balancer = 1;
 1388:             $offloadto = &this_host_spares($dom_in_use);
 1389:         }
 1390:     }
 1391:     if ($is_balancer) {
 1392:         my $lowest_load = 30000;
 1393:         if (ref($offloadto) eq 'HASH') {
 1394:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1395:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1396:                     ($otherserver,$lowest_load) =
 1397:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1398:                 }
 1399:             }
 1400:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1401: 
 1402:             if (!$found_server) {
 1403:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1404:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1405:                         ($otherserver,$lowest_load) =
 1406:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1407:                     }
 1408:                 }
 1409:             }
 1410:         } elsif (ref($offloadto) eq 'ARRAY') {
 1411:             if (@{$offloadto} == 1) {
 1412:                 $otherserver = $offloadto->[0];
 1413:             } elsif (@{$offloadto} > 1) {
 1414:                 foreach my $try_server (@{$offloadto}) {
 1415:                     ($otherserver,$lowest_load) =
 1416:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1417:                 }
 1418:             }
 1419:         }
 1420:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1421:             $is_balancer = 0;
 1422:             if ($uname ne '' && $udom ne '') {
 1423:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1424:                     
 1425:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1426:                              'user.loadbalcheck.time' => time});
 1427:                 }
 1428:             }
 1429:         }
 1430:     }
 1431:     return ($is_balancer,$otherserver);
 1432: }
 1433: 
 1434: sub check_balancer_result {
 1435:     my ($result,@hosts) = @_;
 1436:     my ($is_balancer,$currtargets,$currrules);
 1437:     if (ref($result) eq 'HASH') {
 1438:         if ($result->{'lonhost'} ne '') {
 1439:             my $currbalancer = $result->{'lonhost'};
 1440:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1441:                 $is_balancer = 1;
 1442:                 $currtargets = $result->{'targets'};
 1443:                 $currrules = $result->{'rules'};
 1444:             }
 1445:         } else {
 1446:             foreach my $key (keys(%{$result})) {
 1447:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1448:                     (ref($result->{$key}) eq 'HASH')) {
 1449:                     $is_balancer = 1;
 1450:                     $currrules = $result->{$key}{'rules'};
 1451:                     $currtargets = $result->{$key}{'targets'};
 1452:                     last;
 1453:                 }
 1454:             }
 1455:         }
 1456:     }
 1457:     return ($is_balancer,$currtargets,$currrules);
 1458: }
 1459: 
 1460: sub get_loadbalancer_targets {
 1461:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1462:     my $offloadto;
 1463:     if ($rule_in_effect eq 'none') {
 1464:         return [$perlvar{'lonHostID'}];
 1465:     } elsif ($rule_in_effect eq '') {
 1466:         $offloadto = $currtargets;
 1467:     } else {
 1468:         if ($rule_in_effect eq 'homeserver') {
 1469:             my $homeserver = &homeserver($uname,$udom);
 1470:             if ($homeserver ne 'no_host') {
 1471:                 $offloadto = [$homeserver];
 1472:             }
 1473:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1474:             my %domconfig =
 1475:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1476:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1477:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1478:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1479:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1480:                     }
 1481:                 }
 1482:             } else {
 1483:                 my %servers = &internet_dom_servers($udom);
 1484:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1485:                 if (&hostname($remotebalancer) ne '') {
 1486:                     $offloadto = [$remotebalancer];
 1487:                 }
 1488:             }
 1489:         } elsif (&hostname($rule_in_effect) ne '') {
 1490:             $offloadto = [$rule_in_effect];
 1491:         }
 1492:     }
 1493:     return $offloadto;
 1494: }
 1495: 
 1496: sub internet_dom_servers {
 1497:     my ($dom) = @_;
 1498:     my (%uniqservers,%servers);
 1499:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1500:     my @machinedoms = &machine_domains($primaryserver);
 1501:     foreach my $mdom (@machinedoms) {
 1502:         my %currservers = %servers;
 1503:         my %server = &get_servers($mdom);
 1504:         %servers = (%currservers,%server);
 1505:     }
 1506:     my %by_hostname;
 1507:     foreach my $id (keys(%servers)) {
 1508:         push(@{$by_hostname{$servers{$id}}},$id);
 1509:     }
 1510:     foreach my $hostname (sort(keys(%by_hostname))) {
 1511:         if (@{$by_hostname{$hostname}} > 1) {
 1512:             my $match = 0;
 1513:             foreach my $id (@{$by_hostname{$hostname}}) {
 1514:                 if (&host_domain($id) eq $dom) {
 1515:                     $uniqservers{$id} = $hostname;
 1516:                     $match = 1;
 1517:                 }
 1518:             }
 1519:             unless ($match) {
 1520:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1521:             }
 1522:         } else {
 1523:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1524:         }
 1525:     }
 1526:     return %uniqservers;
 1527: }
 1528: 
 1529: # ---------------------- Find the homebase for a user from domain's lib servers
 1530: 
 1531: my %homecache;
 1532: sub homeserver {
 1533:     my ($uname,$udom,$ignoreBadCache)=@_;
 1534:     my $index="$uname:$udom";
 1535: 
 1536:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1537: 
 1538:     my %servers = &get_servers($udom,'library');
 1539:     foreach my $tryserver (keys(%servers)) {
 1540:         next if ($ignoreBadCache ne 'true' && 
 1541: 		 exists($badServerCache{$tryserver}));
 1542: 
 1543: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1544: 	if ($answer eq 'found') {
 1545: 	    delete($badServerCache{$tryserver}); 
 1546: 	    return $homecache{$index}=$tryserver;
 1547: 	} elsif ($answer eq 'no_host') {
 1548: 	    $badServerCache{$tryserver}=1;
 1549: 	}
 1550:     }    
 1551:     return 'no_host';
 1552: }
 1553: 
 1554: # ------------------------------------- Find the usernames behind a list of IDs
 1555: 
 1556: sub idget {
 1557:     my ($udom,@ids)=@_;
 1558:     my %returnhash=();
 1559:     
 1560:     my %servers = &get_servers($udom,'library');
 1561:     foreach my $tryserver (keys(%servers)) {
 1562: 	my $idlist=join('&',@ids);
 1563: 	$idlist=~tr/A-Z/a-z/; 
 1564: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1565: 	my @answer=();
 1566: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1567: 	    @answer=split(/\&/,$reply);
 1568: 	}                    ;
 1569: 	my $i;
 1570: 	for ($i=0;$i<=$#ids;$i++) {
 1571: 	    if ($answer[$i]) {
 1572: 		$returnhash{$ids[$i]}=$answer[$i];
 1573: 	    } 
 1574: 	}
 1575:     } 
 1576:     return %returnhash;
 1577: }
 1578: 
 1579: # ------------------------------------- Find the IDs behind a list of usernames
 1580: 
 1581: sub idrget {
 1582:     my ($udom,@unames)=@_;
 1583:     my %returnhash=();
 1584:     foreach my $uname (@unames) {
 1585:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1586:     }
 1587:     return %returnhash;
 1588: }
 1589: 
 1590: # ------------------------------- Store away a list of names and associated IDs
 1591: 
 1592: sub idput {
 1593:     my ($udom,%ids)=@_;
 1594:     my %servers=();
 1595:     foreach my $uname (keys(%ids)) {
 1596: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1597:         my $uhom=&homeserver($uname,$udom);
 1598:         if ($uhom ne 'no_host') {
 1599:             my $id=&escape($ids{$uname});
 1600:             $id=~tr/A-Z/a-z/;
 1601:             my $esc_unam=&escape($uname);
 1602: 	    if ($servers{$uhom}) {
 1603: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1604:             } else {
 1605:                 $servers{$uhom}=$id.'='.$esc_unam;
 1606:             }
 1607:         }
 1608:     }
 1609:     foreach my $server (keys(%servers)) {
 1610:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1611:     }
 1612: }
 1613: 
 1614: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1615: 
 1616: sub iddel {
 1617:     my ($udom,$idshashref,$uhome)=@_;
 1618:     my %result=();
 1619:     unless (ref($idshashref) eq 'HASH') {
 1620:         return %result;
 1621:     }
 1622:     my %servers=();
 1623:     while (my ($id,$uname) = each(%{$idshashref})) {
 1624:         my $uhom;
 1625:         if ($uhome) {
 1626:             $uhom = $uhome;
 1627:         } else {
 1628:             $uhom=&homeserver($uname,$udom);
 1629:         }
 1630:         if ($uhom ne 'no_host') {
 1631:             if ($servers{$uhom}) {
 1632:                 $servers{$uhom}.='&'.&escape($id);
 1633:             } else {
 1634:                 $servers{$uhom}=&escape($id);
 1635:             }
 1636:         }
 1637:     }
 1638:     foreach my $server (keys(%servers)) {
 1639:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1640:     }
 1641:     return %result;
 1642: }
 1643: 
 1644: # ------------------------------dump from db file owned by domainconfig user
 1645: sub dump_dom {
 1646:     my ($namespace, $udom, $regexp) = @_;
 1647: 
 1648:     $udom ||= $env{'user.domain'};
 1649: 
 1650:     return () unless $udom;
 1651: 
 1652:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1653: }
 1654: 
 1655: # ------------------------------------------ get items from domain db files   
 1656: 
 1657: sub get_dom {
 1658:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1659:     return if ($udom eq 'public');
 1660:     my $items='';
 1661:     foreach my $item (@$storearr) {
 1662:         $items.=&escape($item).'&';
 1663:     }
 1664:     $items=~s/\&$//;
 1665:     if (!$udom) {
 1666:         $udom=$env{'user.domain'};
 1667:         return if ($udom eq 'public');
 1668:         if (defined(&domain($udom,'primary'))) {
 1669:             $uhome=&domain($udom,'primary');
 1670:         } else {
 1671:             undef($uhome);
 1672:         }
 1673:     } else {
 1674:         if (!$uhome) {
 1675:             if (defined(&domain($udom,'primary'))) {
 1676:                 $uhome=&domain($udom,'primary');
 1677:             }
 1678:         }
 1679:     }
 1680:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1681:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1682:         my %returnhash;
 1683:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1684:             return %returnhash;
 1685:         }
 1686:         my @pairs=split(/\&/,$rep);
 1687:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1688:             return @pairs;
 1689:         }
 1690:         my $i=0;
 1691:         foreach my $item (@$storearr) {
 1692:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1693:             $i++;
 1694:         }
 1695:         return %returnhash;
 1696:     } else {
 1697:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1698:     }
 1699: }
 1700: 
 1701: # -------------------------------------------- put items in domain db files 
 1702: 
 1703: sub put_dom {
 1704:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1705:     if (!$udom) {
 1706:         $udom=$env{'user.domain'};
 1707:         if (defined(&domain($udom,'primary'))) {
 1708:             $uhome=&domain($udom,'primary');
 1709:         } else {
 1710:             undef($uhome);
 1711:         }
 1712:     } else {
 1713:         if (!$uhome) {
 1714:             if (defined(&domain($udom,'primary'))) {
 1715:                 $uhome=&domain($udom,'primary');
 1716:             }
 1717:         }
 1718:     } 
 1719:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1720:         my $items='';
 1721:         foreach my $item (keys(%$storehash)) {
 1722:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1723:         }
 1724:         $items=~s/\&$//;
 1725:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1726:     } else {
 1727:         &logthis("put_dom failed - no homeserver and/or domain");
 1728:     }
 1729: }
 1730: 
 1731: # --------------------- newput for items in db file owned by domainconfig user
 1732: sub newput_dom {
 1733:     my ($namespace,$storehash,$udom) = @_;
 1734:     my $result;
 1735:     if (!$udom) {
 1736:         $udom=$env{'user.domain'};
 1737:     }
 1738:     if ($udom) {
 1739:         my $uname = &get_domainconfiguser($udom);
 1740:         $result = &newput($namespace,$storehash,$udom,$uname);
 1741:     }
 1742:     return $result;
 1743: }
 1744: 
 1745: # --------------------- delete for items in db file owned by domainconfig user
 1746: sub del_dom {
 1747:     my ($namespace,$storearr,$udom)=@_;
 1748:     if (ref($storearr) eq 'ARRAY') {
 1749:         if (!$udom) {
 1750:             $udom=$env{'user.domain'};
 1751:         }
 1752:         if ($udom) {
 1753:             my $uname = &get_domainconfiguser($udom); 
 1754:             return &del($namespace,$storearr,$udom,$uname);
 1755:         }
 1756:     }
 1757: }
 1758: 
 1759: # ----------------------------------construct domainconfig user for a domain 
 1760: sub get_domainconfiguser {
 1761:     my ($udom) = @_;
 1762:     return $udom.'-domainconfig';
 1763: }
 1764: 
 1765: sub retrieve_inst_usertypes {
 1766:     my ($udom) = @_;
 1767:     my (%returnhash,@order);
 1768:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1769:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1770:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1771:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1772:     } else {
 1773:         if (defined(&domain($udom,'primary'))) {
 1774:             my $uhome=&domain($udom,'primary');
 1775:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1776:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1777:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1778:                 return (\%returnhash,\@order);
 1779:             }
 1780:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1781:             my @pairs=split(/\&/,$hashitems);
 1782:             foreach my $item (@pairs) {
 1783:                 my ($key,$value)=split(/=/,$item,2);
 1784:                 $key = &unescape($key);
 1785:                 next if ($key =~ /^error: 2 /);
 1786:                 $returnhash{$key}=&thaw_unescape($value);
 1787:             }
 1788:             my @esc_order = split(/\&/,$orderitems);
 1789:             foreach my $item (@esc_order) {
 1790:                 push(@order,&unescape($item));
 1791:             }
 1792:         } else {
 1793:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 1794:         }
 1795:         return (\%returnhash,\@order);
 1796:     }
 1797: }
 1798: 
 1799: sub is_domainimage {
 1800:     my ($url) = @_;
 1801:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1802:         if (&domain($1) ne '') {
 1803:             return '1';
 1804:         }
 1805:     }
 1806:     return;
 1807: }
 1808: 
 1809: sub inst_directory_query {
 1810:     my ($srch) = @_;
 1811:     my $udom = $srch->{'srchdomain'};
 1812:     my %results;
 1813:     my $homeserver = &domain($udom,'primary');
 1814:     my $outcome;
 1815:     if ($homeserver ne '') {
 1816: 	my $queryid=&reply("querysend:instdirsearch:".
 1817: 			   &escape($srch->{'srchby'}).':'.
 1818: 			   &escape($srch->{'srchterm'}).':'.
 1819: 			   &escape($srch->{'srchtype'}),$homeserver);
 1820: 	my $host=&hostname($homeserver);
 1821: 	if ($queryid !~/^\Q$host\E\_/) {
 1822: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1823: 	    return;
 1824: 	}
 1825: 	my $response = &get_query_reply($queryid);
 1826: 	my $maxtries = 5;
 1827: 	my $tries = 1;
 1828: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1829: 	    $response = &get_query_reply($queryid);
 1830: 	    $tries ++;
 1831: 	}
 1832: 
 1833:         if (!&error($response) && $response ne 'refused') {
 1834:             if ($response eq 'unavailable') {
 1835:                 $outcome = $response;
 1836:             } else {
 1837:                 $outcome = 'ok';
 1838:                 my @matches = split(/\n/,$response);
 1839:                 foreach my $match (@matches) {
 1840:                     my ($key,$value) = split(/=/,$match);
 1841:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1842:                 }
 1843:             }
 1844:         }
 1845:     }
 1846:     return ($outcome,%results);
 1847: }
 1848: 
 1849: sub usersearch {
 1850:     my ($srch) = @_;
 1851:     my $dom = $srch->{'srchdomain'};
 1852:     my %results;
 1853:     my %libserv = &all_library();
 1854:     my $query = 'usersearch';
 1855:     foreach my $tryserver (keys(%libserv)) {
 1856:         if (&host_domain($tryserver) eq $dom) {
 1857:             my $host=&hostname($tryserver);
 1858:             my $queryid=
 1859:                 &reply("querysend:".&escape($query).':'.
 1860:                        &escape($srch->{'srchby'}).':'.
 1861:                        &escape($srch->{'srchtype'}).':'.
 1862:                        &escape($srch->{'srchterm'}),$tryserver);
 1863:             if ($queryid !~/^\Q$host\E\_/) {
 1864:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1865:                 next;
 1866:             }
 1867:             my $reply = &get_query_reply($queryid);
 1868:             my $maxtries = 1;
 1869:             my $tries = 1;
 1870:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1871:                 $reply = &get_query_reply($queryid);
 1872:                 $tries ++;
 1873:             }
 1874:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1875:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1876:             } else {
 1877:                 my @matches;
 1878:                 if ($reply =~ /\n/) {
 1879:                     @matches = split(/\n/,$reply);
 1880:                 } else {
 1881:                     @matches = split(/\&/,$reply);
 1882:                 }
 1883:                 foreach my $match (@matches) {
 1884:                     my ($uname,$udom,%userhash);
 1885:                     foreach my $entry (split(/:/,$match)) {
 1886:                         my ($key,$value) =
 1887:                             map {&unescape($_);} split(/=/,$entry);
 1888:                         $userhash{$key} = $value;
 1889:                         if ($key eq 'username') {
 1890:                             $uname = $value;
 1891:                         } elsif ($key eq 'domain') {
 1892:                             $udom = $value;
 1893:                         }
 1894:                     }
 1895:                     $results{$uname.':'.$udom} = \%userhash;
 1896:                 }
 1897:             }
 1898:         }
 1899:     }
 1900:     return %results;
 1901: }
 1902: 
 1903: sub get_instuser {
 1904:     my ($udom,$uname,$id) = @_;
 1905:     my $homeserver = &domain($udom,'primary');
 1906:     my ($outcome,%results);
 1907:     if ($homeserver ne '') {
 1908:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1909:                            &escape($id).':'.&escape($udom),$homeserver);
 1910:         my $host=&hostname($homeserver);
 1911:         if ($queryid !~/^\Q$host\E\_/) {
 1912:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1913:             return;
 1914:         }
 1915:         my $response = &get_query_reply($queryid);
 1916:         my $maxtries = 5;
 1917:         my $tries = 1;
 1918:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1919:             $response = &get_query_reply($queryid);
 1920:             $tries ++;
 1921:         }
 1922:         if (!&error($response) && $response ne 'refused') {
 1923:             if ($response eq 'unavailable') {
 1924:                 $outcome = $response;
 1925:             } else {
 1926:                 $outcome = 'ok';
 1927:                 my @matches = split(/\n/,$response);
 1928:                 foreach my $match (@matches) {
 1929:                     my ($key,$value) = split(/=/,$match);
 1930:                     $results{&unescape($key)} = &thaw_unescape($value);
 1931:                 }
 1932:             }
 1933:         }
 1934:     }
 1935:     my %userinfo;
 1936:     if (ref($results{$uname}) eq 'HASH') {
 1937:         %userinfo = %{$results{$uname}};
 1938:     } 
 1939:     return ($outcome,%userinfo);
 1940: }
 1941: 
 1942: sub inst_rulecheck {
 1943:     my ($udom,$uname,$id,$item,$rules) = @_;
 1944:     my %returnhash;
 1945:     if ($udom ne '') {
 1946:         if (ref($rules) eq 'ARRAY') {
 1947:             @{$rules} = map {&escape($_);} (@{$rules});
 1948:             my $rulestr = join(':',@{$rules});
 1949:             my $homeserver=&domain($udom,'primary');
 1950:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1951:                 my $response;
 1952:                 if ($item eq 'username') {                
 1953:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1954:                                               ':'.&escape($uname).':'.$rulestr,
 1955:                                               $homeserver));
 1956:                 } elsif ($item eq 'id') {
 1957:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1958:                                               ':'.&escape($id).':'.$rulestr,
 1959:                                               $homeserver));
 1960:                 } elsif ($item eq 'selfcreate') {
 1961:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1962:                                                &escape($udom).':'.&escape($uname).
 1963:                                               ':'.$rulestr,$homeserver));
 1964:                 }
 1965:                 if ($response ne 'refused') {
 1966:                     my @pairs=split(/\&/,$response);
 1967:                     foreach my $item (@pairs) {
 1968:                         my ($key,$value)=split(/=/,$item,2);
 1969:                         $key = &unescape($key);
 1970:                         next if ($key =~ /^error: 2 /);
 1971:                         $returnhash{$key}=&thaw_unescape($value);
 1972:                     }
 1973:                 }
 1974:             }
 1975:         }
 1976:     }
 1977:     return %returnhash;
 1978: }
 1979: 
 1980: sub inst_userrules {
 1981:     my ($udom,$check) = @_;
 1982:     my (%ruleshash,@ruleorder);
 1983:     if ($udom ne '') {
 1984:         my $homeserver=&domain($udom,'primary');
 1985:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1986:             my $response;
 1987:             if ($check eq 'id') {
 1988:                 $response=&reply('instidrules:'.&escape($udom),
 1989:                                  $homeserver);
 1990:             } elsif ($check eq 'email') {
 1991:                 $response=&reply('instemailrules:'.&escape($udom),
 1992:                                  $homeserver);
 1993:             } else {
 1994:                 $response=&reply('instuserrules:'.&escape($udom),
 1995:                                  $homeserver);
 1996:             }
 1997:             if (($response ne 'refused') && ($response ne 'error') && 
 1998:                 ($response ne 'unknown_cmd') && 
 1999:                 ($response ne 'no_such_host')) {
 2000:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2001:                 my @pairs=split(/\&/,$hashitems);
 2002:                 foreach my $item (@pairs) {
 2003:                     my ($key,$value)=split(/=/,$item,2);
 2004:                     $key = &unescape($key);
 2005:                     next if ($key =~ /^error: 2 /);
 2006:                     $ruleshash{$key}=&thaw_unescape($value);
 2007:                 }
 2008:                 my @esc_order = split(/\&/,$orderitems);
 2009:                 foreach my $item (@esc_order) {
 2010:                     push(@ruleorder,&unescape($item));
 2011:                 }
 2012:             }
 2013:         }
 2014:     }
 2015:     return (\%ruleshash,\@ruleorder);
 2016: }
 2017: 
 2018: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2019: 
 2020: sub get_domain_defaults {
 2021:     my ($domain,$ignore_cache) = @_;
 2022:     return if (($domain eq '') || ($domain eq 'public'));
 2023:     my $cachetime = 60*60*24;
 2024:     unless ($ignore_cache) {
 2025:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2026:         if (defined($cached)) {
 2027:             if (ref($result) eq 'HASH') {
 2028:                 return %{$result};
 2029:             }
 2030:         }
 2031:     }
 2032:     my %domdefaults;
 2033:     my %domconfig =
 2034:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2035:                                   'requestcourses','inststatus',
 2036:                                   'coursedefaults','usersessions',
 2037:                                   'requestauthor','selfenrollment',
 2038:                                   'coursecategories'],$domain);
 2039:     my @coursetypes = ('official','unofficial','community','textbook');
 2040:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2041:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2042:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2043:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2044:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2045:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2046:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2047:     } else {
 2048:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2049:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2050:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2051:     }
 2052:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2053:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2054:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2055:         } else {
 2056:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2057:         }
 2058:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2059:         foreach my $item (@usertools) {
 2060:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2061:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2062:             }
 2063:         }
 2064:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2065:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2066:         }
 2067:     }
 2068:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2069:         foreach my $item ('official','unofficial','community','textbook') {
 2070:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2071:         }
 2072:     }
 2073:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2074:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2075:     }
 2076:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2077:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2078:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2079:         }
 2080:     }
 2081:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2082:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2083:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2084:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2085:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2086:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2087:         }
 2088:         foreach my $type (@coursetypes) {
 2089:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2090:                 unless ($type eq 'community') {
 2091:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2092:                 }
 2093:             }
 2094:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2095:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2096:             }
 2097:             if ($domdefaults{'postsubmit'} eq 'on') {
 2098:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2099:                     $domdefaults{$type.'postsubtimeout'} = 
 2100:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2101:                 }
 2102:             }
 2103:         }
 2104:     }
 2105:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2106:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2107:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2108:         }
 2109:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2110:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2111:         }
 2112:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2113:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2114:         }
 2115:     }
 2116:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2117:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2118:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2119:                             'approval','limit');
 2120:             foreach my $type (@coursetypes) {
 2121:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2122:                     my @mgrdc = ();
 2123:                     foreach my $item (@settings) {
 2124:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2125:                             push(@mgrdc,$item);
 2126:                         }
 2127:                     }
 2128:                     if (@mgrdc) {
 2129:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2130:                     }
 2131:                 }
 2132:             }
 2133:         }
 2134:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2135:             foreach my $type (@coursetypes) {
 2136:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2137:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2138:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2139:                     }
 2140:                 }
 2141:             }
 2142:         }
 2143:     }
 2144:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2145:         $domdefaults{'catauth'} = 'std';
 2146:         $domdefaults{'catunauth'} = 'std';
 2147:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2148:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2149:         }
 2150:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2151:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2152:         }
 2153:     }
 2154:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2155:     return %domdefaults;
 2156: }
 2157: 
 2158: # --------------------------------------------------- Assign a key to a student
 2159: 
 2160: sub assign_access_key {
 2161: #
 2162: # a valid key looks like uname:udom#comments
 2163: # comments are being appended
 2164: #
 2165:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2166:     $kdom=
 2167:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2168:     $knum=
 2169:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2170:     $cdom=
 2171:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2172:     $cnum=
 2173:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2174:     $udom=$env{'user.name'} unless (defined($udom));
 2175:     $uname=$env{'user.domain'} unless (defined($uname));
 2176:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2177:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2178:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2179:                                                   # assigned to this person
 2180:                                                   # - this should not happen,
 2181:                                                   # unless something went wrong
 2182:                                                   # the first time around
 2183: # ready to assign
 2184:         $logentry=$1.'; '.$logentry;
 2185:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2186:                                                  $kdom,$knum) eq 'ok') {
 2187: # key now belongs to user
 2188: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2189:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2190:                 &appenv({'environment.'.$envkey => $ckey});
 2191:                 return 'ok';
 2192:             } else {
 2193:                 return 
 2194:   'error: Count not permanently assign key, will need to be re-entered later.';
 2195: 	    }
 2196:         } else {
 2197:             return 'error: Could not assign key, try again later.';
 2198:         }
 2199:     } elsif (!$existing{$ckey}) {
 2200: # the key does not exist
 2201: 	return 'error: The key does not exist';
 2202:     } else {
 2203: # the key is somebody else's
 2204: 	return 'error: The key is already in use';
 2205:     }
 2206: }
 2207: 
 2208: # ------------------------------------------ put an additional comment on a key
 2209: 
 2210: sub comment_access_key {
 2211: #
 2212: # a valid key looks like uname:udom#comments
 2213: # comments are being appended
 2214: #
 2215:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2216:     $cdom=
 2217:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2218:     $cnum=
 2219:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2220:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2221:     if ($existing{$ckey}) {
 2222:         $existing{$ckey}.='; '.$logentry;
 2223: # ready to assign
 2224:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2225:                                                  $cdom,$cnum) eq 'ok') {
 2226: 	    return 'ok';
 2227:         } else {
 2228: 	    return 'error: Count not store comment.';
 2229:         }
 2230:     } else {
 2231: # the key does not exist
 2232: 	return 'error: The key does not exist';
 2233:     }
 2234: }
 2235: 
 2236: # ------------------------------------------------------ Generate a set of keys
 2237: 
 2238: sub generate_access_keys {
 2239:     my ($number,$cdom,$cnum,$logentry)=@_;
 2240:     $cdom=
 2241:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2242:     $cnum=
 2243:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2244:     unless (&allowed('mky',$cdom)) { return 0; }
 2245:     unless (($cdom) && ($cnum)) { return 0; }
 2246:     if ($number>10000) { return 0; }
 2247:     sleep(2); # make sure don't get same seed twice
 2248:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2249:     my $total=0;
 2250:     for (my $i=1;$i<=$number;$i++) {
 2251:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2252:                   sprintf("%lx",int(100000*rand)).'-'.
 2253:                   sprintf("%lx",int(100000*rand));
 2254:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2255:        $newkey=~s/0/h/g; # and also 0 and O
 2256:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2257:        if ($existing{$newkey}) {
 2258:            $i--;
 2259:        } else {
 2260: 	  if (&put('accesskeys',
 2261:               { $newkey => '# generated '.localtime().
 2262:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2263:                            '; '.$logentry },
 2264: 		   $cdom,$cnum) eq 'ok') {
 2265:               $total++;
 2266: 	  }
 2267:        }
 2268:     }
 2269:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2270:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2271:     return $total;
 2272: }
 2273: 
 2274: # ------------------------------------------------------- Validate an accesskey
 2275: 
 2276: sub validate_access_key {
 2277:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2278:     $cdom=
 2279:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2280:     $cnum=
 2281:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2282:     $udom=$env{'user.domain'} unless (defined($udom));
 2283:     $uname=$env{'user.name'} unless (defined($uname));
 2284:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2285:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2286: }
 2287: 
 2288: # ------------------------------------- Find the section of student in a course
 2289: sub devalidate_getsection_cache {
 2290:     my ($udom,$unam,$courseid)=@_;
 2291:     my $hashid="$udom:$unam:$courseid";
 2292:     &devalidate_cache_new('getsection',$hashid);
 2293: }
 2294: 
 2295: sub courseid_to_courseurl {
 2296:     my ($courseid) = @_;
 2297:     #already url style courseid
 2298:     return $courseid if ($courseid =~ m{^/});
 2299: 
 2300:     if (exists($env{'course.'.$courseid.'.num'})) {
 2301: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2302: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2303: 	return "/$cdom/$cnum";
 2304:     }
 2305: 
 2306:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2307:     if (exists($courseinfo{'num'})) {
 2308: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2309:     }
 2310: 
 2311:     return undef;
 2312: }
 2313: 
 2314: sub getsection {
 2315:     my ($udom,$unam,$courseid)=@_;
 2316:     my $cachetime=1800;
 2317: 
 2318:     my $hashid="$udom:$unam:$courseid";
 2319:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2320:     if (defined($cached)) { return $result; }
 2321: 
 2322:     my %Pending; 
 2323:     my %Expired;
 2324:     #
 2325:     # Each role can either have not started yet (pending), be active, 
 2326:     #    or have expired.
 2327:     #
 2328:     # If there is an active role, we are done.
 2329:     #
 2330:     # If there is more than one role which has not started yet, 
 2331:     #     choose the one which will start sooner
 2332:     # If there is one role which has not started yet, return it.
 2333:     #
 2334:     # If there is more than one expired role, choose the one which ended last.
 2335:     # If there is a role which has expired, return it.
 2336:     #
 2337:     $courseid = &courseid_to_courseurl($courseid);
 2338:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2339:     foreach my $key (keys(%roleshash)) {
 2340:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2341:         my $section=$1;
 2342:         if ($key eq $courseid.'_st') { $section=''; }
 2343:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2344:         my $now=time;
 2345:         if (defined($end) && $end && ($now > $end)) {
 2346:             $Expired{$end}=$section;
 2347:             next;
 2348:         }
 2349:         if (defined($start) && $start && ($now < $start)) {
 2350:             $Pending{$start}=$section;
 2351:             next;
 2352:         }
 2353:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2354:     }
 2355:     #
 2356:     # Presumedly there will be few matching roles from the above
 2357:     # loop and the sorting time will be negligible.
 2358:     if (scalar(keys(%Pending))) {
 2359:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2360:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2361:     } 
 2362:     if (scalar(keys(%Expired))) {
 2363:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2364:         my $time = pop(@sorted);
 2365:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2366:     }
 2367:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2368: }
 2369: 
 2370: sub save_cache {
 2371:     &purge_remembered();
 2372:     #&Apache::loncommon::validate_page();
 2373:     undef(%env);
 2374:     undef($env_loaded);
 2375: }
 2376: 
 2377: my $to_remember=-1;
 2378: my %remembered;
 2379: my %accessed;
 2380: my $kicks=0;
 2381: my $hits=0;
 2382: sub make_key {
 2383:     my ($name,$id) = @_;
 2384:     if (length($id) > 65 
 2385: 	&& length(&escape($id)) > 200) {
 2386: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2387:     }
 2388:     return &escape($name.':'.$id);
 2389: }
 2390: 
 2391: sub devalidate_cache_new {
 2392:     my ($name,$id,$debug) = @_;
 2393:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2394:     $id=&make_key($name,$id);
 2395:     $memcache->delete($id);
 2396:     delete($remembered{$id});
 2397:     delete($accessed{$id});
 2398: }
 2399: 
 2400: sub is_cached_new {
 2401:     my ($name,$id,$debug) = @_;
 2402:     $id=&make_key($name,$id);
 2403:     if (exists($remembered{$id})) {
 2404: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2405: 	$accessed{$id}=[&gettimeofday()];
 2406: 	$hits++;
 2407: 	return ($remembered{$id},1);
 2408:     }
 2409:     my $value = $memcache->get($id);
 2410:     if (!(defined($value))) {
 2411: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2412: 	return (undef,undef);
 2413:     }
 2414:     if ($value eq '__undef__') {
 2415: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2416: 	$value=undef;
 2417:     }
 2418:     &make_room($id,$value,$debug);
 2419:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2420:     return ($value,1);
 2421: }
 2422: 
 2423: sub do_cache_new {
 2424:     my ($name,$id,$value,$time,$debug) = @_;
 2425:     $id=&make_key($name,$id);
 2426:     my $setvalue=$value;
 2427:     if (!defined($setvalue)) {
 2428: 	$setvalue='__undef__';
 2429:     }
 2430:     if (!defined($time) ) {
 2431: 	$time=600;
 2432:     }
 2433:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2434:     my $result = $memcache->set($id,$setvalue,$time);
 2435:     if (! $result) {
 2436: 	&logthis("caching of id -> $id  failed");
 2437: 	$memcache->disconnect_all();
 2438:     }
 2439:     # need to make a copy of $value
 2440:     &make_room($id,$value,$debug);
 2441:     return $value;
 2442: }
 2443: 
 2444: sub make_room {
 2445:     my ($id,$value,$debug)=@_;
 2446: 
 2447:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2448:                                     : $value;
 2449:     if ($to_remember<0) { return; }
 2450:     $accessed{$id}=[&gettimeofday()];
 2451:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2452:     my $to_kick;
 2453:     my $max_time=0;
 2454:     foreach my $other (keys(%accessed)) {
 2455: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2456: 	    $to_kick=$other;
 2457: 	    $max_time=&tv_interval($accessed{$other});
 2458: 	}
 2459:     }
 2460:     delete($remembered{$to_kick});
 2461:     delete($accessed{$to_kick});
 2462:     $kicks++;
 2463:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2464:     return;
 2465: }
 2466: 
 2467: sub purge_remembered {
 2468:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2469:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2470:     undef(%remembered);
 2471:     undef(%accessed);
 2472: }
 2473: # ------------------------------------- Read an entry from a user's environment
 2474: 
 2475: sub userenvironment {
 2476:     my ($udom,$unam,@what)=@_;
 2477:     my $items;
 2478:     foreach my $item (@what) {
 2479:         $items.=&escape($item).'&';
 2480:     }
 2481:     $items=~s/\&$//;
 2482:     my %returnhash=();
 2483:     my $uhome = &homeserver($unam,$udom);
 2484:     unless ($uhome eq 'no_host') {
 2485:         my @answer=split(/\&/, 
 2486:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2487:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2488:             return %returnhash;
 2489:         }
 2490:         my $i;
 2491:         for ($i=0;$i<=$#what;$i++) {
 2492: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2493:         }
 2494:     }
 2495:     return %returnhash;
 2496: }
 2497: 
 2498: # ---------------------------------------------------------- Get a studentphoto
 2499: sub studentphoto {
 2500:     my ($udom,$unam,$ext) = @_;
 2501:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2502:     if (defined($env{'request.course.id'})) {
 2503:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2504:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2505:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2506:             } else {
 2507:                 my ($result,$perm_reqd)=
 2508: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2509:                 if ($result eq 'ok') {
 2510:                     if (!($perm_reqd eq 'yes')) {
 2511:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2512:                     }
 2513:                 }
 2514:             }
 2515:         }
 2516:     } else {
 2517:         my ($result,$perm_reqd) = 
 2518: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2519:         if ($result eq 'ok') {
 2520:             if (!($perm_reqd eq 'yes')) {
 2521:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2522:             }
 2523:         }
 2524:     }
 2525:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2526: }
 2527: 
 2528: sub retrievestudentphoto {
 2529:     my ($udom,$unam,$ext,$type) = @_;
 2530:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2531:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2532:     if ($ret eq 'ok') {
 2533:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2534:         if ($type eq 'thumbnail') {
 2535:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2536:         }
 2537:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2538:         return $tokenurl;
 2539:     } else {
 2540:         if ($type eq 'thumbnail') {
 2541:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2542:         } else { 
 2543:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2544:         }
 2545:     }
 2546: }
 2547: 
 2548: # -------------------------------------------------------------------- New chat
 2549: 
 2550: sub chatsend {
 2551:     my ($newentry,$anon,$group)=@_;
 2552:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2553:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2554:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2555:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2556: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2557: 		   &escape($newentry)).':'.$group,$chome);
 2558: }
 2559: 
 2560: # ------------------------------------------ Find current version of a resource
 2561: 
 2562: sub getversion {
 2563:     my $fname=&clutter(shift);
 2564:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2565:     return &currentversion(&filelocation('',$fname));
 2566: }
 2567: 
 2568: sub currentversion {
 2569:     my $fname=shift;
 2570:     my $author=$fname;
 2571:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2572:     my ($udom,$uname)=split(/\//,$author);
 2573:     my $home=&homeserver($uname,$udom);
 2574:     if ($home eq 'no_host') { 
 2575:         return -1; 
 2576:     }
 2577:     my $answer=&reply("currentversion:$fname",$home);
 2578:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2579: 	return -1;
 2580:     }
 2581:     return $answer;
 2582: }
 2583: 
 2584: #
 2585: # Return special version number of resource if set by override, empty otherwise
 2586: #
 2587: sub usedversion {
 2588:     my $fname=shift;
 2589:     unless ($fname) { $fname=$env{'request.uri'}; }
 2590:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2591:     if ($urlversion) { return $urlversion; }
 2592:     return '';
 2593: }
 2594: 
 2595: # ----------------------------- Subscribe to a resource, return URL if possible
 2596: 
 2597: sub subscribe {
 2598:     my $fname=shift;
 2599:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2600:     $fname=~s/[\n\r]//g;
 2601:     my $author=$fname;
 2602:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2603:     my ($udom,$uname)=split(/\//,$author);
 2604:     my $home=homeserver($uname,$udom);
 2605:     if ($home eq 'no_host') {
 2606:         return 'not_found';
 2607:     }
 2608:     my $answer=reply("sub:$fname",$home);
 2609:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2610: 	$answer.=' by '.$home;
 2611:     }
 2612:     return $answer;
 2613: }
 2614:     
 2615: # -------------------------------------------------------------- Replicate file
 2616: 
 2617: sub repcopy {
 2618:     my $filename=shift;
 2619:     $filename=~s/\/+/\//g;
 2620:     my $londocroot = $perlvar{'lonDocRoot'};
 2621:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2622:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2623:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2624: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2625: 	return &repcopy_userfile($filename);
 2626:     }
 2627:     $filename=~s/[\n\r]//g;
 2628:     my $transname="$filename.in.transfer";
 2629: # FIXME: this should flock
 2630:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2631:     my $remoteurl=subscribe($filename);
 2632:     if ($remoteurl =~ /^con_lost by/) {
 2633: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2634:            return 'unavailable';
 2635:     } elsif ($remoteurl eq 'not_found') {
 2636: 	   #&logthis("Subscribe returned not_found: $filename");
 2637: 	   return 'not_found';
 2638:     } elsif ($remoteurl =~ /^rejected by/) {
 2639: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2640:            return 'forbidden';
 2641:     } elsif ($remoteurl eq 'directory') {
 2642:            return 'ok';
 2643:     } else {
 2644:         my $author=$filename;
 2645:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2646:         my ($udom,$uname)=split(/\//,$author);
 2647:         my $home=homeserver($uname,$udom);
 2648:         unless ($home eq $perlvar{'lonHostID'}) {
 2649:            my @parts=split(/\//,$filename);
 2650:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2651:            if ($path ne "$londocroot/res") {
 2652:                &logthis("Malconfiguration for replication: $filename");
 2653: 	       return 'bad_request';
 2654:            }
 2655:            my $count;
 2656:            for ($count=5;$count<$#parts;$count++) {
 2657:                $path.="/$parts[$count]";
 2658:                if ((-e $path)!=1) {
 2659: 		   mkdir($path,0777);
 2660:                }
 2661:            }
 2662:            my $ua=new LWP::UserAgent;
 2663:            my $request=new HTTP::Request('GET',"$remoteurl");
 2664:            my $response=$ua->request($request,$transname);
 2665:            if ($response->is_error()) {
 2666: 	       unlink($transname);
 2667:                my $message=$response->status_line;
 2668:                &logthis("<font color=\"blue\">WARNING:"
 2669:                        ." LWP get: $message: $filename</font>");
 2670:                return 'unavailable';
 2671:            } else {
 2672: 	       if ($remoteurl!~/\.meta$/) {
 2673:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2674:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2675:                   if ($mresponse->is_error()) {
 2676: 		      unlink($filename.'.meta');
 2677:                       &logthis(
 2678:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2679:                   }
 2680: 	       }
 2681:                rename($transname,$filename);
 2682:                return 'ok';
 2683:            }
 2684:        }
 2685:     }
 2686: }
 2687: 
 2688: # ------------------------------------------------ Get server side include body
 2689: sub ssi_body {
 2690:     my ($filelink,%form)=@_;
 2691:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2692:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2693:     }
 2694:     my $output='';
 2695:     my $response;
 2696:     if ($filelink=~/^https?\:/) {
 2697:        ($output,$response)=&externalssi($filelink);
 2698:     } else {
 2699:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2700:        $filelink .= 'inhibitmenu=yes';
 2701:        ($output,$response)=&ssi($filelink,%form);
 2702:     }
 2703:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2704:     $output=~s/^.*?\<body[^\>]*\>//si;
 2705:     $output=~s/\<\/body\s*\>.*?$//si;
 2706:     if (wantarray) {
 2707:         return ($output, $response);
 2708:     } else {
 2709:         return $output;
 2710:     }
 2711: }
 2712: 
 2713: # --------------------------------------------------------- Server Side Include
 2714: 
 2715: sub absolute_url {
 2716:     my ($host_name) = @_;
 2717:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2718:     if ($host_name eq '') {
 2719: 	$host_name = $ENV{'SERVER_NAME'};
 2720:     }
 2721:     return $protocol.$host_name;
 2722: }
 2723: 
 2724: #
 2725: #   Server side include.
 2726: # Parameters:
 2727: #  fn     Possibly encrypted resource name/id.
 2728: #  form   Hash that describes how the rendering should be done
 2729: #         and other things.
 2730: # Returns:
 2731: #   Scalar context: The content of the response.
 2732: #   Array context:  2 element list of the content and the full response object.
 2733: #     
 2734: sub ssi {
 2735: 
 2736:     my ($fn,%form)=@_;
 2737:     my $ua=new LWP::UserAgent;
 2738:     my $request;
 2739: 
 2740:     $form{'no_update_last_known'}=1;
 2741:     &Apache::lonenc::check_encrypt(\$fn);
 2742:     if (%form) {
 2743:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2744:       $request->content(join('&',map { 
 2745:             my $name = escape($_);
 2746:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 2747:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 2748:             : &escape($form{$_}) );    
 2749:         } keys(%form)));
 2750:     } else {
 2751:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2752:     }
 2753: 
 2754:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2755:     my $response= $ua->request($request);
 2756:     my $content = $response->content;
 2757: 
 2758: 
 2759:     if (wantarray) {
 2760: 	return ($content, $response);
 2761:     } else {
 2762: 	return $content;
 2763:     }
 2764: }
 2765: 
 2766: sub externalssi {
 2767:     my ($url)=@_;
 2768:     my $ua=new LWP::UserAgent;
 2769:     my $request=new HTTP::Request('GET',$url);
 2770:     my $response=$ua->request($request);
 2771:     if (wantarray) {
 2772:         return ($response->content, $response);
 2773:     } else {
 2774:         return $response->content;
 2775:     }
 2776: }
 2777: 
 2778: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2779: 
 2780: sub allowuploaded {
 2781:     my ($srcurl,$url)=@_;
 2782:     $url=&clutter(&declutter($url));
 2783:     my $dir=$url;
 2784:     $dir=~s/\/[^\/]+$//;
 2785:     my %httpref=();
 2786:     my $httpurl=&hreflocation('',$url);
 2787:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2788:     &Apache::lonnet::appenv(\%httpref);
 2789: }
 2790: 
 2791: #
 2792: # Determine if the current user should be able to edit a particular resource,
 2793: # when viewing in course context.
 2794: # (a) When viewing resource used to determine if "Edit" item is included in 
 2795: #     Functions.
 2796: # (b) When displaying folder contents in course editor, used to determine if
 2797: #     "Edit" link will be displayed alongside resource.
 2798: #
 2799: #  input: six args -- filename (decluttered), course number, course domain,
 2800: #                   url, symb (if registered) and group (if this is a group
 2801: #                   item -- e.g., bulletin board, group page etc.).
 2802: #  output: array of five scalars -- 
 2803: #          $cfile -- url for file editing if editable on current server
 2804: #          $home -- homeserver of resource (i.e., for author if published,
 2805: #                                           or course if uploaded.).
 2806: #          $switchserver --  1 if server switch will be needed.
 2807: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2808: #          $forceview -- 1 if icon/link should be to go to view mode
 2809: #
 2810: 
 2811: sub can_edit_resource {
 2812:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2813:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2814: #
 2815: # For aboutme pages user can only edit his/her own.
 2816: #
 2817:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2818:         my ($sdom,$sname) = ($1,$2);
 2819:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2820:             $home = $env{'user.home'};
 2821:             $cfile = $resurl;
 2822:             if ($env{'form.forceedit'}) {
 2823:                 $forceview = 1;
 2824:             } else {
 2825:                 $forceedit = 1;
 2826:             }
 2827:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2828:         } else {
 2829:             return;
 2830:         }
 2831:     }
 2832: 
 2833:     if ($env{'request.course.id'}) {
 2834:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2835:         if ($group ne '') {
 2836: # if this is a group homepage or group bulletin board, check group privs
 2837:             my $allowed = 0;
 2838:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2839:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2840:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2841:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2842:                     $allowed = 1;
 2843:                 }
 2844:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2845:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2846:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2847:                     $allowed = 1;
 2848:                 }
 2849:             }
 2850:             if ($allowed) {
 2851:                 $home=&homeserver($cnum,$cdom);
 2852:                 if ($env{'form.forceedit'}) {
 2853:                     $forceview = 1;
 2854:                 } else {
 2855:                     $forceedit = 1;
 2856:                 }
 2857:                 $cfile = $resurl;
 2858:             } else {
 2859:                 return;
 2860:             }
 2861:         } else {
 2862:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2863:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2864:                     return;
 2865:                 }
 2866:             } elsif (!$crsedit) {
 2867: #
 2868: # No edit allowed where CC has switched to student role.
 2869: #
 2870:                 return;
 2871:             }
 2872:         }
 2873:     }
 2874: 
 2875:     if ($file ne '') {
 2876:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2877:             if (&is_course_upload($file,$cnum,$cdom)) {
 2878:                 $uploaded = 1;
 2879:                 $incourse = 1;
 2880:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2881:                     $cfile = &hreflocation('',$file);
 2882:                     if ($env{'form.forceedit'}) {
 2883:                         $forceview = 1;
 2884:                     } else {
 2885:                         $forceedit = 1;
 2886:                     }
 2887:                 }
 2888:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2889:                 $incourse = 1;
 2890:                 if ($env{'form.forceedit'}) {
 2891:                     $forceview = 1;
 2892:                 } else {
 2893:                     $forceedit = 1;
 2894:                 }
 2895:                 $cfile = $resurl;
 2896:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2897:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2898:                     $incourse = 1;
 2899:                     if ($env{'form.forceedit'}) {
 2900:                         $forceview = 1;
 2901:                     } else {
 2902:                         $forceedit = 1;
 2903:                     }
 2904:                     $cfile = $resurl;
 2905:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2906:                     $incourse = 1;
 2907:                     $cfile = $resurl.'/smpedit';
 2908:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2909:                     $incourse = 1;
 2910:                     if ($env{'form.forceedit'}) {
 2911:                         $forceview = 1;
 2912:                     } else {
 2913:                         $forceedit = 1;
 2914:                     }
 2915:                     $cfile = $resurl;
 2916:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2917:                     $incourse = 1;
 2918:                     if ($env{'form.forceedit'}) {
 2919:                         $forceview = 1;
 2920:                     } else {
 2921:                         $forceedit = 1;
 2922:                     }
 2923:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2924:                 }
 2925:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2926:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2927:                 if (&is_on_map($template)) { 
 2928:                     $incourse = 1;
 2929:                     $forceview = 1;
 2930:                     $cfile = $template;
 2931:                 }
 2932:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2933:                     $incourse = 1;
 2934:                     if ($env{'form.forceedit'}) {
 2935:                         $forceview = 1;
 2936:                     } else {
 2937:                         $forceedit = 1;
 2938:                     }
 2939:                     $cfile = $resurl;
 2940:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2941:                 $incourse = 1;
 2942:                 $forceview = 1;
 2943:                 if ($symb) {
 2944:                     my ($map,$id,$res)=&decode_symb($symb);
 2945:                     $env{'request.symb'} = $symb;
 2946:                     $cfile = &clutter($res);
 2947:                 } else {
 2948:                     $cfile = $env{'form.suppurl'};
 2949:                     $cfile =~ s{^http://}{};
 2950:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2951:                 }
 2952:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2953:                 if ($env{'form.forceedit'}) {
 2954:                     $forceview = 1;
 2955:                 } else {
 2956:                     $forceedit = 1;
 2957:                 }
 2958:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2959:             }
 2960:         }
 2961:         if ($uploaded || $incourse) {
 2962:             $home=&homeserver($cnum,$cdom);
 2963:         } elsif ($file !~ m{/$}) {
 2964:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2965:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2966:             # Check that the user has permission to edit this resource
 2967:             my $setpriv = 1;
 2968:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2969:             if (defined($cfudom)) {
 2970:                 $home=&homeserver($cfuname,$cfudom);
 2971:                 $cfile=$file;
 2972:             }
 2973:         }
 2974:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2975:             (($home ne '') && ($home ne 'no_host'))) {
 2976:             my @ids=&current_machine_ids();
 2977:             unless (grep(/^\Q$home\E$/,@ids)) {
 2978:                 $switchserver=1;
 2979:             }
 2980:         }
 2981:     }
 2982:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2983: }
 2984: 
 2985: sub is_course_upload {
 2986:     my ($file,$cnum,$cdom) = @_;
 2987:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2988:     $uploadpath =~ s{^\/}{};
 2989:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2990:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2991:         return 1;
 2992:     }
 2993:     return;
 2994: }
 2995: 
 2996: sub in_course {
 2997:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2998:     if ($hideprivileged) {
 2999:         my $skipuser;
 3000:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3001:         my @possdoms = ($cdom);  
 3002:         if ($coursehash{'checkforpriv'}) { 
 3003:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3004:         }
 3005:         if (&privileged($uname,$udom,\@possdoms)) {
 3006:             $skipuser = 1;
 3007:             if ($coursehash{'nothideprivileged'}) {
 3008:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3009:                     my $user;
 3010:                     if ($item =~ /:/) {
 3011:                         $user = $item;
 3012:                     } else {
 3013:                         $user = join(':',split(/[\@]/,$item));
 3014:                     }
 3015:                     if ($user eq $uname.':'.$udom) {
 3016:                         undef($skipuser);
 3017:                         last;
 3018:                     }
 3019:                 }
 3020:             }
 3021:             if ($skipuser) {
 3022:                 return 0;
 3023:             }
 3024:         }
 3025:     }
 3026:     $type ||= 'any';
 3027:     if (!defined($cdom) || !defined($cnum)) {
 3028:         my $cid  = $env{'request.course.id'};
 3029:         $cdom = $env{'course.'.$cid.'.domain'};
 3030:         $cnum = $env{'course.'.$cid.'.num'};
 3031:     }
 3032:     my $typesref;
 3033:     if (($type eq 'any') || ($type eq 'all')) {
 3034:         $typesref = ['active','previous','future'];
 3035:     } elsif ($type eq 'previous' || $type eq 'future') {
 3036:         $typesref = [$type];
 3037:     }
 3038:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3039:                               $typesref,undef,[$cdom]);
 3040:     my ($tmp) = keys(%roles);
 3041:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3042:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3043:     if (@course_roles > 0) {
 3044:         return 1;
 3045:     }
 3046:     return 0;
 3047: }
 3048: 
 3049: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3050: # input: action, courseID, current domain, intended
 3051: #        path to file, source of file, instruction to parse file for objects,
 3052: #        ref to hash for embedded objects,
 3053: #        ref to hash for codebase of java objects.
 3054: #        reference to scalar to accommodate mime type determined
 3055: #          from File::MMagic if $parser = parse.
 3056: #
 3057: # output: url to file (if action was uploaddoc), 
 3058: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3059: #
 3060: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3061: # course.
 3062: #
 3063: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3064: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3065: #          course's home server.
 3066: #
 3067: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3068: #          be copied from $source (current location) to 
 3069: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3070: #         and will then be copied to
 3071: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3072: #         course's home server.
 3073: #
 3074: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3075: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3076: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3077: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3078: #         in course's home server.
 3079: #
 3080: 
 3081: sub process_coursefile {
 3082:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3083:         $mimetype)=@_;
 3084:     my $fetchresult;
 3085:     my $home=&homeserver($docuname,$docudom);
 3086:     if ($action eq 'propagate') {
 3087:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3088: 			     $home);
 3089:     } else {
 3090:         my $fpath = '';
 3091:         my $fname = $file;
 3092:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3093:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3094:         my $filepath = &build_filepath($fpath);
 3095:         if ($action eq 'copy') {
 3096:             if ($source eq '') {
 3097:                 $fetchresult = 'no source file';
 3098:                 return $fetchresult;
 3099:             } else {
 3100:                 my $destination = $filepath.'/'.$fname;
 3101:                 rename($source,$destination);
 3102:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3103:                                  $home);
 3104:             }
 3105:         } elsif ($action eq 'uploaddoc') {
 3106:             open(my $fh,'>'.$filepath.'/'.$fname);
 3107:             print $fh $env{'form.'.$source};
 3108:             close($fh);
 3109:             if ($parser eq 'parse') {
 3110:                 my $mm = new File::MMagic;
 3111:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3112:                 if ($type eq 'text/html') {
 3113:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3114:                     unless ($parse_result eq 'ok') {
 3115:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3116:                     }
 3117:                 }
 3118:                 if (ref($mimetype)) {
 3119:                     $$mimetype = $type;
 3120:                 } 
 3121:             }
 3122:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3123:                                  $home);
 3124:             if ($fetchresult eq 'ok') {
 3125:                 return '/uploaded/'.$fpath.'/'.$fname;
 3126:             } else {
 3127:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3128:                         ' to host '.$home.': '.$fetchresult);
 3129:                 return '/adm/notfound.html';
 3130:             }
 3131:         }
 3132:     }
 3133:     unless ( $fetchresult eq 'ok') {
 3134:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3135:              ' to host '.$home.': '.$fetchresult);
 3136:     }
 3137:     return $fetchresult;
 3138: }
 3139: 
 3140: sub build_filepath {
 3141:     my ($fpath) = @_;
 3142:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3143:     unless ($fpath eq '') {
 3144:         my @parts=split('/',$fpath);
 3145:         foreach my $part (@parts) {
 3146:             $filepath.= '/'.$part;
 3147:             if ((-e $filepath)!=1) {
 3148:                 mkdir($filepath,0777);
 3149:             }
 3150:         }
 3151:     }
 3152:     return $filepath;
 3153: }
 3154: 
 3155: sub store_edited_file {
 3156:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3157:     my $file = $primary_url;
 3158:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3159:     my $fpath = '';
 3160:     my $fname = $file;
 3161:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3162:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3163:     my $filepath = &build_filepath($fpath);
 3164:     open(my $fh,'>'.$filepath.'/'.$fname);
 3165:     print $fh $content;
 3166:     close($fh);
 3167:     my $home=&homeserver($docuname,$docudom);
 3168:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3169: 			  $home);
 3170:     if ($$fetchresult eq 'ok') {
 3171:         return '/uploaded/'.$fpath.'/'.$fname;
 3172:     } else {
 3173:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3174: 		 ' to host '.$home.': '.$$fetchresult);
 3175:         return '/adm/notfound.html';
 3176:     }
 3177: }
 3178: 
 3179: sub clean_filename {
 3180:     my ($fname,$args)=@_;
 3181: # Replace Windows backslashes by forward slashes
 3182:     $fname=~s/\\/\//g;
 3183:     if (!$args->{'keep_path'}) {
 3184:         # Get rid of everything but the actual filename
 3185: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3186:     }
 3187: # Replace spaces by underscores
 3188:     $fname=~s/\s+/\_/g;
 3189: # Replace all other weird characters by nothing
 3190:     $fname=~s{[^/\w\.\-]}{}g;
 3191: # Replace all .\d. sequences with _\d. so they no longer look like version
 3192: # numbers
 3193:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3194:     return $fname;
 3195: }
 3196: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3197: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3198: # image with the same aspect ratio as the original, but with dimensions which do 
 3199: # not exceed $resizewidth and $resizeheight.
 3200:  
 3201: sub resizeImage {
 3202:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3203:     my $ima = Image::Magick->new;
 3204:     my $resized;
 3205:     if (-e $img_path) {
 3206:         $ima->Read($img_path);
 3207:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3208:             my $width = $ima->Get('width');
 3209:             my $height = $ima->Get('height');
 3210:             if ($width > $resizewidth) {
 3211: 	        my $factor = $width/$resizewidth;
 3212:                 my $newheight = $height/$factor;
 3213:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3214:                 $resized = 1;
 3215:             }
 3216:         }
 3217:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3218:             my $width = $ima->Get('width');
 3219:             my $height = $ima->Get('height');
 3220:             if ($height > $resizeheight) {
 3221:                 my $factor = $height/$resizeheight;
 3222:                 my $newwidth = $width/$factor;
 3223:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3224:                 $resized = 1;
 3225:             }
 3226:         }
 3227:         if ($resized) {
 3228:             $ima->Write($img_path);
 3229:         }
 3230:     }
 3231:     return;
 3232: }
 3233: 
 3234: # --------------- Take an uploaded file and put it into the userfiles directory
 3235: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3236: #                    the desired filename is in $env{"form.$formname.filename"}
 3237: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3238: #                                    canceloverwrite, or ''. 
 3239: #                   if 'coursedoc': upload to the current course
 3240: #                   if 'existingfile': write file to tmp/overwrites directory 
 3241: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3242: #                   $context is passed as argument to &finishuserfileupload
 3243: #        $subdir - directory in userfile to store the file into
 3244: #        $parser - instruction to parse file for objects ($parser = parse)    
 3245: #        $allfiles - reference to hash for embedded objects
 3246: #        $codebase - reference to hash for codebase of java objects
 3247: #        $desuname - username for permanent storage of uploaded file
 3248: #        $dsetudom - domain for permanaent storage of uploaded file
 3249: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3250: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3251: #        $resizewidth - width (pixels) to which to resize uploaded image
 3252: #        $resizeheight - height (pixels) to which to resize uploaded image
 3253: #        $mimetype - reference to scalar to accommodate mime type determined
 3254: #                    from File::MMagic.
 3255: # 
 3256: # output: url of file in userspace, or error: <message> 
 3257: #             or /adm/notfound.html if failure to upload occurse
 3258: 
 3259: sub userfileupload {
 3260:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3261:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3262:     if (!defined($subdir)) { $subdir='unknown'; }
 3263:     my $fname=$env{'form.'.$formname.'.filename'};
 3264:     $fname=&clean_filename($fname);
 3265:     # See if there is anything left
 3266:     unless ($fname) { return 'error: no uploaded file'; }
 3267:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3268:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3269:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3270:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3271:         my $now = time;
 3272:         my $filepath;
 3273:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3274:              $filepath = 'tmp/helprequests/'.$now;
 3275:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3276:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3277:                          '_'.$env{'user.domain'}.'/pending';
 3278:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3279:             my ($docuname,$docudom);
 3280:             if ($destudom) {
 3281:                 $docudom = $destudom;
 3282:             } else {
 3283:                 $docudom = $env{'user.domain'};
 3284:             }
 3285:             if ($destuname) {
 3286:                 $docuname = $destuname;
 3287:             } else {
 3288:                 $docuname = $env{'user.name'};
 3289:             }
 3290:             if (exists($env{'form.group'})) {
 3291:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3292:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3293:             }
 3294:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3295:             if ($context eq 'canceloverwrite') {
 3296:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3297:                 if (-e  $tempfile) {
 3298:                     my @info = stat($tempfile);
 3299:                     if ($info[9] eq $env{'form.timestamp'}) {
 3300:                         unlink($tempfile);
 3301:                     }
 3302:                 }
 3303:                 return;
 3304:             }
 3305:         }
 3306:         # Create the directory if not present
 3307:         my @parts=split(/\//,$filepath);
 3308:         my $fullpath = $perlvar{'lonDaemons'};
 3309:         for (my $i=0;$i<@parts;$i++) {
 3310:             $fullpath .= '/'.$parts[$i];
 3311:             if ((-e $fullpath)!=1) {
 3312:                 mkdir($fullpath,0777);
 3313:             }
 3314:         }
 3315:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3316:         print $fh $env{'form.'.$formname};
 3317:         close($fh);
 3318:         if ($context eq 'existingfile') {
 3319:             my @info = stat($fullpath.'/'.$fname);
 3320:             return ($fullpath.'/'.$fname,$info[9]);
 3321:         } else {
 3322:             return $fullpath.'/'.$fname;
 3323:         }
 3324:     }
 3325:     if ($subdir eq 'scantron') {
 3326:         $fname = 'scantron_orig_'.$fname;
 3327:     } else {
 3328:         $fname="$subdir/$fname";
 3329:     }
 3330:     if ($context eq 'coursedoc') {
 3331: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3332: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3333:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3334:             return &finishuserfileupload($docuname,$docudom,
 3335: 					 $formname,$fname,$parser,$allfiles,
 3336: 					 $codebase,$thumbwidth,$thumbheight,
 3337:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3338:         } else {
 3339:             if ($env{'form.folder'}) {
 3340:                 $fname=$env{'form.folder'}.'/'.$fname;
 3341:             }
 3342:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3343: 				       $fname,$formname,$parser,
 3344: 				       $allfiles,$codebase,$mimetype);
 3345:         }
 3346:     } elsif (defined($destuname)) {
 3347:         my $docuname=$destuname;
 3348:         my $docudom=$destudom;
 3349: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3350: 				     $parser,$allfiles,$codebase,
 3351:                                      $thumbwidth,$thumbheight,
 3352:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3353:     } else {
 3354:         my $docuname=$env{'user.name'};
 3355:         my $docudom=$env{'user.domain'};
 3356:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3357:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3358:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3359:         }
 3360: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3361: 				     $parser,$allfiles,$codebase,
 3362:                                      $thumbwidth,$thumbheight,
 3363:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3364:     }
 3365: }
 3366: 
 3367: sub finishuserfileupload {
 3368:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3369:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3370:     my $path=$docudom.'/'.$docuname.'/';
 3371:     my $filepath=$perlvar{'lonDocRoot'};
 3372:   
 3373:     my ($fnamepath,$file,$fetchthumb);
 3374:     $file=$fname;
 3375:     if ($fname=~m|/|) {
 3376:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3377: 	$path.=$fnamepath.'/';
 3378:     }
 3379:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3380:     my $count;
 3381:     for ($count=4;$count<=$#parts;$count++) {
 3382:         $filepath.="/$parts[$count]";
 3383:         if ((-e $filepath)!=1) {
 3384: 	    mkdir($filepath,0777);
 3385:         }
 3386:     }
 3387: 
 3388: # Save the file
 3389:     {
 3390: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3391: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3392: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3393: 	    return '/adm/notfound.html';
 3394: 	}
 3395:         if ($context eq 'overwrite') {
 3396:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3397:             my $target = $filepath.'/'.$file;
 3398:             if (-e $source) {
 3399:                 my @info = stat($source);
 3400:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3401:                     unless (&File::Copy::move($source,$target)) {
 3402:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3403:                         return "Moving from $source failed";
 3404:                     }
 3405:                 } else {
 3406:                     return "Temporary file: $source had unexpected date/time for last modification";
 3407:                 }
 3408:             } else {
 3409:                 return "Temporary file: $source missing";
 3410:             }
 3411:         } elsif (!print FH ($env{'form.'.$formname})) {
 3412: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3413: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3414: 	    return '/adm/notfound.html';
 3415: 	}
 3416: 	close(FH);
 3417:         if ($resizewidth && $resizeheight) {
 3418:             my $mm = new File::MMagic;
 3419:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3420:             if ($mime_type =~ m{^image/}) {
 3421: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3422:             }  
 3423: 	}
 3424:     }
 3425:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3426:         if (ref($mimetype)) {
 3427:             if ($$mimetype eq '') {
 3428:                 my $mm = new File::MMagic;
 3429:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3430:                 $$mimetype = $type;
 3431:             }
 3432:         }
 3433:     }
 3434:     if ($parser eq 'parse') {
 3435:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3436:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3437:                                                        $allfiles,$codebase);
 3438:             unless ($parse_result eq 'ok') {
 3439:                 &logthis('Failed to parse '.$filepath.$file.
 3440: 	   	         ' for embedded media: '.$parse_result); 
 3441:             }
 3442:         }
 3443:     }
 3444:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3445:         my $input = $filepath.'/'.$file;
 3446:         my $output = $filepath.'/'.'tn-'.$file;
 3447:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3448:         system("convert -sample $thumbsize $input $output");
 3449:         if (-e $filepath.'/'.'tn-'.$file) {
 3450:             $fetchthumb  = 1; 
 3451:         }
 3452:     }
 3453:  
 3454: # Notify homeserver to grep it
 3455: #
 3456:     my $docuhome=&homeserver($docuname,$docudom);	
 3457:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3458:     if ($fetchresult eq 'ok') {
 3459:         if ($fetchthumb) {
 3460:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3461:             if ($thumbresult ne 'ok') {
 3462:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3463:                          $docuhome.': '.$thumbresult);
 3464:             }
 3465:         }
 3466: #
 3467: # Return the URL to it
 3468:         return '/uploaded/'.$path.$file;
 3469:     } else {
 3470:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3471: 		 ': '.$fetchresult);
 3472:         return '/adm/notfound.html';
 3473:     }
 3474: }
 3475: 
 3476: sub extract_embedded_items {
 3477:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3478:     my @state = ();
 3479:     my (%lastids,%related,%shockwave,%flashvars);
 3480:     my %javafiles = (
 3481:                       codebase => '',
 3482:                       code => '',
 3483:                       archive => ''
 3484:                     );
 3485:     my %mediafiles = (
 3486:                       src => '',
 3487:                       movie => '',
 3488:                      );
 3489:     my $p;
 3490:     if ($content) {
 3491:         $p = HTML::LCParser->new($content);
 3492:     } else {
 3493:         $p = HTML::LCParser->new($fullpath);
 3494:     }
 3495:     while (my $t=$p->get_token()) {
 3496: 	if ($t->[0] eq 'S') {
 3497: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3498: 	    push(@state, $tagname);
 3499:             if (lc($tagname) eq 'allow') {
 3500:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3501:             }
 3502: 	    if (lc($tagname) eq 'img') {
 3503: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3504: 	    }
 3505: 	    if (lc($tagname) eq 'a') {
 3506:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3507:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3508:                 }
 3509: 	    }
 3510:             if (lc($tagname) eq 'script') {
 3511:                 my $src;
 3512:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3513:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3514:                 } else {
 3515:                     if ($attr->{'src'} ne '') {
 3516:                         $src = $attr->{'src'};
 3517:                         &add_filetype($allfiles,$src,'src');
 3518:                     }
 3519:                 }
 3520:                 my $text = $p->get_trimmed_text();
 3521:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3522:                     my @swfargs = split(/,/,$1);
 3523:                     foreach my $item (@swfargs) {
 3524:                         $item =~ s/["']//g;
 3525:                         $item =~ s/^\s+//;
 3526:                         $item =~ s/\s+$//;
 3527:                     }
 3528:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3529:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3530:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3531:                         } else {
 3532:                             $related{$swfargs[0]} = [$swfargs[2]];
 3533:                         }
 3534:                     }
 3535:                 }
 3536:             }
 3537:             if (lc($tagname) eq 'link') {
 3538:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3539:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3540:                 }
 3541:             }
 3542: 	    if (lc($tagname) eq 'object' ||
 3543: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3544: 		foreach my $item (keys(%javafiles)) {
 3545: 		    $javafiles{$item} = '';
 3546: 		}
 3547:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3548:                     $lastids{lc($tagname)} = $attr->{'id'};
 3549:                 }
 3550: 	    }
 3551: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3552: 		my $name = lc($attr->{'name'});
 3553: 		foreach my $item (keys(%javafiles)) {
 3554: 		    if ($name eq $item) {
 3555: 			$javafiles{$item} = $attr->{'value'};
 3556: 			last;
 3557: 		    }
 3558: 		}
 3559:                 my $pathfrom;
 3560: 		foreach my $item (keys(%mediafiles)) {
 3561: 		    if ($name eq $item) {
 3562:                         $pathfrom = $attr->{'value'};
 3563:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3564: 			&add_filetype($allfiles,$pathfrom,$name);
 3565: 			last;
 3566: 		    }
 3567: 		}
 3568:                 if ($name eq 'flashvars') {
 3569:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3570:                 }
 3571:                 if ($pathfrom ne '') {
 3572:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3573:                                          $pathfrom);
 3574:                 }
 3575: 	    }
 3576: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3577: 		foreach my $item (keys(%javafiles)) {
 3578: 		    if ($attr->{$item}) {
 3579: 			$javafiles{$item} = $attr->{$item};
 3580: 			last;
 3581: 		    }
 3582: 		}
 3583: 		foreach my $item (keys(%mediafiles)) {
 3584: 		    if ($attr->{$item}) {
 3585: 			&add_filetype($allfiles,$attr->{$item},$item);
 3586: 			last;
 3587: 		    }
 3588: 		}
 3589:                 if (lc($tagname) eq 'embed') {
 3590:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3591:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3592:                                              $attr->{'src'});
 3593:                     }
 3594:                 }
 3595: 	    }
 3596:             if (lc($tagname) eq 'iframe') {
 3597:                 my $src = $attr->{'src'} ;
 3598:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3599:                     &add_filetype($allfiles,$src,'src');
 3600:                 } elsif ($src =~ m{^/}) {
 3601:                     if ($env{'request.course.id'}) {
 3602:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3603:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3604:                         my $url = &hreflocation('',$fullpath);
 3605:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3606:                             my $relpath = $1;
 3607:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3608:                                 &add_filetype($allfiles,$1,'src');
 3609:                             }
 3610:                         }
 3611:                     }
 3612:                 }
 3613:             }
 3614:             if ($t->[4] =~ m{/>$}) {
 3615:                 pop(@state);
 3616:             }
 3617: 	} elsif ($t->[0] eq 'E') {
 3618: 	    my ($tagname) = ($t->[1]);
 3619: 	    if ($javafiles{'codebase'} ne '') {
 3620: 		$javafiles{'codebase'} .= '/';
 3621: 	    }  
 3622: 	    if (lc($tagname) eq 'applet' ||
 3623: 		lc($tagname) eq 'object' ||
 3624: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3625: 		) {
 3626: 		foreach my $item (keys(%javafiles)) {
 3627: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3628: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3629: 			&add_filetype($allfiles,$file,$item);
 3630: 		    }
 3631: 		}
 3632: 	    } 
 3633: 	    pop @state;
 3634: 	}
 3635:     }
 3636:     foreach my $id (sort(keys(%flashvars))) {
 3637:         if ($shockwave{$id} ne '') {
 3638:             my @pairs = split(/\&/,$flashvars{$id});
 3639:             foreach my $pair (@pairs) {
 3640:                 my ($key,$value) = split(/\=/,$pair);
 3641:                 if ($key eq 'thumb') {
 3642:                     &add_filetype($allfiles,$value,$key);
 3643:                 } elsif ($key eq 'content') {
 3644:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3645:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3646:                     if ($ext ne '') {
 3647:                         &add_filetype($allfiles,$path.$value,$ext);
 3648:                     }
 3649:                 }
 3650:             }
 3651:         }
 3652:     }
 3653:     return 'ok';
 3654: }
 3655: 
 3656: sub add_filetype {
 3657:     my ($allfiles,$file,$type)=@_;
 3658:     if (exists($allfiles->{$file})) {
 3659: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3660: 	    push(@{$allfiles->{$file}}, &escape($type));
 3661: 	}
 3662:     } else {
 3663: 	@{$allfiles->{$file}} = (&escape($type));
 3664:     }
 3665: }
 3666: 
 3667: sub embedded_dependency {
 3668:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3669:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3670:         if (($identifier ne '') &&
 3671:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3672:             ($pathfrom ne '')) {
 3673:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3674:             foreach my $dep (@{$related->{$identifier}}) {
 3675:                 &add_filetype($allfiles,$path.$dep,'object');
 3676:             }
 3677:         }
 3678:     }
 3679:     return;
 3680: }
 3681: 
 3682: sub removeuploadedurl {
 3683:     my ($url)=@_;	
 3684:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3685:     return &removeuserfile($uname,$udom,$fname);
 3686: }
 3687: 
 3688: sub removeuserfile {
 3689:     my ($docuname,$docudom,$fname)=@_;
 3690:     my $home=&homeserver($docuname,$docudom);    
 3691:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3692:     if ($result eq 'ok') {	
 3693:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3694:             my $metafile = $fname.'.meta';
 3695:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3696: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3697:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3698:             my $sqlresult = 
 3699:                 &update_portfolio_table($docuname,$docudom,$file,
 3700:                                         'portfolio_metadata',$group,
 3701:                                         'delete');
 3702:         }
 3703:     }
 3704:     return $result;
 3705: }
 3706: 
 3707: sub mkdiruserfile {
 3708:     my ($docuname,$docudom,$dir)=@_;
 3709:     my $home=&homeserver($docuname,$docudom);
 3710:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3711: }
 3712: 
 3713: sub renameuserfile {
 3714:     my ($docuname,$docudom,$old,$new)=@_;
 3715:     my $home=&homeserver($docuname,$docudom);
 3716:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3717:                         &escape("$old").':'.&escape("$new"),$home);
 3718:     if ($result eq 'ok') {
 3719:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3720:             my $oldmeta = $old.'.meta';
 3721:             my $newmeta = $new.'.meta';
 3722:             my $metaresult = 
 3723:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3724: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3725:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3726:             my $sqlresult = 
 3727:                 &update_portfolio_table($docuname,$docudom,$file,
 3728:                                         'portfolio_metadata',$group,
 3729:                                         'delete');
 3730:         }
 3731:     }
 3732:     return $result;
 3733: }
 3734: 
 3735: # ------------------------------------------------------------------------- Log
 3736: 
 3737: sub log {
 3738:     my ($dom,$nam,$hom,$what)=@_;
 3739:     return critical("log:$dom:$nam:$what",$hom);
 3740: }
 3741: 
 3742: # ------------------------------------------------------------------ Course Log
 3743: #
 3744: # This routine flushes several buffers of non-mission-critical nature
 3745: #
 3746: 
 3747: sub flushcourselogs {
 3748:     &logthis('Flushing log buffers');
 3749: #
 3750: # course logs
 3751: # This is a log of all transactions in a course, which can be used
 3752: # for data mining purposes
 3753: #
 3754: # It also collects the courseid database, which lists last transaction
 3755: # times and course titles for all courseids
 3756: #
 3757:     my %courseidbuffer=();
 3758:     foreach my $crsid (keys(%courselogs)) {
 3759:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3760: 		          &escape($courselogs{$crsid}),
 3761: 		          $coursehombuf{$crsid}) eq 'ok') {
 3762: 	    delete $courselogs{$crsid};
 3763:         } else {
 3764:             &logthis('Failed to flush log buffer for '.$crsid);
 3765:             if (length($courselogs{$crsid})>40000) {
 3766:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3767:                         " exceeded maximum size, deleting.</font>");
 3768:                delete $courselogs{$crsid};
 3769:             }
 3770:         }
 3771:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3772:             'description' => $coursedescrbuf{$crsid},
 3773:             'inst_code'    => $courseinstcodebuf{$crsid},
 3774:             'type'        => $coursetypebuf{$crsid},
 3775:             'owner'       => $courseownerbuf{$crsid},
 3776:         };
 3777:     }
 3778: #
 3779: # Write course id database (reverse lookup) to homeserver of courses 
 3780: # Is used in pickcourse
 3781: #
 3782:     foreach my $crs_home (keys(%courseidbuffer)) {
 3783:         my $response = &courseidput(&host_domain($crs_home),
 3784:                                     $courseidbuffer{$crs_home},
 3785:                                     $crs_home,'timeonly');
 3786:     }
 3787: #
 3788: # File accesses
 3789: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3790: #
 3791:     foreach my $entry (keys(%accesshash)) {
 3792:         if ($entry =~ /___count$/) {
 3793:             my ($dom,$name);
 3794:             ($dom,$name,undef)=
 3795: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3796:             if (! defined($dom) || $dom eq '' || 
 3797:                 ! defined($name) || $name eq '') {
 3798:                 my $cid = $env{'request.course.id'};
 3799:                 $dom  = $env{'request.'.$cid.'.domain'};
 3800:                 $name = $env{'request.'.$cid.'.num'};
 3801:             }
 3802:             my $value = $accesshash{$entry};
 3803:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3804:             my %temphash=($url => $value);
 3805:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3806:             if ($result eq 'ok') {
 3807:                 delete $accesshash{$entry};
 3808:             }
 3809:         } else {
 3810:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3811:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3812:             my %temphash=($entry => $accesshash{$entry});
 3813:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3814:                 delete $accesshash{$entry};
 3815:             }
 3816:         }
 3817:     }
 3818: #
 3819: # Roles
 3820: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3821: #
 3822:     foreach my $entry (keys(%userrolehash)) {
 3823:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3824: 	    split(/\:/,$entry);
 3825:         if (&Apache::lonnet::put('nohist_userroles',
 3826:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3827:                 $rudom,$runame) eq 'ok') {
 3828: 	    delete $userrolehash{$entry};
 3829:         }
 3830:     }
 3831: #
 3832: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3833: #
 3834:     my %domrolebuffer = ();
 3835:     foreach my $entry (keys(%domainrolehash)) {
 3836:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3837:         if ($domrolebuffer{$rudom}) {
 3838:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3839:                       '='.&escape($domainrolehash{$entry});
 3840:         } else {
 3841:             $domrolebuffer{$rudom}.=&escape($entry).
 3842:                       '='.&escape($domainrolehash{$entry});
 3843:         }
 3844:         delete $domainrolehash{$entry};
 3845:     }
 3846:     foreach my $dom (keys(%domrolebuffer)) {
 3847: 	my %servers = &get_servers($dom,'library');
 3848: 	foreach my $tryserver (keys(%servers)) {
 3849: 	    unless (&reply('domroleput:'.$dom.':'.
 3850: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3851: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3852: 	    }
 3853:         }
 3854:     }
 3855:     $dumpcount++;
 3856: }
 3857: 
 3858: sub courselog {
 3859:     my $what=shift;
 3860:     $what=time.':'.$what;
 3861:     unless ($env{'request.course.id'}) { return ''; }
 3862:     $coursedombuf{$env{'request.course.id'}}=
 3863:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3864:     $coursenumbuf{$env{'request.course.id'}}=
 3865:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3866:     $coursehombuf{$env{'request.course.id'}}=
 3867:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3868:     $coursedescrbuf{$env{'request.course.id'}}=
 3869:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3870:     $courseinstcodebuf{$env{'request.course.id'}}=
 3871:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3872:     $courseownerbuf{$env{'request.course.id'}}=
 3873:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3874:     $coursetypebuf{$env{'request.course.id'}}=
 3875:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3876:     if (defined $courselogs{$env{'request.course.id'}}) {
 3877: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3878:     } else {
 3879: 	$courselogs{$env{'request.course.id'}}.=$what;
 3880:     }
 3881:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3882: 	&flushcourselogs();
 3883:     }
 3884: }
 3885: 
 3886: sub courseacclog {
 3887:     my $fnsymb=shift;
 3888:     unless ($env{'request.course.id'}) { return ''; }
 3889:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3890:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3891:         $what.=':POST';
 3892:         # FIXME: Probably ought to escape things....
 3893: 	foreach my $key (keys(%env)) {
 3894:             if ($key=~/^form\.(.*)/) {
 3895:                 my $formitem = $1;
 3896:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3897:                     $what.=':'.$formitem.'='.$env{$key};
 3898:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3899:                     $what.=':'.$formitem.'='.$env{$key};
 3900:                 }
 3901:             }
 3902:         }
 3903:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3904:         # FIXME: We should not be depending on a form parameter that someone
 3905:         # editing lonsearchcat.pm might change in the future.
 3906:         if ($env{'form.phase'} eq 'course_search') {
 3907:             $what.= ':POST';
 3908:             # FIXME: Probably ought to escape things....
 3909:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3910:                                  'crsdiscuss') {
 3911:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3912:             }
 3913:         }
 3914:     }
 3915:     &courselog($what);
 3916: }
 3917: 
 3918: sub countacc {
 3919:     my $url=&declutter(shift);
 3920:     return if (! defined($url) || $url eq '');
 3921:     unless ($env{'request.course.id'}) { return ''; }
 3922: #
 3923: # Mark that this url was used in this course
 3924: #
 3925:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3926: #
 3927: # Increase the access count for this resource in this child process
 3928: #
 3929:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3930:     $accesshash{$key}++;
 3931: }
 3932: 
 3933: sub linklog {
 3934:     my ($from,$to)=@_;
 3935:     $from=&declutter($from);
 3936:     $to=&declutter($to);
 3937:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3938:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3939: }
 3940: 
 3941: sub statslog {
 3942:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3943:     if ($users<2) { return; }
 3944:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3945:             'course'       => $env{'request.course.id'},
 3946:             'sections'     => '"all"',
 3947:             'num_students' => $users,
 3948:             'part'         => $part,
 3949:             'symb'         => $symb,
 3950:             'mean_tries'   => $av_attempts,
 3951:             'deg_of_diff'  => $degdiff});
 3952:     foreach my $key (keys(%dynstore)) {
 3953:         $accesshash{$key}=$dynstore{$key};
 3954:     }
 3955: }
 3956:   
 3957: sub userrolelog {
 3958:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3959:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3960:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3961:        $userrolehash
 3962:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3963:                     =$tend.':'.$tstart;
 3964:     }
 3965:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3966:        $userrolehash
 3967:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3968:                     =$tend.':'.$tstart;
 3969:     }
 3970:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3971:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3972:        $domainrolehash
 3973:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3974:                     = $tend.':'.$tstart;
 3975:     }
 3976: }
 3977: 
 3978: sub courserolelog {
 3979:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3980:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3981:         my $cdom = $1;
 3982:         my $cnum = $2;
 3983:         my $sec = $3;
 3984:         my $namespace = 'rolelog';
 3985:         my %storehash = (
 3986:                            role    => $trole,
 3987:                            start   => $tstart,
 3988:                            end     => $tend,
 3989:                            selfenroll => $selfenroll,
 3990:                            context    => $context,
 3991:                         );
 3992:         if ($trole eq 'gr') {
 3993:             $namespace = 'groupslog';
 3994:             $storehash{'group'} = $sec;
 3995:         } else {
 3996:             $storehash{'section'} = $sec;
 3997:         }
 3998:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3999:                    $domain,$cnum,$cdom);
 4000:         if (($trole ne 'st') || ($sec ne '')) {
 4001:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4002:         }
 4003:     }
 4004:     return;
 4005: }
 4006: 
 4007: sub domainrolelog {
 4008:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4009:     if ($area =~ m{^/($match_domain)/$}) {
 4010:         my $cdom = $1;
 4011:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4012:         my $namespace = 'rolelog';
 4013:         my %storehash = (
 4014:                            role    => $trole,
 4015:                            start   => $tstart,
 4016:                            end     => $tend,
 4017:                            context => $context,
 4018:                         );
 4019:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4020:                    $domain,$domconfiguser,$cdom);
 4021:     }
 4022:     return;
 4023: 
 4024: }
 4025: 
 4026: sub coauthorrolelog {
 4027:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4028:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4029:         my $audom = $1;
 4030:         my $auname = $2;
 4031:         my $namespace = 'rolelog';
 4032:         my %storehash = (
 4033:                            role    => $trole,
 4034:                            start   => $tstart,
 4035:                            end     => $tend,
 4036:                            context => $context,
 4037:                         );
 4038:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4039:                    $domain,$auname,$audom);
 4040:     }
 4041:     return;
 4042: }
 4043: 
 4044: sub get_course_adv_roles {
 4045:     my ($cid,$codes) = @_;
 4046:     $cid=$env{'request.course.id'} unless (defined($cid));
 4047:     my %coursehash=&coursedescription($cid);
 4048:     my $crstype = &Apache::loncommon::course_type($cid);
 4049:     my %nothide=();
 4050:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4051:         if ($user !~ /:/) {
 4052: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4053:         } else {
 4054:             $nothide{$user}=1;
 4055:         }
 4056:     }
 4057:     my @possdoms = ($coursehash{'domain'});
 4058:     if ($coursehash{'checkforpriv'}) {
 4059:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4060:     }
 4061:     my %returnhash=();
 4062:     my %dumphash=
 4063:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4064:     my $now=time;
 4065:     my %privileged;
 4066:     foreach my $entry (keys(%dumphash)) {
 4067: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4068:         if (($tstart) && ($tstart<0)) { next; }
 4069:         if (($tend) && ($tend<$now)) { next; }
 4070:         if (($tstart) && ($now<$tstart)) { next; }
 4071:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4072: 	if ($username eq '' || $domain eq '') { next; }
 4073:         if ((&privileged($username,$domain,\@possdoms)) &&
 4074:             (!$nothide{$username.':'.$domain})) { next; }
 4075: 	if ($role eq 'cr') { next; }
 4076:         if ($codes) {
 4077:             if ($section) { $role .= ':'.$section; }
 4078:             if ($returnhash{$role}) {
 4079:                 $returnhash{$role}.=','.$username.':'.$domain;
 4080:             } else {
 4081:                 $returnhash{$role}=$username.':'.$domain;
 4082:             }
 4083:         } else {
 4084:             my $key=&plaintext($role,$crstype);
 4085:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4086:             if ($returnhash{$key}) {
 4087: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4088:             } else {
 4089:                 $returnhash{$key}=$username.':'.$domain;
 4090:             }
 4091:         }
 4092:     }
 4093:     return %returnhash;
 4094: }
 4095: 
 4096: sub get_my_roles {
 4097:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4098:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4099:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4100:     my (%dumphash,%nothide);
 4101:     if ($context eq 'userroles') {
 4102:         %dumphash = &dump('roles',$udom,$uname);
 4103:     } else {
 4104:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4105:         if ($hidepriv) {
 4106:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4107:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4108:                 if ($user !~ /:/) {
 4109:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4110:                 } else {
 4111:                     $nothide{$user} = 1;
 4112:                 }
 4113:             }
 4114:         }
 4115:     }
 4116:     my %returnhash=();
 4117:     my $now=time;
 4118:     my %privileged;
 4119:     foreach my $entry (keys(%dumphash)) {
 4120:         my ($role,$tend,$tstart);
 4121:         if ($context eq 'userroles') {
 4122:             next if ($entry =~ /^rolesdef/);
 4123: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4124:         } else {
 4125:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4126:         }
 4127:         if (($tstart) && ($tstart<0)) { next; }
 4128:         my $status = 'active';
 4129:         if (($tend) && ($tend<=$now)) {
 4130:             $status = 'previous';
 4131:         } 
 4132:         if (($tstart) && ($now<$tstart)) {
 4133:             $status = 'future';
 4134:         }
 4135:         if (ref($types) eq 'ARRAY') {
 4136:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4137:                 next;
 4138:             } 
 4139:         } else {
 4140:             if ($status ne 'active') {
 4141:                 next;
 4142:             }
 4143:         }
 4144:         my ($rolecode,$username,$domain,$section,$area);
 4145:         if ($context eq 'userroles') {
 4146:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4147:             (undef,$domain,$username,$section) = split(/\//,$area);
 4148:         } else {
 4149:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4150:         }
 4151:         if (ref($roledoms) eq 'ARRAY') {
 4152:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4153:                 next;
 4154:             }
 4155:         }
 4156:         if (ref($roles) eq 'ARRAY') {
 4157:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4158:                 if ($role =~ /^cr\//) {
 4159:                     if (!grep(/^cr$/,@{$roles})) {
 4160:                         next;
 4161:                     }
 4162:                 } elsif ($role =~ /^gr\//) {
 4163:                     if (!grep(/^gr$/,@{$roles})) {
 4164:                         next;
 4165:                     }
 4166:                 } else {
 4167:                     next;
 4168:                 }
 4169:             }
 4170:         }
 4171:         if ($hidepriv) {
 4172:             my @privroles = ('dc','su');
 4173:             if ($context eq 'userroles') {
 4174:                 next if (grep(/^\Q$role\E$/,@privroles));
 4175:             } else {
 4176:                 my $possdoms = [$domain];
 4177:                 if (ref($roledoms) eq 'ARRAY') {
 4178:                    push(@{$possdoms},@{$roledoms}); 
 4179:                 }
 4180:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4181:                     if (!$nothide{$username.':'.$domain}) {
 4182:                         next;
 4183:                     }
 4184:                 }
 4185:             }
 4186:         }
 4187:         if ($withsec) {
 4188:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4189:                 $tstart.':'.$tend;
 4190:         } else {
 4191:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4192:         }
 4193:     }
 4194:     return %returnhash;
 4195: }
 4196: 
 4197: # ----------------------------------------------------- Frontpage Announcements
 4198: #
 4199: #
 4200: 
 4201: sub postannounce {
 4202:     my ($server,$text)=@_;
 4203:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4204:     unless ($text=~/\w/) { $text=''; }
 4205:     return &reply('setannounce:'.&escape($text),$server);
 4206: }
 4207: 
 4208: sub getannounce {
 4209: 
 4210:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4211: 	my $announcement='';
 4212: 	while (my $line = <$fh>) { $announcement .= $line; }
 4213: 	close($fh);
 4214: 	if ($announcement=~/\w/) { 
 4215: 	    return 
 4216:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4217:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4218: 	} else {
 4219: 	    return '';
 4220: 	}
 4221:     } else {
 4222: 	return '';
 4223:     }
 4224: }
 4225: 
 4226: # ---------------------------------------------------------- Course ID routines
 4227: # Deal with domain's nohist_courseid.db files
 4228: #
 4229: 
 4230: sub courseidput {
 4231:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4232:     return unless (ref($storehash) eq 'HASH');
 4233:     my $outcome;
 4234:     if ($caller eq 'timeonly') {
 4235:         my $cids = '';
 4236:         foreach my $item (keys(%$storehash)) {
 4237:             $cids.=&escape($item).'&';
 4238:         }
 4239:         $cids=~s/\&$//;
 4240:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4241:                           $coursehome);       
 4242:     } else {
 4243:         my $items = '';
 4244:         foreach my $item (keys(%$storehash)) {
 4245:             $items.= &escape($item).'='.
 4246:                      &freeze_escape($$storehash{$item}).'&';
 4247:         }
 4248:         $items=~s/\&$//;
 4249:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4250:                           $coursehome);
 4251:     }
 4252:     if ($outcome eq 'unknown_cmd') {
 4253:         my $what;
 4254:         foreach my $cid (keys(%$storehash)) {
 4255:             $what .= &escape($cid).'=';
 4256:             foreach my $item ('description','inst_code','owner','type') {
 4257:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4258:             }
 4259:             $what =~ s/\:$/&/;
 4260:         }
 4261:         $what =~ s/\&$//;  
 4262:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4263:     } else {
 4264:         return $outcome;
 4265:     }
 4266: }
 4267: 
 4268: sub courseiddump {
 4269:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4270:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4271:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4272:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4273:         $hasuniquecode)=@_;
 4274:     my $as_hash = 1;
 4275:     my %returnhash;
 4276:     if (!$domfilter) { $domfilter=''; }
 4277:     my %libserv = &all_library();
 4278:     foreach my $tryserver (keys(%libserv)) {
 4279:         if ( (  $hostidflag == 1 
 4280: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4281: 	     || (!defined($hostidflag)) ) {
 4282: 
 4283: 	    if (($domfilter eq '') ||
 4284: 		(&host_domain($tryserver) eq $domfilter)) {
 4285:                 my $rep;
 4286:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4287:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4288:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4289:                                 &escape($descfilter), &escape($instcodefilter), 
 4290:                                 &escape($ownerfilter), &escape($coursefilter),
 4291:                                 &escape($typefilter), &escape($regexp_ok), 
 4292:                                 $as_hash, &escape($selfenrollonly), 
 4293:                                 &escape($catfilter), $showhidden, $caller, 
 4294:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4295:                                 &escape($createdbefore), &escape($createdafter), 
 4296:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
 4297:                 } else {
 4298:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4299:                              $sincefilter.':'.&escape($descfilter).':'.
 4300:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4301:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4302:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4303:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4304:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4305:                              &escape($cc_clone).':'.$cloneonly.':'.
 4306:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4307:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
 4308:                              $tryserver);
 4309:                 }
 4310:                      
 4311:                 my @pairs=split(/\&/,$rep);
 4312:                 foreach my $item (@pairs) {
 4313:                     my ($key,$value)=split(/\=/,$item,2);
 4314:                     $key = &unescape($key);
 4315:                     next if ($key =~ /^error: 2 /);
 4316:                     my $result = &thaw_unescape($value);
 4317:                     if (ref($result) eq 'HASH') {
 4318:                         $returnhash{$key}=$result;
 4319:                     } else {
 4320:                         my @responses = split(/:/,$value);
 4321:                         my @items = ('description','inst_code','owner','type');
 4322:                         for (my $i=0; $i<@responses; $i++) {
 4323:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4324:                         }
 4325:                     }
 4326:                 }
 4327:             }
 4328:         }
 4329:     }
 4330:     return %returnhash;
 4331: }
 4332: 
 4333: sub courselastaccess {
 4334:     my ($cdom,$cnum,$hostidref) = @_;
 4335:     my %returnhash;
 4336:     if ($cdom && $cnum) {
 4337:         my $chome = &homeserver($cnum,$cdom);
 4338:         if ($chome ne 'no_host') {
 4339:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4340:             &extract_lastaccess(\%returnhash,$rep);
 4341:         }
 4342:     } else {
 4343:         if (!$cdom) { $cdom=''; }
 4344:         my %libserv = &all_library();
 4345:         foreach my $tryserver (keys(%libserv)) {
 4346:             if (ref($hostidref) eq 'ARRAY') {
 4347:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4348:             } 
 4349:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4350:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4351:                 &extract_lastaccess(\%returnhash,$rep);
 4352:             }
 4353:         }
 4354:     }
 4355:     return %returnhash;
 4356: }
 4357: 
 4358: sub extract_lastaccess {
 4359:     my ($returnhash,$rep) = @_;
 4360:     if (ref($returnhash) eq 'HASH') {
 4361:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4362:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4363:                  $rep eq '') {
 4364:             my @pairs=split(/\&/,$rep);
 4365:             foreach my $item (@pairs) {
 4366:                 my ($key,$value)=split(/\=/,$item,2);
 4367:                 $key = &unescape($key);
 4368:                 next if ($key =~ /^error: 2 /);
 4369:                 $returnhash->{$key} = &thaw_unescape($value);
 4370:             }
 4371:         }
 4372:     }
 4373:     return;
 4374: }
 4375: 
 4376: # ---------------------------------------------------------- DC e-mail
 4377: 
 4378: sub dcmailput {
 4379:     my ($domain,$msgid,$message,$server)=@_;
 4380:     my $status = &Apache::lonnet::critical(
 4381:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4382:        &escape($message),$server);
 4383:     return $status;
 4384: }
 4385: 
 4386: sub dcmaildump {
 4387:     my ($dom,$startdate,$enddate,$senders) = @_;
 4388:     my %returnhash=();
 4389: 
 4390:     if (defined(&domain($dom,'primary'))) {
 4391:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4392:                                                          &escape($enddate).':';
 4393: 	my @esc_senders=map { &escape($_)} @$senders;
 4394: 	$cmd.=&escape(join('&',@esc_senders));
 4395: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4396:             my ($key,$value) = split(/\=/,$line,2);
 4397:             if (($key) && ($value)) {
 4398:                 $returnhash{&unescape($key)} = &unescape($value);
 4399:             }
 4400:         }
 4401:     }
 4402:     return %returnhash;
 4403: }
 4404: # ---------------------------------------------------------- Domain roles
 4405: 
 4406: sub get_domain_roles {
 4407:     my ($dom,$roles,$startdate,$enddate)=@_;
 4408:     if ((!defined($startdate)) || ($startdate eq '')) {
 4409:         $startdate = '.';
 4410:     }
 4411:     if ((!defined($enddate)) || ($enddate eq '')) {
 4412:         $enddate = '.';
 4413:     }
 4414:     my $rolelist;
 4415:     if (ref($roles) eq 'ARRAY') {
 4416:         $rolelist = join('&',@{$roles});
 4417:     }
 4418:     my %personnel = ();
 4419: 
 4420:     my %servers = &get_servers($dom,'library');
 4421:     foreach my $tryserver (keys(%servers)) {
 4422: 	%{$personnel{$tryserver}}=();
 4423: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4424: 					    &escape($startdate).':'.
 4425: 					    &escape($enddate).':'.
 4426: 					    &escape($rolelist), $tryserver))) {
 4427: 	    my ($key,$value) = split(/\=/,$line,2);
 4428: 	    if (($key) && ($value)) {
 4429: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4430: 	    }
 4431: 	}
 4432:     }
 4433:     return %personnel;
 4434: }
 4435: 
 4436: # ----------------------------------------------------------- Interval timing 
 4437: 
 4438: {
 4439: # Caches needed for speedup of navmaps
 4440: # We don't want to cache this for very long at all (5 seconds at most)
 4441: # 
 4442: # The user for whom we cache
 4443: my $cachedkey='';
 4444: # The cached times for this user
 4445: my %cachedtimes=();
 4446: # When this was last done
 4447: my $cachedtime=();
 4448: 
 4449: sub load_all_first_access {
 4450:     my ($uname,$udom)=@_;
 4451:     if (($cachedkey eq $uname.':'.$udom) &&
 4452:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4453:         return;
 4454:     }
 4455:     $cachedtime=time;
 4456:     $cachedkey=$uname.':'.$udom;
 4457:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4458: }
 4459: 
 4460: sub get_first_access {
 4461:     my ($type,$argsymb,$argmap)=@_;
 4462:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4463:     if ($argsymb) { $symb=$argsymb; }
 4464:     my ($map,$id,$res)=&decode_symb($symb);
 4465:     if ($argmap) { $map = $argmap; }
 4466:     if ($type eq 'course') {
 4467: 	$res='course';
 4468:     } elsif ($type eq 'map') {
 4469: 	$res=&symbread($map);
 4470:     } else {
 4471: 	$res=$symb;
 4472:     }
 4473:     &load_all_first_access($uname,$udom);
 4474:     return $cachedtimes{"$courseid\0$res"};
 4475: }
 4476: 
 4477: sub set_first_access {
 4478:     my ($type,$interval)=@_;
 4479:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4480:     my ($map,$id,$res)=&decode_symb($symb);
 4481:     if ($type eq 'course') {
 4482: 	$res='course';
 4483:     } elsif ($type eq 'map') {
 4484: 	$res=&symbread($map);
 4485:     } else {
 4486: 	$res=$symb;
 4487:     }
 4488:     $cachedkey='';
 4489:     my $firstaccess=&get_first_access($type,$symb,$map);
 4490:     if (!$firstaccess) {
 4491:         my $start = time;
 4492: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4493:                           $udom,$uname);
 4494:         if ($putres eq 'ok') {
 4495:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4496:                  $udom,$uname); 
 4497:             &appenv(
 4498:                      {
 4499:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4500:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4501:                      }
 4502:                   );
 4503:         }
 4504:         return $putres;
 4505:     }
 4506:     return 'already_set';
 4507: }
 4508: }
 4509: # --------------------------------------------- Set Expire Date for Spreadsheet
 4510: 
 4511: sub expirespread {
 4512:     my ($uname,$udom,$stype,$usymb)=@_;
 4513:     my $cid=$env{'request.course.id'}; 
 4514:     if ($cid) {
 4515:        my $now=time;
 4516:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4517:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4518:                             $env{'course.'.$cid.'.num'}.
 4519: 	        	    ':nohist_expirationdates:'.
 4520:                             &escape($key).'='.$now,
 4521:                             $env{'course.'.$cid.'.home'})
 4522:     }
 4523:     return 'ok';
 4524: }
 4525: 
 4526: # ----------------------------------------------------- Devalidate Spreadsheets
 4527: 
 4528: sub devalidate {
 4529:     my ($symb,$uname,$udom)=@_;
 4530:     my $cid=$env{'request.course.id'}; 
 4531:     if ($cid) {
 4532:         # delete the stored spreadsheets for
 4533:         # - the student level sheet of this user in course's homespace
 4534:         # - the assessment level sheet for this resource 
 4535:         #   for this user in user's homespace
 4536: 	# - current conditional state info
 4537: 	my $key=$uname.':'.$udom.':';
 4538:         my $status=
 4539: 	    &del('nohist_calculatedsheets',
 4540: 		 [$key.'studentcalc:'],
 4541: 		 $env{'course.'.$cid.'.domain'},
 4542: 		 $env{'course.'.$cid.'.num'})
 4543: 		.' '.
 4544: 	    &del('nohist_calculatedsheets_'.$cid,
 4545: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4546:         unless ($status eq 'ok ok') {
 4547:            &logthis('Could not devalidate spreadsheet '.
 4548:                     $uname.' at '.$udom.' for '.
 4549: 		    $symb.': '.$status);
 4550:         }
 4551: 	&delenv('user.state.'.$cid);
 4552:     }
 4553: }
 4554: 
 4555: sub get_scalar {
 4556:     my ($string,$end) = @_;
 4557:     my $value;
 4558:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4559: 	$value = $1;
 4560:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4561: 	$value = $1;
 4562:     }
 4563:     return &unescape($value);
 4564: }
 4565: 
 4566: sub array2str {
 4567:   my (@array) = @_;
 4568:   my $result=&arrayref2str(\@array);
 4569:   $result=~s/^__ARRAY_REF__//;
 4570:   $result=~s/__END_ARRAY_REF__$//;
 4571:   return $result;
 4572: }
 4573: 
 4574: sub arrayref2str {
 4575:   my ($arrayref) = @_;
 4576:   my $result='__ARRAY_REF__';
 4577:   foreach my $elem (@$arrayref) {
 4578:     if(ref($elem) eq 'ARRAY') {
 4579:       $result.=&arrayref2str($elem).'&';
 4580:     } elsif(ref($elem) eq 'HASH') {
 4581:       $result.=&hashref2str($elem).'&';
 4582:     } elsif(ref($elem)) {
 4583:       #print("Got a ref of ".(ref($elem))." skipping.");
 4584:     } else {
 4585:       $result.=&escape($elem).'&';
 4586:     }
 4587:   }
 4588:   $result=~s/\&$//;
 4589:   $result .= '__END_ARRAY_REF__';
 4590:   return $result;
 4591: }
 4592: 
 4593: sub hash2str {
 4594:   my (%hash) = @_;
 4595:   my $result=&hashref2str(\%hash);
 4596:   $result=~s/^__HASH_REF__//;
 4597:   $result=~s/__END_HASH_REF__$//;
 4598:   return $result;
 4599: }
 4600: 
 4601: sub hashref2str {
 4602:   my ($hashref)=@_;
 4603:   my $result='__HASH_REF__';
 4604:   foreach my $key (sort(keys(%$hashref))) {
 4605:     if (ref($key) eq 'ARRAY') {
 4606:       $result.=&arrayref2str($key).'=';
 4607:     } elsif (ref($key) eq 'HASH') {
 4608:       $result.=&hashref2str($key).'=';
 4609:     } elsif (ref($key)) {
 4610:       $result.='=';
 4611:       #print("Got a ref of ".(ref($key))." skipping.");
 4612:     } else {
 4613: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4614:     }
 4615: 
 4616:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4617:       $result.=&arrayref2str($hashref->{$key}).'&';
 4618:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4619:       $result.=&hashref2str($hashref->{$key}).'&';
 4620:     } elsif(ref($hashref->{$key})) {
 4621:        $result.='&';
 4622:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4623:     } else {
 4624:       $result.=&escape($hashref->{$key}).'&';
 4625:     }
 4626:   }
 4627:   $result=~s/\&$//;
 4628:   $result .= '__END_HASH_REF__';
 4629:   return $result;
 4630: }
 4631: 
 4632: sub str2hash {
 4633:     my ($string)=@_;
 4634:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4635:     return %$hash;
 4636: }
 4637: 
 4638: sub str2hashref {
 4639:   my ($string) = @_;
 4640: 
 4641:   my %hash;
 4642: 
 4643:   if($string !~ /^__HASH_REF__/) {
 4644:       if (! ($string eq '' || !defined($string))) {
 4645: 	  $hash{'error'}='Not hash reference';
 4646:       }
 4647:       return (\%hash, $string);
 4648:   }
 4649: 
 4650:   $string =~ s/^__HASH_REF__//;
 4651: 
 4652:   while($string !~ /^__END_HASH_REF__/) {
 4653:       #key
 4654:       my $key='';
 4655:       if($string =~ /^__HASH_REF__/) {
 4656:           ($key, $string)=&str2hashref($string);
 4657:           if(defined($key->{'error'})) {
 4658:               $hash{'error'}='Bad data';
 4659:               return (\%hash, $string);
 4660:           }
 4661:       } elsif($string =~ /^__ARRAY_REF__/) {
 4662:           ($key, $string)=&str2arrayref($string);
 4663:           if($key->[0] eq 'Array reference error') {
 4664:               $hash{'error'}='Bad data';
 4665:               return (\%hash, $string);
 4666:           }
 4667:       } else {
 4668:           $string =~ s/^(.*?)=//;
 4669: 	  $key=&unescape($1);
 4670:       }
 4671:       $string =~ s/^=//;
 4672: 
 4673:       #value
 4674:       my $value='';
 4675:       if($string =~ /^__HASH_REF__/) {
 4676:           ($value, $string)=&str2hashref($string);
 4677:           if(defined($value->{'error'})) {
 4678:               $hash{'error'}='Bad data';
 4679:               return (\%hash, $string);
 4680:           }
 4681:       } elsif($string =~ /^__ARRAY_REF__/) {
 4682:           ($value, $string)=&str2arrayref($string);
 4683:           if($value->[0] eq 'Array reference error') {
 4684:               $hash{'error'}='Bad data';
 4685:               return (\%hash, $string);
 4686:           }
 4687:       } else {
 4688: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4689:       }
 4690:       $string =~ s/^&//;
 4691: 
 4692:       $hash{$key}=$value;
 4693:   }
 4694: 
 4695:   $string =~ s/^__END_HASH_REF__//;
 4696: 
 4697:   return (\%hash, $string);
 4698: }
 4699: 
 4700: sub str2array {
 4701:     my ($string)=@_;
 4702:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4703:     return @$array;
 4704: }
 4705: 
 4706: sub str2arrayref {
 4707:   my ($string) = @_;
 4708:   my @array;
 4709: 
 4710:   if($string !~ /^__ARRAY_REF__/) {
 4711:       if (! ($string eq '' || !defined($string))) {
 4712: 	  $array[0]='Array reference error';
 4713:       }
 4714:       return (\@array, $string);
 4715:   }
 4716: 
 4717:   $string =~ s/^__ARRAY_REF__//;
 4718: 
 4719:   while($string !~ /^__END_ARRAY_REF__/) {
 4720:       my $value='';
 4721:       if($string =~ /^__HASH_REF__/) {
 4722:           ($value, $string)=&str2hashref($string);
 4723:           if(defined($value->{'error'})) {
 4724:               $array[0] ='Array reference error';
 4725:               return (\@array, $string);
 4726:           }
 4727:       } elsif($string =~ /^__ARRAY_REF__/) {
 4728:           ($value, $string)=&str2arrayref($string);
 4729:           if($value->[0] eq 'Array reference error') {
 4730:               $array[0] ='Array reference error';
 4731:               return (\@array, $string);
 4732:           }
 4733:       } else {
 4734: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4735:       }
 4736:       $string =~ s/^&//;
 4737: 
 4738:       push(@array, $value);
 4739:   }
 4740: 
 4741:   $string =~ s/^__END_ARRAY_REF__//;
 4742: 
 4743:   return (\@array, $string);
 4744: }
 4745: 
 4746: # -------------------------------------------------------------------Temp Store
 4747: 
 4748: sub tmpreset {
 4749:   my ($symb,$namespace,$domain,$stuname) = @_;
 4750:   if (!$symb) {
 4751:     $symb=&symbread();
 4752:     if (!$symb) { $symb= $env{'request.url'}; }
 4753:   }
 4754:   $symb=escape($symb);
 4755: 
 4756:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4757:   $namespace=~s/\//\_/g;
 4758:   $namespace=~s/\W//g;
 4759: 
 4760:   if (!$domain) { $domain=$env{'user.domain'}; }
 4761:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4762:   if ($domain eq 'public' && $stuname eq 'public') {
 4763:       $stuname=$ENV{'REMOTE_ADDR'};
 4764:   }
 4765:   my $path=LONCAPA::tempdir();
 4766:   my %hash;
 4767:   if (tie(%hash,'GDBM_File',
 4768: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4769: 	  &GDBM_WRCREAT(),0640)) {
 4770:     foreach my $key (keys(%hash)) {
 4771:       if ($key=~ /:$symb/) {
 4772: 	delete($hash{$key});
 4773:       }
 4774:     }
 4775:   }
 4776: }
 4777: 
 4778: sub tmpstore {
 4779:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4780: 
 4781:   if (!$symb) {
 4782:     $symb=&symbread();
 4783:     if (!$symb) { $symb= $env{'request.url'}; }
 4784:   }
 4785:   $symb=escape($symb);
 4786: 
 4787:   if (!$namespace) {
 4788:     # I don't think we would ever want to store this for a course.
 4789:     # it seems this will only be used if we don't have a course.
 4790:     #$namespace=$env{'request.course.id'};
 4791:     #if (!$namespace) {
 4792:       $namespace=$env{'request.state'};
 4793:     #}
 4794:   }
 4795:   $namespace=~s/\//\_/g;
 4796:   $namespace=~s/\W//g;
 4797:   if (!$domain) { $domain=$env{'user.domain'}; }
 4798:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4799:   if ($domain eq 'public' && $stuname eq 'public') {
 4800:       $stuname=$ENV{'REMOTE_ADDR'};
 4801:   }
 4802:   my $now=time;
 4803:   my %hash;
 4804:   my $path=LONCAPA::tempdir();
 4805:   if (tie(%hash,'GDBM_File',
 4806: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4807: 	  &GDBM_WRCREAT(),0640)) {
 4808:     $hash{"version:$symb"}++;
 4809:     my $version=$hash{"version:$symb"};
 4810:     my $allkeys=''; 
 4811:     foreach my $key (keys(%$storehash)) {
 4812:       $allkeys.=$key.':';
 4813:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4814:     }
 4815:     $hash{"$version:$symb:timestamp"}=$now;
 4816:     $allkeys.='timestamp';
 4817:     $hash{"$version:keys:$symb"}=$allkeys;
 4818:     if (untie(%hash)) {
 4819:       return 'ok';
 4820:     } else {
 4821:       return "error:$!";
 4822:     }
 4823:   } else {
 4824:     return "error:$!";
 4825:   }
 4826: }
 4827: 
 4828: # -----------------------------------------------------------------Temp Restore
 4829: 
 4830: sub tmprestore {
 4831:   my ($symb,$namespace,$domain,$stuname) = @_;
 4832: 
 4833:   if (!$symb) {
 4834:     $symb=&symbread();
 4835:     if (!$symb) { $symb= $env{'request.url'}; }
 4836:   }
 4837:   $symb=escape($symb);
 4838: 
 4839:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4840: 
 4841:   if (!$domain) { $domain=$env{'user.domain'}; }
 4842:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4843:   if ($domain eq 'public' && $stuname eq 'public') {
 4844:       $stuname=$ENV{'REMOTE_ADDR'};
 4845:   }
 4846:   my %returnhash;
 4847:   $namespace=~s/\//\_/g;
 4848:   $namespace=~s/\W//g;
 4849:   my %hash;
 4850:   my $path=LONCAPA::tempdir();
 4851:   if (tie(%hash,'GDBM_File',
 4852: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4853: 	  &GDBM_READER(),0640)) {
 4854:     my $version=$hash{"version:$symb"};
 4855:     $returnhash{'version'}=$version;
 4856:     my $scope;
 4857:     for ($scope=1;$scope<=$version;$scope++) {
 4858:       my $vkeys=$hash{"$scope:keys:$symb"};
 4859:       my @keys=split(/:/,$vkeys);
 4860:       my $key;
 4861:       $returnhash{"$scope:keys"}=$vkeys;
 4862:       foreach $key (@keys) {
 4863: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4864: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4865:       }
 4866:     }
 4867:     if (!(untie(%hash))) {
 4868:       return "error:$!";
 4869:     }
 4870:   } else {
 4871:     return "error:$!";
 4872:   }
 4873:   return %returnhash;
 4874: }
 4875: 
 4876: # ----------------------------------------------------------------------- Store
 4877: 
 4878: sub store {
 4879:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4880:     my $home='';
 4881: 
 4882:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4883: 
 4884:     $symb=&symbclean($symb);
 4885:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4886: 
 4887:     if (!$domain) { $domain=$env{'user.domain'}; }
 4888:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4889: 
 4890:     &devalidate($symb,$stuname,$domain);
 4891: 
 4892:     $symb=escape($symb);
 4893:     if (!$namespace) { 
 4894:        unless ($namespace=$env{'request.course.id'}) { 
 4895:           return ''; 
 4896:        } 
 4897:     }
 4898:     if (!$home) { $home=$env{'user.home'}; }
 4899: 
 4900:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4901:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4902: 
 4903:     my $namevalue='';
 4904:     foreach my $key (keys(%$storehash)) {
 4905:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4906:     }
 4907:     $namevalue=~s/\&$//;
 4908:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4909:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4910: }
 4911: 
 4912: # -------------------------------------------------------------- Critical Store
 4913: 
 4914: sub cstore {
 4915:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4916:     my $home='';
 4917: 
 4918:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4919: 
 4920:     $symb=&symbclean($symb);
 4921:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4922: 
 4923:     if (!$domain) { $domain=$env{'user.domain'}; }
 4924:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4925: 
 4926:     &devalidate($symb,$stuname,$domain);
 4927: 
 4928:     $symb=escape($symb);
 4929:     if (!$namespace) { 
 4930:        unless ($namespace=$env{'request.course.id'}) { 
 4931:           return ''; 
 4932:        } 
 4933:     }
 4934:     if (!$home) { $home=$env{'user.home'}; }
 4935: 
 4936:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4937:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4938: 
 4939:     my $namevalue='';
 4940:     foreach my $key (keys(%$storehash)) {
 4941:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4942:     }
 4943:     $namevalue=~s/\&$//;
 4944:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4945:     return critical
 4946:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4947: }
 4948: 
 4949: # --------------------------------------------------------------------- Restore
 4950: 
 4951: sub restore {
 4952:     my ($symb,$namespace,$domain,$stuname) = @_;
 4953:     my $home='';
 4954: 
 4955:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4956: 
 4957:     if (!$symb) {
 4958:         return if ($namespace eq 'courserequests');
 4959:         unless ($symb=escape(&symbread())) { return ''; }
 4960:     } else {
 4961:         unless ($namespace eq 'courserequests') {
 4962:             $symb=&escape(&symbclean($symb));
 4963:         }
 4964:     }
 4965:     if (!$namespace) { 
 4966:        unless ($namespace=$env{'request.course.id'}) { 
 4967:           return ''; 
 4968:        } 
 4969:     }
 4970:     if (!$domain) { $domain=$env{'user.domain'}; }
 4971:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4972:     if (!$home) { $home=$env{'user.home'}; }
 4973:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4974: 
 4975:     my %returnhash=();
 4976:     foreach my $line (split(/\&/,$answer)) {
 4977: 	my ($name,$value)=split(/\=/,$line);
 4978:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4979:     }
 4980:     my $version;
 4981:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4982:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4983:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4984:        }
 4985:     }
 4986:     return %returnhash;
 4987: }
 4988: 
 4989: # ---------------------------------------------------------- Course Description
 4990: #
 4991: #  
 4992: 
 4993: sub coursedescription {
 4994:     my ($courseid,$args)=@_;
 4995:     $courseid=~s/^\///;
 4996:     $courseid=~s/\_/\//g;
 4997:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4998:     my $chome=&homeserver($cnum,$cdomain);
 4999:     my $normalid=$cdomain.'_'.$cnum;
 5000:     # need to always cache even if we get errors otherwise we keep 
 5001:     # trying and trying and trying to get the course description.
 5002:     my %envhash=();
 5003:     my %returnhash=();
 5004:     
 5005:     my $expiretime=600;
 5006:     if ($env{'request.course.id'} eq $normalid) {
 5007: 	$expiretime=120;
 5008:     }
 5009: 
 5010:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5011:     if (!$args->{'freshen_cache'}
 5012: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5013: 	foreach my $key (keys(%env)) {
 5014: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5015: 	    my ($setting) = $1;
 5016: 	    $returnhash{$setting} = $env{$key};
 5017: 	}
 5018: 	return %returnhash;
 5019:     }
 5020: 
 5021:     # get the data again
 5022: 
 5023:     if (!$args->{'one_time'}) {
 5024: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5025:     }
 5026: 
 5027:     if ($chome ne 'no_host') {
 5028:        %returnhash=&dump('environment',$cdomain,$cnum);
 5029:        if (!exists($returnhash{'con_lost'})) {
 5030: 	   my $username = $env{'user.name'}; # Defult username
 5031: 	   if(defined $args->{'user'}) {
 5032: 	       $username = $args->{'user'};
 5033: 	   }
 5034:            $returnhash{'home'}= $chome;
 5035: 	   $returnhash{'domain'} = $cdomain;
 5036: 	   $returnhash{'num'} = $cnum;
 5037:            if (!defined($returnhash{'type'})) {
 5038:                $returnhash{'type'} = 'Course';
 5039:            }
 5040:            while (my ($name,$value) = each %returnhash) {
 5041:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5042:            }
 5043:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5044:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5045: 	       $username.'_'.$cdomain.'_'.$cnum;
 5046:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5047:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5048:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5049:        }
 5050:     }
 5051:     if (!$args->{'one_time'}) {
 5052: 	&appenv(\%envhash);
 5053:     }
 5054:     return %returnhash;
 5055: }
 5056: 
 5057: sub update_released_required {
 5058:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5059:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5060:         $cid = $env{'request.course.id'};
 5061:         $cdom = $env{'course.'.$cid.'.domain'};
 5062:         $cnum = $env{'course.'.$cid.'.num'};
 5063:         $chome = $env{'course.'.$cid.'.home'};
 5064:     }
 5065:     if ($needsrelease) {
 5066:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5067:         my $needsupdate;
 5068:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5069:             $needsupdate = 1;
 5070:         } else {
 5071:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5072:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5073:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5074:                 $needsupdate = 1;
 5075:             }
 5076:         }
 5077:         if ($needsupdate) {
 5078:             my %needshash = (
 5079:                              'internal.releaserequired' => $needsrelease,
 5080:                             );
 5081:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5082:             if ($putresult eq 'ok') {
 5083:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5084:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5085:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5086:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5087:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5088:                 }
 5089:             }
 5090:         }
 5091:     }
 5092:     return;
 5093: }
 5094: 
 5095: # -------------------------------------------------See if a user is privileged
 5096: 
 5097: sub privileged {
 5098:     my ($username,$domain,$possdomains,$possroles)=@_;
 5099:     my $now = time;
 5100:     my $roles;
 5101:     if (ref($possroles) eq 'ARRAY') {
 5102:         $roles = $possroles; 
 5103:     } else {
 5104:         $roles = ['dc','su'];
 5105:     }
 5106:     if (ref($possdomains) eq 'ARRAY') {
 5107:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5108:         foreach my $dom (@{$possdomains}) {
 5109:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5110:                 (ref($privileged{$dom}) eq 'HASH')) {
 5111:                 foreach my $role (@{$roles}) {
 5112:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5113:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5114:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5115:                             return 1 unless (($end && $end < $now) ||
 5116:                                              ($start && $start > $now));
 5117:                         }
 5118:                     }
 5119:                 }
 5120:             }
 5121:         }
 5122:     } else {
 5123:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5124:         my $now = time;
 5125: 
 5126:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5127:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5128:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5129:                 return 1 unless ($tend && $tend < $now) 
 5130:                         or ($tstart && $tstart > $now);
 5131:             }
 5132:         }
 5133:     }
 5134:     return 0;
 5135: }
 5136: 
 5137: sub privileged_by_domain {
 5138:     my ($domains,$roles) = @_;
 5139:     my %privileged = ();
 5140:     my $cachetime = 60*60*24;
 5141:     my $now = time;
 5142:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5143:         return %privileged;
 5144:     }
 5145:     foreach my $dom (@{$domains}) {
 5146:         next if (ref($privileged{$dom}) eq 'HASH');
 5147:         my $needroles;
 5148:         foreach my $role (@{$roles}) {
 5149:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5150:             if (defined($cached)) {
 5151:                 if (ref($result) eq 'HASH') {
 5152:                     $privileged{$dom}{$role} = $result;
 5153:                 }
 5154:             } else {
 5155:                 $needroles = 1;
 5156:             }
 5157:         }
 5158:         if ($needroles) {
 5159:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5160:             $privileged{$dom} = {};
 5161:             foreach my $server (keys(%dompersonnel)) {
 5162:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5163:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5164:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5165:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5166:                         next if ($end && $end < $now);
 5167:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5168:                             $dompersonnel{$server}{$item};
 5169:                     }
 5170:                 }
 5171:             }
 5172:             if (ref($privileged{$dom}) eq 'HASH') {
 5173:                 foreach my $role (@{$roles}) {
 5174:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5175:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5176:                     } else {
 5177:                         my %hash = ();
 5178:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5179:                     }
 5180:                 }
 5181:             }
 5182:         }
 5183:     }
 5184:     return %privileged;
 5185: }
 5186: 
 5187: # -------------------------------------------------------- Get user privileges
 5188: 
 5189: sub rolesinit {
 5190:     my ($domain, $username) = @_;
 5191:     my %userroles = ('user.login.time' => time);
 5192:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5193: 
 5194:     # firstaccess and timerinterval are related to timed maps/resources. 
 5195:     # also, blocking can be triggered by an activating timer
 5196:     # it's saved in the user's %env.
 5197:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5198:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5199:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5200:         %timerintchk, %timerintenv);
 5201: 
 5202:     foreach my $key (keys(%firstaccess)) {
 5203:         my ($cid, $rest) = split(/\0/, $key);
 5204:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5205:     }
 5206: 
 5207:     foreach my $key (keys(%timerinterval)) {
 5208:         my ($cid,$rest) = split(/\0/,$key);
 5209:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5210:     }
 5211: 
 5212:     my %allroles=();
 5213:     my %allgroups=();
 5214: 
 5215:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5216:         my $role = $rolesdump{$area};
 5217:         $area =~ s/\_\w\w$//;
 5218: 
 5219:         my ($trole, $tend, $tstart, $group_privs);
 5220: 
 5221:         if ($role =~ /^cr/) {
 5222:         # Custom role, defined by a user 
 5223:         # e.g., user.role.cr/msu/smith/mynewrole
 5224:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5225:                 $trole = $1;
 5226:                 ($tend, $tstart) = split('_', $2);
 5227:             } else {
 5228:                 $trole = $role;
 5229:             }
 5230:         } elsif ($role =~ m|^gr/|) {
 5231:         # Role of member in a group, defined within a course/community
 5232:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5233:             ($trole, $tend, $tstart) = split(/_/, $role);
 5234:             next if $tstart eq '-1';
 5235:             ($trole, $group_privs) = split(/\//, $trole);
 5236:             $group_privs = &unescape($group_privs);
 5237:         } else {
 5238:         # Just a normal role, defined in roles.tab
 5239:             ($trole, $tend, $tstart) = split(/_/,$role);
 5240:         }
 5241: 
 5242:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5243:                  $username);
 5244:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5245: 
 5246:         # role expired or not available yet?
 5247:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5248:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5249: 
 5250:         next if $area eq '' or $trole eq '';
 5251: 
 5252:         my $spec = "$trole.$area";
 5253:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5254: 
 5255:         if ($trole =~ /^cr\//) {
 5256:         # Custom role, defined by a user
 5257:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5258:         } elsif ($trole eq 'gr') {
 5259:         # Role of a member in a group, defined within a course/community
 5260:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5261:             next;
 5262:         } else {
 5263:         # Normal role, defined in roles.tab
 5264:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5265:         }
 5266: 
 5267:         my $cid = $tdomain.'_'.$trest;
 5268:         unless ($firstaccchk{$cid}) {
 5269:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5270:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5271:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5272:                         $coursetimerstarts{$cid}{$item}; 
 5273:                 }
 5274:             }
 5275:             $firstaccchk{$cid} = 1;
 5276:         }
 5277:         unless ($timerintchk{$cid}) {
 5278:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5279:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5280:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5281:                        $coursetimerintervals{$cid}{$item};
 5282:                 }
 5283:             }
 5284:             $timerintchk{$cid} = 1;
 5285:         }
 5286:     }
 5287: 
 5288:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5289:         \%allroles, \%allgroups);
 5290:     $env{'user.adv'} = $userroles{'user.adv'};
 5291: 
 5292:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5293: }
 5294: 
 5295: sub set_arearole {
 5296:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5297:     unless ($nolog) {
 5298: # log the associated role with the area
 5299:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5300:     }
 5301:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5302: }
 5303: 
 5304: sub custom_roleprivs {
 5305:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5306:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5307:     my $homsvr = &homeserver($rauthor,$rdomain);
 5308:     if (&hostname($homsvr) ne '') {
 5309:         my ($rdummy,$roledef)=
 5310:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5311:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5312:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5313:             if (defined($syspriv)) {
 5314:                 if ($trest =~ /^$match_community$/) {
 5315:                     $syspriv =~ s/bre\&S//; 
 5316:                 }
 5317:                 $$allroles{'cm./'}.=':'.$syspriv;
 5318:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5319:             }
 5320:             if ($tdomain ne '') {
 5321:                 if (defined($dompriv)) {
 5322:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5323:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5324:                 }
 5325:                 if (($trest ne '') && (defined($coursepriv))) {
 5326:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5327:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5328:                 }
 5329:             }
 5330:         }
 5331:     }
 5332: }
 5333: 
 5334: sub group_roleprivs {
 5335:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5336:     my $access = 1;
 5337:     my $now = time;
 5338:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5339:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5340:     if ($access) {
 5341:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5342:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5343:     }
 5344: }
 5345: 
 5346: sub standard_roleprivs {
 5347:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5348:     if (defined($pr{$trole.':s'})) {
 5349:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5350:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5351:     }
 5352:     if ($tdomain ne '') {
 5353:         if (defined($pr{$trole.':d'})) {
 5354:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5355:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5356:         }
 5357:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5358:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5359:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5360:         }
 5361:     }
 5362: }
 5363: 
 5364: sub set_userprivs {
 5365:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5366:     my $author=0;
 5367:     my $adv=0;
 5368:     my %grouproles = ();
 5369:     if (keys(%{$allgroups}) > 0) {
 5370:         my @groupkeys; 
 5371:         foreach my $role (keys(%{$allroles})) {
 5372:             push(@groupkeys,$role);
 5373:         }
 5374:         if (ref($groups_roles) eq 'HASH') {
 5375:             foreach my $key (keys(%{$groups_roles})) {
 5376:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5377:                     push(@groupkeys,$key);
 5378:                 }
 5379:             }
 5380:         }
 5381:         if (@groupkeys > 0) {
 5382:             foreach my $role (@groupkeys) {
 5383:                 my ($trole,$area,$sec,$extendedarea);
 5384:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5385:                     $trole = $1;
 5386:                     $area = $2;
 5387:                     $sec = $3;
 5388:                     $extendedarea = $area.$sec;
 5389:                     if (exists($$allgroups{$area})) {
 5390:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5391:                             my $spec = $trole.'.'.$extendedarea;
 5392:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5393:                                                 $$allgroups{$area}{$group};
 5394:                         }
 5395:                     }
 5396:                 }
 5397:             }
 5398:         }
 5399:     }
 5400:     foreach my $group (keys(%grouproles)) {
 5401:         $$allroles{$group} = $grouproles{$group};
 5402:     }
 5403:     foreach my $role (keys(%{$allroles})) {
 5404:         my %thesepriv;
 5405:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5406:         foreach my $item (split(/:/,$$allroles{$role})) {
 5407:             if ($item ne '') {
 5408:                 my ($privilege,$restrictions)=split(/&/,$item);
 5409:                 if ($restrictions eq '') {
 5410:                     $thesepriv{$privilege}='F';
 5411:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5412:                     $thesepriv{$privilege}.=$restrictions;
 5413:                 }
 5414:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5415:             }
 5416:         }
 5417:         my $thesestr='';
 5418:         foreach my $priv (sort(keys(%thesepriv))) {
 5419: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5420: 	}
 5421:         $userroles->{'user.priv.'.$role} = $thesestr;
 5422:     }
 5423:     return ($author,$adv);
 5424: }
 5425: 
 5426: sub role_status {
 5427:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5428:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5429:         my ($one,$two) = split(m{\./},$rolekey,2);
 5430:         (undef,undef,$$role) = split(/\./,$one,3);
 5431:         unless (!defined($$role) || $$role eq '') {
 5432:             $$where = '/'.$two;
 5433:             $$trolecode=$$role.'.'.$$where;
 5434:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5435:             $$tstatus='is';
 5436:             if ($$tstart && $$tstart>$update) {
 5437:                 $$tstatus='future';
 5438:                 if ($$tstart<$now) {
 5439:                     if ($$tstart && $$tstart>$refresh) {
 5440:                         if (($$where ne '') && ($$role ne '')) {
 5441:                             my (%allroles,%allgroups,$group_privs,
 5442:                                 %groups_roles,@rolecodes);
 5443:                             my %userroles = (
 5444:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5445:                             );
 5446:                             @rolecodes = ('cm'); 
 5447:                             my $spec=$$role.'.'.$$where;
 5448:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5449:                             if ($$role =~ /^cr\//) {
 5450:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5451:                                 push(@rolecodes,'cr');
 5452:                             } elsif ($$role eq 'gr') {
 5453:                                 push(@rolecodes,$$role);
 5454:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5455:                                                     $env{'user.name'});
 5456:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5457:                                 (undef,my $group_privs) = split(/\//,$trole);
 5458:                                 $group_privs = &unescape($group_privs);
 5459:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5460:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5461:                                 &get_groups_roles($tdomain,$trest,
 5462:                                                   \%course_roles,\@rolecodes,
 5463:                                                   \%groups_roles);
 5464:                             } else {
 5465:                                 push(@rolecodes,$$role);
 5466:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5467:                             }
 5468:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5469:                             &appenv(\%userroles,\@rolecodes);
 5470:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5471:                         }
 5472:                     }
 5473:                     $$tstatus = 'is';
 5474:                 }
 5475:             }
 5476:             if ($$tend) {
 5477:                 if ($$tend<$update) {
 5478:                     $$tstatus='expired';
 5479:                 } elsif ($$tend<$now) {
 5480:                     $$tstatus='will_not';
 5481:                 }
 5482:             }
 5483:         }
 5484:     }
 5485: }
 5486: 
 5487: sub get_groups_roles {
 5488:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5489:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5490:                   (ref($rolecodes) eq 'ARRAY') && 
 5491:                   (ref($groups_roles) eq 'HASH')); 
 5492:     if (keys(%{$cdom_courseroles}) > 0) {
 5493:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5494:         if ($cdom ne '' && $cnum ne '') {
 5495:             foreach my $key (keys(%{$cdom_courseroles})) {
 5496:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5497:                     my $crsrole = $1;
 5498:                     my $crssec = $2;
 5499:                     if ($crsrole =~ /^cr/) {
 5500:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5501:                             push(@{$rolecodes},'cr');
 5502:                         }
 5503:                     } else {
 5504:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5505:                             push(@{$rolecodes},$crsrole);
 5506:                         }
 5507:                     }
 5508:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5509:                     if ($crssec ne '') {
 5510:                         $rolekey .= "/$crssec";
 5511:                     }
 5512:                     $rolekey .= './';
 5513:                     $groups_roles->{$rolekey} = $rolecodes;
 5514:                 }
 5515:             }
 5516:         }
 5517:     }
 5518:     return;
 5519: }
 5520: 
 5521: sub delete_env_groupprivs {
 5522:     my ($where,$courseroles,$possroles) = @_;
 5523:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5524:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5525:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5526:         %{$courseroles->{$udom}} =
 5527:             &get_my_roles('','','userroles',['active'],
 5528:                           $possroles,[$udom],1);
 5529:     }
 5530:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5531:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5532:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5533:             my $area = '/'.$cdom.'/'.$cnum;
 5534:             my $privkey = "user.priv.$crsrole.$area";
 5535:             if ($crssec ne '') {
 5536:                 $privkey .= '/'.$crssec;
 5537:             }
 5538:             $privkey .= ".$area/$group";
 5539:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5540:         }
 5541:     }
 5542:     return;
 5543: }
 5544: 
 5545: sub check_adhoc_privs {
 5546:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5547:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5548:     my $setprivs;
 5549:     if ($env{$cckey}) {
 5550:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5551:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5552:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5553:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5554:             $setprivs = 1;
 5555:         }
 5556:     } else {
 5557:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5558:         $setprivs = 1;
 5559:     }
 5560:     return $setprivs;
 5561: }
 5562: 
 5563: sub set_adhoc_privileges {
 5564: # role can be cc or ca
 5565:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5566:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5567:     my $spec = $role.'.'.$area;
 5568:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5569:                                   $env{'user.name'},1);
 5570:     my %ccrole = ();
 5571:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5572:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5573:     &appenv(\%userroles,[$role,'cm']);
 5574:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5575:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5576:         &appenv( {'request.role'        => $spec,
 5577:                   'request.role.domain' => $dcdom,
 5578:                   'request.course.sec'  => ''
 5579:                  }
 5580:                );
 5581:         my $tadv=0;
 5582:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5583:         &appenv({'request.role.adv'    => $tadv});
 5584:     }
 5585: }
 5586: 
 5587: # --------------------------------------------------------------- get interface
 5588: 
 5589: sub get {
 5590:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5591:    my $items='';
 5592:    foreach my $item (@$storearr) {
 5593:        $items.=&escape($item).'&';
 5594:    }
 5595:    $items=~s/\&$//;
 5596:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5597:    if (!$uname) { $uname=$env{'user.name'}; }
 5598:    my $uhome=&homeserver($uname,$udomain);
 5599: 
 5600:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5601:    my @pairs=split(/\&/,$rep);
 5602:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5603:      return @pairs;
 5604:    }
 5605:    my %returnhash=();
 5606:    my $i=0;
 5607:    foreach my $item (@$storearr) {
 5608:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5609:       $i++;
 5610:    }
 5611:    return %returnhash;
 5612: }
 5613: 
 5614: # --------------------------------------------------------------- del interface
 5615: 
 5616: sub del {
 5617:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5618:    my $items='';
 5619:    foreach my $item (@$storearr) {
 5620:        $items.=&escape($item).'&';
 5621:    }
 5622: 
 5623:    $items=~s/\&$//;
 5624:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5625:    if (!$uname) { $uname=$env{'user.name'}; }
 5626:    my $uhome=&homeserver($uname,$udomain);
 5627:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5628: }
 5629: 
 5630: # -------------------------------------------------------------- dump interface
 5631: 
 5632: sub unserialize {
 5633:     my ($rep, $escapedkeys) = @_;
 5634: 
 5635:     return {} if $rep =~ /^error/;
 5636: 
 5637:     my %returnhash=();
 5638: 	foreach my $item (split(/\&/,$rep)) {
 5639: 	    my ($key, $value) = split(/=/, $item, 2);
 5640: 	    $key = unescape($key) unless $escapedkeys;
 5641: 	    next if $key =~ /^error: 2 /;
 5642: 	    $returnhash{$key} = &thaw_unescape($value);
 5643: 	}
 5644:     #return %returnhash;
 5645:     return \%returnhash;
 5646: }        
 5647: 
 5648: # see Lond::dump_with_regexp
 5649: # if $escapedkeys hash keys won't get unescaped.
 5650: sub dump {
 5651:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5652:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5653:     if (!$uname) { $uname=$env{'user.name'}; }
 5654:     my $uhome=&homeserver($uname,$udomain);
 5655: 
 5656:     if ($regexp) {
 5657:         $regexp=&escape($regexp);
 5658:     } else {
 5659:         $regexp='.';
 5660:     }
 5661:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5662:         # user is hosted on this machine
 5663:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5664:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5665:         return %{unserialize($reply, $escapedkeys)};
 5666:     }
 5667:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5668:     my @pairs=split(/\&/,$rep);
 5669:     my %returnhash=();
 5670:     if (!($rep =~ /^error/ )) {
 5671: 	foreach my $item (@pairs) {
 5672: 	    my ($key,$value)=split(/=/,$item,2);
 5673:         $key = unescape($key) unless $escapedkeys;
 5674:         #$key = &unescape($key);
 5675: 	    next if ($key =~ /^error: 2 /);
 5676: 	    $returnhash{$key}=&thaw_unescape($value);
 5677: 	}
 5678:     }
 5679:     return %returnhash;
 5680: }
 5681: 
 5682: 
 5683: # --------------------------------------------------------- dumpstore interface
 5684: 
 5685: sub dumpstore {
 5686:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5687:    # same as dump but keys must be escaped. They may contain colon separated
 5688:    # lists of values that may themself contain colons (e.g. symbs).
 5689:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5690: }
 5691: 
 5692: # -------------------------------------------------------------- keys interface
 5693: 
 5694: sub getkeys {
 5695:    my ($namespace,$udomain,$uname)=@_;
 5696:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5697:    if (!$uname) { $uname=$env{'user.name'}; }
 5698:    my $uhome=&homeserver($uname,$udomain);
 5699:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5700:    my @keyarray=();
 5701:    foreach my $key (split(/\&/,$rep)) {
 5702:       next if ($key =~ /^error: 2 /);
 5703:       push(@keyarray,&unescape($key));
 5704:    }
 5705:    return @keyarray;
 5706: }
 5707: 
 5708: # --------------------------------------------------------------- currentdump
 5709: sub currentdump {
 5710:    my ($courseid,$sdom,$sname)=@_;
 5711:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5712:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5713:    $sname    = $env{'user.name'}         if (! defined($sname));
 5714:    my $uhome = &homeserver($sname,$sdom);
 5715:    my $rep;
 5716: 
 5717:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5718:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5719:                    $courseid)));
 5720:    } else {
 5721:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5722:    }
 5723: 
 5724:    return if ($rep =~ /^(error:|no_such_host)/);
 5725:    #
 5726:    my %returnhash=();
 5727:    #
 5728:    if ($rep eq "unknown_cmd") { 
 5729:        # an old lond will not know currentdump
 5730:        # Do a dump and make it look like a currentdump
 5731:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5732:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5733:        my %hash = @tmp;
 5734:        @tmp=();
 5735:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5736:    } else {
 5737:        my @pairs=split(/\&/,$rep);
 5738:        foreach my $pair (@pairs) {
 5739:            my ($key,$value)=split(/=/,$pair,2);
 5740:            my ($symb,$param) = split(/:/,$key);
 5741:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5742:                                                         &thaw_unescape($value);
 5743:        }
 5744:    }
 5745:    return %returnhash;
 5746: }
 5747: 
 5748: sub convert_dump_to_currentdump{
 5749:     my %hash = %{shift()};
 5750:     my %returnhash;
 5751:     # Code ripped from lond, essentially.  The only difference
 5752:     # here is the unescaping done by lonnet::dump().  Conceivably
 5753:     # we might run in to problems with parameter names =~ /^v\./
 5754:     while (my ($key,$value) = each(%hash)) {
 5755:         my ($v,$symb,$param) = split(/:/,$key);
 5756: 	$symb  = &unescape($symb);
 5757: 	$param = &unescape($param);
 5758:         next if ($v eq 'version' || $symb eq 'keys');
 5759:         next if (exists($returnhash{$symb}) &&
 5760:                  exists($returnhash{$symb}->{$param}) &&
 5761:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5762:         $returnhash{$symb}->{$param}=$value;
 5763:         $returnhash{$symb}->{'v.'.$param}=$v;
 5764:     }
 5765:     #
 5766:     # Remove all of the keys in the hashes which keep track of
 5767:     # the version of the parameter.
 5768:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5769:         # use a foreach because we are going to delete from the hash.
 5770:         foreach my $key (keys(%$param_hash)) {
 5771:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5772:         }
 5773:     }
 5774:     return \%returnhash;
 5775: }
 5776: 
 5777: # ------------------------------------------------------ critical inc interface
 5778: 
 5779: sub cinc {
 5780:     return &inc(@_,'critical');
 5781: }
 5782: 
 5783: # --------------------------------------------------------------- inc interface
 5784: 
 5785: sub inc {
 5786:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5787:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5788:     if (!$uname) { $uname=$env{'user.name'}; }
 5789:     my $uhome=&homeserver($uname,$udomain);
 5790:     my $items='';
 5791:     if (! ref($store)) {
 5792:         # got a single value, so use that instead
 5793:         $items = &escape($store).'=&';
 5794:     } elsif (ref($store) eq 'SCALAR') {
 5795:         $items = &escape($$store).'=&';        
 5796:     } elsif (ref($store) eq 'ARRAY') {
 5797:         $items = join('=&',map {&escape($_);} @{$store});
 5798:     } elsif (ref($store) eq 'HASH') {
 5799:         while (my($key,$value) = each(%{$store})) {
 5800:             $items.= &escape($key).'='.&escape($value).'&';
 5801:         }
 5802:     }
 5803:     $items=~s/\&$//;
 5804:     if ($critical) {
 5805: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5806:     } else {
 5807: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5808:     }
 5809: }
 5810: 
 5811: # --------------------------------------------------------------- put interface
 5812: 
 5813: sub put {
 5814:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5815:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5816:    if (!$uname) { $uname=$env{'user.name'}; }
 5817:    my $uhome=&homeserver($uname,$udomain);
 5818:    my $items='';
 5819:    foreach my $item (keys(%$storehash)) {
 5820:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5821:    }
 5822:    $items=~s/\&$//;
 5823:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5824: }
 5825: 
 5826: # ------------------------------------------------------------ newput interface
 5827: 
 5828: sub newput {
 5829:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5830:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5831:    if (!$uname) { $uname=$env{'user.name'}; }
 5832:    my $uhome=&homeserver($uname,$udomain);
 5833:    my $items='';
 5834:    foreach my $key (keys(%$storehash)) {
 5835:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5836:    }
 5837:    $items=~s/\&$//;
 5838:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5839: }
 5840: 
 5841: # ---------------------------------------------------------  putstore interface
 5842: 
 5843: sub putstore {
 5844:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 5845:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5846:    if (!$uname) { $uname=$env{'user.name'}; }
 5847:    my $uhome=&homeserver($uname,$udomain);
 5848:    my $items='';
 5849:    foreach my $key (keys(%$storehash)) {
 5850:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5851:    }
 5852:    $items=~s/\&$//;
 5853:    my $esc_symb=&escape($symb);
 5854:    my $esc_v=&escape($version);
 5855:    my $reply =
 5856:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5857: 	      $uhome);
 5858:    if (($tolog) && ($reply eq 'ok')) {
 5859:        my $namevalue='';
 5860:        foreach my $key (keys(%{$storehash})) {
 5861:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5862:        }
 5863:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 5864:                      '&host='.&escape($perlvar{'lonHostID'}).
 5865:                      '&version='.$esc_v.
 5866:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 5867:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 5868:    }
 5869:    if ($reply eq 'unknown_cmd') {
 5870:        # gfall back to way things use to be done
 5871:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5872: 			    $uname);
 5873:    }
 5874:    return $reply;
 5875: }
 5876: 
 5877: sub old_putstore {
 5878:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5879:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5880:     if (!$uname) { $uname=$env{'user.name'}; }
 5881:     my $uhome=&homeserver($uname,$udomain);
 5882:     my %newstorehash;
 5883:     foreach my $item (keys(%$storehash)) {
 5884: 	my $key = $version.':'.&escape($symb).':'.$item;
 5885: 	$newstorehash{$key} = $storehash->{$item};
 5886:     }
 5887:     my $items='';
 5888:     my %allitems = ();
 5889:     foreach my $item (keys(%newstorehash)) {
 5890: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5891: 	    my $key = $1.':keys:'.$2;
 5892: 	    $allitems{$key} .= $3.':';
 5893: 	}
 5894: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5895:     }
 5896:     foreach my $item (keys(%allitems)) {
 5897: 	$allitems{$item} =~ s/\:$//;
 5898: 	$items.= $item.'='.$allitems{$item}.'&';
 5899:     }
 5900:     $items=~s/\&$//;
 5901:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5902: }
 5903: 
 5904: # ------------------------------------------------------ critical put interface
 5905: 
 5906: sub cput {
 5907:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5908:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5909:    if (!$uname) { $uname=$env{'user.name'}; }
 5910:    my $uhome=&homeserver($uname,$udomain);
 5911:    my $items='';
 5912:    foreach my $item (keys(%$storehash)) {
 5913:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5914:    }
 5915:    $items=~s/\&$//;
 5916:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5917: }
 5918: 
 5919: # -------------------------------------------------------------- eget interface
 5920: 
 5921: sub eget {
 5922:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5923:    my $items='';
 5924:    foreach my $item (@$storearr) {
 5925:        $items.=&escape($item).'&';
 5926:    }
 5927:    $items=~s/\&$//;
 5928:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5929:    if (!$uname) { $uname=$env{'user.name'}; }
 5930:    my $uhome=&homeserver($uname,$udomain);
 5931:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5932:    my @pairs=split(/\&/,$rep);
 5933:    my %returnhash=();
 5934:    my $i=0;
 5935:    foreach my $item (@$storearr) {
 5936:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5937:       $i++;
 5938:    }
 5939:    return %returnhash;
 5940: }
 5941: 
 5942: # ------------------------------------------------------------ tmpput interface
 5943: sub tmpput {
 5944:     my ($storehash,$server,$context)=@_;
 5945:     my $items='';
 5946:     foreach my $item (keys(%$storehash)) {
 5947: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5948:     }
 5949:     $items=~s/\&$//;
 5950:     if (defined($context)) {
 5951:         $items .= ':'.&escape($context);
 5952:     }
 5953:     return &reply("tmpput:$items",$server);
 5954: }
 5955: 
 5956: # ------------------------------------------------------------ tmpget interface
 5957: sub tmpget {
 5958:     my ($token,$server)=@_;
 5959:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5960:     my $rep=&reply("tmpget:$token",$server);
 5961:     my %returnhash;
 5962:     foreach my $item (split(/\&/,$rep)) {
 5963: 	my ($key,$value)=split(/=/,$item);
 5964:         next if ($key =~ /^error: 2 /);
 5965: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5966:     }
 5967:     return %returnhash;
 5968: }
 5969: 
 5970: # ------------------------------------------------------------ tmpdel interface
 5971: sub tmpdel {
 5972:     my ($token,$server)=@_;
 5973:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5974:     return &reply("tmpdel:$token",$server);
 5975: }
 5976: 
 5977: # ------------------------------------------------------------ get_timebased_id 
 5978: 
 5979: sub get_timebased_id {
 5980:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5981:         $maxtries) = @_;
 5982:     my ($newid,$error,$dellock);
 5983:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5984:         return ('','ok','invalid call to get suffix');
 5985:     }
 5986: 
 5987: # set defaults for any optional args for which values were not supplied
 5988:     if ($who eq '') {
 5989:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5990:     }
 5991:     if (!$locktries) {
 5992:         $locktries = 3;
 5993:     }
 5994:     if (!$maxtries) {
 5995:         $maxtries = 10;
 5996:     }
 5997:     
 5998:     if (($cdom eq '') || ($cnum eq '')) {
 5999:         if ($env{'request.course.id'}) {
 6000:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6001:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6002:         }
 6003:         if (($cdom eq '') || ($cnum eq '')) {
 6004:             return ('','ok','call to get suffix not in course context');
 6005:         }
 6006:     }
 6007: 
 6008: # construct locking item
 6009:     my $lockhash = {
 6010:                       $prefix."\0".'locked_'.$keyid => $who,
 6011:                    };
 6012:     my $tries = 0;
 6013: 
 6014: # attempt to get lock on nohist_$namespace file
 6015:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6016:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6017:         $tries ++;
 6018:         sleep 1;
 6019:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6020:     }
 6021: 
 6022: # attempt to get unique identifier, based on current timestamp
 6023:     if ($gotlock eq 'ok') {
 6024:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6025:         my $id = time;
 6026:         $newid = $id;
 6027:         if ($idtype eq 'addcode') {
 6028:             $newid .= &sixnum_code();
 6029:         }
 6030:         my $idtries = 0;
 6031:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6032:             if ($idtype eq 'concat') {
 6033:                 $newid = $id.$idtries;
 6034:             } elsif ($idtype eq 'addcode') {
 6035:                 $newid = $newid.&sixnum_code();
 6036:             } else {
 6037:                 $newid ++;
 6038:             }
 6039:             $idtries ++;
 6040:         }
 6041:         if (!exists($inuse{$prefix."\0".$newid})) {
 6042:             my %new_item =  (
 6043:                               $prefix."\0".$newid => $who,
 6044:                             );
 6045:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6046:                                                  $cdom,$cnum);
 6047:             if ($putresult ne 'ok') {
 6048:                 undef($newid);
 6049:                 $error = 'error saving new item: '.$putresult;
 6050:             }
 6051:         } else {
 6052:              undef($newid);
 6053:              $error = ('error: no unique suffix available for the new item ');
 6054:         }
 6055: #  remove lock
 6056:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6057:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6058:     } else {
 6059:         $error = "error: could not obtain lockfile\n";
 6060:         $dellock = 'ok';
 6061:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6062:             $dellock = 'nolock';
 6063:         }
 6064:     }
 6065:     return ($newid,$dellock,$error);
 6066: }
 6067: 
 6068: sub sixnum_code {
 6069:     my $code;
 6070:     for (0..6) {
 6071:         $code .= int( rand(9) );
 6072:     }
 6073:     return $code;
 6074: }
 6075: 
 6076: # -------------------------------------------------- portfolio access checking
 6077: 
 6078: sub portfolio_access {
 6079:     my ($requrl,$clientip) = @_;
 6080:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6081:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6082:     if ($result) {
 6083:         my %setters;
 6084:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6085:             my ($startblock,$endblock) =
 6086:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6087:             if ($startblock && $endblock) {
 6088:                 return 'B';
 6089:             }
 6090:         } else {
 6091:             my ($startblock,$endblock) =
 6092:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6093:             if ($startblock && $endblock) {
 6094:                 return 'B';
 6095:             }
 6096:         }
 6097:     }
 6098:     if ($result eq 'ok') {
 6099:        return 'F';
 6100:     } elsif ($result =~ /^[^:]+:guest_/) {
 6101:        return 'A';
 6102:     }
 6103:     return '';
 6104: }
 6105: 
 6106: sub get_portfolio_access {
 6107:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6108: 
 6109:     if (!ref($access_hash)) {
 6110: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6111: 	my %access_controls = &get_access_controls($current_perms,$group,
 6112: 						   $file_name);
 6113: 	$access_hash = $access_controls{$file_name};
 6114:     }
 6115: 
 6116:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6117:     my $now = time;
 6118:     if (ref($access_hash) eq 'HASH') {
 6119:         foreach my $key (keys(%{$access_hash})) {
 6120:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6121:             if ($start > $now) {
 6122:                 next;
 6123:             }
 6124:             if ($end && $end<$now) {
 6125:                 next;
 6126:             }
 6127:             if ($scope eq 'public') {
 6128:                 $public = $key;
 6129:                 last;
 6130:             } elsif ($scope eq 'guest') {
 6131:                 $guest = $key;
 6132:             } elsif ($scope eq 'domains') {
 6133:                 push(@domains,$key);
 6134:             } elsif ($scope eq 'users') {
 6135:                 push(@users,$key);
 6136:             } elsif ($scope eq 'course') {
 6137:                 push(@courses,$key);
 6138:             } elsif ($scope eq 'group') {
 6139:                 push(@groups,$key);
 6140:             } elsif ($scope eq 'ip') {
 6141:                 push(@ips,$key);
 6142:             }
 6143:         }
 6144:         if ($public) {
 6145:             return 'ok';
 6146:         } elsif (@ips > 0) {
 6147:             my $allowed;
 6148:             foreach my $ipkey (@ips) {
 6149:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6150:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6151:                         $allowed = 1;
 6152:                         last; 
 6153:                     }
 6154:                 }
 6155:             }
 6156:             if ($allowed) {
 6157:                 return 'ok';
 6158:             }
 6159:         }
 6160:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6161:             if ($guest) {
 6162:                 return $guest;
 6163:             }
 6164:         } else {
 6165:             if (@domains > 0) {
 6166:                 foreach my $domkey (@domains) {
 6167:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6168:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6169:                             return 'ok';
 6170:                         }
 6171:                     }
 6172:                 }
 6173:             }
 6174:             if (@users > 0) {
 6175:                 foreach my $userkey (@users) {
 6176:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6177:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6178:                             if (ref($item) eq 'HASH') {
 6179:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6180:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6181:                                     return 'ok';
 6182:                                 }
 6183:                             }
 6184:                         }
 6185:                     } 
 6186:                 }
 6187:             }
 6188:             my %roleshash;
 6189:             my @courses_and_groups = @courses;
 6190:             push(@courses_and_groups,@groups); 
 6191:             if (@courses_and_groups > 0) {
 6192:                 my (%allgroups,%allroles); 
 6193:                 my ($start,$end,$role,$sec,$group);
 6194:                 foreach my $envkey (%env) {
 6195:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6196:                         my $cid = $2.'_'.$3; 
 6197:                         if ($1 eq 'gr') {
 6198:                             $group = $4;
 6199:                             $allgroups{$cid}{$group} = $env{$envkey};
 6200:                         } else {
 6201:                             if ($4 eq '') {
 6202:                                 $sec = 'none';
 6203:                             } else {
 6204:                                 $sec = $4;
 6205:                             }
 6206:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6207:                         }
 6208:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6209:                         my $cid = $2.'_'.$3;
 6210:                         if ($4 eq '') {
 6211:                             $sec = 'none';
 6212:                         } else {
 6213:                             $sec = $4;
 6214:                         }
 6215:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6216:                     }
 6217:                 }
 6218:                 if (keys(%allroles) == 0) {
 6219:                     return;
 6220:                 }
 6221:                 foreach my $key (@courses_and_groups) {
 6222:                     my %content = %{$$access_hash{$key}};
 6223:                     my $cnum = $content{'number'};
 6224:                     my $cdom = $content{'domain'};
 6225:                     my $cid = $cdom.'_'.$cnum;
 6226:                     if (!exists($allroles{$cid})) {
 6227:                         next;
 6228:                     }    
 6229:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6230:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6231:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6232:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6233:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6234:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6235:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6236:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6237:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6238:                                         if (grep/^all$/,@sections) {
 6239:                                             return 'ok';
 6240:                                         } else {
 6241:                                             if (grep/^$sec$/,@sections) {
 6242:                                                 return 'ok';
 6243:                                             }
 6244:                                         }
 6245:                                     }
 6246:                                 }
 6247:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6248:                                     if (grep/^none$/,@groups) {
 6249:                                         return 'ok';
 6250:                                     }
 6251:                                 } else {
 6252:                                     if (grep/^all$/,@groups) {
 6253:                                         return 'ok';
 6254:                                     } 
 6255:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6256:                                         if (grep/^$group$/,@groups) {
 6257:                                             return 'ok';
 6258:                                         }
 6259:                                     }
 6260:                                 } 
 6261:                             }
 6262:                         }
 6263:                     }
 6264:                 }
 6265:             }
 6266:             if ($guest) {
 6267:                 return $guest;
 6268:             }
 6269:         }
 6270:     }
 6271:     return;
 6272: }
 6273: 
 6274: sub course_group_datechecker {
 6275:     my ($dates,$now,$status) = @_;
 6276:     my ($start,$end) = split(/\./,$dates);
 6277:     if (!$start && !$end) {
 6278:         return 'ok';
 6279:     }
 6280:     if (grep/^active$/,@{$status}) {
 6281:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6282:             return 'ok';
 6283:         }
 6284:     }
 6285:     if (grep/^previous$/,@{$status}) {
 6286:         if ($end > $now ) {
 6287:             return 'ok';
 6288:         }
 6289:     }
 6290:     if (grep/^future$/,@{$status}) {
 6291:         if ($start > $now) {
 6292:             return 'ok';
 6293:         }
 6294:     }
 6295:     return; 
 6296: }
 6297: 
 6298: sub parse_portfolio_url {
 6299:     my ($url) = @_;
 6300: 
 6301:     my ($type,$udom,$unum,$group,$file_name);
 6302:     
 6303:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6304: 	$type = 1;
 6305:         $udom = $1;
 6306:         $unum = $2;
 6307:         $file_name = $3;
 6308:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6309: 	$type = 2;
 6310:         $udom = $1;
 6311:         $unum = $2;
 6312:         $group = $3;
 6313:         $file_name = $3.'/'.$4;
 6314:     }
 6315:     if (wantarray) {
 6316: 	return ($type,$udom,$unum,$file_name,$group);
 6317:     }
 6318:     return $type;
 6319: }
 6320: 
 6321: sub is_portfolio_url {
 6322:     my ($url) = @_;
 6323:     return scalar(&parse_portfolio_url($url));
 6324: }
 6325: 
 6326: sub is_portfolio_file {
 6327:     my ($file) = @_;
 6328:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6329:         return 1;
 6330:     }
 6331:     return;
 6332: }
 6333: 
 6334: sub usertools_access {
 6335:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6336:     my ($access,%tools);
 6337:     if ($context eq '') {
 6338:         $context = 'tools';
 6339:     }
 6340:     if ($context eq 'requestcourses') {
 6341:         %tools = (
 6342:                       official   => 1,
 6343:                       unofficial => 1,
 6344:                       community  => 1,
 6345:                       textbook   => 1,
 6346:                  );
 6347:     } elsif ($context eq 'requestauthor') {
 6348:         %tools = (
 6349:                       requestauthor => 1,
 6350:                  );
 6351:     } else {
 6352:         %tools = (
 6353:                       aboutme   => 1,
 6354:                       blog      => 1,
 6355:                       webdav    => 1,
 6356:                       portfolio => 1,
 6357:                  );
 6358:     }
 6359:     return if (!defined($tools{$tool}));
 6360: 
 6361:     if (($udom eq '') || ($uname eq '')) {
 6362:         $udom = $env{'user.domain'};
 6363:         $uname = $env{'user.name'};
 6364:     }
 6365: 
 6366:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6367:         if ($action ne 'reload') {
 6368:             if ($context eq 'requestcourses') {
 6369:                 return $env{'environment.canrequest.'.$tool};
 6370:             } elsif ($context eq 'requestauthor') {
 6371:                 return $env{'environment.canrequest.author'};
 6372:             } else {
 6373:                 return $env{'environment.availabletools.'.$tool};
 6374:             }
 6375:         }
 6376:     }
 6377: 
 6378:     my ($toolstatus,$inststatus,$envkey);
 6379:     if ($context eq 'requestauthor') {
 6380:         $envkey = $context; 
 6381:     } else {
 6382:         $envkey = $context.'.'.$tool;
 6383:     }
 6384: 
 6385:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6386:          ($action ne 'reload')) {
 6387:         $toolstatus = $env{'environment.'.$envkey};
 6388:         $inststatus = $env{'environment.inststatus'};
 6389:     } else {
 6390:         if (ref($userenvref) eq 'HASH') {
 6391:             $toolstatus = $userenvref->{$envkey};
 6392:             $inststatus = $userenvref->{'inststatus'};
 6393:         } else {
 6394:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6395:             $toolstatus = $userenv{$envkey};
 6396:             $inststatus = $userenv{'inststatus'};
 6397:         }
 6398:     }
 6399: 
 6400:     if ($toolstatus ne '') {
 6401:         if ($toolstatus) {
 6402:             $access = 1;
 6403:         } else {
 6404:             $access = 0;
 6405:         }
 6406:         return $access;
 6407:     }
 6408: 
 6409:     my ($is_adv,%domdef);
 6410:     if (ref($is_advref) eq 'HASH') {
 6411:         $is_adv = $is_advref->{'is_adv'};
 6412:     } else {
 6413:         $is_adv = &is_advanced_user($udom,$uname);
 6414:     }
 6415:     if (ref($domdefref) eq 'HASH') {
 6416:         %domdef = %{$domdefref};
 6417:     } else {
 6418:         %domdef = &get_domain_defaults($udom);
 6419:     }
 6420:     if (ref($domdef{$tool}) eq 'HASH') {
 6421:         if ($is_adv) {
 6422:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6423:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6424:                     $access = 1;
 6425:                 } else {
 6426:                     $access = 0;
 6427:                 }
 6428:                 return $access;
 6429:             }
 6430:         }
 6431:         if ($inststatus ne '') {
 6432:             my ($hasaccess,$hasnoaccess);
 6433:             foreach my $affiliation (split(/:/,$inststatus)) {
 6434:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6435:                     if ($domdef{$tool}{$affiliation}) {
 6436:                         $hasaccess = 1;
 6437:                     } else {
 6438:                         $hasnoaccess = 1;
 6439:                     }
 6440:                 }
 6441:             }
 6442:             if ($hasaccess || $hasnoaccess) {
 6443:                 if ($hasaccess) {
 6444:                     $access = 1;
 6445:                 } elsif ($hasnoaccess) {
 6446:                     $access = 0; 
 6447:                 }
 6448:                 return $access;
 6449:             }
 6450:         } else {
 6451:             if ($domdef{$tool}{'default'} ne '') {
 6452:                 if ($domdef{$tool}{'default'}) {
 6453:                     $access = 1;
 6454:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6455:                     $access = 0;
 6456:                 }
 6457:                 return $access;
 6458:             }
 6459:         }
 6460:     } else {
 6461:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6462:             $access = 1;
 6463:         } else {
 6464:             $access = 0;
 6465:         }
 6466:         return $access;
 6467:     }
 6468: }
 6469: 
 6470: sub is_course_owner {
 6471:     my ($cdom,$cnum,$udom,$uname) = @_;
 6472:     if (($udom eq '') || ($uname eq '')) {
 6473:         $udom = $env{'user.domain'};
 6474:         $uname = $env{'user.name'};
 6475:     }
 6476:     unless (($udom eq '') || ($uname eq '')) {
 6477:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6478:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6479:                 return 1;
 6480:             } else {
 6481:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6482:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6483:                     return 1;
 6484:                 }
 6485:             }
 6486:         }
 6487:     }
 6488:     return;
 6489: }
 6490: 
 6491: sub is_advanced_user {
 6492:     my ($udom,$uname) = @_;
 6493:     if ($udom ne '' && $uname ne '') {
 6494:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6495:             if (wantarray) {
 6496:                 return ($env{'user.adv'},$env{'user.author'});
 6497:             } else {
 6498:                 return $env{'user.adv'};
 6499:             }
 6500:         }
 6501:     }
 6502:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6503:     my %allroles;
 6504:     my ($is_adv,$is_author);
 6505:     foreach my $role (keys(%roleshash)) {
 6506:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6507:         my $area = '/'.$tdomain.'/'.$trest;
 6508:         if ($sec ne '') {
 6509:             $area .= '/'.$sec;
 6510:         }
 6511:         if (($area ne '') && ($trole ne '')) {
 6512:             my $spec=$trole.'.'.$area;
 6513:             if ($trole =~ /^cr\//) {
 6514:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6515:             } elsif ($trole ne 'gr') {
 6516:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6517:             }
 6518:             if ($trole eq 'au') {
 6519:                 $is_author = 1;
 6520:             }
 6521:         }
 6522:     }
 6523:     foreach my $role (keys(%allroles)) {
 6524:         last if ($is_adv);
 6525:         foreach my $item (split(/:/,$allroles{$role})) {
 6526:             if ($item ne '') {
 6527:                 my ($privilege,$restrictions)=split(/&/,$item);
 6528:                 if ($privilege eq 'adv') {
 6529:                     $is_adv = 1;
 6530:                     last;
 6531:                 }
 6532:             }
 6533:         }
 6534:     }
 6535:     if (wantarray) {
 6536:         return ($is_adv,$is_author);
 6537:     }
 6538:     return $is_adv;
 6539: }
 6540: 
 6541: sub check_can_request {
 6542:     my ($dom,$can_request,$request_domains) = @_;
 6543:     my $canreq = 0;
 6544:     my ($types,$typename) = &Apache::loncommon::course_types();
 6545:     my @options = ('approval','validate','autolimit');
 6546:     my $optregex = join('|',@options);
 6547:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6548:         foreach my $type (@{$types}) {
 6549:             if (&usertools_access($env{'user.name'},
 6550:                                   $env{'user.domain'},
 6551:                                   $type,undef,'requestcourses')) {
 6552:                 $canreq ++;
 6553:                 if (ref($request_domains) eq 'HASH') {
 6554:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6555:                 }
 6556:                 if ($dom eq $env{'user.domain'}) {
 6557:                     $can_request->{$type} = 1;
 6558:                 }
 6559:             }
 6560:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6561:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6562:                 if (@curr > 0) {
 6563:                     foreach my $item (@curr) {
 6564:                         if (ref($request_domains) eq 'HASH') {
 6565:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6566:                             if ($otherdom ne '') {
 6567:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6568:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6569:                                         push(@{$request_domains->{$type}},$otherdom);
 6570:                                     }
 6571:                                 } else {
 6572:                                     push(@{$request_domains->{$type}},$otherdom);
 6573:                                 }
 6574:                             }
 6575:                         }
 6576:                     }
 6577:                     unless($dom eq $env{'user.domain'}) {
 6578:                         $canreq ++;
 6579:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6580:                             $can_request->{$type} = 1;
 6581:                         }
 6582:                     }
 6583:                 }
 6584:             }
 6585:         }
 6586:     }
 6587:     return $canreq;
 6588: }
 6589: 
 6590: # ---------------------------------------------- Custom access rule evaluation
 6591: 
 6592: sub customaccess {
 6593:     my ($priv,$uri)=@_;
 6594:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6595:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6596:     $udom = &LONCAPA::clean_domain($udom);
 6597:     $ucrs = &LONCAPA::clean_username($ucrs);
 6598:     my $access=0;
 6599:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6600: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6601: 	if ($type eq 'user') {
 6602: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6603: 		my ($tdom,$tuname)=split(m{/},$scope);
 6604: 		if ($tdom) {
 6605: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6606: 		}
 6607: 		if ($tuname) {
 6608: 		    if ($tuname ne $env{'user.name'}) { next; }
 6609: 		}
 6610: 		$access=($effect eq 'allow');
 6611: 		last;
 6612: 	    }
 6613: 	} else {
 6614: 	    if ($role) {
 6615: 		if ($role ne $urole) { next; }
 6616: 	    }
 6617: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6618: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6619: 		if ($tdom) {
 6620: 		    if ($tdom ne $udom) { next; }
 6621: 		}
 6622: 		if ($tcrs) {
 6623: 		    if ($tcrs ne $ucrs) { next; }
 6624: 		}
 6625: 		if ($tsec) {
 6626: 		    if ($tsec ne $usec) { next; }
 6627: 		}
 6628: 		$access=($effect eq 'allow');
 6629: 		last;
 6630: 	    }
 6631: 	    if ($realm eq '' && $role eq '') {
 6632: 		$access=($effect eq 'allow');
 6633: 	    }
 6634: 	}
 6635:     }
 6636:     return $access;
 6637: }
 6638: 
 6639: # ------------------------------------------------- Check for a user privilege
 6640: 
 6641: sub allowed {
 6642:     my ($priv,$uri,$symb,$role,$clientip)=@_;
 6643:     my $ver_orguri=$uri;
 6644:     $uri=&deversion($uri);
 6645:     my $orguri=$uri;
 6646:     $uri=&declutter($uri);
 6647: 
 6648:     if ($priv eq 'evb') {
 6649: # Evade communication block restrictions for specified role in a course
 6650:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6651:             return $1;
 6652:         } else {
 6653:             return;
 6654:         }
 6655:     }
 6656: 
 6657:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6658: # Free bre access to adm and meta resources
 6659:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6660: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6661: 	&& ($priv eq 'bre')) {
 6662: 	return 'F';
 6663:     }
 6664: 
 6665: # Free bre access to user's own portfolio contents
 6666:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6667:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6668: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6669:         my %setters;
 6670:         my ($startblock,$endblock) = 
 6671:             &Apache::loncommon::blockcheck(\%setters,'port');
 6672:         if ($startblock && $endblock) {
 6673:             return 'B';
 6674:         } else {
 6675:             return 'F';
 6676:         }
 6677:     }
 6678: 
 6679: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6680:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6681:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6682:         if (exists($env{'request.course.id'})) {
 6683:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6684:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6685:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6686:                 my $courseprivid=$env{'request.course.id'};
 6687:                 $courseprivid=~s/\_/\//;
 6688:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6689:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6690:                     return $1; 
 6691:                 } else {
 6692:                     if ($env{'request.course.sec'}) {
 6693:                         $courseprivid.='/'.$env{'request.course.sec'};
 6694:                     }
 6695:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6696:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6697:                         return $2;
 6698:                     }
 6699:                 }
 6700:             }
 6701:         }
 6702:     }
 6703: 
 6704: # Free bre to public access
 6705: 
 6706:     if ($priv eq 'bre') {
 6707:         my $copyright=&metadata($uri,'copyright');
 6708: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6709:            return 'F'; 
 6710:         }
 6711:         if ($copyright eq 'priv') {
 6712:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6713: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6714: 		return '';
 6715:             }
 6716:         }
 6717:         if ($copyright eq 'domain') {
 6718:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6719: 	    unless (($env{'user.domain'} eq $1) ||
 6720:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6721: 		return '';
 6722:             }
 6723:         }
 6724:         if ($env{'request.role'}=~ /li\.\//) {
 6725:             # Library role, so allow browsing of resources in this domain.
 6726:             return 'F';
 6727:         }
 6728:         if ($copyright eq 'custom') {
 6729: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6730:         }
 6731:     }
 6732:     # Domain coordinator is trying to create a course
 6733:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6734:         # uri is the requested domain in this case.
 6735:         # comparison to 'request.role.domain' shows if the user has selected
 6736:         # a role of dc for the domain in question.
 6737:         return 'F' if ($uri eq $env{'request.role.domain'});
 6738:     }
 6739: 
 6740:     my $thisallowed='';
 6741:     my $statecond=0;
 6742:     my $courseprivid='';
 6743: 
 6744:     my $ownaccess;
 6745:     # Community Coordinator or Assistant Co-author browsing resource space.
 6746:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6747:         if ($uri eq '') {
 6748:             $ownaccess = 1;
 6749:         } else {
 6750:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6751:                 my $udom = $env{'user.domain'};
 6752:                 my $uname = $env{'user.name'};
 6753:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6754:                     $ownaccess = 1;
 6755:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6756:                     unless ($uri =~ m{\.\./}) {
 6757:                         $ownaccess = 1;
 6758:                     }
 6759:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6760:                     my $now = time;
 6761:                     if ($uri =~ m{^([^/]+)/?$}) {
 6762:                         my $adom = $1;
 6763:                         foreach my $key (keys(%env)) {
 6764:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6765:                                 my ($start,$end) = split('.',$env{$key});
 6766:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6767:                                     $ownaccess = 1;
 6768:                                     last;
 6769:                                 }
 6770:                             }
 6771:                         }
 6772:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6773:                         my $adom = $1;
 6774:                         my $aname = $2;
 6775:                         foreach my $role ('ca','aa') { 
 6776:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6777:                                 my ($start,$end) =
 6778:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6779:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6780:                                     $ownaccess = 1;
 6781:                                     last;
 6782:                                 }
 6783:                             }
 6784:                         }
 6785:                     }
 6786:                 }
 6787:             }
 6788:         }
 6789:     }
 6790: 
 6791: # Course
 6792: 
 6793:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6794:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6795:             $thisallowed.=$1;
 6796:         }
 6797:     }
 6798: 
 6799: # Domain
 6800: 
 6801:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6802:        =~/\Q$priv\E\&([^\:]*)/) {
 6803:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6804:             $thisallowed.=$1;
 6805:         }
 6806:     }
 6807: 
 6808: # User who is not author or co-author might still be able to edit
 6809: # resource of an author in the domain (e.g., if Domain Coordinator).
 6810:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6811:         (&allowed('mdc',$env{'request.course.id'}))) {
 6812:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6813:             $thisallowed.=$1;
 6814:         }
 6815:     }
 6816: 
 6817: # Course: uri itself is a course
 6818:     my $courseuri=$uri;
 6819:     $courseuri=~s/\_(\d)/\/$1/;
 6820:     $courseuri=~s/^([^\/])/\/$1/;
 6821: 
 6822:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6823:        =~/\Q$priv\E\&([^\:]*)/) {
 6824:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6825:             $thisallowed.=$1;
 6826:         }
 6827:     }
 6828: 
 6829: # URI is an uploaded document for this course, default permissions don't matter
 6830: # not allowing 'edit' access (editupload) to uploaded course docs
 6831:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6832: 	$thisallowed='';
 6833:         my ($match)=&is_on_map($uri);
 6834:         if ($match) {
 6835:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6836:                   =~/\Q$priv\E\&([^\:]*)/) {
 6837:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6838:                 if (@blockers > 0) {
 6839:                     $thisallowed = 'B';
 6840:                 } else {
 6841:                     $thisallowed.=$1;
 6842:                 }
 6843:             }
 6844:         } else {
 6845:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6846:             if ($refuri) {
 6847:                 if ($refuri =~ m|^/adm/|) {
 6848:                     $thisallowed='F';
 6849:                 } else {
 6850:                     $refuri=&declutter($refuri);
 6851:                     my ($match) = &is_on_map($refuri);
 6852:                     if ($match) {
 6853:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6854:                         if (@blockers > 0) {
 6855:                             $thisallowed = 'B';
 6856:                         } else {
 6857:                             $thisallowed='F';
 6858:                         }
 6859:                     }
 6860:                 }
 6861:             }
 6862:         }
 6863:     }
 6864: 
 6865:     if ($priv eq 'bre'
 6866: 	&& $thisallowed ne 'F' 
 6867: 	&& $thisallowed ne '2'
 6868: 	&& &is_portfolio_url($uri)) {
 6869: 	$thisallowed = &portfolio_access($uri,$clientip);
 6870:     }
 6871: 
 6872: # Full access at system, domain or course-wide level? Exit.
 6873:     if ($thisallowed=~/F/) {
 6874: 	return 'F';
 6875:     }
 6876: 
 6877: # If this is generating or modifying users, exit with special codes
 6878: 
 6879:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6880: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6881: 	    my ($audom,$auname)=split('/',$uri);
 6882: # no author name given, so this just checks on the general right to make a co-author in this domain
 6883: 	    unless ($auname) { return $thisallowed; }
 6884: # an author name is given, so we are about to actually make a co-author for a certain account
 6885: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6886: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6887: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6888: 	}
 6889: 	return $thisallowed;
 6890:     }
 6891: #
 6892: # Gathered so far: system, domain and course wide privileges
 6893: #
 6894: # Course: See if uri or referer is an individual resource that is part of 
 6895: # the course
 6896: 
 6897:     if ($env{'request.course.id'}) {
 6898: 
 6899:        $courseprivid=$env{'request.course.id'};
 6900:        if ($env{'request.course.sec'}) {
 6901:           $courseprivid.='/'.$env{'request.course.sec'};
 6902:        }
 6903:        $courseprivid=~s/\_/\//;
 6904:        my $checkreferer=1;
 6905:        my ($match,$cond)=&is_on_map($uri);
 6906:        if ($match) {
 6907:            $statecond=$cond;
 6908:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6909:                =~/\Q$priv\E\&([^\:]*)/) {
 6910:                my $value = $1;
 6911:                if ($priv eq 'bre') {
 6912:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6913:                    if (@blockers > 0) {
 6914:                        $thisallowed = 'B';
 6915:                    } else {
 6916:                        $thisallowed.=$value;
 6917:                    }
 6918:                } else {
 6919:                    $thisallowed.=$value;
 6920:                }
 6921:                $checkreferer=0;
 6922:            }
 6923:        }
 6924:        
 6925:        if ($checkreferer) {
 6926: 	  my $refuri=$env{'httpref.'.$orguri};
 6927:             unless ($refuri) {
 6928:                 foreach my $key (keys(%env)) {
 6929: 		    if ($key=~/^httpref\..*\*/) {
 6930: 			my $pattern=$key;
 6931:                         $pattern=~s/^httpref\.\/res\///;
 6932:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6933:                         $pattern=~s/\//\\\//g;
 6934:                         if ($orguri=~/$pattern/) {
 6935: 			    $refuri=$env{$key};
 6936:                         }
 6937:                     }
 6938:                 }
 6939:             }
 6940: 
 6941:          if ($refuri) { 
 6942: 	  $refuri=&declutter($refuri);
 6943:           my ($match,$cond)=&is_on_map($refuri);
 6944:             if ($match) {
 6945:               my $refstatecond=$cond;
 6946:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6947:                   =~/\Q$priv\E\&([^\:]*)/) {
 6948:                   my $value = $1;
 6949:                   if ($priv eq 'bre') {
 6950:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6951:                       if (@blockers > 0) {
 6952:                           $thisallowed = 'B';
 6953:                       } else {
 6954:                           $thisallowed.=$value;
 6955:                       }
 6956:                   } else {
 6957:                       $thisallowed.=$value;
 6958:                   }
 6959:                   $uri=$refuri;
 6960:                   $statecond=$refstatecond;
 6961:               }
 6962:           }
 6963:         }
 6964:        }
 6965:    }
 6966: 
 6967: #
 6968: # Gathered now: all privileges that could apply, and condition number
 6969: # 
 6970: #
 6971: # Full or no access?
 6972: #
 6973: 
 6974:     if ($thisallowed=~/F/) {
 6975: 	return 'F';
 6976:     }
 6977: 
 6978:     unless ($thisallowed) {
 6979:         return '';
 6980:     }
 6981: 
 6982: # Restrictions exist, deal with them
 6983: #
 6984: #   C:according to course preferences
 6985: #   R:according to resource settings
 6986: #   L:unless locked
 6987: #   X:according to user session state
 6988: #
 6989: 
 6990: # Possibly locked functionality, check all courses
 6991: # Locks might take effect only after 10 minutes cache expiration for other
 6992: # courses, and 2 minutes for current course
 6993: 
 6994:     my $envkey;
 6995:     if ($thisallowed=~/L/) {
 6996:         foreach $envkey (keys(%env)) {
 6997:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6998:                my $courseid=$2;
 6999:                my $roleid=$1.'.'.$2;
 7000:                $courseid=~s/^\///;
 7001:                my $expiretime=600;
 7002:                if ($env{'request.role'} eq $roleid) {
 7003: 		  $expiretime=120;
 7004:                }
 7005: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7006:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7007:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7008: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7009:                }
 7010:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7011:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7012: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7013:                        &log($env{'user.domain'},$env{'user.name'},
 7014:                             $env{'user.home'},
 7015:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7016:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7017:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7018: 		       return '';
 7019:                    }
 7020:                }
 7021:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7022:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7023: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7024:                        &log($env{'user.domain'},$env{'user.name'},
 7025:                             $env{'user.home'},
 7026:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7027:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7028:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7029: 		       return '';
 7030:                    }
 7031:                }
 7032: 	   }
 7033:        }
 7034:     }
 7035:    
 7036: #
 7037: # Rest of the restrictions depend on selected course
 7038: #
 7039: 
 7040:     unless ($env{'request.course.id'}) {
 7041: 	if ($thisallowed eq 'A') {
 7042: 	    return 'A';
 7043:         } elsif ($thisallowed eq 'B') {
 7044:             return 'B';
 7045: 	} else {
 7046: 	    return '1';
 7047: 	}
 7048:     }
 7049: 
 7050: #
 7051: # Now user is definitely in a course
 7052: #
 7053: 
 7054: 
 7055: # Course preferences
 7056: 
 7057:    if ($thisallowed=~/C/) {
 7058:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7059:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7060:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7061: 	   =~/\Q$rolecode\E/) {
 7062: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7063: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7064: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7065: 			$env{'request.course.id'});
 7066: 	   }
 7067:            return '';
 7068:        }
 7069: 
 7070:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7071: 	   =~/\Q$unamedom\E/) {
 7072: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7073: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7074: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7075: 			$env{'request.course.id'});
 7076: 	   }
 7077:            return '';
 7078:        }
 7079:    }
 7080: 
 7081: # Resource preferences
 7082: 
 7083:    if ($thisallowed=~/R/) {
 7084:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7085:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7086: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7087: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7088: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7089: 	   }
 7090: 	   return '';
 7091:        }
 7092:    }
 7093: 
 7094: # Restricted by state or randomout?
 7095: 
 7096:    if ($thisallowed=~/X/) {
 7097:       if ($env{'acc.randomout'}) {
 7098: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7099:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7100:             return ''; 
 7101:          }
 7102:       }
 7103:       if (&condval($statecond)) {
 7104: 	 return '2';
 7105:       } else {
 7106:          return '';
 7107:       }
 7108:    }
 7109: 
 7110:     if ($thisallowed eq 'A') {
 7111: 	return 'A';
 7112:     } elsif ($thisallowed eq 'B') {
 7113:         return 'B';
 7114:     }
 7115:    return 'F';
 7116: }
 7117: 
 7118: # ------------------------------------------- Check construction space access
 7119: 
 7120: sub constructaccess {
 7121:     my ($url,$setpriv)=@_;
 7122: 
 7123: # We do not allow editing of previous versions of files
 7124:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7125: 
 7126: # Get username and domain from URL
 7127:     my ($ownername,$ownerdomain,$ownerhome);
 7128: 
 7129:     ($ownerdomain,$ownername) =
 7130:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 7131: 
 7132: # The URL does not really point to any authorspace, forget it
 7133:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7134: 
 7135: # Now we need to see if the user has access to the authorspace of
 7136: # $ownername at $ownerdomain
 7137: 
 7138:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7139: # Real author for this?
 7140:        $ownerhome = $env{'user.home'};
 7141:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7142:           return ($ownername,$ownerdomain,$ownerhome);
 7143:        }
 7144:     } else {
 7145: # Co-author for this?
 7146:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7147:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7148:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7149:             return ($ownername,$ownerdomain,$ownerhome);
 7150:         }
 7151:     }
 7152: 
 7153: # We don't have any access right now. If we are not possibly going to do anything about this,
 7154: # we might as well leave
 7155:    unless ($setpriv) { return ''; }
 7156: 
 7157: # Backdoor access?
 7158:     my $allowed=&allowed('eco',$ownerdomain);
 7159: # Nope
 7160:     unless ($allowed) { return ''; }
 7161: # Looks like we may have access, but could be locked by the owner of the construction space
 7162:     if ($allowed eq 'U') {
 7163:         my %blocked=&get('environment',['domcoord.author'],
 7164:                          $ownerdomain,$ownername);
 7165: # Is blocked by owner
 7166:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7167:     }
 7168:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7169: # Grant temporary access
 7170:         my $then=$env{'user.login.time'};
 7171:         my $update=$env{'user.update.time'};
 7172:         if (!$update) { $update = $then; }
 7173:         my $refresh=$env{'user.refresh.time'};
 7174:         if (!$refresh) { $refresh = $update; }
 7175:         my $now = time;
 7176:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7177:                            $now,'ca','constructaccess');
 7178:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7179:         return($ownername,$ownerdomain,$ownerhome);
 7180:     }
 7181: # No business here
 7182:     return '';
 7183: }
 7184: 
 7185: sub get_comm_blocks {
 7186:     my ($cdom,$cnum) = @_;
 7187:     if ($cdom eq '' || $cnum eq '') {
 7188:         return unless ($env{'request.course.id'});
 7189:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7190:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7191:     }
 7192:     my %commblocks;
 7193:     my $hashid=$cdom.'_'.$cnum;
 7194:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7195:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7196:         %commblocks = %{$blocksref};
 7197:     } else {
 7198:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7199:         my $cachetime = 600;
 7200:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7201:     }
 7202:     return %commblocks;
 7203: }
 7204: 
 7205: sub has_comm_blocking {
 7206:     my ($priv,$symb,$uri,$blocks) = @_;
 7207:     return unless ($env{'request.course.id'});
 7208:     return unless ($priv eq 'bre');
 7209:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7210:     my %commblocks;
 7211:     if (ref($blocks) eq 'HASH') {
 7212:         %commblocks = %{$blocks};
 7213:     } else {
 7214:         %commblocks = &get_comm_blocks();
 7215:     }
 7216:     return unless (keys(%commblocks) > 0);
 7217:     if (!$symb) { $symb=&symbread($uri,1); }
 7218:     my ($map,$resid,undef)=&decode_symb($symb);
 7219:     my %tocheck = (
 7220:                     maps      => $map,
 7221:                     resources => $symb,
 7222:                   );
 7223:     my @blockers;
 7224:     my $now = time;
 7225:     my $navmap = Apache::lonnavmaps::navmap->new();
 7226:     foreach my $block (keys(%commblocks)) {
 7227:         if ($block =~ /^(\d+)____(\d+)$/) {
 7228:             my ($start,$end) = ($1,$2);
 7229:             if ($start <= $now && $end >= $now) {
 7230:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7231:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7232:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7233:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7234:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7235:                                     push(@blockers,$block);
 7236:                                 }
 7237:                             }
 7238:                         }
 7239:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7240:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7241:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7242:                                     push(@blockers,$block);
 7243:                                 }
 7244:                             }
 7245:                         }
 7246:                     }
 7247:                 }
 7248:             }
 7249:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7250:             my $item = $1;
 7251:             my @to_test;
 7252:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7253:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7254:                     my $check_interval;
 7255:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7256:                         my @interval;
 7257:                         my $type = 'map';
 7258:                         if ($item eq 'course') {
 7259:                             $type = 'course';
 7260:                             @interval=&EXT("resource.0.interval");
 7261:                         } else {
 7262:                             if ($item =~ /___\d+___/) {
 7263:                                 $type = 'resource';
 7264:                                 @interval=&EXT("resource.0.interval",$item);
 7265:                                 if (ref($navmap)) {                        
 7266:                                     my $res = $navmap->getBySymb($item); 
 7267:                                     push(@to_test,$res);
 7268:                                 }
 7269:                             } else {
 7270:                                 my $mapsymb = &symbread($item,1);
 7271:                                 if ($mapsymb) {
 7272:                                     if (ref($navmap)) {
 7273:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7274:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7275:                                         foreach my $res (@to_test) {
 7276:                                             my $symb = $res->symb();
 7277:                                             next if ($symb eq $mapsymb);
 7278:                                             if ($symb ne '') {
 7279:                                                 @interval=&EXT("resource.0.interval",$symb);
 7280:                                                 last;
 7281:                                             }
 7282:                                         }
 7283:                                     }
 7284:                                 }
 7285:                             }
 7286:                         }
 7287:                         if ($interval[0] =~ /\d+/) {
 7288:                             my $first_access;
 7289:                             if ($type eq 'resource') {
 7290:                                 $first_access=&get_first_access($interval[1],$item);
 7291:                             } elsif ($type eq 'map') {
 7292:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7293:                             } else {
 7294:                                 $first_access=&get_first_access($interval[1]);
 7295:                             }
 7296:                             if ($first_access) {
 7297:                                 my $timesup = $first_access+$interval[0];
 7298:                                 if ($timesup > $now) {
 7299:                                     foreach my $res (@to_test) {
 7300:                                         if ($res->is_problem()) {
 7301:                                             if ($res->completable()) {
 7302:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7303:                                                     push(@blockers,$block);
 7304:                                                 }
 7305:                                                 last;
 7306:                                             }
 7307:                                         }
 7308:                                     }
 7309:                                 }
 7310:                             }
 7311:                         }
 7312:                     }
 7313:                 }
 7314:             }
 7315:         }
 7316:     }
 7317:     return @blockers;
 7318: }
 7319: 
 7320: sub check_docs_block {
 7321:     my ($docsblock,$tocheck) =@_;
 7322:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7323:         return;
 7324:     }
 7325:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7326:         if ($tocheck->{'maps'}) {
 7327:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7328:                 return 1;
 7329:             }
 7330:         }
 7331:     }
 7332:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7333:         if ($tocheck->{'resources'}) {
 7334:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7335:                 return 1;
 7336:             }
 7337:         }
 7338:     }
 7339:     return;
 7340: }
 7341: 
 7342: #
 7343: #   Removes the versino from a URI and
 7344: #   splits it in to its filename and path to the filename.
 7345: #   Seems like File::Basename could have done this more clearly.
 7346: #   Parameters:
 7347: #      $uri   - input URI
 7348: #   Returns:
 7349: #     Two element list consisting of 
 7350: #     $pathname  - the URI up to and excluding the trailing /
 7351: #     $filename  - The part of the URI following the last /
 7352: #  NOTE:
 7353: #    Another realization of this is simply:
 7354: #    use File::Basename;
 7355: #    ...
 7356: #    $uri = shift;
 7357: #    $filename = basename($uri);
 7358: #    $path     = dirname($uri);
 7359: #    return ($filename, $path);
 7360: #
 7361: #     The implementation below is probably faster however.
 7362: #
 7363: sub split_uri_for_cond {
 7364:     my $uri=&deversion(&declutter(shift));
 7365:     my @uriparts=split(/\//,$uri);
 7366:     my $filename=pop(@uriparts);
 7367:     my $pathname=join('/',@uriparts);
 7368:     return ($pathname,$filename);
 7369: }
 7370: # --------------------------------------------------- Is a resource on the map?
 7371: 
 7372: sub is_on_map {
 7373:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7374:     #Trying to find the conditional for the file
 7375:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7376: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7377:     if ($match) {
 7378: 	return (1,$1);
 7379:     } else {
 7380: 	return (0,0);
 7381:     }
 7382: }
 7383: 
 7384: # --------------------------------------------------------- Get symb from alias
 7385: 
 7386: sub get_symb_from_alias {
 7387:     my $symb=shift;
 7388:     my ($map,$resid,$url)=&decode_symb($symb);
 7389: # Already is a symb
 7390:     if ($url) { return $symb; }
 7391: # Must be an alias
 7392:     my $aliassymb='';
 7393:     my %bighash;
 7394:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7395:                             &GDBM_READER(),0640)) {
 7396:         my $rid=$bighash{'mapalias_'.$symb};
 7397: 	if ($rid) {
 7398: 	    my ($mapid,$resid)=split(/\./,$rid);
 7399: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7400: 				    $resid,$bighash{'src_'.$rid});
 7401: 	}
 7402:         untie %bighash;
 7403:     }
 7404:     return $aliassymb;
 7405: }
 7406: 
 7407: # ----------------------------------------------------------------- Define Role
 7408: 
 7409: sub definerole {
 7410:   if (allowed('mcr','/')) {
 7411:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7412:     foreach my $role (split(':',$sysrole)) {
 7413: 	my ($crole,$cqual)=split(/\&/,$role);
 7414:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7415:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7416: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7417:                return "refused:s:$crole&$cqual"; 
 7418:             }
 7419:         }
 7420:     }
 7421:     foreach my $role (split(':',$domrole)) {
 7422: 	my ($crole,$cqual)=split(/\&/,$role);
 7423:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7424:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7425: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7426:                return "refused:d:$crole&$cqual"; 
 7427:             }
 7428:         }
 7429:     }
 7430:     foreach my $role (split(':',$courole)) {
 7431: 	my ($crole,$cqual)=split(/\&/,$role);
 7432:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7433:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7434: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7435:                return "refused:c:$crole&$cqual"; 
 7436:             }
 7437:         }
 7438:     }
 7439:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7440:                 "$env{'user.domain'}:$env{'user.name'}:".
 7441: 	        "rolesdef_$rolename=".
 7442:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7443:     return reply($command,$env{'user.home'});
 7444:   } else {
 7445:     return 'refused';
 7446:   }
 7447: }
 7448: 
 7449: # ---------------- Make a metadata query against the network of library servers
 7450: 
 7451: sub metadata_query {
 7452:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7453:     my %rhash;
 7454:     my %libserv = &all_library();
 7455:     my @server_list = (defined($server_array) ? @$server_array
 7456:                                               : keys(%libserv) );
 7457:     for my $server (@server_list) {
 7458:         my $domains = ''; 
 7459:         if (ref($domains_hash) eq 'HASH') {
 7460:             $domains = $domains_hash->{$server}; 
 7461:         }
 7462: 	unless ($custom or $customshow) {
 7463: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7464: 	    $rhash{$server}=$reply;
 7465: 	}
 7466: 	else {
 7467: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7468: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7469: 			     $server);
 7470: 	    $rhash{$server}=$reply;
 7471: 	}
 7472:     }
 7473:     return \%rhash;
 7474: }
 7475: 
 7476: # ----------------------------------------- Send log queries and wait for reply
 7477: 
 7478: sub log_query {
 7479:     my ($uname,$udom,$query,%filters)=@_;
 7480:     my $uhome=&homeserver($uname,$udom);
 7481:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7482:     my $uhost=&hostname($uhome);
 7483:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7484:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7485:                        $uhome);
 7486:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7487:     return get_query_reply($queryid);
 7488: }
 7489: 
 7490: # -------------------------- Update MySQL table for portfolio file
 7491: 
 7492: sub update_portfolio_table {
 7493:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7494:     if ($group ne '') {
 7495:         $file_name =~s /^\Q$group\E//;
 7496:     }
 7497:     my $homeserver = &homeserver($uname,$udom);
 7498:     my $queryid=
 7499:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7500:                ':'.&escape($file_name).':'.$action,$homeserver);
 7501:     my $reply = &get_query_reply($queryid);
 7502:     return $reply;
 7503: }
 7504: 
 7505: # -------------------------- Update MySQL allusers table
 7506: 
 7507: sub update_allusers_table {
 7508:     my ($uname,$udom,$names) = @_;
 7509:     my $homeserver = &homeserver($uname,$udom);
 7510:     my $queryid=
 7511:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7512:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7513:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7514:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7515:                'generation='.&escape($names->{'generation'}).'%%'.
 7516:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7517:                'id='.&escape($names->{'id'}),$homeserver);
 7518:     return;
 7519: }
 7520: 
 7521: # ------- Request retrieval of institutional classlists for course(s)
 7522: 
 7523: sub fetch_enrollment_query {
 7524:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7525:     my $homeserver;
 7526:     my $maxtries = 1;
 7527:     if ($context eq 'automated') {
 7528:         $homeserver = $perlvar{'lonHostID'};
 7529:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7530:     } else {
 7531:         $homeserver = &homeserver($cnum,$dom);
 7532:     }
 7533:     my $host=&hostname($homeserver);
 7534:     my $cmd = '';
 7535:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7536:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7537:     }
 7538:     $cmd =~ s/%%$//;
 7539:     $cmd = &escape($cmd);
 7540:     my $query = 'fetchenrollment';
 7541:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7542:     unless ($queryid=~/^\Q$host\E\_/) { 
 7543:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7544:         return 'error: '.$queryid;
 7545:     }
 7546:     my $reply = &get_query_reply($queryid);
 7547:     my $tries = 1;
 7548:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7549:         $reply = &get_query_reply($queryid);
 7550:         $tries ++;
 7551:     }
 7552:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7553:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7554:     } else {
 7555:         my @responses = split(/:/,$reply);
 7556:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7557:             foreach my $line (@responses) {
 7558:                 my ($key,$value) = split(/=/,$line,2);
 7559:                 $$replyref{$key} = $value;
 7560:             }
 7561:         } else {
 7562:             my $pathname = LONCAPA::tempdir();
 7563:             foreach my $line (@responses) {
 7564:                 my ($key,$value) = split(/=/,$line);
 7565:                 $$replyref{$key} = $value;
 7566:                 if ($value > 0) {
 7567:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7568:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7569:                         my $destname = $pathname.'/'.$filename;
 7570:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7571:                         if ($xml_classlist =~ /^error/) {
 7572:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7573:                         } else {
 7574:                             if ( open(FILE,">$destname") ) {
 7575:                                 print FILE &unescape($xml_classlist);
 7576:                                 close(FILE);
 7577:                             } else {
 7578:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7579:                             }
 7580:                         }
 7581:                     }
 7582:                 }
 7583:             }
 7584:         }
 7585:         return 'ok';
 7586:     }
 7587:     return 'error';
 7588: }
 7589: 
 7590: sub get_query_reply {
 7591:     my $queryid=shift;
 7592:     my $replyfile=LONCAPA::tempdir().$queryid;
 7593:     my $reply='';
 7594:     for (1..100) {
 7595: 	sleep 2;
 7596:         if (-e $replyfile.'.end') {
 7597: 	    if (open(my $fh,$replyfile)) {
 7598: 		$reply = join('',<$fh>);
 7599: 		close($fh);
 7600: 	   } else { return 'error: reply_file_error'; }
 7601:            return &unescape($reply);
 7602: 	}
 7603:     }
 7604:     return 'timeout:'.$queryid;
 7605: }
 7606: 
 7607: sub courselog_query {
 7608: #
 7609: # possible filters:
 7610: # url: url or symb
 7611: # username
 7612: # domain
 7613: # action: view, submit, grade
 7614: # start: timestamp
 7615: # end: timestamp
 7616: #
 7617:     my (%filters)=@_;
 7618:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7619:     if ($filters{'url'}) {
 7620: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7621:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7622:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7623:     }
 7624:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7625:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7626:     return &log_query($cname,$cdom,'courselog',%filters);
 7627: }
 7628: 
 7629: sub userlog_query {
 7630: #
 7631: # possible filters:
 7632: # action: log check role
 7633: # start: timestamp
 7634: # end: timestamp
 7635: #
 7636:     my ($uname,$udom,%filters)=@_;
 7637:     return &log_query($uname,$udom,'userlog',%filters);
 7638: }
 7639: 
 7640: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7641: 
 7642: sub auto_run {
 7643:     my ($cnum,$cdom) = @_;
 7644:     my $response = 0;
 7645:     my $settings;
 7646:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7647:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7648:         $settings = $domconfig{'autoenroll'};
 7649:         if ($settings->{'run'} eq '1') {
 7650:             $response = 1;
 7651:         }
 7652:     } else {
 7653:         my $homeserver;
 7654:         if (&is_course($cdom,$cnum)) {
 7655:             $homeserver = &homeserver($cnum,$cdom);
 7656:         } else {
 7657:             $homeserver = &domain($cdom,'primary');
 7658:         }
 7659:         if ($homeserver ne 'no_host') {
 7660:             $response = &reply('autorun:'.$cdom,$homeserver);
 7661:         }
 7662:     }
 7663:     return $response;
 7664: }
 7665: 
 7666: sub auto_get_sections {
 7667:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7668:     my $homeserver;
 7669:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7670:         $homeserver = &homeserver($cnum,$cdom);
 7671:     }
 7672:     if (!defined($homeserver)) { 
 7673:         if ($cdom =~ /^$match_domain$/) {
 7674:             $homeserver = &domain($cdom,'primary');
 7675:         }
 7676:     }
 7677:     my @secs;
 7678:     if (defined($homeserver)) {
 7679:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7680:         unless ($response eq 'refused') {
 7681:             @secs = split(/:/,$response);
 7682:         }
 7683:     }
 7684:     return @secs;
 7685: }
 7686: 
 7687: sub auto_new_course {
 7688:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7689:     my $homeserver = &homeserver($cnum,$cdom);
 7690:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7691:     return $response;
 7692: }
 7693: 
 7694: sub auto_validate_courseID {
 7695:     my ($cnum,$cdom,$inst_course_id) = @_;
 7696:     my $homeserver = &homeserver($cnum,$cdom);
 7697:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7698:     return $response;
 7699: }
 7700: 
 7701: sub auto_validate_instcode {
 7702:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7703:     my ($homeserver,$response);
 7704:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7705:         $homeserver = &homeserver($cnum,$cdom);
 7706:     }
 7707:     if (!defined($homeserver)) {
 7708:         if ($cdom =~ /^$match_domain$/) {
 7709:             $homeserver = &domain($cdom,'primary');
 7710:         }
 7711:     }
 7712:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7713:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7714:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7715:     return ($outcome,$description,$defaultcredits);
 7716: }
 7717: 
 7718: sub auto_create_password {
 7719:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7720:     my ($homeserver,$response);
 7721:     my $create_passwd = 0;
 7722:     my $authchk = '';
 7723:     if ($udom =~ /^$match_domain$/) {
 7724:         $homeserver = &domain($udom,'primary');
 7725:     }
 7726:     if ($homeserver eq '') {
 7727:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7728:             $homeserver = &homeserver($cnum,$cdom);
 7729:         }
 7730:     }
 7731:     if ($homeserver eq '') {
 7732:         $authchk = 'nodomain';
 7733:     } else {
 7734:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7735:         if ($response eq 'refused') {
 7736:             $authchk = 'refused';
 7737:         } else {
 7738:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7739:         }
 7740:     }
 7741:     return ($authparam,$create_passwd,$authchk);
 7742: }
 7743: 
 7744: sub auto_photo_permission {
 7745:     my ($cnum,$cdom,$students) = @_;
 7746:     my $homeserver = &homeserver($cnum,$cdom);
 7747:     my ($outcome,$perm_reqd,$conditions) = 
 7748: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7749:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7750: 	return (undef,undef);
 7751:     }
 7752:     return ($outcome,$perm_reqd,$conditions);
 7753: }
 7754: 
 7755: sub auto_checkphotos {
 7756:     my ($uname,$udom,$pid) = @_;
 7757:     my $homeserver = &homeserver($uname,$udom);
 7758:     my ($result,$resulttype);
 7759:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7760: 				   &escape($uname).':'.&escape($pid),
 7761: 				   $homeserver));
 7762:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7763: 	return (undef,undef);
 7764:     }
 7765:     if ($outcome) {
 7766:         ($result,$resulttype) = split(/:/,$outcome);
 7767:     } 
 7768:     return ($result,$resulttype);
 7769: }
 7770: 
 7771: sub auto_photochoice {
 7772:     my ($cnum,$cdom) = @_;
 7773:     my $homeserver = &homeserver($cnum,$cdom);
 7774:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7775: 						       &escape($cdom),
 7776: 						       $homeserver)));
 7777:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7778: 	return (undef,undef);
 7779:     }
 7780:     return ($update,$comment);
 7781: }
 7782: 
 7783: sub auto_photoupdate {
 7784:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7785:     my $homeserver = &homeserver($cnum,$dom);
 7786:     my $host=&hostname($homeserver);
 7787:     my $cmd = '';
 7788:     my $maxtries = 1;
 7789:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7790:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7791:     }
 7792:     $cmd =~ s/%%$//;
 7793:     $cmd = &escape($cmd);
 7794:     my $query = 'institutionalphotos';
 7795:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7796:     unless ($queryid=~/^\Q$host\E\_/) {
 7797:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7798:         return 'error: '.$queryid;
 7799:     }
 7800:     my $reply = &get_query_reply($queryid);
 7801:     my $tries = 1;
 7802:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7803:         $reply = &get_query_reply($queryid);
 7804:         $tries ++;
 7805:     }
 7806:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7807:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7808:     } else {
 7809:         my @responses = split(/:/,$reply);
 7810:         my $outcome = shift(@responses); 
 7811:         foreach my $item (@responses) {
 7812:             my ($key,$value) = split(/=/,$item);
 7813:             $$photo{$key} = $value;
 7814:         }
 7815:         return $outcome;
 7816:     }
 7817:     return 'error';
 7818: }
 7819: 
 7820: sub auto_instcode_format {
 7821:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7822: 	$cat_order) = @_;
 7823:     my $courses = '';
 7824:     my @homeservers;
 7825:     if ($caller eq 'global') {
 7826: 	my %servers = &get_servers($codedom,'library');
 7827: 	foreach my $tryserver (keys(%servers)) {
 7828: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7829: 		push(@homeservers,$tryserver);
 7830: 	    }
 7831:         }
 7832:     } elsif ($caller eq 'requests') {
 7833:         if ($codedom =~ /^$match_domain$/) {
 7834:             my $chome = &domain($codedom,'primary');
 7835:             unless ($chome eq 'no_host') {
 7836:                 push(@homeservers,$chome);
 7837:             }
 7838:         }
 7839:     } else {
 7840:         push(@homeservers,&homeserver($caller,$codedom));
 7841:     }
 7842:     foreach my $code (keys(%{$instcodes})) {
 7843:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7844:     }
 7845:     chop($courses);
 7846:     my $ok_response = 0;
 7847:     my $response;
 7848:     while (@homeservers > 0 && $ok_response == 0) {
 7849:         my $server = shift(@homeservers); 
 7850:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7851:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7852:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7853: 		split(/:/,$response);
 7854:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7855:             push(@{$codetitles},&str2array($codetitles_str));
 7856:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7857:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7858:             $ok_response = 1;
 7859:         }
 7860:     }
 7861:     if ($ok_response) {
 7862:         return 'ok';
 7863:     } else {
 7864:         return $response;
 7865:     }
 7866: }
 7867: 
 7868: sub auto_instcode_defaults {
 7869:     my ($domain,$returnhash,$code_order) = @_;
 7870:     my @homeservers;
 7871: 
 7872:     my %servers = &get_servers($domain,'library');
 7873:     foreach my $tryserver (keys(%servers)) {
 7874: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7875: 	    push(@homeservers,$tryserver);
 7876: 	}
 7877:     }
 7878: 
 7879:     my $response;
 7880:     foreach my $server (@homeservers) {
 7881:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7882:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7883: 	
 7884: 	foreach my $pair (split(/\&/,$response)) {
 7885: 	    my ($name,$value)=split(/\=/,$pair);
 7886: 	    if ($name eq 'code_order') {
 7887: 		@{$code_order} = split(/\&/,&unescape($value));
 7888: 	    } else {
 7889: 		$returnhash->{&unescape($name)}=&unescape($value);
 7890: 	    }
 7891: 	}
 7892: 	return 'ok';
 7893:     }
 7894: 
 7895:     return $response;
 7896: }
 7897: 
 7898: sub auto_possible_instcodes {
 7899:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7900:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7901:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7902:         return;
 7903:     }
 7904:     my (@homeservers,$uhome);
 7905:     if (defined(&domain($domain,'primary'))) {
 7906:         $uhome=&domain($domain,'primary');
 7907:         push(@homeservers,&domain($domain,'primary'));
 7908:     } else {
 7909:         my %servers = &get_servers($domain,'library');
 7910:         foreach my $tryserver (keys(%servers)) {
 7911:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7912:                 push(@homeservers,$tryserver);
 7913:             }
 7914:         }
 7915:     }
 7916:     my $response;
 7917:     foreach my $server (@homeservers) {
 7918:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7919:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7920:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7921:             split(':',$response);
 7922:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7923:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7924:         foreach my $item (split('&',$cat_title)) {   
 7925:             my ($name,$value)=split('=',$item);
 7926:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7927:         }
 7928:         foreach my $item (split('&',$cat_order)) {
 7929:             my ($name,$value)=split('=',$item);
 7930:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7931:         }
 7932:         return 'ok';
 7933:     }
 7934:     return $response;
 7935: }
 7936: 
 7937: sub auto_courserequest_checks {
 7938:     my ($dom) = @_;
 7939:     my ($homeserver,%validations);
 7940:     if ($dom =~ /^$match_domain$/) {
 7941:         $homeserver = &domain($dom,'primary');
 7942:     }
 7943:     unless ($homeserver eq 'no_host') {
 7944:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7945:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7946:             my @items = split(/&/,$response);
 7947:             foreach my $item (@items) {
 7948:                 my ($key,$value) = split('=',$item);
 7949:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7950:             }
 7951:         }
 7952:     }
 7953:     return %validations; 
 7954: }
 7955: 
 7956: sub auto_courserequest_validation {
 7957:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 7958:     my ($homeserver,$response);
 7959:     if ($dom =~ /^$match_domain$/) {
 7960:         $homeserver = &domain($dom,'primary');
 7961:     }
 7962:     unless ($homeserver eq 'no_host') {
 7963:         my $customdata;
 7964:         if (ref($custominfo) eq 'HASH') {
 7965:             $customdata = &freeze_escape($custominfo);
 7966:         }
 7967:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7968:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7969:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 7970:                                     $customdata,$homeserver));
 7971:     }
 7972:     return $response;
 7973: }
 7974: 
 7975: sub auto_validate_class_sec {
 7976:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7977:     my $homeserver = &homeserver($cnum,$cdom);
 7978:     my $ownerlist;
 7979:     if (ref($owners) eq 'ARRAY') {
 7980:         $ownerlist = join(',',@{$owners});
 7981:     } else {
 7982:         $ownerlist = $owners;
 7983:     }
 7984:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7985:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7986:     return $response;
 7987: }
 7988: 
 7989: sub auto_crsreq_update {
 7990:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 7991:         $code,$accessstart,$accessend,$inbound) = @_;
 7992:     my ($homeserver,%crsreqresponse);
 7993:     if ($cdom =~ /^$match_domain$/) {
 7994:         $homeserver = &domain($cdom,'primary');
 7995:     }
 7996:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 7997:         my $info;
 7998:         if (ref($inbound) eq 'HASH') {
 7999:             $info = &freeze_escape($inbound);
 8000:         }
 8001:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8002:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8003:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8004:                             &escape($title).':'.&escape($code).':'.
 8005:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8006:                             $homeserver);
 8007:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8008:             my @items = split(/&/,$response);
 8009:             foreach my $item (@items) {
 8010:                 my ($key,$value) = split('=',$item);
 8011:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8012:             }
 8013:         }
 8014:     }
 8015:     return \%crsreqresponse;
 8016: }
 8017: 
 8018: # ------------------------------------------------------- Course Group routines
 8019: 
 8020: sub get_coursegroups {
 8021:     my ($cdom,$cnum,$group,$namespace) = @_;
 8022:     return(&dump($namespace,$cdom,$cnum,$group));
 8023: }
 8024: 
 8025: sub modify_coursegroup {
 8026:     my ($cdom,$cnum,$groupsettings) = @_;
 8027:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 8028: }
 8029: 
 8030: sub toggle_coursegroup_status {
 8031:     my ($cdom,$cnum,$group,$action) = @_;
 8032:     my ($from_namespace,$to_namespace);
 8033:     if ($action eq 'delete') {
 8034:         $from_namespace = 'coursegroups';
 8035:         $to_namespace = 'deleted_groups';
 8036:     } else {
 8037:         $from_namespace = 'deleted_groups';
 8038:         $to_namespace = 'coursegroups';
 8039:     }
 8040:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8041:     if (my $tmp = &error(%curr_group)) {
 8042:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8043:         return ('read error',$tmp);
 8044:     } else {
 8045:         my %savedsettings = %curr_group; 
 8046:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8047:         my $deloutcome;
 8048:         if ($result eq 'ok') {
 8049:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 8050:         } else {
 8051:             return ('write error',$result);
 8052:         }
 8053:         if ($deloutcome eq 'ok') {
 8054:             return 'ok';
 8055:         } else {
 8056:             return ('delete error',$deloutcome);
 8057:         }
 8058:     }
 8059: }
 8060: 
 8061: sub modify_group_roles {
 8062:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 8063:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 8064:     my $role = 'gr/'.&escape($userprivs);
 8065:     my ($uname,$udom) = split(/:/,$user);
 8066:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 8067:     if ($result eq 'ok') {
 8068:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 8069:     }
 8070:     return $result;
 8071: }
 8072: 
 8073: sub modify_coursegroup_membership {
 8074:     my ($cdom,$cnum,$membership) = @_;
 8075:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 8076:     return $result;
 8077: }
 8078: 
 8079: sub get_active_groups {
 8080:     my ($udom,$uname,$cdom,$cnum) = @_;
 8081:     my $now = time;
 8082:     my %groups = ();
 8083:     foreach my $key (keys(%env)) {
 8084:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8085:             my ($start,$end) = split(/\./,$env{$key});
 8086:             if (($end!=0) && ($end<$now)) { next; }
 8087:             if (($start!=0) && ($start>$now)) { next; }
 8088:             if ($1 eq $cdom && $2 eq $cnum) {
 8089:                 $groups{$3} = $env{$key} ;
 8090:             }
 8091:         }
 8092:     }
 8093:     return %groups;
 8094: }
 8095: 
 8096: sub get_group_membership {
 8097:     my ($cdom,$cnum,$group) = @_;
 8098:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8099: }
 8100: 
 8101: sub get_users_groups {
 8102:     my ($udom,$uname,$courseid) = @_;
 8103:     my @usersgroups;
 8104:     my $cachetime=1800;
 8105: 
 8106:     my $hashid="$udom:$uname:$courseid";
 8107:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8108:     if (defined($cached)) {
 8109:         @usersgroups = split(/:/,$grouplist);
 8110:     } else {  
 8111:         $grouplist = '';
 8112:         my $courseurl = &courseid_to_courseurl($courseid);
 8113:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8114:         my $access_end = $env{'course.'.$courseid.
 8115:                               '.default_enrollment_end_date'};
 8116:         my $now = time;
 8117:         foreach my $key (keys(%roleshash)) {
 8118:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8119:                 my $group = $1;
 8120:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8121:                     my $start = $2;
 8122:                     my $end = $1;
 8123:                     if ($start == -1) { next; } # deleted from group
 8124:                     if (($start!=0) && ($start>$now)) { next; }
 8125:                     if (($end!=0) && ($end<$now)) {
 8126:                         if ($access_end && $access_end < $now) {
 8127:                             if ($access_end - $end < 86400) {
 8128:                                 push(@usersgroups,$group);
 8129:                             }
 8130:                         }
 8131:                         next;
 8132:                     }
 8133:                     push(@usersgroups,$group);
 8134:                 }
 8135:             }
 8136:         }
 8137:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8138:         $grouplist = join(':',@usersgroups);
 8139:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8140:     }
 8141:     return @usersgroups;
 8142: }
 8143: 
 8144: sub devalidate_getgroups_cache {
 8145:     my ($udom,$uname,$cdom,$cnum)=@_;
 8146:     my $courseid = $cdom.'_'.$cnum;
 8147: 
 8148:     my $hashid="$udom:$uname:$courseid";
 8149:     &devalidate_cache_new('getgroups',$hashid);
 8150: }
 8151: 
 8152: # ------------------------------------------------------------------ Plain Text
 8153: 
 8154: sub plaintext {
 8155:     my ($short,$type,$cid,$forcedefault) = @_;
 8156:     if ($short =~ m{^cr/}) {
 8157: 	return (split('/',$short))[-1];
 8158:     }
 8159:     if (!defined($cid)) {
 8160:         $cid = $env{'request.course.id'};
 8161:     }
 8162:     my %rolenames = (
 8163:                       Course    => 'std',
 8164:                       Community => 'alt1',
 8165:                     );
 8166:     if ($cid ne '') {
 8167:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8168:             unless ($forcedefault) {
 8169:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8170:                 &Apache::lonlocal::mt_escape(\$roletext);
 8171:                 return &Apache::lonlocal::mt($roletext);
 8172:             }
 8173:         }
 8174:     }
 8175:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8176:         (defined($rolenames{$type})) && 
 8177:         (defined($prp{$short}{$rolenames{$type}}))) {
 8178:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8179:     } elsif ($cid ne '') {
 8180:         my $crstype = $env{'course.'.$cid.'.type'};
 8181:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8182:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8183:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8184:         }
 8185:     }
 8186:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8187: }
 8188: 
 8189: # ----------------------------------------------------------------- Assign Role
 8190: 
 8191: sub assignrole {
 8192:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8193:         $context)=@_;
 8194:     my $mrole;
 8195:     if ($role =~ /^cr\//) {
 8196:         my $cwosec=$url;
 8197:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8198: 	unless (&allowed('ccr',$cwosec)) {
 8199:            my $refused = 1;
 8200:            if ($context eq 'requestcourses') {
 8201:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8202:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8203:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8204:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8205:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8206:                            if ($crsenv{'internal.courseowner'} eq
 8207:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8208:                                $refused = '';
 8209:                            }
 8210:                        }
 8211:                    }
 8212:                }
 8213:            }
 8214:            if ($refused) {
 8215:                &logthis('Refused custom assignrole: '.
 8216:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8217:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8218:                return 'refused';
 8219:            }
 8220:         }
 8221:         $mrole='cr';
 8222:     } elsif ($role =~ /^gr\//) {
 8223:         my $cwogrp=$url;
 8224:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8225:         unless (&allowed('mdg',$cwogrp)) {
 8226:             &logthis('Refused group assignrole: '.
 8227:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8228:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8229:             return 'refused';
 8230:         }
 8231:         $mrole='gr';
 8232:     } else {
 8233:         my $cwosec=$url;
 8234:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8235:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8236:             my $refused;
 8237:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8238:                 if (!(&allowed('c'.$role,$url))) {
 8239:                     $refused = 1;
 8240:                 }
 8241:             } else {
 8242:                 $refused = 1;
 8243:             }
 8244:             if ($refused) {
 8245:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8246:                 if (!$selfenroll && $context eq 'course') {
 8247:                     my %crsenv;
 8248:                     if ($role eq 'cc' || $role eq 'co') {
 8249:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8250:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8251:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8252:                                 if ($crsenv{'internal.courseowner'} eq 
 8253:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8254:                                     $refused = '';
 8255:                                 }
 8256:                             }
 8257:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8258:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8259:                                 if ($crsenv{'internal.courseowner'} eq 
 8260:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8261:                                     $refused = '';
 8262:                                 }
 8263:                             }
 8264:                         }
 8265:                     }
 8266:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8267:                     $refused = '';
 8268:                 } elsif ($context eq 'requestcourses') {
 8269:                     my @possroles = ('st','ta','ep','in','cc','co');
 8270:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8271:                         my $wrongcc;
 8272:                         if ($cnum =~ /^$match_community$/) {
 8273:                             $wrongcc = 1 if ($role eq 'cc');
 8274:                         } else {
 8275:                             $wrongcc = 1 if ($role eq 'co');
 8276:                         }
 8277:                         unless ($wrongcc) {
 8278:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8279:                             if ($crsenv{'internal.courseowner'} eq 
 8280:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8281:                                 $refused = '';
 8282:                             }
 8283:                         }
 8284:                     }
 8285:                 } elsif ($context eq 'requestauthor') {
 8286:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8287:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8288:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8289:                             $refused = '';
 8290:                         } else {
 8291:                             my %domdefaults = &get_domain_defaults($udom);
 8292:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8293:                                 my $checkbystatus;
 8294:                                 if ($env{'user.adv'}) { 
 8295:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8296:                                     if ($disposition eq 'automatic') {
 8297:                                         $refused = '';
 8298:                                     } elsif ($disposition eq '') {
 8299:                                         $checkbystatus = 1;
 8300:                                     } 
 8301:                                 } else {
 8302:                                     $checkbystatus = 1;
 8303:                                 }
 8304:                                 if ($checkbystatus) {
 8305:                                     if ($env{'environment.inststatus'}) {
 8306:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8307:                                         foreach my $type (@inststatuses) {
 8308:                                             if (($type ne '') &&
 8309:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8310:                                                 $refused = '';
 8311:                                             }
 8312:                                         }
 8313:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8314:                                         $refused = '';
 8315:                                     }
 8316:                                 }
 8317:                             }
 8318:                         }
 8319:                     }
 8320:                 }
 8321:                 if ($refused) {
 8322:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8323:                              ' '.$role.' '.$end.' '.$start.' by '.
 8324: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8325:                     return 'refused';
 8326:                 }
 8327:             }
 8328:         } elsif ($role eq 'au') {
 8329:             if ($url ne '/'.$udom.'/') {
 8330:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8331:                          ' to assign author role for '.$uname.':'.$udom.
 8332:                          ' in domain: '.$url.' refused (wrong domain).');
 8333:                 return 'refused';
 8334:             }
 8335:         }
 8336:         $mrole=$role;
 8337:     }
 8338:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8339:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8340:     if ($end) { $command.='_'.$end; }
 8341:     if ($start) {
 8342: 	if ($end) { 
 8343:            $command.='_'.$start; 
 8344:         } else {
 8345:            $command.='_0_'.$start;
 8346:         }
 8347:     }
 8348:     my $origstart = $start;
 8349:     my $origend = $end;
 8350:     my $delflag;
 8351: # actually delete
 8352:     if ($deleteflag) {
 8353: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8354: # modify command to delete the role
 8355:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8356:                 "$udom:$uname:$url".'_'."$mrole";
 8357: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8358: # set start and finish to negative values for userrolelog
 8359:            $start=-1;
 8360:            $end=-1;
 8361:            $delflag = 1;
 8362:         }
 8363:     }
 8364: # send command
 8365:     my $answer=&reply($command,&homeserver($uname,$udom));
 8366: # log new user role if status is ok
 8367:     if ($answer eq 'ok') {
 8368: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8369:         if (($role eq 'cc') || ($role eq 'in') ||
 8370:             ($role eq 'ep') || ($role eq 'ad') ||
 8371:             ($role eq 'ta') || ($role eq 'st') ||
 8372:             ($role=~/^cr/) || ($role eq 'gr') ||
 8373:             ($role eq 'co')) {
 8374: # for course roles, perform group memberships changes triggered by role change.
 8375:             unless ($role =~ /^gr/) {
 8376:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8377:                                                  $origstart,$selfenroll,$context);
 8378:             }
 8379:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8380:                            $selfenroll,$context);
 8381:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8382:                  ($role eq 'au') || ($role eq 'dc')) {
 8383:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8384:                            $context);
 8385:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8386:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8387:                              $context); 
 8388:         }
 8389:         if ($role eq 'cc') {
 8390:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8391:         }
 8392:     }
 8393:     return $answer;
 8394: }
 8395: 
 8396: sub autoupdate_coowners {
 8397:     my ($url,$end,$start,$uname,$udom) = @_;
 8398:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8399:     if (($cdom ne '') && ($cnum ne '')) {
 8400:         my $now = time;
 8401:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8402:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8403:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8404:             my $instcode = $coursehash{'internal.coursecode'};
 8405:             if ($instcode ne '') {
 8406:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8407:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8408:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8409:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8410:                         if ($result eq 'valid') {
 8411:                             if ($coursehash{'internal.co-owners'}) {
 8412:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8413:                                     push(@newcoowners,$coowner);
 8414:                                 }
 8415:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8416:                                     push(@newcoowners,$uname.':'.$udom);
 8417:                                 }
 8418:                                 @newcoowners = sort(@newcoowners);
 8419:                             } else {
 8420:                                 push(@newcoowners,$uname.':'.$udom);
 8421:                             }
 8422:                         } else {
 8423:                             if ($coursehash{'internal.co-owners'}) {
 8424:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8425:                                     unless ($coowner eq $uname.':'.$udom) {
 8426:                                         push(@newcoowners,$coowner);
 8427:                                     }
 8428:                                 }
 8429:                                 unless (@newcoowners > 0) {
 8430:                                     $delcoowners = 1;
 8431:                                     $coowners = '';
 8432:                                 }
 8433:                             }
 8434:                         }
 8435:                         if (@newcoowners || $delcoowners) {
 8436:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8437:                                             $delcoowners,@newcoowners);
 8438:                         }
 8439:                     }
 8440:                 }
 8441:             }
 8442:         }
 8443:     }
 8444: }
 8445: 
 8446: sub store_coowners {
 8447:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8448:     my $cid = $cdom.'_'.$cnum;
 8449:     my ($coowners,$delresult,$putresult);
 8450:     if (@newcoowners) {
 8451:         $coowners = join(',',@newcoowners);
 8452:         my %coownershash = (
 8453:                             'internal.co-owners' => $coowners,
 8454:                            );
 8455:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8456:         if ($putresult eq 'ok') {
 8457:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8458:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8459:             }
 8460:         }
 8461:     }
 8462:     if ($delcoowners) {
 8463:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8464:         if ($delresult eq 'ok') {
 8465:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8466:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8467:             }
 8468:         }
 8469:     }
 8470:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8471:         my %crsinfo =
 8472:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8473:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8474:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8475:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8476:         }
 8477:     }
 8478: }
 8479: 
 8480: # -------------------------------------------------- Modify user authentication
 8481: # Overrides without validation
 8482: 
 8483: sub modifyuserauth {
 8484:     my ($udom,$uname,$umode,$upass)=@_;
 8485:     my $uhome=&homeserver($uname,$udom);
 8486:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8487:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8488:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8489:              ' in domain '.$env{'request.role.domain'});  
 8490:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8491: 		     &escape($upass),$uhome);
 8492:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8493:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8494:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8495:     &log($udom,,$uname,$uhome,
 8496:         'Authentication changed by '.$env{'user.domain'}.', '.
 8497:                                      $env{'user.name'}.', '.$umode.
 8498:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8499:     unless ($reply eq 'ok') {
 8500:         &logthis('Authentication mode error: '.$reply);
 8501: 	return 'error: '.$reply;
 8502:     }   
 8503:     return 'ok';
 8504: }
 8505: 
 8506: # --------------------------------------------------------------- Modify a user
 8507: 
 8508: sub modifyuser {
 8509:     my ($udom,    $uname, $uid,
 8510:         $umode,   $upass, $first,
 8511:         $middle,  $last,  $gene,
 8512:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8513:     $udom= &LONCAPA::clean_domain($udom);
 8514:     $uname=&LONCAPA::clean_username($uname);
 8515:     my $showcandelete = 'none';
 8516:     if (ref($candelete) eq 'ARRAY') {
 8517:         if (@{$candelete} > 0) {
 8518:             $showcandelete = join(', ',@{$candelete});
 8519:         }
 8520:     }
 8521:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8522:              $umode.', '.$first.', '.$middle.', '.
 8523: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8524:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8525:                                      ' desiredhome not specified'). 
 8526:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8527:              ' in domain '.$env{'request.role.domain'});
 8528:     my $uhome=&homeserver($uname,$udom,'true');
 8529:     my $newuser;
 8530:     if ($uhome eq 'no_host') {
 8531:         $newuser = 1;
 8532:     }
 8533: # ----------------------------------------------------------------- Create User
 8534:     if (($uhome eq 'no_host') && 
 8535: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8536:         my $unhome='';
 8537:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8538:             $unhome = $desiredhome;
 8539: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8540: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8541:         } else { # load balancing routine for determining $unhome
 8542:             my $loadm=10000000;
 8543: 	    my %servers = &get_servers($udom,'library');
 8544: 	    foreach my $tryserver (keys(%servers)) {
 8545: 		my $answer=reply('load',$tryserver);
 8546: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8547: 		    $loadm=$answer;
 8548: 		    $unhome=$tryserver;
 8549: 		}
 8550: 	    }
 8551:         }
 8552:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8553: 	    return 'error: unable to find a home server for '.$uname.
 8554:                    ' in domain '.$udom;
 8555:         }
 8556:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8557:                          &escape($upass),$unhome);
 8558: 	unless ($reply eq 'ok') {
 8559:             return 'error: '.$reply;
 8560:         }   
 8561:         $uhome=&homeserver($uname,$udom,'true');
 8562:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8563: 	    return 'error: unable verify users home machine.';
 8564:         }
 8565:     }   # End of creation of new user
 8566: # ---------------------------------------------------------------------- Add ID
 8567:     if ($uid) {
 8568:        $uid=~tr/A-Z/a-z/;
 8569:        my %uidhash=&idrget($udom,$uname);
 8570:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8571:          && (!$forceid)) {
 8572: 	  unless ($uid eq $uidhash{$uname}) {
 8573: 	      return 'error: user id "'.$uid.'" does not match '.
 8574:                   'current user id "'.$uidhash{$uname}.'".';
 8575:           }
 8576:        } else {
 8577: 	  &idput($udom,($uname => $uid));
 8578:        }
 8579:     }
 8580: # -------------------------------------------------------------- Add names, etc
 8581:     my @tmp=&get('environment',
 8582: 		   ['firstname','middlename','lastname','generation','id',
 8583:                     'permanentemail','inststatus'],
 8584: 		   $udom,$uname);
 8585:     my (%names,%oldnames);
 8586:     if ($tmp[0] =~ m/^error:.*/) { 
 8587:         %names=(); 
 8588:     } else {
 8589:         %names = @tmp;
 8590:         %oldnames = %names;
 8591:     }
 8592: #
 8593: # If name, email and/or uid are blank (e.g., because an uploaded file
 8594: # of users did not contain them), do not overwrite existing values
 8595: # unless field is in $candelete array ref.  
 8596: #
 8597: 
 8598:     my @fields = ('firstname','middlename','lastname','generation',
 8599:                   'permanentemail','id');
 8600:     my %newvalues;
 8601:     if (ref($candelete) eq 'ARRAY') {
 8602:         foreach my $field (@fields) {
 8603:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8604:                 if ($field eq 'firstname') {
 8605:                     $names{$field} = $first;
 8606:                 } elsif ($field eq 'middlename') {
 8607:                     $names{$field} = $middle;
 8608:                 } elsif ($field eq 'lastname') {
 8609:                     $names{$field} = $last;
 8610:                 } elsif ($field eq 'generation') { 
 8611:                     $names{$field} = $gene;
 8612:                 } elsif ($field eq 'permanentemail') {
 8613:                     $names{$field} = $email;
 8614:                 } elsif ($field eq 'id') {
 8615:                     $names{$field}  = $uid;
 8616:                 }
 8617:             }
 8618:         }
 8619:     }
 8620:     if ($first)  { $names{'firstname'}  = $first; }
 8621:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8622:     if ($last)   { $names{'lastname'}   = $last; }
 8623:     if (defined($gene))   { $names{'generation'} = $gene; }
 8624:     if ($email) {
 8625:        $email=~s/[^\w\@\.\-\,]//gs;
 8626:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8627:     }
 8628:     if ($uid) { $names{'id'}  = $uid; }
 8629:     if (defined($inststatus)) {
 8630:         $names{'inststatus'} = '';
 8631:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8632:         if (ref($usertypes) eq 'HASH') {
 8633:             my @okstatuses; 
 8634:             foreach my $item (split(/:/,$inststatus)) {
 8635:                 if (defined($usertypes->{$item})) {
 8636:                     push(@okstatuses,$item);  
 8637:                 }
 8638:             }
 8639:             if (@okstatuses) {
 8640:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8641:             }
 8642:         }
 8643:     }
 8644:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8645:                  $umode.', '.$first.', '.$middle.', '.
 8646:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8647:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8648:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8649:     } else {
 8650:         $logmsg .= ' during self creation';
 8651:     }
 8652:     my $changed;
 8653:     if ($newuser) {
 8654:         $changed = 1;
 8655:     } else {
 8656:         foreach my $field (@fields) {
 8657:             if ($names{$field} ne $oldnames{$field}) {
 8658:                 $changed = 1;
 8659:                 last;
 8660:             }
 8661:         }
 8662:     }
 8663:     unless ($changed) {
 8664:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8665:         &logthis($logmsg);
 8666:         return 'ok';
 8667:     }
 8668:     my $reply = &put('environment', \%names, $udom,$uname);
 8669:     if ($reply ne 'ok') { 
 8670:         return 'error: '.$reply;
 8671:     }
 8672:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8673:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8674:     }
 8675:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8676:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8677:     $logmsg = 'Success modifying user '.$logmsg;
 8678:     &logthis($logmsg);
 8679:     return 'ok';
 8680: }
 8681: 
 8682: # -------------------------------------------------------------- Modify student
 8683: 
 8684: sub modifystudent {
 8685:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8686:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8687:         $selfenroll,$context,$inststatus,$credits)=@_;
 8688:     if (!$cid) {
 8689: 	unless ($cid=$env{'request.course.id'}) {
 8690: 	    return 'not_in_class';
 8691: 	}
 8692:     }
 8693: # --------------------------------------------------------------- Make the user
 8694:     my $reply=&modifyuser
 8695: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8696:          $desiredhome,$email,$inststatus);
 8697:     unless ($reply eq 'ok') { return $reply; }
 8698:     # This will cause &modify_student_enrollment to get the uid from the
 8699:     # student's environment
 8700:     $uid = undef if (!$forceid);
 8701:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8702:                                         $gene,$usec,$end,$start,$type,$locktype,
 8703:                                         $cid,$selfenroll,$context,$credits);
 8704:     return $reply;
 8705: }
 8706: 
 8707: sub modify_student_enrollment {
 8708:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8709:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8710:     my ($cdom,$cnum,$chome);
 8711:     if (!$cid) {
 8712: 	unless ($cid=$env{'request.course.id'}) {
 8713: 	    return 'not_in_class';
 8714: 	}
 8715: 	$cdom=$env{'course.'.$cid.'.domain'};
 8716: 	$cnum=$env{'course.'.$cid.'.num'};
 8717:     } else {
 8718: 	($cdom,$cnum)=split(/_/,$cid);
 8719:     }
 8720:     $chome=$env{'course.'.$cid.'.home'};
 8721:     if (!$chome) {
 8722: 	$chome=&homeserver($cnum,$cdom);
 8723:     }
 8724:     if (!$chome) { return 'unknown_course'; }
 8725:     # Make sure the user exists
 8726:     my $uhome=&homeserver($uname,$udom);
 8727:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8728: 	return 'error: no such user';
 8729:     }
 8730:     # Get student data if we were not given enough information
 8731:     if (!defined($first)  || $first  eq '' || 
 8732:         !defined($last)   || $last   eq '' || 
 8733:         !defined($uid)    || $uid    eq '' || 
 8734:         !defined($middle) || $middle eq '' || 
 8735:         !defined($gene)   || $gene   eq '') {
 8736:         # They did not supply us with enough data to enroll the student, so
 8737:         # we need to pick up more information.
 8738:         my %tmp = &get('environment',
 8739:                        ['firstname','middlename','lastname', 'generation','id']
 8740:                        ,$udom,$uname);
 8741: 
 8742:         #foreach my $key (keys(%tmp)) {
 8743:         #    &logthis("key $key = ".$tmp{$key});
 8744:         #}
 8745:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8746:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8747:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8748:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8749:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8750:     }
 8751:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8752:     my $user = "$uname:$udom";
 8753:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8754:     my $reply=cput('classlist',
 8755: 		   {$user => 
 8756: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8757: 		   $cdom,$cnum);
 8758:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8759:         &devalidate_getsection_cache($udom,$uname,$cid);
 8760:     } else { 
 8761: 	return 'error: '.$reply;
 8762:     }
 8763:     # Add student role to user
 8764:     my $uurl='/'.$cid;
 8765:     $uurl=~s/\_/\//g;
 8766:     if ($usec) {
 8767: 	$uurl.='/'.$usec;
 8768:     }
 8769:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8770:                              $selfenroll,$context);
 8771:     if ($result ne 'ok') {
 8772:         if ($old_entry{$user} ne '') {
 8773:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8774:         } else {
 8775:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8776:         }
 8777:     }
 8778:     return $result; 
 8779: }
 8780: 
 8781: sub format_name {
 8782:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8783:     my $name;
 8784:     if ($first ne 'lastname') {
 8785: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8786:     } else {
 8787: 	if ($lastname=~/\S/) {
 8788: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8789: 	    $name=~s/\s+,/,/;
 8790: 	} else {
 8791: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8792: 	}
 8793:     }
 8794:     $name=~s/^\s+//;
 8795:     $name=~s/\s+$//;
 8796:     $name=~s/\s+/ /g;
 8797:     return $name;
 8798: }
 8799: 
 8800: # ------------------------------------------------- Write to course preferences
 8801: 
 8802: sub writecoursepref {
 8803:     my ($courseid,%prefs)=@_;
 8804:     $courseid=~s/^\///;
 8805:     $courseid=~s/\_/\//g;
 8806:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8807:     my $chome=homeserver($cnum,$cdomain);
 8808:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8809: 	return 'error: no such course';
 8810:     }
 8811:     my $cstring='';
 8812:     foreach my $pref (keys(%prefs)) {
 8813: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8814:     }
 8815:     $cstring=~s/\&$//;
 8816:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8817: }
 8818: 
 8819: # ---------------------------------------------------------- Make/modify course
 8820: 
 8821: sub createcourse {
 8822:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8823:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8824:     $url=&declutter($url);
 8825:     my $cid='';
 8826:     if ($context eq 'requestcourses') {
 8827:         my $can_create = 0;
 8828:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8829:         if ($udom eq $ownerdom) {
 8830:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8831:                                   $context)) {
 8832:                 $can_create = 1;
 8833:             }
 8834:         } else {
 8835:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8836:                                            $category);
 8837:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8838:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8839:                 if (@curr > 0) {
 8840:                     my @options = qw(approval validate autolimit);
 8841:                     my $optregex = join('|',@options);
 8842:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8843:                         $can_create = 1;
 8844:                     }
 8845:                 }
 8846:             }
 8847:         }
 8848:         if ($can_create) {
 8849:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8850:                 unless (&allowed('ccc',$udom)) {
 8851:                     return 'refused'; 
 8852:                 }
 8853:             }
 8854:         } else {
 8855:             return 'refused';
 8856:         }
 8857:     } elsif (!&allowed('ccc',$udom)) {
 8858:         return 'refused';
 8859:     }
 8860: # --------------------------------------------------------------- Get Unique ID
 8861:     my $uname;
 8862:     if ($cnum =~ /^$match_courseid$/) {
 8863:         my $chome=&homeserver($cnum,$udom,'true');
 8864:         if (($chome eq '') || ($chome eq 'no_host')) {
 8865:             $uname = $cnum;
 8866:         } else {
 8867:             $uname = &generate_coursenum($udom,$crstype);
 8868:         }
 8869:     } else {
 8870:         $uname = &generate_coursenum($udom,$crstype);
 8871:     }
 8872:     return $uname if ($uname =~ /^error/);
 8873: # -------------------------------------------------- Check supplied server name
 8874:     if (!defined($course_server)) {
 8875:         if (defined(&domain($udom,'primary'))) {
 8876:             $course_server = &domain($udom,'primary');
 8877:         } else {
 8878:             $course_server = $env{'user.home'}; 
 8879:         }
 8880:     }
 8881:     my %host_servers =
 8882:         &Apache::lonnet::get_servers($udom,'library');
 8883:     unless ($host_servers{$course_server}) {
 8884:         return 'error: invalid home server for course: '.$course_server;
 8885:     }
 8886: # ------------------------------------------------------------- Make the course
 8887:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8888:                       $course_server);
 8889:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8890:     my $uhome=&homeserver($uname,$udom,'true');
 8891:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8892: 	return 'error: no such course';
 8893:     }
 8894: # ----------------------------------------------------------------- Course made
 8895: # log existence
 8896:     my $now = time;
 8897:     my $newcourse = {
 8898:                     $udom.'_'.$uname => {
 8899:                                      description => $description,
 8900:                                      inst_code   => $inst_code,
 8901:                                      owner       => $course_owner,
 8902:                                      type        => $crstype,
 8903:                                      creator     => $env{'user.name'}.':'.
 8904:                                                     $env{'user.domain'},
 8905:                                      created     => $now,
 8906:                                      context     => $context,
 8907:                                                 },
 8908:                     };
 8909:     &courseidput($udom,$newcourse,$uhome,'notime');
 8910: # set toplevel url
 8911:     my $topurl=$url;
 8912:     unless ($nonstandard) {
 8913: # ------------------------------------------ For standard courses, make top url
 8914:         my $mapurl=&clutter($url);
 8915:         if ($mapurl eq '/res/') { $mapurl=''; }
 8916:         $env{'form.initmap'}=(<<ENDINITMAP);
 8917: <map>
 8918: <resource id="1" type="start"></resource>
 8919: <resource id="2" src="$mapurl"></resource>
 8920: <resource id="3" type="finish"></resource>
 8921: <link index="1" from="1" to="2"></link>
 8922: <link index="2" from="2" to="3"></link>
 8923: </map>
 8924: ENDINITMAP
 8925:         $topurl=&declutter(
 8926:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8927:                           );
 8928:     }
 8929: # ----------------------------------------------------------- Write preferences
 8930:     &writecoursepref($udom.'_'.$uname,
 8931:                      ('description'              => $description,
 8932:                       'url'                      => $topurl,
 8933:                       'internal.creator'         => $env{'user.name'}.':'.
 8934:                                                     $env{'user.domain'},
 8935:                       'internal.created'         => $now,
 8936:                       'internal.creationcontext' => $context)
 8937:                     );
 8938:     return '/'.$udom.'/'.$uname;
 8939: }
 8940: 
 8941: # ------------------------------------------------------------------- Create ID
 8942: sub generate_coursenum {
 8943:     my ($udom,$crstype) = @_;
 8944:     my $domdesc = &domain($udom);
 8945:     return 'error: invalid domain' if ($domdesc eq '');
 8946:     my $first;
 8947:     if ($crstype eq 'Community') {
 8948:         $first = '0';
 8949:     } else {
 8950:         $first = int(1+rand(9)); 
 8951:     } 
 8952:     my $uname=$first.
 8953:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8954:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8955:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8956: # ----------------------------------------------- Make sure that does not exist
 8957:     my $uhome=&homeserver($uname,$udom,'true');
 8958:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8959:         if ($crstype eq 'Community') {
 8960:             $first = '0';
 8961:         } else {
 8962:             $first = int(1+rand(9));
 8963:         }
 8964:         $uname=$first.
 8965:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8966:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8967:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8968:         $uhome=&homeserver($uname,$udom,'true');
 8969:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8970:             return 'error: unable to generate unique course-ID';
 8971:         }
 8972:     }
 8973:     return $uname;
 8974: }
 8975: 
 8976: sub is_course {
 8977:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8978:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8979: 
 8980:     return unless $cdom and $cnum;
 8981: 
 8982:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8983:         '.');
 8984: 
 8985:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8986:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8987: }
 8988: 
 8989: sub store_userdata {
 8990:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8991:     my $result;
 8992:     if ($datakey ne '') {
 8993:         if (ref($storehash) eq 'HASH') {
 8994:             if ($udom eq '' || $uname eq '') {
 8995:                 $udom = $env{'user.domain'};
 8996:                 $uname = $env{'user.name'};
 8997:             }
 8998:             my $uhome=&homeserver($uname,$udom);
 8999:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 9000:                 $result = 'error: no_host';
 9001:             } else {
 9002:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 9003:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 9004: 
 9005:                 my $namevalue='';
 9006:                 foreach my $key (keys(%{$storehash})) {
 9007:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 9008:                 }
 9009:                 $namevalue=~s/\&$//;
 9010:                 unless ($namespace eq 'courserequests') {
 9011:                     $datakey = &escape($datakey);
 9012:                 }
 9013:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 9014:                                   $namevalue,$uhome);
 9015:             }
 9016:         } else {
 9017:             $result = 'error: data to store was not a hash reference'; 
 9018:         }
 9019:     } else {
 9020:         $result= 'error: invalid requestkey'; 
 9021:     }
 9022:     return $result;
 9023: }
 9024: 
 9025: # ---------------------------------------------------------- Assign Custom Role
 9026: 
 9027: sub assigncustomrole {
 9028:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 9029:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 9030:                        $end,$start,$deleteflag,$selfenroll,$context);
 9031: }
 9032: 
 9033: # ----------------------------------------------------------------- Revoke Role
 9034: 
 9035: sub revokerole {
 9036:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 9037:     my $now=time;
 9038:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 9039: }
 9040: 
 9041: # ---------------------------------------------------------- Revoke Custom Role
 9042: 
 9043: sub revokecustomrole {
 9044:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9045:     my $now=time;
 9046:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9047:            $deleteflag,$selfenroll,$context);
 9048: }
 9049: 
 9050: # ------------------------------------------------------------ Disk usage
 9051: sub diskusage {
 9052:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 9053:     $directorypath =~ s/\/$//;
 9054:     my $listing=&reply('du2:'.&escape($directorypath).':'
 9055:                        .&escape($getpropath).':'.&escape($uname).':'
 9056:                        .&escape($udom),homeserver($uname,$udom));
 9057:     if ($listing eq 'unknown_cmd') {
 9058:         if ($getpropath) {
 9059:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 9060:         }
 9061:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 9062:     }
 9063:     return $listing;
 9064: }
 9065: 
 9066: sub is_locked {
 9067:     my ($file_name, $domain, $user, $which) = @_;
 9068:     my @check;
 9069:     my $is_locked;
 9070:     push (@check,$file_name);
 9071:     my %locked = &get('file_permissions',\@check,
 9072: 		      $env{'user.domain'},$env{'user.name'});
 9073:     my ($tmp)=keys(%locked);
 9074:     if ($tmp=~/^error:/) { undef(%locked); }
 9075:     
 9076:     if (ref($locked{$file_name}) eq 'ARRAY') {
 9077:         $is_locked = 'false';
 9078:         foreach my $entry (@{$locked{$file_name}}) {
 9079:            if (ref($entry) eq 'ARRAY') {
 9080:                $is_locked = 'true';
 9081:                if (ref($which) eq 'ARRAY') {
 9082:                    push(@{$which},$entry);
 9083:                } else {
 9084:                    last;
 9085:                }
 9086:            }
 9087:        }
 9088:     } else {
 9089:         $is_locked = 'false';
 9090:     }
 9091:     return $is_locked;
 9092: }
 9093: 
 9094: sub declutter_portfile {
 9095:     my ($file) = @_;
 9096:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9097:     return $file;
 9098: }
 9099: 
 9100: # ------------------------------------------------------------- Mark as Read Only
 9101: 
 9102: sub mark_as_readonly {
 9103:     my ($domain,$user,$files,$what) = @_;
 9104:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9105:     my ($tmp)=keys(%current_permissions);
 9106:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9107:     foreach my $file (@{$files}) {
 9108: 	$file = &declutter_portfile($file);
 9109:         push(@{$current_permissions{$file}},$what);
 9110:     }
 9111:     &put('file_permissions',\%current_permissions,$domain,$user);
 9112:     return;
 9113: }
 9114: 
 9115: # ------------------------------------------------------------Save Selected Files
 9116: 
 9117: sub save_selected_files {
 9118:     my ($user, $path, @files) = @_;
 9119:     my $filename = $user."savedfiles";
 9120:     my @other_files = &files_not_in_path($user, $path);
 9121:     open (OUT, '>'.$tmpdir.$filename);
 9122:     foreach my $file (@files) {
 9123:         print (OUT $env{'form.currentpath'}.$file."\n");
 9124:     }
 9125:     foreach my $file (@other_files) {
 9126:         print (OUT $file."\n");
 9127:     }
 9128:     close (OUT);
 9129:     return 'ok';
 9130: }
 9131: 
 9132: sub clear_selected_files {
 9133:     my ($user) = @_;
 9134:     my $filename = $user."savedfiles";
 9135:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9136:     print (OUT undef);
 9137:     close (OUT);
 9138:     return ("ok");    
 9139: }
 9140: 
 9141: sub files_in_path {
 9142:     my ($user, $path) = @_;
 9143:     my $filename = $user."savedfiles";
 9144:     my %return_files;
 9145:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9146:     while (my $line_in = <IN>) {
 9147:         chomp ($line_in);
 9148:         my @paths_and_file = split (m!/!, $line_in);
 9149:         my $file_part = pop (@paths_and_file);
 9150:         my $path_part = join ('/', @paths_and_file);
 9151:         $path_part.='/';
 9152:         my $path_and_file = $path_part.$file_part;
 9153:         if ($path_part eq $path) {
 9154:             $return_files{$file_part}= 'selected';
 9155:         }
 9156:     }
 9157:     close (IN);
 9158:     return (\%return_files);
 9159: }
 9160: 
 9161: # called in portfolio select mode, to show files selected NOT in current directory
 9162: sub files_not_in_path {
 9163:     my ($user, $path) = @_;
 9164:     my $filename = $user."savedfiles";
 9165:     my @return_files;
 9166:     my $path_part;
 9167:     open(IN, '<'.LONCAPA::.$filename);
 9168:     while (my $line = <IN>) {
 9169:         #ok, I know it's clunky, but I want it to work
 9170:         my @paths_and_file = split(m|/|, $line);
 9171:         my $file_part = pop(@paths_and_file);
 9172:         chomp($file_part);
 9173:         my $path_part = join('/', @paths_and_file);
 9174:         $path_part .= '/';
 9175:         my $path_and_file = $path_part.$file_part;
 9176:         if ($path_part ne $path) {
 9177:             push(@return_files, ($path_and_file));
 9178:         }
 9179:     }
 9180:     close(OUT);
 9181:     return (@return_files);
 9182: }
 9183: 
 9184: #------------------------------Submitted/Handedback Portfolio Files Versioning
 9185:  
 9186: sub portfiles_versioning {
 9187:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
 9188:     my $portfolio_root = '/userfiles/portfolio';
 9189:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
 9190:     foreach my $file (@{$portfiles}) {
 9191:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 9192:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 9193:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
 9194:         my $getpropath = 1;
 9195:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
 9196:                                              $stu_name,$getpropath);
 9197:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 9198:         my $new_answer = 
 9199:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
 9200:         if ($new_answer ne 'problem getting file') {
 9201:             push(@{$versioned_portfiles}, $directory.$new_answer);
 9202:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
 9203:                               [$symb,$env{'request.course.id'},'graded']);
 9204:         }
 9205:     }
 9206: }
 9207: 
 9208: sub get_next_version {
 9209:     my ($answer_name, $answer_ext, $dir_list) = @_;
 9210:     my $version;
 9211:     if (ref($dir_list) eq 'ARRAY') {
 9212:         foreach my $row (@{$dir_list}) {
 9213:             my ($file) = split(/\&/,$row,2);
 9214:             my ($file_name,$file_version,$file_ext) =
 9215:                 &file_name_version_ext($file);
 9216:             if (($file_name eq $answer_name) &&
 9217:                 ($file_ext eq $answer_ext)) {
 9218:                      # gets here if filename and extension match,
 9219:                      # regardless of version
 9220:                 if ($file_version ne '') {
 9221:                     # a versioned file is found  so save it for later
 9222:                     if ($file_version > $version) {
 9223:                         $version = $file_version;
 9224:                     }
 9225:                 }
 9226:             }
 9227:         }
 9228:     }
 9229:     $version ++;
 9230:     return($version);
 9231: }
 9232: 
 9233: sub version_selected_portfile {
 9234:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 9235:     my ($answer_name,$answer_ver,$answer_ext) =
 9236:         &file_name_version_ext($file_name);
 9237:     my $new_answer;
 9238:     $env{'form.copy'} =
 9239:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 9240:     if($env{'form.copy'} eq '-1') {
 9241:         $new_answer = 'problem getting file';
 9242:     } else {
 9243:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 9244:         my $copy_result = 
 9245:             &finishuserfileupload($stu_name,$domain,'copy',
 9246:                                   '/portfolio'.$directory.$new_answer);
 9247:     }
 9248:     undef($env{'form.copy'});
 9249:     return ($new_answer);
 9250: }
 9251: 
 9252: sub file_name_version_ext {
 9253:     my ($file)=@_;
 9254:     my @file_parts = split(/\./, $file);
 9255:     my ($name,$version,$ext);
 9256:     if (@file_parts > 1) {
 9257:         $ext=pop(@file_parts);
 9258:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 9259:             $version=pop(@file_parts);
 9260:         }
 9261:         $name=join('.',@file_parts);
 9262:     } else {
 9263:         $name=join('.',@file_parts);
 9264:     }
 9265:     return($name,$version,$ext);
 9266: }
 9267: 
 9268: #----------------------------------------------Get portfolio file permissions
 9269: 
 9270: sub get_portfile_permissions {
 9271:     my ($domain,$user) = @_;
 9272:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9273:     my ($tmp)=keys(%current_permissions);
 9274:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9275:     return \%current_permissions;
 9276: }
 9277: 
 9278: #---------------------------------------------Get portfolio file access controls
 9279: 
 9280: sub get_access_controls {
 9281:     my ($current_permissions,$group,$file) = @_;
 9282:     my %access;
 9283:     my $real_file = $file;
 9284:     $file =~ s/\.meta$//;
 9285:     if (defined($file)) {
 9286:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9287:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9288:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9289:             }
 9290:         }
 9291:     } else {
 9292:         foreach my $key (keys(%{$current_permissions})) {
 9293:             if ($key =~ /\0accesscontrol$/) {
 9294:                 if (defined($group)) {
 9295:                     if ($key !~ m-^\Q$group\E/-) {
 9296:                         next;
 9297:                     }
 9298:                 }
 9299:                 my ($fullpath) = split(/\0/,$key);
 9300:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9301:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9302:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9303:                     }
 9304:                 }
 9305:             }
 9306:         }
 9307:     }
 9308:     return %access;
 9309: }
 9310: 
 9311: sub modify_access_controls {
 9312:     my ($file_name,$changes,$domain,$user)=@_;
 9313:     my ($outcome,$deloutcome);
 9314:     my %store_permissions;
 9315:     my %new_values;
 9316:     my %new_control;
 9317:     my %translation;
 9318:     my @deletions = ();
 9319:     my $now = time;
 9320:     if (exists($$changes{'activate'})) {
 9321:         if (ref($$changes{'activate'}) eq 'HASH') {
 9322:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9323:             my $numnew = scalar(@newitems);
 9324:             for (my $i=0; $i<$numnew; $i++) {
 9325:                 my $newkey = $newitems[$i];
 9326:                 my $newid = &Apache::loncommon::get_cgi_id();
 9327:                 if ($newkey =~ /^\d+:/) { 
 9328:                     $newkey =~ s/^(\d+)/$newid/;
 9329:                     $translation{$1} = $newid;
 9330:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9331:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9332:                     $translation{$1} = $newid;
 9333:                 }
 9334:                 $new_values{$file_name."\0".$newkey} = 
 9335:                                           $$changes{'activate'}{$newitems[$i]};
 9336:                 $new_control{$newkey} = $now;
 9337:             }
 9338:         }
 9339:     }
 9340:     my %todelete;
 9341:     my %changed_items;
 9342:     foreach my $action ('delete','update') {
 9343:         if (exists($$changes{$action})) {
 9344:             if (ref($$changes{$action}) eq 'HASH') {
 9345:                 foreach my $key (keys(%{$$changes{$action}})) {
 9346:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9347:                     if ($action eq 'delete') { 
 9348:                         $todelete{$itemnum} = 1;
 9349:                     } else {
 9350:                         $changed_items{$itemnum} = $key;
 9351:                     }
 9352:                 }
 9353:             }
 9354:         }
 9355:     }
 9356:     # get lock on access controls for file.
 9357:     my $lockhash = {
 9358:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9359:                                                        ':'.$env{'user.domain'},
 9360:                    }; 
 9361:     my $tries = 0;
 9362:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9363:    
 9364:     while (($gotlock ne 'ok') && $tries <3) {
 9365:         $tries ++;
 9366:         sleep 1;
 9367:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9368:     }
 9369:     if ($gotlock eq 'ok') {
 9370:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9371:         my ($tmp)=keys(%curr_permissions);
 9372:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9373:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9374:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9375:             if (ref($curr_controls) eq 'HASH') {
 9376:                 foreach my $control_item (keys(%{$curr_controls})) {
 9377:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9378:                     if (defined($todelete{$itemnum})) {
 9379:                         push(@deletions,$file_name."\0".$control_item);
 9380:                     } else {
 9381:                         if (defined($changed_items{$itemnum})) {
 9382:                             $new_control{$changed_items{$itemnum}} = $now;
 9383:                             push(@deletions,$file_name."\0".$control_item);
 9384:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9385:                         } else {
 9386:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9387:                         }
 9388:                     }
 9389:                 }
 9390:             }
 9391:         }
 9392:         my ($group);
 9393:         if (&is_course($domain,$user)) {
 9394:             ($group,my $file) = split(/\//,$file_name,2);
 9395:         }
 9396:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9397:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9398:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9399:         #  remove lock
 9400:         my @del_lock = ($file_name."\0".'locked_access_records');
 9401:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9402:         my $sqlresult =
 9403:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9404:                                     $group);
 9405:     } else {
 9406:         $outcome = "error: could not obtain lockfile\n";  
 9407:     }
 9408:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9409: }
 9410: 
 9411: sub make_public_indefinitely {
 9412:     my (@requrl) = @_;
 9413:     return &automated_portfile_access('public',\@requrl);
 9414: }
 9415: 
 9416: sub automated_portfile_access {
 9417:     my ($accesstype,$addsref,$delsref,$info) = @_;
 9418:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
 9419:         return 'invalid';
 9420:     }
 9421:     my %urls;
 9422:     if (ref($addsref) eq 'ARRAY') {
 9423:         foreach my $requrl (@{$addsref}) {
 9424:             if (&is_portfolio_url($requrl)) {
 9425:                 unless (exists($urls{$requrl})) {
 9426:                     $urls{$requrl} = 'add';
 9427:                 }
 9428:             }
 9429:         }
 9430:     }
 9431:     if (ref($delsref) eq 'ARRAY') {
 9432:         foreach my $requrl (@{$delsref}) { 
 9433:             if (&is_portfolio_url($requrl)) {
 9434:                 unless (exists($urls{$requrl})) {
 9435:                     $urls{$requrl} = 'delete'; 
 9436:                 }
 9437:             }
 9438:         }
 9439:     }
 9440:     unless (keys(%urls)) {
 9441:         return 'invalid';
 9442:     }
 9443:     my $ip;
 9444:     if ($accesstype eq 'ip') {
 9445:         if (ref($info) eq 'HASH') {
 9446:             if ($info->{'ip'} ne '') {
 9447:                 $ip = $info->{'ip'};
 9448:             }
 9449:         }
 9450:         if ($ip eq '') {
 9451:             return 'invalid';
 9452:         }
 9453:     }
 9454:     my $errors;
 9455:     my $now = time;
 9456:     my %current_perms;
 9457:     foreach my $requrl (sort(keys(%urls))) {
 9458:         my $action;
 9459:         if ($urls{$requrl} eq 'add') {
 9460:             $action = 'activate';
 9461:         } else {
 9462:             $action = 'none';
 9463:         }
 9464:         my $aclnum = 0;
 9465:         my (undef,$udom,$unum,$file_name,$group) =
 9466:             &parse_portfolio_url($requrl);
 9467:         unless (exists($current_perms{$unum.':'.$udom})) {
 9468:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
 9469:         }
 9470:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
 9471:                                                    $group,$file_name);
 9472:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9473:             my ($num,$scope,$end,$start) = 
 9474:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9475:             if ($scope eq $accesstype) {
 9476:                 if (($start <= $now) && ($end == 0)) {
 9477:                     if ($accesstype eq 'ip') {
 9478:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
 9479:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
 9480:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
 9481:                                     if ($urls{$requrl} eq 'add') {
 9482:                                         $action = 'none';
 9483:                                         last;
 9484:                                     } else {
 9485:                                         $action = 'delete';
 9486:                                         $aclnum = $num;
 9487:                                         last;
 9488:                                     }
 9489:                                 }
 9490:                             }
 9491:                         }
 9492:                     } elsif ($accesstype eq 'public') {
 9493:                         if ($urls{$requrl} eq 'add') {
 9494:                             $action = 'none';
 9495:                             last;
 9496:                         } else {
 9497:                             $action = 'delete';
 9498:                             $aclnum = $num;
 9499:                             last;
 9500:                         }
 9501:                     }
 9502:                 } elsif ($accesstype eq 'public') {
 9503:                     $action = 'update';
 9504:                     $aclnum = $num;
 9505:                     last;
 9506:                 }
 9507:             }
 9508:         }
 9509:         if ($action eq 'none') {
 9510:             next;
 9511:         } else {
 9512:             my %changes;
 9513:             my $newend = 0;
 9514:             my $newstart = $now;
 9515:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
 9516:             $changes{$action}{$newkey} = {
 9517:                 type => $accesstype,
 9518:                 time => {
 9519:                     start => $newstart,
 9520:                     end   => $newend,
 9521:                 },
 9522:             };
 9523:             if ($accesstype eq 'ip') {
 9524:                 $changes{$action}{$newkey}{'ip'} = [$ip];
 9525:             }
 9526:             my ($outcome,$deloutcome,$new_values,$translation) =
 9527:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9528:             unless ($outcome eq 'ok') {
 9529:                 $errors .= $outcome.' ';
 9530:             }
 9531:         }
 9532:     }
 9533:     if ($errors) {
 9534:         $errors =~ s/\s$//;
 9535:         return $errors;
 9536:     } else {
 9537:         return 'ok';
 9538:     }
 9539: }
 9540: 
 9541: #------------------------------------------------------Get Marked as Read Only
 9542: 
 9543: sub get_marked_as_readonly {
 9544:     my ($domain,$user,$what,$group) = @_;
 9545:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9546:     my @readonly_files;
 9547:     my $cmp1=$what;
 9548:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9549:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9550:         if (defined($group)) {
 9551:             if ($file_name !~ m-^\Q$group\E/-) {
 9552:                 next;
 9553:             }
 9554:         }
 9555:         if (ref($value) eq "ARRAY"){
 9556:             foreach my $stored_what (@{$value}) {
 9557:                 my $cmp2=$stored_what;
 9558:                 if (ref($stored_what) eq 'ARRAY') {
 9559:                     $cmp2=join('',@{$stored_what});
 9560:                 }
 9561:                 if ($cmp1 eq $cmp2) {
 9562:                     push(@readonly_files, $file_name);
 9563:                     last;
 9564:                 } elsif (!defined($what)) {
 9565:                     push(@readonly_files, $file_name);
 9566:                     last;
 9567:                 }
 9568:             }
 9569:         }
 9570:     }
 9571:     return @readonly_files;
 9572: }
 9573: #-----------------------------------------------------------Get Marked as Read Only Hash
 9574: 
 9575: sub get_marked_as_readonly_hash {
 9576:     my ($current_permissions,$group,$what) = @_;
 9577:     my %readonly_files;
 9578:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9579:         if (defined($group)) {
 9580:             if ($file_name !~ m-^\Q$group\E/-) {
 9581:                 next;
 9582:             }
 9583:         }
 9584:         if (ref($value) eq "ARRAY"){
 9585:             foreach my $stored_what (@{$value}) {
 9586:                 if (ref($stored_what) eq 'ARRAY') {
 9587:                     foreach my $lock_descriptor(@{$stored_what}) {
 9588:                         if ($lock_descriptor eq 'graded') {
 9589:                             $readonly_files{$file_name} = 'graded';
 9590:                         } elsif ($lock_descriptor eq 'handback') {
 9591:                             $readonly_files{$file_name} = 'handback';
 9592:                         } else {
 9593:                             if (!exists($readonly_files{$file_name})) {
 9594:                                 $readonly_files{$file_name} = 'locked';
 9595:                             }
 9596:                         }
 9597:                     }
 9598:                 } 
 9599:             }
 9600:         } 
 9601:     }
 9602:     return %readonly_files;
 9603: }
 9604: # ------------------------------------------------------------ Unmark as Read Only
 9605: 
 9606: sub unmark_as_readonly {
 9607:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9608:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9609:     my ($domain,$user,$what,$file_name,$group) = @_;
 9610:     $file_name = &declutter_portfile($file_name);
 9611:     my $symb_crs = $what;
 9612:     if (ref($what)) { $symb_crs=join('',@$what); }
 9613:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9614:     my ($tmp)=keys(%current_permissions);
 9615:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9616:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9617:     foreach my $file (@readonly_files) {
 9618: 	my $clean_file = &declutter_portfile($file);
 9619: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9620: 	my $current_locks = $current_permissions{$file};
 9621:         my @new_locks;
 9622:         my @del_keys;
 9623:         if (ref($current_locks) eq "ARRAY"){
 9624:             foreach my $locker (@{$current_locks}) {
 9625:                 my $compare=$locker;
 9626:                 if (ref($locker) eq 'ARRAY') {
 9627:                     $compare=join('',@{$locker});
 9628:                     if ($compare ne $symb_crs) {
 9629:                         push(@new_locks, $locker);
 9630:                     }
 9631:                 }
 9632:             }
 9633:             if (scalar(@new_locks) > 0) {
 9634:                 $current_permissions{$file} = \@new_locks;
 9635:             } else {
 9636:                 push(@del_keys, $file);
 9637:                 &del('file_permissions',\@del_keys, $domain, $user);
 9638:                 delete($current_permissions{$file});
 9639:             }
 9640:         }
 9641:     }
 9642:     &put('file_permissions',\%current_permissions,$domain,$user);
 9643:     return;
 9644: }
 9645: 
 9646: # ------------------------------------------------------------ Directory lister
 9647: 
 9648: sub dirlist {
 9649:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9650:     $uri=~s/^\///;
 9651:     $uri=~s/\/$//;
 9652:     my ($udom, $uname);
 9653:     if ($getuserdir) {
 9654:         $udom = $userdomain;
 9655:         $uname = $username;
 9656:     } else {
 9657:         (undef,$udom,$uname)=split(/\//,$uri);
 9658:         if(defined($userdomain)) {
 9659:             $udom = $userdomain;
 9660:         }
 9661:         if(defined($username)) {
 9662:             $uname = $username;
 9663:         }
 9664:     }
 9665:     my ($dirRoot,$listing,@listing_results);
 9666: 
 9667:     $dirRoot = $perlvar{'lonDocRoot'};
 9668:     if (defined($getpropath)) {
 9669:         $dirRoot = &propath($udom,$uname);
 9670:         $dirRoot =~ s/\/$//;
 9671:     } elsif (defined($getuserdir)) {
 9672:         my $subdir=$uname.'__';
 9673:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9674:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9675:                    ."/$udom/$subdir/$uname";
 9676:     } elsif (defined($alternateRoot)) {
 9677:         $dirRoot = $alternateRoot;
 9678:     }
 9679: 
 9680:     if($udom) {
 9681:         if($uname) {
 9682:             my $uhome = &homeserver($uname,$udom);
 9683:             if ($uhome eq 'no_host') {
 9684:                 return ([],'no_host');
 9685:             }
 9686:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9687:                               .$getuserdir.':'.&escape($dirRoot)
 9688:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9689:             if ($listing eq 'unknown_cmd') {
 9690:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9691:             } else {
 9692:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9693:             }
 9694:             if ($listing eq 'unknown_cmd') {
 9695:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9696:                 @listing_results = split(/:/,$listing);
 9697:             } else {
 9698:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9699:             }
 9700:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9701:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9702:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9703:                 return ([],$listing);
 9704:             } else {
 9705:                 return (\@listing_results);
 9706:             }
 9707:         } elsif(!$alternateRoot) {
 9708:             my (%allusers,%listerror);
 9709: 	    my %servers = &get_servers($udom,'library');
 9710:  	    foreach my $tryserver (keys(%servers)) {
 9711:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9712:                                   &escape($udom),$tryserver);
 9713:                 if ($listing eq 'unknown_cmd') {
 9714: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9715: 				      $udom, $tryserver);
 9716:                 } else {
 9717:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9718:                 }
 9719: 		if ($listing eq 'unknown_cmd') {
 9720: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9721: 				      $udom, $tryserver);
 9722: 		    @listing_results = split(/:/,$listing);
 9723: 		} else {
 9724: 		    @listing_results =
 9725: 			map { &unescape($_); } split(/:/,$listing);
 9726: 		}
 9727:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9728:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9729:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9730:                     $listerror{$tryserver} = $listing;
 9731:                 } else {
 9732: 		    foreach my $line (@listing_results) {
 9733: 			my ($entry) = split(/&/,$line,2);
 9734: 			$allusers{$entry} = 1;
 9735: 		    }
 9736: 		}
 9737:             }
 9738:             my @alluserslist=();
 9739:             foreach my $user (sort(keys(%allusers))) {
 9740:                 push(@alluserslist,$user.'&user');
 9741:             }
 9742:             return (\@alluserslist);
 9743:         } else {
 9744:             return ([],'missing username');
 9745:         }
 9746:     } elsif(!defined($getpropath)) {
 9747:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9748:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9749:         return (\@all_domains);
 9750:     } else {
 9751:         return ([],'missing domain');
 9752:     }
 9753: }
 9754: 
 9755: # --------------------------------------------- GetFileTimestamp
 9756: # This function utilizes dirlist and returns the date stamp for
 9757: # when it was last modified.  It will also return an error of -1
 9758: # if an error occurs
 9759: 
 9760: sub GetFileTimestamp {
 9761:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9762:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9763:     $studentName   = &LONCAPA::clean_username($studentName);
 9764:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9765:                                     undef,$getuserdir);
 9766:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9767:         return -1;
 9768:     }
 9769:     if (ref($fileref) eq 'ARRAY') {
 9770:         my @stats = split('&',$fileref->[0]);
 9771:         # @stats contains first the filename, then the stat output
 9772:         return $stats[10]; # so this is 10 instead of 9.
 9773:     } else {
 9774:         return -1;
 9775:     }
 9776: }
 9777: 
 9778: sub stat_file {
 9779:     my ($uri) = @_;
 9780:     $uri = &clutter_with_no_wrapper($uri);
 9781: 
 9782:     my ($udom,$uname,$file);
 9783:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9784: 	($udom,$uname,$file) =
 9785: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9786: 	$file = 'userfiles/'.$file;
 9787:     }
 9788:     if ($uri =~ m-^/res/-) {
 9789: 	($udom,$uname) = 
 9790: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9791: 	$file = $uri;
 9792:     }
 9793: 
 9794:     if (!$udom || !$uname || !$file) {
 9795: 	# unable to handle the uri
 9796: 	return ();
 9797:     }
 9798:     my $getpropath;
 9799:     if ($file =~ /^userfiles\//) {
 9800:         $getpropath = 1;
 9801:     }
 9802:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9803:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9804:         return ();
 9805:     } else {
 9806:         if (ref($listref) eq 'ARRAY') {
 9807:             my @stats = split('&',$listref->[0]);
 9808: 	    shift(@stats); #filename is first
 9809: 	    return @stats;
 9810:         }
 9811:     }
 9812:     return ();
 9813: }
 9814: 
 9815: # -------------------------------------------------------- Value of a Condition
 9816: 
 9817: # gets the value of a specific preevaluated condition
 9818: #    stored in the string  $env{user.state.<cid>}
 9819: # or looks up a condition reference in the bighash and if if hasn't
 9820: # already been evaluated recurses into docondval to get the value of
 9821: # the condition, then memoizing it to 
 9822: #   $env{user.state.<cid>.<condition>}
 9823: sub directcondval {
 9824:     my $number=shift;
 9825:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9826: 	&Apache::lonuserstate::evalstate();
 9827:     }
 9828:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9829: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9830:     } elsif ($number =~ /^_/) {
 9831: 	my $sub_condition;
 9832: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9833: 		&GDBM_READER(),0640)) {
 9834: 	    $sub_condition=$bighash{'conditions'.$number};
 9835: 	    untie(%bighash);
 9836: 	}
 9837: 	my $value = &docondval($sub_condition);
 9838: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9839: 	return $value;
 9840:     }
 9841:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9842:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9843:     } else {
 9844:        return 2;
 9845:     }
 9846: }
 9847: 
 9848: # get the collection of conditions for this resource
 9849: sub condval {
 9850:     my $condidx=shift;
 9851:     my $allpathcond='';
 9852:     foreach my $cond (split(/\|/,$condidx)) {
 9853: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9854: 	    $allpathcond.=
 9855: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9856: 	}
 9857:     }
 9858:     $allpathcond=~s/\|$//;
 9859:     return &docondval($allpathcond);
 9860: }
 9861: 
 9862: #evaluates an expression of conditions
 9863: sub docondval {
 9864:     my ($allpathcond) = @_;
 9865:     my $result=0;
 9866:     if ($env{'request.course.id'}
 9867: 	&& defined($allpathcond)) {
 9868: 	my $operand='|';
 9869: 	my @stack;
 9870: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9871: 	    if ($chunk eq '(') {
 9872: 		push @stack,($operand,$result);
 9873: 	    } elsif ($chunk eq ')') {
 9874: 		my $before=pop @stack;
 9875: 		if (pop @stack eq '&') {
 9876: 		    $result=$result>$before?$before:$result;
 9877: 		} else {
 9878: 		    $result=$result>$before?$result:$before;
 9879: 		}
 9880: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9881: 		$operand=$chunk;
 9882: 	    } else {
 9883: 		my $new=directcondval($chunk);
 9884: 		if ($operand eq '&') {
 9885: 		    $result=$result>$new?$new:$result;
 9886: 		} else {
 9887: 		    $result=$result>$new?$result:$new;
 9888: 		}
 9889: 	    }
 9890: 	}
 9891:     }
 9892:     return $result;
 9893: }
 9894: 
 9895: # ---------------------------------------------------- Devalidate courseresdata
 9896: 
 9897: sub devalidatecourseresdata {
 9898:     my ($coursenum,$coursedomain)=@_;
 9899:     my $hashid=$coursenum.':'.$coursedomain;
 9900:     &devalidate_cache_new('courseres',$hashid);
 9901: }
 9902: 
 9903: 
 9904: # --------------------------------------------------- Course Resourcedata Query
 9905: #
 9906: #  Parameters:
 9907: #      $coursenum    - Number of the course.
 9908: #      $coursedomain - Domain at which the course was created.
 9909: #  Returns:
 9910: #     A hash of the course parameters along (I think) with timestamps
 9911: #     and version info.
 9912: 
 9913: sub get_courseresdata {
 9914:     my ($coursenum,$coursedomain)=@_;
 9915:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9916:     my $hashid=$coursenum.':'.$coursedomain;
 9917:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9918:     my %dumpreply;
 9919:     unless (defined($cached)) {
 9920: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9921: 	$result=\%dumpreply;
 9922: 	my ($tmp) = keys(%dumpreply);
 9923: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9924: 	    &do_cache_new('courseres',$hashid,$result,600);
 9925: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9926: 	    return $tmp;
 9927: 	} elsif ($tmp =~ /^(error)/) {
 9928: 	    $result=undef;
 9929: 	    &do_cache_new('courseres',$hashid,$result,600);
 9930: 	}
 9931:     }
 9932:     return $result;
 9933: }
 9934: 
 9935: sub devalidateuserresdata {
 9936:     my ($uname,$udom)=@_;
 9937:     my $hashid="$udom:$uname";
 9938:     &devalidate_cache_new('userres',$hashid);
 9939: }
 9940: 
 9941: sub get_userresdata {
 9942:     my ($uname,$udom)=@_;
 9943:     #most student don\'t have any data set, check if there is some data
 9944:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9945: 
 9946:     my $hashid="$udom:$uname";
 9947:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9948:     if (!defined($cached)) {
 9949: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9950: 	$result=\%resourcedata;
 9951: 	&do_cache_new('userres',$hashid,$result,600);
 9952:     }
 9953:     my ($tmp)=keys(%$result);
 9954:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9955: 	return $result;
 9956:     }
 9957:     #error 2 occurs when the .db doesn't exist
 9958:     if ($tmp!~/error: 2 /) {
 9959: 	&logthis("<font color=\"blue\">WARNING:".
 9960: 		 " Trying to get resource data for ".
 9961: 		 $uname." at ".$udom.": ".
 9962: 		 $tmp."</font>");
 9963:     } elsif ($tmp=~/error: 2 /) {
 9964: 	#&EXT_cache_set($udom,$uname);
 9965: 	&do_cache_new('userres',$hashid,undef,600);
 9966: 	undef($tmp); # not really an error so don't send it back
 9967:     }
 9968:     return $tmp;
 9969: }
 9970: #----------------------------------------------- resdata - return resource data
 9971: #  Purpose:
 9972: #    Return resource data for either users or for a course.
 9973: #  Parameters:
 9974: #     $name      - Course/user name.
 9975: #     $domain    - Name of the domain the user/course is registered on.
 9976: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9977: #     @which     - Array of names of resources desired.
 9978: #  Returns:
 9979: #     The value of the first reasource in @which that is found in the
 9980: #     resource hash.
 9981: #  Exceptional Conditions:
 9982: #     If the $type passed in is not valid (not the string 'course' or 
 9983: #     'user', an undefined  reference is returned.
 9984: #     If none of the resources are found, an undef is returned
 9985: sub resdata {
 9986:     my ($name,$domain,$type,@which)=@_;
 9987:     my $result;
 9988:     if ($type eq 'course') {
 9989: 	$result=&get_courseresdata($name,$domain);
 9990:     } elsif ($type eq 'user') {
 9991: 	$result=&get_userresdata($name,$domain);
 9992:     }
 9993:     if (!ref($result)) { return $result; }    
 9994:     foreach my $item (@which) {
 9995: 	if (defined($result->{$item->[0]})) {
 9996: 	    return [$result->{$item->[0]},$item->[1]];
 9997: 	}
 9998:     }
 9999:     return undef;
10000: }
10001: 
10002: sub get_numsuppfiles {
10003:     my ($cnum,$cdom,$ignorecache)=@_;
10004:     my $hashid=$cnum.':'.$cdom;
10005:     my ($suppcount,$cached);
10006:     unless ($ignorecache) {
10007:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10008:     }
10009:     unless (defined($cached)) {
10010:         my $chome=&homeserver($cnum,$cdom);
10011:         unless ($chome eq 'no_host') {
10012:             ($suppcount,my $errors) = (0,0);
10013:             my $suppmap = 'supplemental.sequence';
10014:             ($suppcount,$errors) = 
10015:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10016:         }
10017:         &do_cache_new('suppcount',$hashid,$suppcount,600);
10018:     }
10019:     return $suppcount;
10020: }
10021: 
10022: #
10023: # EXT resource caching routines
10024: #
10025: 
10026: sub clear_EXT_cache_status {
10027:     &delenv('cache.EXT.');
10028: }
10029: 
10030: sub EXT_cache_status {
10031:     my ($target_domain,$target_user) = @_;
10032:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10033:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
10034:         # We know already the user has no data
10035:         return 1;
10036:     } else {
10037:         return 0;
10038:     }
10039: }
10040: 
10041: sub EXT_cache_set {
10042:     my ($target_domain,$target_user) = @_;
10043:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10044:     #&appenv({$cachename => time});
10045: }
10046: 
10047: # --------------------------------------------------------- Value of a Variable
10048: sub EXT {
10049: 
10050:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
10051:     unless ($varname) { return ''; }
10052:     #get real user name/domain, courseid and symb
10053:     my $courseid;
10054:     my $publicuser;
10055:     if ($symbparm) {
10056: 	$symbparm=&get_symb_from_alias($symbparm);
10057:     }
10058:     if (!($uname && $udom)) {
10059:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
10060:       if (!$symbparm) {	$symbparm=$cursymb; }
10061:     } else {
10062: 	$courseid=$env{'request.course.id'};
10063:     }
10064:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10065:     my $rest;
10066:     if (defined($therest[0])) {
10067:        $rest=join('.',@therest);
10068:     } else {
10069:        $rest='';
10070:     }
10071: 
10072:     my $qualifierrest=$qualifier;
10073:     if ($rest) { $qualifierrest.='.'.$rest; }
10074:     my $spacequalifierrest=$space;
10075:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
10076:     if ($realm eq 'user') {
10077: # --------------------------------------------------------------- user.resource
10078: 	if ($space eq 'resource') {
10079: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
10080: 		  || defined($Apache::lonhomework::parsing_a_task))
10081: 		 &&
10082: 		 ($symbparm eq &symbread()) ) {	
10083: 		# if we are in the middle of processing the resource the
10084: 		# get the value we are planning on committing
10085:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
10086:                     return $Apache::lonhomework::results{$qualifierrest};
10087:                 } else {
10088:                     return $Apache::lonhomework::history{$qualifierrest};
10089:                 }
10090: 	    } else {
10091: 		my %restored;
10092: 		if ($publicuser || $env{'request.state'} eq 'construct') {
10093: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10094: 		} else {
10095: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
10096: 		}
10097: 		return $restored{$qualifierrest};
10098: 	    }
10099: # ----------------------------------------------------------------- user.access
10100:         } elsif ($space eq 'access') {
10101: 	    # FIXME - not supporting calls for a specific user
10102:             return &allowed($qualifier,$rest);
10103: # ------------------------------------------ user.preferences, user.environment
10104:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
10105: 	    if (($uname eq $env{'user.name'}) &&
10106: 		($udom eq $env{'user.domain'})) {
10107: 		return $env{join('.',('environment',$qualifierrest))};
10108: 	    } else {
10109: 		my %returnhash;
10110: 		if (!$publicuser) {
10111: 		    %returnhash=&userenvironment($udom,$uname,
10112: 						 $qualifierrest);
10113: 		}
10114: 		return $returnhash{$qualifierrest};
10115: 	    }
10116: # ----------------------------------------------------------------- user.course
10117:         } elsif ($space eq 'course') {
10118: 	    # FIXME - not supporting calls for a specific user
10119:             return $env{join('.',('request.course',$qualifier))};
10120: # ------------------------------------------------------------------- user.role
10121:         } elsif ($space eq 'role') {
10122: 	    # FIXME - not supporting calls for a specific user
10123:             my ($role,$where)=split(/\./,$env{'request.role'});
10124:             if ($qualifier eq 'value') {
10125: 		return $role;
10126:             } elsif ($qualifier eq 'extent') {
10127:                 return $where;
10128:             }
10129: # ----------------------------------------------------------------- user.domain
10130:         } elsif ($space eq 'domain') {
10131:             return $udom;
10132: # ------------------------------------------------------------------- user.name
10133:         } elsif ($space eq 'name') {
10134:             return $uname;
10135: # ---------------------------------------------------- Any other user namespace
10136:         } else {
10137: 	    my %reply;
10138: 	    if (!$publicuser) {
10139: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
10140: 	    }
10141: 	    return $reply{$qualifierrest};
10142:         }
10143:     } elsif ($realm eq 'query') {
10144: # ---------------------------------------------- pull stuff out of query string
10145:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10146: 						[$spacequalifierrest]);
10147: 	return $env{'form.'.$spacequalifierrest}; 
10148:    } elsif ($realm eq 'request') {
10149: # ------------------------------------------------------------- request.browser
10150:         if ($space eq 'browser') {
10151:             return $env{'browser.'.$qualifier};
10152: # ------------------------------------------------------------ request.filename
10153:         } else {
10154:             return $env{'request.'.$spacequalifierrest};
10155:         }
10156:     } elsif ($realm eq 'course') {
10157: # ---------------------------------------------------------- course.description
10158:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
10159:     } elsif ($realm eq 'resource') {
10160: 
10161: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
10162: 	    if (!$symbparm) { $symbparm=&symbread(); }
10163: 	}
10164: 
10165:         if ($qualifier eq '') {
10166: 	    if ($space eq 'title') {
10167: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10168: 	        return &gettitle($symbparm);
10169: 	    }
10170: 	
10171: 	    if ($space eq 'map') {
10172: 	        my ($map) = &decode_symb($symbparm);
10173: 	        return &symbread($map);
10174: 	    }
10175:             if ($space eq 'maptitle') {
10176:                 my ($map) = &decode_symb($symbparm);
10177:                 return &gettitle($map);
10178:             }
10179: 	    if ($space eq 'filename') {
10180: 	        if ($symbparm) {
10181: 		    return &clutter((&decode_symb($symbparm))[2]);
10182: 	        }
10183: 	        return &hreflocation('',$env{'request.filename'});
10184: 	    }
10185: 
10186:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10187:                 if ($space eq 'visibleparts') {
10188:                     my $navmap = Apache::lonnavmaps::navmap->new();
10189:                     my $item;
10190:                     if (ref($navmap)) {
10191:                         my $res = $navmap->getBySymb($symbparm);
10192:                         my $parts = $res->parts();
10193:                         if (ref($parts) eq 'ARRAY') {
10194:                             $item = join(',',@{$parts});
10195:                         }
10196:                         undef($navmap);
10197:                     }
10198:                     return $item;
10199:                 }
10200:             }
10201:         }
10202: 
10203: 	my ($section, $group, @groups);
10204: 	my ($courselevelm,$courselevel);
10205:         if (($courseid eq '') && ($cid)) {
10206:             $courseid = $cid;
10207:         }
10208: 	if (($symbparm && $courseid) && 
10209: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
10210: 
10211: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
10212: 
10213: # ----------------------------------------------------- Cascading lookup scheme
10214: 	    my $symbp=$symbparm;
10215: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
10216: 
10217: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
10218: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10219: 
10220: 	    if (($env{'user.name'} eq $uname) &&
10221: 		($env{'user.domain'} eq $udom)) {
10222: 		$section=$env{'request.course.sec'};
10223:                 @groups = split(/:/,$env{'request.course.groups'});  
10224:                 @groups=&sort_course_groups($courseid,@groups); 
10225: 	    } else {
10226: 		if (! defined($usection)) {
10227: 		    $section=&getsection($udom,$uname,$courseid);
10228: 		} else {
10229: 		    $section = $usection;
10230: 		}
10231:                 @groups = &get_users_groups($udom,$uname,$courseid);
10232: 	    }
10233: 
10234: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10235: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10236: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10237: 
10238: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
10239: 	    my $courselevelr=$courseid.'.'.$symbparm;
10240: 	    $courselevelm=$courseid.'.'.$mapparm;
10241: 
10242: # ----------------------------------------------------------- first, check user
10243: 
10244: 	    my $userreply=&resdata($uname,$udom,'user',
10245: 				       ([$courselevelr,'resource'],
10246: 					[$courselevelm,'map'     ],
10247: 					[$courselevel, 'course'  ]));
10248: 	    if (defined($userreply)) { return &get_reply($userreply); }
10249: 
10250: # ------------------------------------------------ second, check some of course
10251:             my $coursereply;
10252:             if (@groups > 0) {
10253:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10254:                                        $mapparm,$spacequalifierrest);
10255:                 if (defined($coursereply)) { return &get_reply($coursereply); }
10256:             }
10257: 
10258: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10259: 				  $env{'course.'.$courseid.'.domain'},
10260: 				  'course',
10261: 				  ([$seclevelr,   'resource'],
10262: 				   [$seclevelm,   'map'     ],
10263: 				   [$seclevel,    'course'  ],
10264: 				   [$courselevelr,'resource']));
10265: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10266: 
10267: # ------------------------------------------------------ third, check map parms
10268: 	    my %parmhash=();
10269: 	    my $thisparm='';
10270: 	    if (tie(%parmhash,'GDBM_File',
10271: 		    $env{'request.course.fn'}.'_parms.db',
10272: 		    &GDBM_READER(),0640)) {
10273: 		$thisparm=$parmhash{$symbparm};
10274: 		untie(%parmhash);
10275: 	    }
10276: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10277: 	}
10278: # ------------------------------------------ fourth, look in resource metadata
10279: 
10280: 	$spacequalifierrest=~s/\./\_/;
10281: 	my $filename;
10282: 	if (!$symbparm) { $symbparm=&symbread(); }
10283: 	if ($symbparm) {
10284: 	    $filename=(&decode_symb($symbparm))[2];
10285: 	} else {
10286: 	    $filename=$env{'request.filename'};
10287: 	}
10288: 	my $metadata=&metadata($filename,$spacequalifierrest);
10289: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10290: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10291: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10292: 
10293: # ---------------------------------------------- fourth, look in rest of course
10294: 	if ($symbparm && defined($courseid) && 
10295: 	    $courseid eq $env{'request.course.id'}) {
10296: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10297: 				     $env{'course.'.$courseid.'.domain'},
10298: 				     'course',
10299: 				     ([$courselevelm,'map'   ],
10300: 				      [$courselevel, 'course']));
10301: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10302: 	}
10303: # ------------------------------------------------------------------ Cascade up
10304: 	unless ($space eq '0') {
10305: 	    my @parts=split(/_/,$space);
10306: 	    my $id=pop(@parts);
10307: 	    my $part=join('_',@parts);
10308: 	    if ($part eq '') { $part='0'; }
10309: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10310: 				 $symbparm,$udom,$uname,$section,1);
10311: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10312: 	}
10313: 	if ($recurse) { return undef; }
10314: 	my $pack_def=&packages_tab_default($filename,$varname);
10315: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10316: # ---------------------------------------------------- Any other user namespace
10317:     } elsif ($realm eq 'environment') {
10318: # ----------------------------------------------------------------- environment
10319: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10320: 	    return $env{'environment.'.$spacequalifierrest};
10321: 	} else {
10322: 	    if ($uname eq 'anonymous' && $udom eq '') {
10323: 		return '';
10324: 	    }
10325: 	    my %returnhash=&userenvironment($udom,$uname,
10326: 					    $spacequalifierrest);
10327: 	    return $returnhash{$spacequalifierrest};
10328: 	}
10329:     } elsif ($realm eq 'system') {
10330: # ----------------------------------------------------------------- system.time
10331: 	if ($space eq 'time') {
10332: 	    return time;
10333:         }
10334:     } elsif ($realm eq 'server') {
10335: # ----------------------------------------------------------------- system.time
10336: 	if ($space eq 'name') {
10337: 	    return $ENV{'SERVER_NAME'};
10338:         }
10339:     }
10340:     return '';
10341: }
10342: 
10343: sub get_reply {
10344:     my ($reply_value) = @_;
10345:     if (ref($reply_value) eq 'ARRAY') {
10346:         if (wantarray) {
10347: 	    return @$reply_value;
10348:         }
10349:         return $reply_value->[0];
10350:     } else {
10351:         return $reply_value;
10352:     }
10353: }
10354: 
10355: sub check_group_parms {
10356:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10357:     my @groupitems = ();
10358:     my $resultitem;
10359:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10360:     foreach my $group (@{$groups}) {
10361:         foreach my $level (@levels) {
10362:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10363:              push(@groupitems,[$item,$level->[1]]);
10364:         }
10365:     }
10366:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10367:                             $env{'course.'.$courseid.'.domain'},
10368:                                      'course',@groupitems);
10369:     return $coursereply;
10370: }
10371: 
10372: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10373:     my ($courseid,@groups) = @_;
10374:     @groups = sort(@groups);
10375:     return @groups;
10376: }
10377: 
10378: sub packages_tab_default {
10379:     my ($uri,$varname)=@_;
10380:     my (undef,$part,$name)=split(/\./,$varname);
10381: 
10382:     my (@extension,@specifics,$do_default);
10383:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10384: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10385: 	if ($pack_type eq 'default') {
10386: 	    $do_default=1;
10387: 	} elsif ($pack_type eq 'extension') {
10388: 	    push(@extension,[$package,$pack_type,$pack_part]);
10389: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10390: 	    # only look at packages defaults for packages that this id is
10391: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10392: 	}
10393:     }
10394:     # first look for a package that matches the requested part id
10395:     foreach my $package (@specifics) {
10396: 	my (undef,$pack_type,$pack_part)=@{$package};
10397: 	next if ($pack_part ne $part);
10398: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10399: 	    return $packagetab{"$pack_type&$name&default"};
10400: 	}
10401:     }
10402:     # look for any possible matching non extension_ package
10403:     foreach my $package (@specifics) {
10404: 	my (undef,$pack_type,$pack_part)=@{$package};
10405: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10406: 	    return $packagetab{"$pack_type&$name&default"};
10407: 	}
10408: 	if ($pack_type eq 'part') { $pack_part='0'; }
10409: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10410: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10411: 	}
10412:     }
10413:     # look for any posible extension_ match
10414:     foreach my $package (@extension) {
10415: 	my ($package,$pack_type)=@{$package};
10416: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10417: 	    return $packagetab{"$pack_type&$name&default"};
10418: 	}
10419: 	if (defined($packagetab{$package."&$name&default"})) {
10420: 	    return $packagetab{$package."&$name&default"};
10421: 	}
10422:     }
10423:     # look for a global default setting
10424:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10425: 	return $packagetab{"default&$name&default"};
10426:     }
10427:     return undef;
10428: }
10429: 
10430: sub add_prefix_and_part {
10431:     my ($prefix,$part)=@_;
10432:     my $keyroot;
10433:     if (defined($prefix) && $prefix !~ /^__/) {
10434: 	# prefix that has a part already
10435: 	$keyroot=$prefix;
10436:     } elsif (defined($prefix)) {
10437: 	# prefix that is missing a part
10438: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10439:     } else {
10440: 	# no prefix at all
10441: 	if (defined($part)) { $keyroot='_'.$part; }
10442:     }
10443:     return $keyroot;
10444: }
10445: 
10446: # ---------------------------------------------------------------- Get metadata
10447: 
10448: my %metaentry;
10449: my %importedpartids;
10450: sub metadata {
10451:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10452:     $uri=&declutter($uri);
10453:     # if it is a non metadata possible uri return quickly
10454:     if (($uri eq '') || 
10455: 	(($uri =~ m|^/*adm/|) && 
10456: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10457:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10458: 	return undef;
10459:     }
10460:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
10461: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10462: 	return undef;
10463:     }
10464:     my $filename=$uri;
10465:     $uri=~s/\.meta$//;
10466: #
10467: # Is the metadata already cached?
10468: # Look at timestamp of caching
10469: # Everything is cached by the main uri, libraries are never directly cached
10470: #
10471:     if (!defined($liburi)) {
10472: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10473: 	if (defined($cached)) { return $result->{':'.$what}; }
10474:     }
10475:     {
10476: # Imported parts would go here
10477:         my %importedids=();
10478:         my @origfileimportpartids=();
10479:         my $importedparts=0;
10480: #
10481: # Is this a recursive call for a library?
10482: #
10483: #	if (! exists($metacache{$uri})) {
10484: #	    $metacache{$uri}={};
10485: #	}
10486: 	my $cachetime = 60*60;
10487:         if ($liburi) {
10488: 	    $liburi=&declutter($liburi);
10489:             $filename=$liburi;
10490:         } else {
10491: 	    &devalidate_cache_new('meta',$uri);
10492: 	    undef(%metaentry);
10493: 	}
10494:         my %metathesekeys=();
10495:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10496: 	my $metastring;
10497: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10498: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10499: 	    $metastring = 
10500: 		&Apache::lonnet::ssi_body($which,
10501: 					  ('grade_target' => 'meta'));
10502: 	    $cachetime = 1; # only want this cached in the child not long term
10503: 	} elsif (($uri !~ m -^(editupload)/-) && 
10504:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10505: 	    my $file=&filelocation('',&clutter($filename));
10506: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10507: 	    $metastring=&getfile($file);
10508: 	}
10509:         my $parser=HTML::LCParser->new(\$metastring);
10510:         my $token;
10511:         undef %metathesekeys;
10512:         while ($token=$parser->get_token) {
10513: 	    if ($token->[0] eq 'S') {
10514: 		if (defined($token->[2]->{'package'})) {
10515: #
10516: # This is a package - get package info
10517: #
10518: 		    my $package=$token->[2]->{'package'};
10519: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10520: 		    if (defined($token->[2]->{'id'})) { 
10521: 			$keyroot.='_'.$token->[2]->{'id'}; 
10522: 		    }
10523: 		    if ($metaentry{':packages'}) {
10524: 			$metaentry{':packages'}.=','.$package.$keyroot;
10525: 		    } else {
10526: 			$metaentry{':packages'}=$package.$keyroot;
10527: 		    }
10528: 		    foreach my $pack_entry (keys(%packagetab)) {
10529: 			my $part=$keyroot;
10530: 			$part=~s/^\_//;
10531: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10532: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10533: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10534: 			    # ignore package.tab specified default values
10535:                             # here &package_tab_default() will fetch those
10536: 			    if ($subp eq 'default') { next; }
10537: 			    my $value=$packagetab{$pack_entry};
10538: 			    my $unikey;
10539: 			    if ($pack =~ /_0$/) {
10540: 				$unikey='parameter_0_'.$name;
10541: 				$part=0;
10542: 			    } else {
10543: 				$unikey='parameter'.$keyroot.'_'.$name;
10544: 			    }
10545: 			    if ($subp eq 'display') {
10546: 				$value.=' [Part: '.$part.']';
10547: 			    }
10548: 			    $metaentry{':'.$unikey.'.part'}=$part;
10549: 			    $metathesekeys{$unikey}=1;
10550: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10551: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10552: 			    }
10553: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10554: 				$metaentry{':'.$unikey}=
10555: 				    $metaentry{':'.$unikey.'.default'};
10556: 			    }
10557: 			}
10558: 		    }
10559: 		} else {
10560: #
10561: # This is not a package - some other kind of start tag
10562: #
10563: 		    my $entry=$token->[1];
10564: 		    my $unikey='';
10565: 
10566: 		    if ($entry eq 'import') {
10567: #
10568: # Importing a library here
10569: #
10570:                         my $location=$parser->get_text('/import');
10571:                         my $dir=$filename;
10572:                         $dir=~s|[^/]*$||;
10573:                         $location=&filelocation($dir,$location);
10574:                        
10575:                         my $importmode=$token->[2]->{'importmode'};
10576:                         if ($importmode eq 'problem') {
10577: # Import as problem/response
10578:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10579:                         } elsif ($importmode eq 'part') {
10580: # Import as part(s)
10581:                            $importedparts=1;
10582: # We need to get the original file and the imported file to get the part order correct
10583: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10584: # Load and inspect original file
10585:                            if ($#origfileimportpartids<0) {
10586:                               undef(%importedpartids);
10587:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10588:                               my $origfile=&getfile($origfilelocation);
10589:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10590:                            }
10591: 
10592: # Load and inspect imported file
10593:                            my $impfile=&getfile($location);
10594:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10595:                            if ($#impfilepartids>=0) {
10596: # This problem had parts
10597:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10598:                            } else {
10599: # Importing by turning a single problem into a problem part
10600: # It gets the import-tags ID as part-ID
10601:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10602:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10603:                            }
10604:                         } else {
10605: # Normal import
10606:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10607:                            if (defined($token->[2]->{'id'})) {
10608:                               $unikey.='_'.$token->[2]->{'id'};
10609:                            }
10610:                         }
10611: 
10612: 			if ($depthcount<20) {
10613: 			    my $metadata = 
10614: 				&metadata($uri,'keys', $location,$unikey,
10615: 					  $depthcount+1);
10616: 			    foreach my $meta (split(',',$metadata)) {
10617: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10618: 				$metathesekeys{$meta}=1;
10619: 			    }
10620: 			
10621:                         }
10622: 		    } else {
10623: #
10624: # Not importing, some other kind of non-package, non-library start tag
10625: # 
10626:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10627:                         if (defined($token->[2]->{'id'})) {
10628:                             $unikey.='_'.$token->[2]->{'id'};
10629:                         }
10630: 			if (defined($token->[2]->{'name'})) { 
10631: 			    $unikey.='_'.$token->[2]->{'name'}; 
10632: 			}
10633: 			$metathesekeys{$unikey}=1;
10634: 			foreach my $param (@{$token->[3]}) {
10635: 			    $metaentry{':'.$unikey.'.'.$param} =
10636: 				$token->[2]->{$param};
10637: 			}
10638: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10639: 			my $default=$metaentry{':'.$unikey.'.default'};
10640: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10641: 		 # only ws inside the tag, and not in default, so use default
10642: 		 # as value
10643: 			    $metaentry{':'.$unikey}=$default;
10644: 			} elsif ( $internaltext =~ /\S/ ) {
10645: 		  # something interesting inside the tag
10646: 			    $metaentry{':'.$unikey}=$internaltext;
10647: 			} else {
10648: 		  # no interesting values, don't set a default
10649: 			}
10650: # end of not-a-package not-a-library import
10651: 		    }
10652: # end of not-a-package start tag
10653: 		}
10654: # the next is the end of "start tag"
10655: 	    }
10656: 	}
10657: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10658: 	$extension = lc($extension);
10659: 	if ($extension eq 'htm') { $extension='html'; }
10660: 
10661: 	foreach my $key (keys(%packagetab)) {
10662: 	    #no specific packages #how's our extension
10663: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10664: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10665: 					 \%metathesekeys);
10666: 	}
10667: 
10668: 	if (!exists($metaentry{':packages'})
10669: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10670: 	    foreach my $key (keys(%packagetab)) {
10671: 		#no specific packages well let's get default then
10672: 		if ($key!~/^default&/) { next; }
10673: 		&metadata_create_package_def($uri,$key,'default',
10674: 					     \%metathesekeys);
10675: 	    }
10676: 	}
10677: # are there custom rights to evaluate
10678: 	if ($metaentry{':copyright'} eq 'custom') {
10679: 
10680:     #
10681:     # Importing a rights file here
10682:     #
10683: 	    unless ($depthcount) {
10684: 		my $location=$metaentry{':customdistributionfile'};
10685: 		my $dir=$filename;
10686: 		$dir=~s|[^/]*$||;
10687: 		$location=&filelocation($dir,$location);
10688: 		my $rights_metadata =
10689: 		    &metadata($uri,'keys',$location,'_rights',
10690: 			      $depthcount+1);
10691: 		foreach my $rights (split(',',$rights_metadata)) {
10692: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10693: 		    $metathesekeys{$rights}=1;
10694: 		}
10695: 	    }
10696: 	}
10697: 	# uniqifiy package listing
10698: 	my %seen;
10699: 	my @uniq_packages =
10700: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10701: 	$metaentry{':packages'} = join(',',@uniq_packages);
10702: 
10703:         if ($importedparts) {
10704: # We had imported parts and need to rebuild partorder
10705:            $metaentry{':partorder'}='';
10706:            $metathesekeys{'partorder'}=1;
10707:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10708:                if ($origfileimportpartids[$index] eq 'part') {
10709: # original part, part of the problem
10710:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10711:                } else {
10712: # we have imported parts at this position
10713:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10714:                }
10715:            }
10716:            $metaentry{':partorder'}=~s/^\,//;
10717:         }
10718: 
10719: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10720: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10721: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
10722: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10723: # this is the end of "was not already recently cached
10724:     }
10725:     return $metaentry{':'.$what};
10726: }
10727: 
10728: sub metadata_create_package_def {
10729:     my ($uri,$key,$package,$metathesekeys)=@_;
10730:     my ($pack,$name,$subp)=split(/\&/,$key);
10731:     if ($subp eq 'default') { next; }
10732:     
10733:     if (defined($metaentry{':packages'})) {
10734: 	$metaentry{':packages'}.=','.$package;
10735:     } else {
10736: 	$metaentry{':packages'}=$package;
10737:     }
10738:     my $value=$packagetab{$key};
10739:     my $unikey;
10740:     $unikey='parameter_0_'.$name;
10741:     $metaentry{':'.$unikey.'.part'}=0;
10742:     $$metathesekeys{$unikey}=1;
10743:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10744: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10745:     }
10746:     if (defined($metaentry{':'.$unikey.'.default'})) {
10747: 	$metaentry{':'.$unikey}=
10748: 	    $metaentry{':'.$unikey.'.default'};
10749:     }
10750: }
10751: 
10752: sub metadata_generate_part0 {
10753:     my ($metadata,$metacache,$uri) = @_;
10754:     my %allnames;
10755:     foreach my $metakey (keys(%$metadata)) {
10756: 	if ($metakey=~/^parameter\_(.*)/) {
10757: 	  my $part=$$metacache{':'.$metakey.'.part'};
10758: 	  my $name=$$metacache{':'.$metakey.'.name'};
10759: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10760: 	    $allnames{$name}=$part;
10761: 	  }
10762: 	}
10763:     }
10764:     foreach my $name (keys(%allnames)) {
10765:       $$metadata{"parameter_0_$name"}=1;
10766:       my $key=":parameter_0_$name";
10767:       $$metacache{"$key.part"}='0';
10768:       $$metacache{"$key.name"}=$name;
10769:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10770: 					   $allnames{$name}.'_'.$name.
10771: 					   '.type'};
10772:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10773: 			     '.display'};
10774:       my $expr='[Part: '.$allnames{$name}.']';
10775:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10776:       $$metacache{"$key.display"}=$olddis;
10777:     }
10778: }
10779: 
10780: # ------------------------------------------------------ Devalidate title cache
10781: 
10782: sub devalidate_title_cache {
10783:     my ($url)=@_;
10784:     if (!$env{'request.course.id'}) { return; }
10785:     my $symb=&symbread($url);
10786:     if (!$symb) { return; }
10787:     my $key=$env{'request.course.id'}."\0".$symb;
10788:     &devalidate_cache_new('title',$key);
10789: }
10790: 
10791: # ------------------------------------------------- Get the title of a course
10792: 
10793: sub current_course_title {
10794:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10795: }
10796: # ------------------------------------------------- Get the title of a resource
10797: 
10798: sub gettitle {
10799:     my $urlsymb=shift;
10800:     my $symb=&symbread($urlsymb);
10801:     if ($symb) {
10802: 	my $key=$env{'request.course.id'}."\0".$symb;
10803: 	my ($result,$cached)=&is_cached_new('title',$key);
10804: 	if (defined($cached)) { 
10805: 	    return $result;
10806: 	}
10807: 	my ($map,$resid,$url)=&decode_symb($symb);
10808: 	my $title='';
10809: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10810: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10811: 	} else {
10812: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10813: 		    &GDBM_READER(),0640)) {
10814: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10815: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10816: 		untie(%bighash);
10817: 	    }
10818: 	}
10819: 	$title=~s/\&colon\;/\:/gs;
10820: 	if ($title) {
10821: # Remember both $symb and $title for dynamic metadata
10822:             $accesshash{$symb.'___crstitle'}=$title;
10823:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10824: # Cache this title and then return it
10825: 	    return &do_cache_new('title',$key,$title,600);
10826: 	}
10827: 	$urlsymb=$url;
10828:     }
10829:     my $title=&metadata($urlsymb,'title');
10830:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10831:     return $title;
10832: }
10833: 
10834: sub get_slot {
10835:     my ($which,$cnum,$cdom)=@_;
10836:     if (!$cnum || !$cdom) {
10837: 	(undef,my $courseid)=&whichuser();
10838: 	$cdom=$env{'course.'.$courseid.'.domain'};
10839: 	$cnum=$env{'course.'.$courseid.'.num'};
10840:     }
10841:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10842:     my %slotinfo;
10843:     if (exists($remembered{$key})) {
10844: 	$slotinfo{$which} = $remembered{$key};
10845:     } else {
10846: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10847: 	&Apache::lonhomework::showhash(%slotinfo);
10848: 	my ($tmp)=keys(%slotinfo);
10849: 	if ($tmp=~/^error:/) { return (); }
10850: 	$remembered{$key} = $slotinfo{$which};
10851:     }
10852:     if (ref($slotinfo{$which}) eq 'HASH') {
10853: 	return %{$slotinfo{$which}};
10854:     }
10855:     return $slotinfo{$which};
10856: }
10857: 
10858: sub get_reservable_slots {
10859:     my ($cnum,$cdom,$uname,$udom) = @_;
10860:     my $now = time;
10861:     my $reservable_info;
10862:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10863:     if (exists($remembered{$key})) {
10864:         $reservable_info = $remembered{$key};
10865:     } else {
10866:         my %resv;
10867:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10868:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10869:         $reservable_info = \%resv;
10870:         $remembered{$key} = $reservable_info;
10871:     }
10872:     return $reservable_info;
10873: }
10874: 
10875: sub get_course_slots {
10876:     my ($cnum,$cdom) = @_;
10877:     my $hashid=$cnum.':'.$cdom;
10878:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10879:     if (defined($cached)) {
10880:         if (ref($result) eq 'HASH') {
10881:             return %{$result};
10882:         }
10883:     } else {
10884:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10885:         my ($tmp) = keys(%slots);
10886:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10887:             &do_cache_new('allslots',$hashid,\%slots,600);
10888:             return %slots;
10889:         }
10890:     }
10891:     return;
10892: }
10893: 
10894: sub devalidate_slots_cache {
10895:     my ($cnum,$cdom)=@_;
10896:     my $hashid=$cnum.':'.$cdom;
10897:     &devalidate_cache_new('allslots',$hashid);
10898: }
10899: 
10900: sub get_coursechange {
10901:     my ($cdom,$cnum) = @_;
10902:     if ($cdom eq '' || $cnum eq '') {
10903:         return unless ($env{'request.course.id'});
10904:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10905:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10906:     }
10907:     my $hashid=$cdom.'_'.$cnum;
10908:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10909:     if ((defined($cached)) && ($change ne '')) {
10910:         return $change;
10911:     } else {
10912:         my %crshash;
10913:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10914:         if ($crshash{'internal.contentchange'} eq '') {
10915:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10916:             if ($change eq '') {
10917:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10918:                 $change = $crshash{'internal.created'};
10919:             }
10920:         } else {
10921:             $change = $crshash{'internal.contentchange'};
10922:         }
10923:         my $cachetime = 600;
10924:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10925:     }
10926:     return $change;
10927: }
10928: 
10929: sub devalidate_coursechange_cache {
10930:     my ($cnum,$cdom)=@_;
10931:     my $hashid=$cnum.':'.$cdom;
10932:     &devalidate_cache_new('crschange',$hashid);
10933: }
10934: 
10935: # ------------------------------------------------- Update symbolic store links
10936: 
10937: sub symblist {
10938:     my ($mapname,%newhash)=@_;
10939:     $mapname=&deversion(&declutter($mapname));
10940:     my %hash;
10941:     if (($env{'request.course.fn'}) && (%newhash)) {
10942:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10943:                       &GDBM_WRCREAT(),0640)) {
10944: 	    foreach my $url (keys(%newhash)) {
10945: 		next if ($url eq 'last_known'
10946: 			 && $env{'form.no_update_last_known'});
10947: 		$hash{declutter($url)}=&encode_symb($mapname,
10948: 						    $newhash{$url}->[1],
10949: 						    $newhash{$url}->[0]);
10950:             }
10951:             if (untie(%hash)) {
10952: 		return 'ok';
10953:             }
10954:         }
10955:     }
10956:     return 'error';
10957: }
10958: 
10959: # --------------------------------------------------------------- Verify a symb
10960: 
10961: sub symbverify {
10962:     my ($symb,$thisurl,$encstate)=@_;
10963:     my $thisfn=$thisurl;
10964:     $thisfn=&declutter($thisfn);
10965: # direct jump to resource in page or to a sequence - will construct own symbs
10966:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10967: # check URL part
10968:     my ($map,$resid,$url)=&decode_symb($symb);
10969: 
10970:     unless ($url eq $thisfn) { return 0; }
10971: 
10972:     $symb=&symbclean($symb);
10973:     $thisurl=&deversion($thisurl);
10974:     $thisfn=&deversion($thisfn);
10975: 
10976:     my %bighash;
10977:     my $okay=0;
10978: 
10979:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10980:                             &GDBM_READER(),0640)) {
10981:         my $noclutter;
10982:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10983:             $thisurl =~ s/\?.+$//;
10984:             if ($map =~ m{^uploaded/.+\.page$}) {
10985:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10986:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10987:                 $noclutter = 1;
10988:             }
10989:         }
10990:         my $ids;
10991:         if ($noclutter) {
10992:             $ids=$bighash{'ids_'.$thisurl};
10993:         } else {
10994:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10995:         }
10996:         unless ($ids) {
10997:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10998:             $ids=$bighash{$idkey};
10999:         }
11000:         if ($ids) {
11001: # ------------------------------------------------------------------- Has ID(s)
11002:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11003:                 $symb =~ s/\?.+$//;
11004:             }
11005: 	    foreach my $id (split(/\,/,$ids)) {
11006: 	       my ($mapid,$resid)=split(/\./,$id);
11007:                if (
11008:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
11009:    eq $symb) {
11010:                    if (ref($encstate)) {
11011:                        $$encstate = $bighash{'encrypted_'.$id};
11012:                    }
11013: 		   if (($env{'request.role.adv'}) ||
11014: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11015:                        ($thisurl eq '/adm/navmaps')) {
11016: 		       $okay=1;
11017:                        last;
11018: 		   }
11019: 	       }
11020: 	   }
11021:         }
11022: 	untie(%bighash);
11023:     }
11024:     return $okay;
11025: }
11026: 
11027: # --------------------------------------------------------------- Clean-up symb
11028: 
11029: sub symbclean {
11030:     my $symb=shift;
11031:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11032: # remove version from map
11033:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
11034: 
11035: # remove version from URL
11036:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
11037: 
11038: # remove wrapper
11039: 
11040:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
11041:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
11042:     return $symb;
11043: }
11044: 
11045: # ---------------------------------------------- Split symb to find map and url
11046: 
11047: sub encode_symb {
11048:     my ($map,$resid,$url)=@_;
11049:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11050: }
11051: 
11052: sub decode_symb {
11053:     my $symb=shift;
11054:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11055:     my ($map,$resid,$url)=split(/___/,$symb);
11056:     return (&fixversion($map),$resid,&fixversion($url));
11057: }
11058: 
11059: sub fixversion {
11060:     my $fn=shift;
11061:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
11062:     my %bighash;
11063:     my $uri=&clutter($fn);
11064:     my $key=$env{'request.course.id'}.'_'.$uri;
11065: # is this cached?
11066:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
11067:     if (defined($cached)) { return $result; }
11068: # unfortunately not cached, or expired
11069:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11070: 	    &GDBM_READER(),0640)) {
11071:  	if ($bighash{'version_'.$uri}) {
11072:  	    my $version=$bighash{'version_'.$uri};
11073:  	    unless (($version eq 'mostrecent') || 
11074: 		    ($version==&getversion($uri))) {
11075:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
11076:  	    }
11077:  	}
11078:  	untie %bighash;
11079:     }
11080:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
11081: }
11082: 
11083: sub deversion {
11084:     my $url=shift;
11085:     $url=~s/\.\d+\.(\w+)$/\.$1/;
11086:     return $url;
11087: }
11088: 
11089: # ------------------------------------------------------ Return symb list entry
11090: 
11091: sub symbread {
11092:     my ($thisfn,$donotrecurse)=@_;
11093:     my $cache_str='request.symbread.cached.'.$thisfn;
11094:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
11095: # no filename provided? try from environment
11096:     unless ($thisfn) {
11097:         if ($env{'request.symb'}) {
11098: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
11099: 	}
11100: 	$thisfn=$env{'request.filename'};
11101:     }
11102:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11103: # is that filename actually a symb? Verify, clean, and return
11104:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
11105: 	if (&symbverify($thisfn,$1)) {
11106: 	    return $env{$cache_str}=&symbclean($thisfn);
11107: 	}
11108:     }
11109:     $thisfn=declutter($thisfn);
11110:     my %hash;
11111:     my %bighash;
11112:     my $syval='';
11113:     if (($env{'request.course.fn'}) && ($thisfn)) {
11114:         my $targetfn = $thisfn;
11115:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
11116:             $targetfn = 'adm/wrapper/'.$thisfn;
11117:         }
11118: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11119: 	    $targetfn=$1;
11120: 	}
11121:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11122:                       &GDBM_READER(),0640)) {
11123: 	    $syval=$hash{$targetfn};
11124:             untie(%hash);
11125:         }
11126: # ---------------------------------------------------------- There was an entry
11127:         if ($syval) {
11128: 	    #unless ($syval=~/\_\d+$/) {
11129: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
11130: 		    #&appenv({'request.ambiguous' => $thisfn});
11131: 		    #return $env{$cache_str}='';
11132: 		#}    
11133: 		#$syval.=$1;
11134: 	    #}
11135:         } else {
11136: # ------------------------------------------------------- Was not in symb table
11137:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11138:                             &GDBM_READER(),0640)) {
11139: # ---------------------------------------------- Get ID(s) for current resource
11140:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
11141:               unless ($ids) { 
11142:                  $ids=$bighash{'ids_/'.$thisfn};
11143:               }
11144:               unless ($ids) {
11145: # alias?
11146: 		  $ids=$bighash{'mapalias_'.$thisfn};
11147:               }
11148:               if ($ids) {
11149: # ------------------------------------------------------------------- Has ID(s)
11150:                  my @possibilities=split(/\,/,$ids);
11151:                  if ($#possibilities==0) {
11152: # ----------------------------------------------- There is only one possibility
11153: 		     my ($mapid,$resid)=split(/\./,$ids);
11154: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
11155: 						    $resid,$thisfn);
11156:                  } elsif (!$donotrecurse) {
11157: # ------------------------------------------ There is more than one possibility
11158:                      my $realpossible=0;
11159:                      foreach my $id (@possibilities) {
11160: 			 my $file=$bighash{'src_'.$id};
11161:                          if (&allowed('bre',$file)) {
11162:          		    my ($mapid,$resid)=split(/\./,$id);
11163:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
11164: 				$realpossible++;
11165:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
11166: 						    $resid,$thisfn);
11167:                             }
11168: 			 }
11169:                      }
11170: 		     if ($realpossible!=1) { $syval=''; }
11171:                  } else {
11172:                      $syval='';
11173:                  }
11174: 	      }
11175:               untie(%bighash)
11176:            }
11177:         }
11178:         if ($syval) {
11179: 	    return $env{$cache_str}=$syval;
11180:         }
11181:     }
11182:     &appenv({'request.ambiguous' => $thisfn});
11183:     return $env{$cache_str}='';
11184: }
11185: 
11186: # ---------------------------------------------------------- Return random seed
11187: 
11188: sub numval {
11189:     my $txt=shift;
11190:     $txt=~tr/A-J/0-9/;
11191:     $txt=~tr/a-j/0-9/;
11192:     $txt=~tr/K-T/0-9/;
11193:     $txt=~tr/k-t/0-9/;
11194:     $txt=~tr/U-Z/0-5/;
11195:     $txt=~tr/u-z/0-5/;
11196:     $txt=~s/\D//g;
11197:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
11198:     return int($txt);
11199: }
11200: 
11201: sub numval2 {
11202:     my $txt=shift;
11203:     $txt=~tr/A-J/0-9/;
11204:     $txt=~tr/a-j/0-9/;
11205:     $txt=~tr/K-T/0-9/;
11206:     $txt=~tr/k-t/0-9/;
11207:     $txt=~tr/U-Z/0-5/;
11208:     $txt=~tr/u-z/0-5/;
11209:     $txt=~s/\D//g;
11210:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11211:     my $total;
11212:     foreach my $val (@txts) { $total+=$val; }
11213:     if ($_64bit) { if ($total > 2**32) { return -1; } }
11214:     return int($total);
11215: }
11216: 
11217: sub numval3 {
11218:     use integer;
11219:     my $txt=shift;
11220:     $txt=~tr/A-J/0-9/;
11221:     $txt=~tr/a-j/0-9/;
11222:     $txt=~tr/K-T/0-9/;
11223:     $txt=~tr/k-t/0-9/;
11224:     $txt=~tr/U-Z/0-5/;
11225:     $txt=~tr/u-z/0-5/;
11226:     $txt=~s/\D//g;
11227:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11228:     my $total;
11229:     foreach my $val (@txts) { $total+=$val; }
11230:     if ($_64bit) { $total=(($total<<32)>>32); }
11231:     return $total;
11232: }
11233: 
11234: sub digest {
11235:     my ($data)=@_;
11236:     my $digest=&Digest::MD5::md5($data);
11237:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
11238:     my ($e,$f);
11239:     {
11240:         use integer;
11241:         $e=($a+$b);
11242:         $f=($c+$d);
11243:         if ($_64bit) {
11244:             $e=(($e<<32)>>32);
11245:             $f=(($f<<32)>>32);
11246:         }
11247:     }
11248:     if (wantarray) {
11249: 	return ($e,$f);
11250:     } else {
11251: 	my $g;
11252: 	{
11253: 	    use integer;
11254: 	    $g=($e+$f);
11255: 	    if ($_64bit) {
11256: 		$g=(($g<<32)>>32);
11257: 	    }
11258: 	}
11259: 	return $g;
11260:     }
11261: }
11262: 
11263: sub latest_rnd_algorithm_id {
11264:     return '64bit5';
11265: }
11266: 
11267: sub get_rand_alg {
11268:     my ($courseid)=@_;
11269:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11270:     if ($courseid) {
11271: 	return $env{"course.$courseid.rndseed"};
11272:     }
11273:     return &latest_rnd_algorithm_id();
11274: }
11275: 
11276: sub validCODE {
11277:     my ($CODE)=@_;
11278:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11279:     return 0;
11280: }
11281: 
11282: sub getCODE {
11283:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11284:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11285: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11286: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11287: 	return $Apache::lonhomework::history{'resource.CODE'};
11288:     }
11289:     return undef;
11290: }
11291: #
11292: #  Determines the random seed for a specific context:
11293: #
11294: # parameters:
11295: #   symb      - in course context the symb for the seed.
11296: #   course_id - The course id of the form domain_coursenum.
11297: #   domain    - Domain for the user.
11298: #   course    - Course for the user.
11299: #   cenv      - environment of the course.
11300: #
11301: # NOTE:
11302: #   All parameters are picked out of the environment if missing
11303: #   or not defined.
11304: #   If a symb cannot be determined the current time is used instead.
11305: #
11306: #  For a given well defined symb, courside, domain, username,
11307: #  and course environment, the seed is reproducible.
11308: #
11309: sub rndseed {
11310:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11311:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11312:     if (!defined($symb)) {
11313: 	unless ($symb=$wsymb) { return time; }
11314:     }
11315:     if (!defined $courseid) { 
11316: 	$courseid=$wcourseid; 
11317:     }
11318:     if (!defined $domain) { $domain=$wdomain; }
11319:     if (!defined $username) { $username=$wusername }
11320: 
11321:     my $which;
11322:     if (defined($cenv->{'rndseed'})) {
11323: 	$which = $cenv->{'rndseed'};
11324:     } else {
11325: 	$which =&get_rand_alg($courseid);
11326:     }
11327:     if (defined(&getCODE())) {
11328: 
11329: 	if ($which eq '64bit5') {
11330: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11331: 	} elsif ($which eq '64bit4') {
11332: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11333: 	} else {
11334: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11335: 	}
11336:     } elsif ($which eq '64bit5') {
11337: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11338:     } elsif ($which eq '64bit4') {
11339: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11340:     } elsif ($which eq '64bit3') {
11341: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11342:     } elsif ($which eq '64bit2') {
11343: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11344:     } elsif ($which eq '64bit') {
11345: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11346:     }
11347:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11348: }
11349: 
11350: sub rndseed_32bit {
11351:     my ($symb,$courseid,$domain,$username)=@_;
11352:     {
11353: 	use integer;
11354: 	my $symbchck=unpack("%32C*",$symb) << 27;
11355: 	my $symbseed=numval($symb) << 22;
11356: 	my $namechck=unpack("%32C*",$username) << 17;
11357: 	my $nameseed=numval($username) << 12;
11358: 	my $domainseed=unpack("%32C*",$domain) << 7;
11359: 	my $courseseed=unpack("%32C*",$courseid);
11360: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11361: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11362: 	#&logthis("rndseed :$num:$symb");
11363: 	if ($_64bit) { $num=(($num<<32)>>32); }
11364: 	return $num;
11365:     }
11366: }
11367: 
11368: sub rndseed_64bit {
11369:     my ($symb,$courseid,$domain,$username)=@_;
11370:     {
11371: 	use integer;
11372: 	my $symbchck=unpack("%32S*",$symb) << 21;
11373: 	my $symbseed=numval($symb) << 10;
11374: 	my $namechck=unpack("%32S*",$username);
11375: 	
11376: 	my $nameseed=numval($username) << 21;
11377: 	my $domainseed=unpack("%32S*",$domain) << 10;
11378: 	my $courseseed=unpack("%32S*",$courseid);
11379: 	
11380: 	my $num1=$symbchck+$symbseed+$namechck;
11381: 	my $num2=$nameseed+$domainseed+$courseseed;
11382: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11383: 	#&logthis("rndseed :$num:$symb");
11384: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11385: 	return "$num1,$num2";
11386:     }
11387: }
11388: 
11389: sub rndseed_64bit2 {
11390:     my ($symb,$courseid,$domain,$username)=@_;
11391:     {
11392: 	use integer;
11393: 	# strings need to be an even # of cahracters long, it it is odd the
11394:         # last characters gets thrown away
11395: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11396: 	my $symbseed=numval($symb) << 10;
11397: 	my $namechck=unpack("%32S*",$username.' ');
11398: 	
11399: 	my $nameseed=numval($username) << 21;
11400: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11401: 	my $courseseed=unpack("%32S*",$courseid.' ');
11402: 	
11403: 	my $num1=$symbchck+$symbseed+$namechck;
11404: 	my $num2=$nameseed+$domainseed+$courseseed;
11405: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11406: 	#&logthis("rndseed :$num:$symb");
11407: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11408: 	return "$num1,$num2";
11409:     }
11410: }
11411: 
11412: sub rndseed_64bit3 {
11413:     my ($symb,$courseid,$domain,$username)=@_;
11414:     {
11415: 	use integer;
11416: 	# strings need to be an even # of cahracters long, it it is odd the
11417:         # last characters gets thrown away
11418: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11419: 	my $symbseed=numval2($symb) << 10;
11420: 	my $namechck=unpack("%32S*",$username.' ');
11421: 	
11422: 	my $nameseed=numval2($username) << 21;
11423: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11424: 	my $courseseed=unpack("%32S*",$courseid.' ');
11425: 	
11426: 	my $num1=$symbchck+$symbseed+$namechck;
11427: 	my $num2=$nameseed+$domainseed+$courseseed;
11428: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11429: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11430: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11431: 	
11432: 	return "$num1:$num2";
11433:     }
11434: }
11435: 
11436: sub rndseed_64bit4 {
11437:     my ($symb,$courseid,$domain,$username)=@_;
11438:     {
11439: 	use integer;
11440: 	# strings need to be an even # of cahracters long, it it is odd the
11441:         # last characters gets thrown away
11442: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11443: 	my $symbseed=numval3($symb) << 10;
11444: 	my $namechck=unpack("%32S*",$username.' ');
11445: 	
11446: 	my $nameseed=numval3($username) << 21;
11447: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11448: 	my $courseseed=unpack("%32S*",$courseid.' ');
11449: 	
11450: 	my $num1=$symbchck+$symbseed+$namechck;
11451: 	my $num2=$nameseed+$domainseed+$courseseed;
11452: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11453: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11454: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11455: 	
11456: 	return "$num1:$num2";
11457:     }
11458: }
11459: 
11460: sub rndseed_64bit5 {
11461:     my ($symb,$courseid,$domain,$username)=@_;
11462:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11463:     return "$num1:$num2";
11464: }
11465: 
11466: sub rndseed_CODE_64bit {
11467:     my ($symb,$courseid,$domain,$username)=@_;
11468:     {
11469: 	use integer;
11470: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11471: 	my $symbseed=numval2($symb);
11472: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11473: 	my $CODEseed=numval(&getCODE());
11474: 	my $courseseed=unpack("%32S*",$courseid.' ');
11475: 	my $num1=$symbseed+$CODEchck;
11476: 	my $num2=$CODEseed+$courseseed+$symbchck;
11477: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11478: 	#&logthis("rndseed :$num1:$num2:$symb");
11479: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11480: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11481: 	return "$num1:$num2";
11482:     }
11483: }
11484: 
11485: sub rndseed_CODE_64bit4 {
11486:     my ($symb,$courseid,$domain,$username)=@_;
11487:     {
11488: 	use integer;
11489: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11490: 	my $symbseed=numval3($symb);
11491: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11492: 	my $CODEseed=numval3(&getCODE());
11493: 	my $courseseed=unpack("%32S*",$courseid.' ');
11494: 	my $num1=$symbseed+$CODEchck;
11495: 	my $num2=$CODEseed+$courseseed+$symbchck;
11496: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11497: 	#&logthis("rndseed :$num1:$num2:$symb");
11498: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11499: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11500: 	return "$num1:$num2";
11501:     }
11502: }
11503: 
11504: sub rndseed_CODE_64bit5 {
11505:     my ($symb,$courseid,$domain,$username)=@_;
11506:     my $code = &getCODE();
11507:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11508:     return "$num1:$num2";
11509: }
11510: 
11511: sub setup_random_from_rndseed {
11512:     my ($rndseed)=@_;
11513:     if ($rndseed =~/([,:])/) {
11514:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11515:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11516:             &Math::Random::random_set_seed_from_phrase($rndseed);
11517:         } else {
11518:             &Math::Random::random_set_seed($num1,$num2);
11519:         }
11520:     } else {
11521: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11522:     }
11523: }
11524: 
11525: sub latest_receipt_algorithm_id {
11526:     return 'receipt3';
11527: }
11528: 
11529: sub recunique {
11530:     my $fucourseid=shift;
11531:     my $unique;
11532:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11533: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11534: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11535:     } else {
11536: 	$unique=$perlvar{'lonReceipt'};
11537:     }
11538:     return unpack("%32C*",$unique);
11539: }
11540: 
11541: sub recprefix {
11542:     my $fucourseid=shift;
11543:     my $prefix;
11544:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11545: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11546: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11547:     } else {
11548: 	$prefix=$perlvar{'lonHostID'};
11549:     }
11550:     return unpack("%32C*",$prefix);
11551: }
11552: 
11553: sub ireceipt {
11554:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11555: 
11556:     my $return =&recprefix($fucourseid).'-';
11557: 
11558:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11559: 	$env{'request.state'} eq 'construct') {
11560: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11561: 	return $return;
11562:     }
11563: 
11564:     my $cuname=unpack("%32C*",$funame);
11565:     my $cudom=unpack("%32C*",$fudom);
11566:     my $cucourseid=unpack("%32C*",$fucourseid);
11567:     my $cusymb=unpack("%32C*",$fusymb);
11568:     my $cunique=&recunique($fucourseid);
11569:     my $cpart=unpack("%32S*",$part);
11570:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11571: 
11572: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11573: 			       
11574: 	$return.= ($cunique%$cuname+
11575: 		   $cunique%$cudom+
11576: 		   $cusymb%$cuname+
11577: 		   $cusymb%$cudom+
11578: 		   $cucourseid%$cuname+
11579: 		   $cucourseid%$cudom+
11580: 		   $cpart%$cuname+
11581: 		   $cpart%$cudom);
11582:     } else {
11583: 	$return.= ($cunique%$cuname+
11584: 		   $cunique%$cudom+
11585: 		   $cusymb%$cuname+
11586: 		   $cusymb%$cudom+
11587: 		   $cucourseid%$cuname+
11588: 		   $cucourseid%$cudom);
11589:     }
11590:     return $return;
11591: }
11592: 
11593: sub receipt {
11594:     my ($part)=@_;
11595:     my ($symb,$courseid,$domain,$name) = &whichuser();
11596:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11597: }
11598: 
11599: sub whichuser {
11600:     my ($passedsymb)=@_;
11601:     my ($symb,$courseid,$domain,$name,$publicuser);
11602:     if (defined($env{'form.grade_symb'})) {
11603: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11604: 	my $allowed=&allowed('vgr',$tmp_courseid);
11605: 	if (!$allowed &&
11606: 	    exists($env{'request.course.sec'}) &&
11607: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11608: 	    $allowed=&allowed('vgr',$tmp_courseid.
11609: 			      '/'.$env{'request.course.sec'});
11610: 	}
11611: 	if ($allowed) {
11612: 	    ($symb)=&get_env_multiple('form.grade_symb');
11613: 	    $courseid=$tmp_courseid;
11614: 	    ($domain)=&get_env_multiple('form.grade_domain');
11615: 	    ($name)=&get_env_multiple('form.grade_username');
11616: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11617: 	}
11618:     }
11619:     if (!$passedsymb) {
11620: 	$symb=&symbread();
11621:     } else {
11622: 	$symb=$passedsymb;
11623:     }
11624:     $courseid=$env{'request.course.id'};
11625:     $domain=$env{'user.domain'};
11626:     $name=$env{'user.name'};
11627:     if ($name eq 'public' && $domain eq 'public') {
11628: 	if (!defined($env{'form.username'})) {
11629: 	    $env{'form.username'}.=time.rand(10000000);
11630: 	}
11631: 	$name.=$env{'form.username'};
11632:     }
11633:     return ($symb,$courseid,$domain,$name,$publicuser);
11634: 
11635: }
11636: 
11637: # ------------------------------------------------------------ Serves up a file
11638: # returns either the contents of the file or 
11639: # -1 if the file doesn't exist
11640: #
11641: # if the target is a file that was uploaded via DOCS, 
11642: # a check will be made to see if a current copy exists on the local server,
11643: # if it does this will be served, otherwise a copy will be retrieved from
11644: # the home server for the course and stored in /home/httpd/html/userfiles on
11645: # the local server.   
11646: 
11647: sub getfile {
11648:     my ($file) = @_;
11649:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11650:     &repcopy($file);
11651:     return &readfile($file);
11652: }
11653: 
11654: sub repcopy_userfile {
11655:     my ($file)=@_;
11656:     my $londocroot = $perlvar{'lonDocRoot'};
11657:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11658:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11659:     my ($cdom,$cnum,$filename) = 
11660: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11661:     my $uri="/uploaded/$cdom/$cnum/$filename";
11662:     if (-e "$file") {
11663: # we already have a local copy, check it out
11664: 	my @fileinfo = stat($file);
11665: 	my $rtncode;
11666: 	my $info;
11667: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11668: 	if ($lwpresp ne 'ok') {
11669: # there is no such file anymore, even though we had a local copy
11670: 	    if ($rtncode eq '404') {
11671: 		unlink($file);
11672: 	    }
11673: 	    return -1;
11674: 	}
11675: 	if ($info < $fileinfo[9]) {
11676: # nice, the file we have is up-to-date, just say okay
11677: 	    return 'ok';
11678: 	} else {
11679: # the file is outdated, get rid of it
11680: 	    unlink($file);
11681: 	}
11682:     }
11683: # one way or the other, at this point, we don't have the file
11684: # construct the correct path for the file
11685:     my @parts = ($cdom,$cnum); 
11686:     if ($filename =~ m|^(.+)/[^/]+$|) {
11687: 	push @parts, split(/\//,$1);
11688:     }
11689:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11690:     foreach my $part (@parts) {
11691: 	$path .= '/'.$part;
11692: 	if (!-e $path) {
11693: 	    mkdir($path,0770);
11694: 	}
11695:     }
11696: # now the path exists for sure
11697: # get a user agent
11698:     my $ua=new LWP::UserAgent;
11699:     my $transferfile=$file.'.in.transfer';
11700: # FIXME: this should flock
11701:     if (-e $transferfile) { return 'ok'; }
11702:     my $request;
11703:     $uri=~s/^\///;
11704:     my $homeserver = &homeserver($cnum,$cdom);
11705:     my $protocol = $protocol{$homeserver};
11706:     $protocol = 'http' if ($protocol ne 'https');
11707:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11708:     my $response=$ua->request($request,$transferfile);
11709: # did it work?
11710:     if ($response->is_error()) {
11711: 	unlink($transferfile);
11712: 	&logthis("Userfile repcopy failed for $uri");
11713: 	return -1;
11714:     }
11715: # worked, rename the transfer file
11716:     rename($transferfile,$file);
11717:     return 'ok';
11718: }
11719: 
11720: sub tokenwrapper {
11721:     my $uri=shift;
11722:     $uri=~s|^https?\://([^/]+)||;
11723:     $uri=~s|^/||;
11724:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11725:     my $token=$1;
11726:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11727:     if ($udom && $uname && $file) {
11728: 	$file=~s|(\?\.*)*$||;
11729:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11730:         my $homeserver = &homeserver($uname,$udom);
11731:         my $protocol = $protocol{$homeserver};
11732:         $protocol = 'http' if ($protocol ne 'https');
11733:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11734:                (($uri=~/\?/)?'&':'?').'token='.$token.
11735:                                '&tokenissued='.$perlvar{'lonHostID'};
11736:     } else {
11737:         return '/adm/notfound.html';
11738:     }
11739: }
11740: 
11741: # call with reqtype HEAD: get last modification time
11742: # call with reqtype GET: get the file contents
11743: # Do not call this with reqtype GET for large files! It loads everything into memory
11744: #
11745: sub getuploaded {
11746:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11747:     $uri=~s/^\///;
11748:     my $homeserver = &homeserver($cnum,$cdom);
11749:     my $protocol = $protocol{$homeserver};
11750:     $protocol = 'http' if ($protocol ne 'https');
11751:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11752:     my $ua=new LWP::UserAgent;
11753:     my $request=new HTTP::Request($reqtype,$uri);
11754:     my $response=$ua->request($request);
11755:     $$rtncode = $response->code;
11756:     if (! $response->is_success()) {
11757: 	return 'failed';
11758:     }      
11759:     if ($reqtype eq 'HEAD') {
11760: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11761:     } elsif ($reqtype eq 'GET') {
11762: 	$$info = $response->content;
11763:     }
11764:     return 'ok';
11765: }
11766: 
11767: sub readfile {
11768:     my $file = shift;
11769:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11770:     my $fh;
11771:     open($fh,"<$file");
11772:     my $a='';
11773:     while (my $line = <$fh>) { $a .= $line; }
11774:     return $a;
11775: }
11776: 
11777: sub filelocation {
11778:     my ($dir,$file) = @_;
11779:     my $location;
11780:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11781: 
11782:     if ($file =~ m-^/adm/-) {
11783: 	$file=~s-^/adm/wrapper/-/-;
11784: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11785:     }
11786: 
11787:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11788:         $location = $file;
11789:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11790:         my ($udom,$uname,$filename)=
11791:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11792:         my $home=&homeserver($uname,$udom);
11793:         my $is_me=0;
11794:         my @ids=&current_machine_ids();
11795:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11796:         if ($is_me) {
11797:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11798:         } else {
11799:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11800:   	      $udom.'/'.$uname.'/'.$filename;
11801:         }
11802:     } elsif ($file =~ m-^/adm/-) {
11803: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11804:     } else {
11805:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11806:         $file=~s:^/(res|priv)/:/:;
11807:         my $space=$1;
11808:         if ( !( $file =~ m:^/:) ) {
11809:             $location = $dir. '/'.$file;
11810:         } else {
11811:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11812:         }
11813:     }
11814:     $location=~s://+:/:g; # remove duplicate /
11815:     while ($location=~m{/\.\./}) {
11816: 	if ($location =~ m{/[^/]+/\.\./}) {
11817: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11818: 	} else {
11819: 	    $location=~ s{/\.\./}{/}g;
11820: 	}
11821:     } #remove dir/..
11822:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11823:     return $location;
11824: }
11825: 
11826: sub hreflocation {
11827:     my ($dir,$file)=@_;
11828:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11829: 	$file=filelocation($dir,$file);
11830:     } elsif ($file=~m-^/adm/-) {
11831: 	$file=~s-^/adm/wrapper/-/-;
11832: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11833:     }
11834:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11835: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11836:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11837: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11838: 	        {/uploaded/$1/$2/}x;
11839:     }
11840:     if ($file=~ m{^/userfiles/}) {
11841: 	$file =~ s{^/userfiles/}{/uploaded/};
11842:     }
11843:     return $file;
11844: }
11845: 
11846: 
11847: 
11848: 
11849: 
11850: sub current_machine_domains {
11851:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11852: }
11853: 
11854: sub machine_domains {
11855:     my ($hostname) = @_;
11856:     my @domains;
11857:     my %hostname = &all_hostnames();
11858:     while( my($id, $name) = each(%hostname)) {
11859: #	&logthis("-$id-$name-$hostname-");
11860: 	if ($hostname eq $name) {
11861: 	    push(@domains,&host_domain($id));
11862: 	}
11863:     }
11864:     return @domains;
11865: }
11866: 
11867: sub current_machine_ids {
11868:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11869: }
11870: 
11871: sub machine_ids {
11872:     my ($hostname) = @_;
11873:     $hostname ||= &hostname($perlvar{'lonHostID'});
11874:     my @ids;
11875:     my %name_to_host = &all_names();
11876:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11877: 	return @{ $name_to_host{$hostname} };
11878:     }
11879:     return;
11880: }
11881: 
11882: sub additional_machine_domains {
11883:     my @domains;
11884:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11885:     while( my $line = <$fh>) {
11886:         $line =~ s/\s//g;
11887:         push(@domains,$line);
11888:     }
11889:     return @domains;
11890: }
11891: 
11892: sub default_login_domain {
11893:     my $domain = $perlvar{'lonDefDomain'};
11894:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11895:     foreach my $posdom (&current_machine_domains(),
11896:                         &additional_machine_domains()) {
11897:         if (lc($posdom) eq lc($testdomain)) {
11898:             $domain=$posdom;
11899:             last;
11900:         }
11901:     }
11902:     return $domain;
11903: }
11904: 
11905: # ------------------------------------------------------------- Declutters URLs
11906: 
11907: sub declutter {
11908:     my $thisfn=shift;
11909:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11910:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11911:         $thisfn=~s{^/home/httpd/html}{};
11912:     }
11913:     $thisfn=~s/^\///;
11914:     $thisfn=~s|^adm/wrapper/||;
11915:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11916:     $thisfn=~s/^res\///;
11917:     $thisfn=~s/^priv\///;
11918:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11919:         $thisfn=~s/\?.+$//;
11920:     }
11921:     return $thisfn;
11922: }
11923: 
11924: # ------------------------------------------------------------- Clutter up URLs
11925: 
11926: sub clutter {
11927:     my $thisfn='/'.&declutter(shift);
11928:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11929: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11930:        $thisfn='/res'.$thisfn; 
11931:     }
11932:     if ($thisfn !~m|^/adm|) {
11933: 	if ($thisfn =~ m|^/ext/|) {
11934: 	    $thisfn='/adm/wrapper'.$thisfn;
11935: 	} else {
11936: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11937: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11938: 	    if ($embstyle eq 'ssi'
11939: 		|| ($embstyle eq 'hdn')
11940: 		|| ($embstyle eq 'rat')
11941: 		|| ($embstyle eq 'prv')
11942: 		|| ($embstyle eq 'ign')) {
11943: 		#do nothing with these
11944: 	    } elsif (($embstyle eq 'img') 
11945: 		|| ($embstyle eq 'emb')
11946: 		|| ($embstyle eq 'wrp')) {
11947: 		$thisfn='/adm/wrapper'.$thisfn;
11948: 	    } elsif ($embstyle eq 'unk'
11949: 		     && $thisfn!~/\.(sequence|page)$/) {
11950: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11951: 	    } else {
11952: #		&logthis("Got a blank emb style");
11953: 	    }
11954: 	}
11955:     }
11956:     return $thisfn;
11957: }
11958: 
11959: sub clutter_with_no_wrapper {
11960:     my $uri = &clutter(shift);
11961:     if ($uri =~ m-^/adm/-) {
11962: 	$uri =~ s-^/adm/wrapper/-/-;
11963: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11964:     }
11965:     return $uri;
11966: }
11967: 
11968: sub freeze_escape {
11969:     my ($value)=@_;
11970:     if (ref($value)) {
11971: 	$value=&nfreeze($value);
11972: 	return '__FROZEN__'.&escape($value);
11973:     }
11974:     return &escape($value);
11975: }
11976: 
11977: 
11978: sub thaw_unescape {
11979:     my ($value)=@_;
11980:     if ($value =~ /^__FROZEN__/) {
11981: 	substr($value,0,10,undef);
11982: 	$value=&unescape($value);
11983: 	return &thaw($value);
11984:     }
11985:     return &unescape($value);
11986: }
11987: 
11988: sub correct_line_ends {
11989:     my ($result)=@_;
11990:     $$result =~s/\r\n/\n/mg;
11991:     $$result =~s/\r/\n/mg;
11992: }
11993: # ================================================================ Main Program
11994: 
11995: sub goodbye {
11996:    &logthis("Starting Shut down");
11997: #not converted to using infrastruture and probably shouldn't be
11998:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11999: #converted
12000: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
12001:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12002: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12003: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
12004: #1.1 only
12005: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12006: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12007: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12008: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12009:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
12010:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12011:    &logthis(sprintf("%-20s is %s",'hits',$hits));
12012:    &flushcourselogs();
12013:    &logthis("Shutting down");
12014: }
12015: 
12016: sub get_dns {
12017:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
12018:     if (!$ignore_cache) {
12019: 	my ($content,$cached)=
12020: 	    &Apache::lonnet::is_cached_new('dns',$url);
12021: 	if ($cached) {
12022: 	    &$func($content,$hashref);
12023: 	    return;
12024: 	}
12025:     }
12026: 
12027:     my %alldns;
12028:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12029:     foreach my $dns (<$config>) {
12030: 	next if ($dns !~ /^\^(\S*)/x);
12031:         my $line = $1;
12032:         my ($host,$protocol) = split(/:/,$line);
12033:         if ($protocol ne 'https') {
12034:             $protocol = 'http';
12035:         }
12036: 	$alldns{$host} = $protocol;
12037:     }
12038:     while (%alldns) {
12039: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
12040: 	my $ua=new LWP::UserAgent;
12041:         $ua->timeout(30);
12042: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
12043: 	my $response=$ua->request($request);
12044:         delete($alldns{$dns});
12045: 	next if ($response->is_error());
12046: 	my @content = split("\n",$response->content);
12047: 	unless ($nocache) {
12048: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
12049: 	}
12050: 	&$func(\@content,$hashref);
12051: 	return;
12052:     }
12053:     close($config);
12054:     my $which = (split('/',$url))[3];
12055:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12056:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
12057:     my @content = <$config>;
12058:     &$func(\@content,$hashref);
12059:     return;
12060: }
12061: 
12062: # ------------------------------------------------------Get DNS checksums file
12063: sub parse_dns_checksums_tab {
12064:     my ($lines,$hashref) = @_;
12065:     my $lonhost = $perlvar{'lonHostID'};
12066:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
12067:     my $loncaparev = &get_server_loncaparev($machine_dom);
12068:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12069:     my $webconfdir = '/etc/httpd/conf';
12070:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12071:         $webconfdir = '/etc/apache2';
12072:     } elsif ($distro =~ /^sles(\d+)$/) {
12073:         if ($1 >= 10) {
12074:             $webconfdir = '/etc/apache2';
12075:         }
12076:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12077:         if ($1 >= 10.0) {
12078:             $webconfdir = '/etc/apache2';
12079:         }
12080:     }
12081:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12082:     my (%chksum,%revnum);
12083:     if (ref($lines) eq 'ARRAY') {
12084:         chomp(@{$lines});
12085:         my $version = shift(@{$lines});
12086:         if ($version eq $release) {  
12087:             foreach my $line (@{$lines}) {
12088:                 my ($file,$version,$shasum) = split(/,/,$line);
12089:                 if ($file =~ m{^/etc/httpd/conf}) {
12090:                     if ($webconfdir eq '/etc/apache2') {
12091:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12092:                     }
12093:                 }
12094:                 $chksum{$file} = $shasum;
12095:                 $revnum{$file} = $version;
12096:             }
12097:             if (ref($hashref) eq 'HASH') {
12098:                 %{$hashref} = (
12099:                                 sums     => \%chksum,
12100:                                 versions => \%revnum,
12101:                               );
12102:             }
12103:         }
12104:     }
12105:     return;
12106: }
12107: 
12108: sub fetch_dns_checksums {
12109:     my %checksums;
12110:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
12111:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
12112:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12113:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
12114:              \%checksums);
12115:     return \%checksums;
12116: }
12117: 
12118: # ------------------------------------------------------------ Read domain file
12119: {
12120:     my $loaded;
12121:     my %domain;
12122: 
12123:     sub parse_domain_tab {
12124: 	my ($lines) = @_;
12125: 	foreach my $line (@$lines) {
12126: 	    next if ($line =~ /^(\#|\s*$ )/x);
12127: 
12128: 	    chomp($line);
12129: 	    my ($name,@elements) = split(/:/,$line,9);
12130: 	    my %this_domain;
12131: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
12132: 			       'lang_def', 'city', 'longi', 'lati',
12133: 			       'primary') {
12134: 		$this_domain{$field} = shift(@elements);
12135: 	    }
12136: 	    $domain{$name} = \%this_domain;
12137: 	}
12138:     }
12139: 
12140:     sub reset_domain_info {
12141: 	undef($loaded);
12142: 	undef(%domain);
12143:     }
12144: 
12145:     sub load_domain_tab {
12146: 	my ($ignore_cache) = @_;
12147: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
12148: 	my $fh;
12149: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12150: 	    my @lines = <$fh>;
12151: 	    &parse_domain_tab(\@lines);
12152: 	}
12153: 	close($fh);
12154: 	$loaded = 1;
12155:     }
12156: 
12157:     sub domain {
12158: 	&load_domain_tab() if (!$loaded);
12159: 
12160: 	my ($name,$what) = @_;
12161: 	return if ( !exists($domain{$name}) );
12162: 
12163: 	if (!$what) {
12164: 	    return $domain{$name}{'description'};
12165: 	}
12166: 	return $domain{$name}{$what};
12167:     }
12168: 
12169:     sub domain_info {
12170:         &load_domain_tab() if (!$loaded);
12171:         return %domain;
12172:     }
12173: 
12174: }
12175: 
12176: 
12177: # ------------------------------------------------------------- Read hosts file
12178: {
12179:     my %hostname;
12180:     my %hostdom;
12181:     my %libserv;
12182:     my $loaded;
12183:     my %name_to_host;
12184:     my %internetdom;
12185:     my %LC_dns_serv;
12186: 
12187:     sub parse_hosts_tab {
12188: 	my ($file) = @_;
12189: 	foreach my $configline (@$file) {
12190: 	    next if ($configline =~ /^(\#|\s*$ )/x);
12191:             chomp($configline);
12192: 	    if ($configline =~ /^\^/) {
12193:                 if ($configline =~ /^\^([\w.\-]+)/) {
12194:                     $LC_dns_serv{$1} = 1;
12195:                 }
12196:                 next;
12197:             }
12198: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
12199: 	    $name=~s/\s//g;
12200: 	    if ($id && $domain && $role && $name) {
12201: 		$hostname{$id}=$name;
12202: 		push(@{$name_to_host{$name}}, $id);
12203: 		$hostdom{$id}=$domain;
12204: 		if ($role eq 'library') { $libserv{$id}=$name; }
12205:                 if (defined($protocol)) {
12206:                     if ($protocol eq 'https') {
12207:                         $protocol{$id} = $protocol;
12208:                     } else {
12209:                         $protocol{$id} = 'http'; 
12210:                     }
12211:                 } else {
12212:                     $protocol{$id} = 'http';
12213:                 }
12214:                 if (defined($intdom)) {
12215:                     $internetdom{$id} = $intdom;
12216:                 }
12217: 	    }
12218: 	}
12219:     }
12220:     
12221:     sub reset_hosts_info {
12222: 	&purge_remembered();
12223: 	&reset_domain_info();
12224: 	&reset_hosts_ip_info();
12225: 	undef(%name_to_host);
12226: 	undef(%hostname);
12227: 	undef(%hostdom);
12228: 	undef(%libserv);
12229: 	undef($loaded);
12230:     }
12231: 
12232:     sub load_hosts_tab {
12233: 	my ($ignore_cache) = @_;
12234: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
12235: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12236: 	my @config = <$config>;
12237: 	&parse_hosts_tab(\@config);
12238: 	close($config);
12239: 	$loaded=1;
12240:     }
12241: 
12242:     sub hostname {
12243: 	&load_hosts_tab() if (!$loaded);
12244: 
12245: 	my ($lonid) = @_;
12246: 	return $hostname{$lonid};
12247:     }
12248: 
12249:     sub all_hostnames {
12250: 	&load_hosts_tab() if (!$loaded);
12251: 
12252: 	return %hostname;
12253:     }
12254: 
12255:     sub all_names {
12256: 	&load_hosts_tab() if (!$loaded);
12257: 
12258: 	return %name_to_host;
12259:     }
12260: 
12261:     sub all_host_domain {
12262:         &load_hosts_tab() if (!$loaded);
12263:         return %hostdom;
12264:     }
12265: 
12266:     sub is_library {
12267: 	&load_hosts_tab() if (!$loaded);
12268: 
12269: 	return exists($libserv{$_[0]});
12270:     }
12271: 
12272:     sub all_library {
12273: 	&load_hosts_tab() if (!$loaded);
12274: 
12275: 	return %libserv;
12276:     }
12277: 
12278:     sub unique_library {
12279: 	#2x reverse removes all hostnames that appear more than once
12280:         my %unique = reverse &all_library();
12281:         return reverse %unique;
12282:     }
12283: 
12284:     sub get_servers {
12285: 	&load_hosts_tab() if (!$loaded);
12286: 
12287: 	my ($domain,$type) = @_;
12288: 	my %possible_hosts = ($type eq 'library') ? %libserv
12289: 	                                          : %hostname;
12290: 	my %result;
12291: 	if (ref($domain) eq 'ARRAY') {
12292: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12293: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12294: 		    $result{$host} = $hostname;
12295: 		}
12296: 	    }
12297: 	} else {
12298: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12299: 		if ($hostdom{$host} eq $domain) {
12300: 		    $result{$host} = $hostname;
12301: 		}
12302: 	    }
12303: 	}
12304: 	return %result;
12305:     }
12306: 
12307:     sub get_unique_servers {
12308:         my %unique = reverse &get_servers(@_);
12309: 	return reverse %unique;
12310:     }
12311: 
12312:     sub host_domain {
12313: 	&load_hosts_tab() if (!$loaded);
12314: 
12315: 	my ($lonid) = @_;
12316: 	return $hostdom{$lonid};
12317:     }
12318: 
12319:     sub all_domains {
12320: 	&load_hosts_tab() if (!$loaded);
12321: 
12322: 	my %seen;
12323: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12324: 	return @uniq;
12325:     }
12326: 
12327:     sub internet_dom {
12328:         &load_hosts_tab() if (!$loaded);
12329: 
12330:         my ($lonid) = @_;
12331:         return $internetdom{$lonid};
12332:     }
12333: 
12334:     sub is_LC_dns {
12335:         &load_hosts_tab() if (!$loaded);
12336: 
12337:         my ($hostname) = @_;
12338:         return exists($LC_dns_serv{$hostname});
12339:     }
12340: 
12341: }
12342: 
12343: { 
12344:     my %iphost;
12345:     my %name_to_ip;
12346:     my %lonid_to_ip;
12347: 
12348:     sub get_hosts_from_ip {
12349: 	my ($ip) = @_;
12350: 	my %iphosts = &get_iphost();
12351: 	if (ref($iphosts{$ip})) {
12352: 	    return @{$iphosts{$ip}};
12353: 	}
12354: 	return;
12355:     }
12356:     
12357:     sub reset_hosts_ip_info {
12358: 	undef(%iphost);
12359: 	undef(%name_to_ip);
12360: 	undef(%lonid_to_ip);
12361:     }
12362: 
12363:     sub get_host_ip {
12364: 	my ($lonid) = @_;
12365: 	if (exists($lonid_to_ip{$lonid})) {
12366: 	    return $lonid_to_ip{$lonid};
12367: 	}
12368: 	my $name=&hostname($lonid);
12369:    	my $ip = gethostbyname($name);
12370: 	return if (!$ip || length($ip) ne 4);
12371: 	$ip=inet_ntoa($ip);
12372: 	$name_to_ip{$name}   = $ip;
12373: 	$lonid_to_ip{$lonid} = $ip;
12374: 	return $ip;
12375:     }
12376:     
12377:     sub get_iphost {
12378: 	my ($ignore_cache) = @_;
12379: 
12380: 	if (!$ignore_cache) {
12381: 	    if (%iphost) {
12382: 		return %iphost;
12383: 	    }
12384: 	    my ($ip_info,$cached)=
12385: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12386: 	    if ($cached) {
12387: 		%iphost      = %{$ip_info->[0]};
12388: 		%name_to_ip  = %{$ip_info->[1]};
12389: 		%lonid_to_ip = %{$ip_info->[2]};
12390: 		return %iphost;
12391: 	    }
12392: 	}
12393: 
12394: 	# get yesterday's info for fallback
12395: 	my %old_name_to_ip;
12396: 	my ($ip_info,$cached)=
12397: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12398: 	if ($cached) {
12399: 	    %old_name_to_ip = %{$ip_info->[1]};
12400: 	}
12401: 
12402: 	my %name_to_host = &all_names();
12403: 	foreach my $name (keys(%name_to_host)) {
12404: 	    my $ip;
12405: 	    if (!exists($name_to_ip{$name})) {
12406: 		$ip = gethostbyname($name);
12407: 		if (!$ip || length($ip) ne 4) {
12408: 		    if (defined($old_name_to_ip{$name})) {
12409: 			$ip = $old_name_to_ip{$name};
12410: 			&logthis("Can't find $name defaulting to old $ip");
12411: 		    } else {
12412: 			&logthis("Name $name no IP found");
12413: 			next;
12414: 		    }
12415: 		} else {
12416: 		    $ip=inet_ntoa($ip);
12417: 		}
12418: 		$name_to_ip{$name} = $ip;
12419: 	    } else {
12420: 		$ip = $name_to_ip{$name};
12421: 	    }
12422: 	    foreach my $id (@{ $name_to_host{$name} }) {
12423: 		$lonid_to_ip{$id} = $ip;
12424: 	    }
12425: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12426: 	}
12427: 	&do_cache_new('iphost','iphost',
12428: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12429: 		      48*60*60);
12430: 
12431: 	return %iphost;
12432:     }
12433: 
12434:     #
12435:     #  Given a DNS returns the loncapa host name for that DNS 
12436:     # 
12437:     sub host_from_dns {
12438:         my ($dns) = @_;
12439:         my @hosts;
12440:         my $ip;
12441: 
12442:         if (exists($name_to_ip{$dns})) {
12443:             $ip = $name_to_ip{$dns};
12444:         }
12445:         if (!$ip) {
12446:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12447:             if (length($ip) == 4) { 
12448: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12449:             }
12450:         }
12451:         if ($ip) {
12452: 	    @hosts = get_hosts_from_ip($ip);
12453: 	    return $hosts[0];
12454:         }
12455:         return undef;
12456:     }
12457: 
12458:     sub get_internet_names {
12459:         my ($lonid) = @_;
12460:         return if ($lonid eq '');
12461:         my ($idnref,$cached)=
12462:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12463:         if ($cached) {
12464:             return $idnref;
12465:         }
12466:         my $ip = &get_host_ip($lonid);
12467:         my @hosts = &get_hosts_from_ip($ip);
12468:         my %iphost = &get_iphost();
12469:         my (@idns,%seen);
12470:         foreach my $id (@hosts) {
12471:             my $dom = &host_domain($id);
12472:             my $prim_id = &domain($dom,'primary');
12473:             my $prim_ip = &get_host_ip($prim_id);
12474:             next if ($seen{$prim_ip});
12475:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12476:                 foreach my $id (@{$iphost{$prim_ip}}) {
12477:                     my $intdom = &internet_dom($id);
12478:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12479:                         push(@idns,$intdom);
12480:                     }
12481:                 }
12482:             }
12483:             $seen{$prim_ip} = 1;
12484:         }
12485:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12486:     }
12487: 
12488: }
12489: 
12490: sub all_loncaparevs {
12491:     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 2.11);
12492: }
12493: 
12494: # ---------------------------------------------------------- Read loncaparev table
12495: {
12496:     sub load_loncaparevs { 
12497:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12498:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12499:                 while (my $configline=<$config>) {
12500:                     chomp($configline);
12501:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12502:                     $loncaparevs{$hostid}=$loncaparev;
12503:                 }
12504:                 close($config);
12505:             }
12506:         }
12507:     }
12508: }
12509: 
12510: # ---------------------------------------------------------- Read serverhostID table
12511: {
12512:     sub load_serverhomeIDs {
12513:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12514:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12515:                 while (my $configline=<$config>) {
12516:                     chomp($configline);
12517:                     my ($name,$id)=split(/:/,$configline);
12518:                     $serverhomeIDs{$name}=$id;
12519:                 }
12520:                 close($config);
12521:             }
12522:         }
12523:     }
12524: }
12525: 
12526: 
12527: BEGIN {
12528: 
12529: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12530:     unless ($readit) {
12531: {
12532:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12533:     %perlvar = (%perlvar,%{$configvars});
12534: }
12535: 
12536: 
12537: # ------------------------------------------------------ Read spare server file
12538: {
12539:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12540: 
12541:     while (my $configline=<$config>) {
12542:        chomp($configline);
12543:        if ($configline) {
12544: 	   my ($host,$type) = split(':',$configline,2);
12545: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12546: 	   push(@{ $spareid{$type} }, $host);
12547:        }
12548:     }
12549:     close($config);
12550: }
12551: # ------------------------------------------------------------ Read permissions
12552: {
12553:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12554: 
12555:     while (my $configline=<$config>) {
12556: 	chomp($configline);
12557: 	if ($configline) {
12558: 	    my ($role,$perm)=split(/ /,$configline);
12559: 	    if ($perm ne '') { $pr{$role}=$perm; }
12560: 	}
12561:     }
12562:     close($config);
12563: }
12564: 
12565: # -------------------------------------------- Read plain texts for permissions
12566: {
12567:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12568: 
12569:     while (my $configline=<$config>) {
12570: 	chomp($configline);
12571: 	if ($configline) {
12572: 	    my ($short,@plain)=split(/:/,$configline);
12573:             %{$prp{$short}} = ();
12574: 	    if (@plain > 0) {
12575:                 $prp{$short}{'std'} = $plain[0];
12576:                 for (my $i=1; $i<@plain; $i++) {
12577:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12578:                 }
12579:             }
12580: 	}
12581:     }
12582:     close($config);
12583: }
12584: 
12585: # ---------------------------------------------------------- Read package table
12586: {
12587:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12588: 
12589:     while (my $configline=<$config>) {
12590: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12591: 	chomp($configline);
12592: 	my ($short,$plain)=split(/:/,$configline);
12593: 	my ($pack,$name)=split(/\&/,$short);
12594: 	if ($plain ne '') {
12595: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12596: 	    $packagetab{$short}=$plain; 
12597: 	}
12598:     }
12599:     close($config);
12600: }
12601: 
12602: # ---------------------------------------------------------- Read loncaparev table
12603: 
12604: &load_loncaparevs();
12605: 
12606: # ---------------------------------------------------------- Read serverhostID table
12607: 
12608: &load_serverhomeIDs();
12609: 
12610: # ---------------------------------------------------------- Read releaseslist XML
12611: {
12612:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12613:     if (-e $file) {
12614:         my $parser = HTML::LCParser->new($file);
12615:         while (my $token = $parser->get_token()) {
12616:             if ($token->[0] eq 'S') {
12617:                 my $item = $token->[1];
12618:                 my $name = $token->[2]{'name'};
12619:                 my $value = $token->[2]{'value'};
12620:                 if ($item ne '' && $name ne '' && $value ne '') {
12621:                     my $release = $parser->get_text();
12622:                     $release =~ s/(^\s*|\s*$ )//gx;
12623:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12624:                 }
12625:             }
12626:         }
12627:     }
12628: }
12629: 
12630: # ---------------------------------------------------------- Read managers table
12631: {
12632:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12633:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12634:             while (my $configline=<$config>) {
12635:                 chomp($configline);
12636:                 next if ($configline =~ /^\#/);
12637:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12638:                     $managerstab{$configline} = 1;
12639:                 }
12640:             }
12641:             close($config);
12642:         }
12643:     }
12644: }
12645: 
12646: # ------------- set up temporary directory
12647: {
12648:     $tmpdir = LONCAPA::tempdir();
12649: 
12650: }
12651: 
12652: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12653: 				'compress_threshold'=> 20_000,
12654:  			        });
12655: 
12656: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12657: $dumpcount=0;
12658: $locknum=0;
12659: 
12660: &logtouch();
12661: &logthis('<font color="yellow">INFO: Read configuration</font>');
12662: $readit=1;
12663:     {
12664: 	use integer;
12665: 	my $test=(2**32)+1;
12666: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12667: 	&logthis(" Detected 64bit platform ($_64bit)");
12668:     }
12669: }
12670: }
12671: 
12672: 1;
12673: __END__
12674: 
12675: =pod
12676: 
12677: =head1 NAME
12678: 
12679: Apache::lonnet - Subroutines to ask questions about things in the network.
12680: 
12681: =head1 SYNOPSIS
12682: 
12683: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12684: 
12685:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12686: 
12687: Common parameters:
12688: 
12689: =over 4
12690: 
12691: =item *
12692: 
12693: $uname : an internal username (if $cname expecting a course Id specifically)
12694: 
12695: =item *
12696: 
12697: $udom : a domain (if $cdom expecting a course's domain specifically)
12698: 
12699: =item *
12700: 
12701: $symb : a resource instance identifier
12702: 
12703: =item *
12704: 
12705: $namespace : the name of a .db file that contains the data needed or
12706: being set.
12707: 
12708: =back
12709: 
12710: =head1 OVERVIEW
12711: 
12712: lonnet provides subroutines which interact with the
12713: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12714: about classes, users, and resources.
12715: 
12716: For many of these objects you can also use this to store data about
12717: them or modify them in various ways.
12718: 
12719: =head2 Symbs
12720: 
12721: To identify a specific instance of a resource, LON-CAPA uses symbols
12722: or "symbs"X<symb>. These identifiers are built from the URL of the
12723: map, the resource number of the resource in the map, and the URL of
12724: the resource itself. The latter is somewhat redundant, but might help
12725: if maps change.
12726: 
12727: An example is
12728: 
12729:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12730: 
12731: The respective map entry is
12732: 
12733:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12734:   title="Problem 2">
12735:  </resource>
12736: 
12737: Symbs are used by the random number generator, as well as to store and
12738: restore data specific to a certain instance of for example a problem.
12739: 
12740: =head2 Storing And Retrieving Data
12741: 
12742: X<store()>X<cstore()>X<restore()>Three of the most important functions
12743: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12744: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12745: is is the non-critical message twin of cstore. These functions are for
12746: handlers to store a perl hash to a user's permanent data space in an
12747: easy manner, and to retrieve it again on another call. It is expected
12748: that a handler would use this once at the beginning to retrieve data,
12749: and then again once at the end to send only the new data back.
12750: 
12751: The data is stored in the user's data directory on the user's
12752: homeserver under the ID of the course.
12753: 
12754: The hash that is returned by restore will have all of the previous
12755: value for all of the elements of the hash.
12756: 
12757: Example:
12758: 
12759:  #creating a hash
12760:  my %hash;
12761:  $hash{'foo'}='bar';
12762: 
12763:  #storing it
12764:  &Apache::lonnet::cstore(\%hash);
12765: 
12766:  #changing a value
12767:  $hash{'foo'}='notbar';
12768: 
12769:  #adding a new value
12770:  $hash{'bar'}='foo';
12771:  &Apache::lonnet::cstore(\%hash);
12772: 
12773:  #retrieving the hash
12774:  my %history=&Apache::lonnet::restore();
12775: 
12776:  #print the hash
12777:  foreach my $key (sort(keys(%history))) {
12778:    print("\%history{$key} = $history{$key}");
12779:  }
12780: 
12781: Will print out:
12782: 
12783:  %history{1:foo} = bar
12784:  %history{1:keys} = foo:timestamp
12785:  %history{1:timestamp} = 990455579
12786:  %history{2:bar} = foo
12787:  %history{2:foo} = notbar
12788:  %history{2:keys} = foo:bar:timestamp
12789:  %history{2:timestamp} = 990455580
12790:  %history{bar} = foo
12791:  %history{foo} = notbar
12792:  %history{timestamp} = 990455580
12793:  %history{version} = 2
12794: 
12795: Note that the special hash entries C<keys>, C<version> and
12796: C<timestamp> were added to the hash. C<version> will be equal to the
12797: total number of versions of the data that have been stored. The
12798: C<timestamp> attribute will be the UNIX time the hash was
12799: stored. C<keys> is available in every historical section to list which
12800: keys were added or changed at a specific historical revision of a
12801: hash.
12802: 
12803: B<Warning>: do not store the hash that restore returns directly. This
12804: will cause a mess since it will restore the historical keys as if the
12805: were new keys. I.E. 1:foo will become 1:1:foo etc.
12806: 
12807: Calling convention:
12808: 
12809:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12810:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
12811: 
12812: For more detailed information, see lonnet specific documentation.
12813: 
12814: =head1 RETURN MESSAGES
12815: 
12816: =over 4
12817: 
12818: =item * B<con_lost>: unable to contact remote host
12819: 
12820: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12821: when the connection is brought back up
12822: 
12823: =item * B<con_failed>: unable to contact remote host and unable to save message
12824: for later delivery
12825: 
12826: =item * B<error:>: an error a occurred, a description of the error follows the :
12827: 
12828: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12829: that was requested
12830: 
12831: =back
12832: 
12833: =head1 PUBLIC SUBROUTINES
12834: 
12835: =head2 Session Environment Functions
12836: 
12837: =over 4
12838: 
12839: =item * 
12840: X<appenv()>
12841: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12842: the user envirnoment file, and will be restored for each access this
12843: user makes during this session, also modifies the %env for the current
12844: process. Optional rolesarrayref - if defined contains a reference to an array
12845: of roles which are exempt from the restriction on modifying user.role entries 
12846: in the user's environment.db and in %env.    
12847: 
12848: =item *
12849: X<delenv()>
12850: B<delenv($delthis,$regexp)>: removes all items from the session
12851: environment file that begin with $delthis. If the 
12852: optional second arg - $regexp - is true, $delthis is treated as a 
12853: regular expression, otherwise \Q$delthis\E is used. 
12854: The values are also deleted from the current processes %env.
12855: 
12856: =item * get_env_multiple($name) 
12857: 
12858: gets $name from the %env hash, it seemlessly handles the cases where multiple
12859: values may be defined and end up as an array ref.
12860: 
12861: returns an array of values
12862: 
12863: =back
12864: 
12865: =head2 User Information
12866: 
12867: =over 4
12868: 
12869: =item *
12870: X<queryauthenticate()>
12871: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12872: authentication scheme
12873: 
12874: =item *
12875: X<authenticate()>
12876: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12877: authenticate user from domain's lib servers (first use the current
12878: one). C<$upass> should be the users password.
12879: $checkdefauth is optional (value is 1 if a check should be made to
12880:    authenticate user using default authentication method, and allow
12881:    account creation if username does not have account in the domain).
12882: $clientcancheckhost is optional (value is 1 if checking whether the
12883:    server can host will occur on the client side in lonauth.pm).   
12884: 
12885: =item *
12886: X<homeserver()>
12887: B<homeserver($uname,$udom)>: find the server which has
12888: the user's directory and files (there must be only one), this caches
12889: the answer, and also caches if there is a borken connection.
12890: 
12891: =item *
12892: X<idget()>
12893: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12894: (IDs are a unique resource in a domain, there must be only 1 ID per
12895: username, and only 1 username per ID in a specific domain) (returns
12896: hash: id=>name,id=>name)
12897: 
12898: =item *
12899: X<idrget()>
12900: B<idrget($udom,@unames)>: find the IDs behind a list of
12901: usernames (returns hash: name=>id,name=>id)
12902: 
12903: =item *
12904: X<idput()>
12905: B<idput($udom,%ids)>: store away a list of names and associated IDs
12906: 
12907: =item *
12908: X<rolesinit()>
12909: B<rolesinit($udom,$username)>: get user privileges.
12910: returns user role, first access and timer interval hashes
12911: 
12912: =item *
12913: X<privileged()>
12914: B<privileged($username,$domain)>: returns a true if user has a
12915: privileged and active role (i.e. su or dc), false otherwise.
12916: 
12917: =item *
12918: X<getsection()>
12919: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12920: course $cname, return section name/number or '' for "not in course"
12921: and '-1' for "no section"
12922: 
12923: =item *
12924: X<userenvironment()>
12925: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12926: passed in @what from the requested user's environment, returns a hash
12927: 
12928: =item * 
12929: X<userlog_query()>
12930: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12931: activity.log file. %filters defines filters applied when parsing the
12932: log file. These can be start or end timestamps, or the type of action
12933: - log to look for Login or Logout events, check for Checkin or
12934: Checkout, role for role selection. The response is in the form
12935: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12936: escaped strings of the action recorded in the activity.log file.
12937: 
12938: =back
12939: 
12940: =head2 User Roles
12941: 
12942: =over 4
12943: 
12944: =item *
12945: 
12946: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12947:  F: full access
12948:  U,I,K: authentication modes (cxx only)
12949:  '': forbidden
12950:  1: user needs to choose course
12951:  2: browse allowed
12952:  A: passphrase authentication needed
12953: 
12954: =item *
12955: 
12956: constructaccess($url,$setpriv) : check for access to construction space URL
12957: 
12958: See if the owner domain and name in the URL match those in the
12959: expected environment.  If so, return three element list
12960: ($ownername,$ownerdomain,$ownerhome).
12961: 
12962: Otherwise return the null string.
12963: 
12964: If second argument 'setpriv' is true, it assigns the privileges,
12965: and returns the same three element list, unless the owner has
12966: blocked "ad hoc" Domain Coordinator access to the Author Space,
12967: in which case the null string is returned.
12968: 
12969: =item *
12970: 
12971: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12972: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12973: and course level
12974: 
12975: =item *
12976: 
12977: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12978: (rolesplain.tab); plain text explanation of a user role term.
12979: $type is Course (default) or Community.
12980: If $forcedefault evaluates to true, text returned will be default 
12981: text for $type. Otherwise, if this is a course, the text returned 
12982: will be a custom name for the role (if defined in the course's 
12983: environment).  If no custom name is defined the default is returned.
12984:    
12985: =item *
12986: 
12987: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12988: All arguments are optional. Returns a hash of a roles, either for
12989: co-author/assistant author roles for a user's Construction Space
12990: (default), or if $context is 'userroles', roles for the user himself,
12991: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12992: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12993: For each key, value is set to colon-separated start and end times for
12994: the role.  If no username and domain are specified, will default to
12995: current user/domain. Types, roles, and roledoms are references to arrays
12996: of role statuses (active, future or previous), roles 
12997: (e.g., cc,in, st etc.) and domains of the roles which can be used
12998: to restrict the list of roles reported. If no array ref is 
12999: provided for types, will default to return only active roles.
13000: 
13001: =item *
13002: 
13003: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13004: user: $uname:$udom has a role in the course: $cdom_$cnum. 
13005: 
13006: Additional optional arguments are: $type (if role checking is to be restricted 
13007: to certain user status types -- previous (expired roles), active (currently
13008: available roles) or future (roles available in the future), and
13009: $hideprivileged -- if true will not report course roles for users who
13010: have active Domain Coordinator role in course's domain or in additional
13011: domains (specified in 'Domains to check for privileged users' in course
13012: environment -- set via:  Course Settings -> Classlists and staff listing).
13013: 
13014: =item *
13015: 
13016: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13017: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13018: $possdomains and $possroles are optional array refs -- to domains to check and
13019: roles to check.  If $possdomains is not specified, a dump will be done of the
13020: users' roles.db to check for a dc or su role in any domain. This can be
13021: time consuming if &privileged is called repeatedly (e.g., when displaying a
13022: classlist), so in such cases, supplying a $possdomains array is preferred, as
13023: this then allows &privileged_by_domain() to be used, which caches the identity
13024: of privileged users, eliminating the need for repeated calls to &dump().
13025: 
13026: =item *
13027: 
13028: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13029: where the outer hash keys are domains specified in the $possdomains array ref,
13030: next inner hash keys are privileged roles specified in the $roles array ref,
13031: and the innermost hash contains key = value pairs for username:domain = end:start
13032: for active or future "privileged" users with that role in that domain. To avoid
13033: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13034: innerhash are cached using priv_$role and $dom as the identifiers.
13035: 
13036: =back
13037: 
13038: =head2 User Modification
13039: 
13040: =over 4
13041: 
13042: =item *
13043: 
13044: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
13045: user for the level given by URL.  Optional start and end dates (leave empty
13046: string or zero for "no date")
13047: 
13048: =item *
13049: 
13050: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13051: change a users, password, possible return values are: ok,
13052: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13053: refused
13054: 
13055: =item *
13056: 
13057: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
13058: 
13059: =item *
13060: 
13061: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13062:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
13063: 
13064: will update user information (firstname,middlename,lastname,generation,
13065: permanentemail), and if forceid is true, student/employee ID also.
13066: A user's institutional affiliation(s) can also be updated.
13067: User information fields will not be overwritten with empty entries 
13068: unless the field is included in the $candelete array reference.
13069: This array is included when a single user is modified via "Manage Users",
13070: or when Autoupdate.pl is run by cron in a domain.
13071: 
13072: =item *
13073: 
13074: modifystudent
13075: 
13076: modify a student's enrollment and identification information.
13077: The course id is resolved based on the current user's environment.  
13078: This means the invoking user must be a course coordinator or otherwise
13079: associated with a course.
13080: 
13081: This call is essentially a wrapper for lonnet::modifyuser and
13082: lonnet::modify_student_enrollment
13083: 
13084: Inputs: 
13085: 
13086: =over 4
13087: 
13088: =item B<$udom> Student's loncapa domain
13089: 
13090: =item B<$uname> Student's loncapa login name
13091: 
13092: =item B<$uid> Student/Employee ID
13093: 
13094: =item B<$umode> Student's authentication mode
13095: 
13096: =item B<$upass> Student's password
13097: 
13098: =item B<$first> Student's first name
13099: 
13100: =item B<$middle> Student's middle name
13101: 
13102: =item B<$last> Student's last name
13103: 
13104: =item B<$gene> Student's generation
13105: 
13106: =item B<$usec> Student's section in course
13107: 
13108: =item B<$end> Unix time of the roles expiration
13109: 
13110: =item B<$start> Unix time of the roles start date
13111: 
13112: =item B<$forceid> If defined, allow $uid to be changed
13113: 
13114: =item B<$desiredhome> server to use as home server for student
13115: 
13116: =item B<$email> Student's permanent e-mail address
13117: 
13118: =item B<$type> Type of enrollment (auto or manual)
13119: 
13120: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
13121: 
13122: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
13123: 
13124: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
13125: 
13126: =item B<$context> role change context (shown in User Management Logs display in a course)
13127: 
13128: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13129: 
13130: =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.
13131: 
13132: =back
13133: 
13134: =item *
13135: 
13136: modify_student_enrollment
13137: 
13138: Change a student's enrollment status in a class.  The environment variable
13139: 'role.request.course' must be defined for this function to proceed.
13140: 
13141: Inputs:
13142: 
13143: =over 4
13144: 
13145: =item $udom, student's domain
13146: 
13147: =item $uname, student's name
13148: 
13149: =item $uid, student's user id
13150: 
13151: =item $first, student's first name
13152: 
13153: =item $middle
13154: 
13155: =item $last
13156: 
13157: =item $gene
13158: 
13159: =item $usec
13160: 
13161: =item $end
13162: 
13163: =item $start
13164: 
13165: =item $type
13166: 
13167: =item $locktype
13168: 
13169: =item $cid
13170: 
13171: =item $selfenroll
13172: 
13173: =item $context
13174: 
13175: =item $credits, number of credits student will earn from this class
13176: 
13177: =back
13178: 
13179: 
13180: =item *
13181: 
13182: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13183: custom role; give a custom role to a user for the level given by URL.  Specify
13184: name and domain of role author, and role name
13185: 
13186: =item *
13187: 
13188: revokerole($udom,$uname,$url,$role) : revoke a role for url
13189: 
13190: =item *
13191: 
13192: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13193: 
13194: =back
13195: 
13196: =head2 Course Infomation
13197: 
13198: =over 4
13199: 
13200: =item *
13201: 
13202: coursedescription($courseid,$options) : returns a hash of information about the
13203: specified course id, including all environment settings for the
13204: course, the description of the course will be in the hash under the
13205: key 'description'
13206: 
13207: $options is an optional parameter that if supplied is a hash reference that controls
13208: what how this function works.  It has the following key/values:
13209: 
13210: =over 4
13211: 
13212: =item freshen_cache
13213: 
13214: If defined, and the environment cache for the course is valid, it is 
13215: returned in the returned hash.
13216: 
13217: =item one_time
13218: 
13219: If defined, the last cache time is set to _now_
13220: 
13221: =item user
13222: 
13223: If defined, the supplied username is used instead of the current user.
13224: 
13225: 
13226: =back
13227: 
13228: =item *
13229: 
13230: resdata($name,$domain,$type,@which) : request for current parameter
13231: setting for a specific $type, where $type is either 'course' or 'user',
13232: @what should be a list of parameters to ask about. This routine caches
13233: answers for 10 minutes.
13234: 
13235: =item *
13236: 
13237: get_courseresdata($courseid, $domain) : dump the entire course resource
13238: data base, returning a hash that is keyed by the resource name and has
13239: values that are the resource value.  I believe that the timestamps and
13240: versions are also returned.
13241: 
13242: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13243: supplemental content area. This routine caches the number of files for 
13244: 10 minutes.
13245: 
13246: =back
13247: 
13248: =head2 Course Modification
13249: 
13250: =over 4
13251: 
13252: =item *
13253: 
13254: writecoursepref($courseid,%prefs) : write preferences (environment
13255: database) for a course
13256: 
13257: =item *
13258: 
13259: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13260: 
13261: =item *
13262: 
13263: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
13264: 
13265: =item *
13266: 
13267: is_course($courseid), is_course($cdom, $cnum)
13268: 
13269: Accepts either a combined $courseid (in the form of domain_courseid) or the
13270: two component version $cdom, $cnum. It checks if the specified course exists.
13271: 
13272: Returns:
13273:     undef if the course doesn't exist, otherwise
13274:     in scalar context the combined courseid.
13275:     in list context the two components of the course identifier, domain and 
13276:     courseid.    
13277: 
13278: =back
13279: 
13280: =head2 Resource Subroutines
13281: 
13282: =over 4
13283: 
13284: =item *
13285: 
13286: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13287: 
13288: =item *
13289: 
13290: repcopy($filename) : subscribes to the requested file, and attempts to
13291: replicate from the owning library server, Might return
13292: 'unavailable', 'not_found', 'forbidden', 'ok', or
13293: 'bad_request', also attempts to grab the metadata for the
13294: resource. Expects the local filesystem pathname
13295: (/home/httpd/html/res/....)
13296: 
13297: =back
13298: 
13299: =head2 Resource Information
13300: 
13301: =over 4
13302: 
13303: =item *
13304: 
13305: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13306: and returns the value of a variety of different possible values,
13307: $varname should be a request string, and the other parameters can be
13308: used to specify who and what one is asking about. Ordinarily, $cid 
13309: does not need to be specified, as it is retrived from 
13310: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13311: within lonuserstate::loadmap() when initializing a course, before
13312: $env{'request.course.id'} has been set, so it needs to be provided
13313: in that one case.
13314: 
13315: Possible values for $varname are environment.lastname (or other item
13316: from the envirnment hash), user.name (or someother aspect about the
13317: user), resource.0.maxtries (or some other part and parameter of a
13318: resource)
13319: 
13320: =item *
13321: 
13322: directcondval($number) : get current value of a condition; reads from a state
13323: string
13324: 
13325: =item *
13326: 
13327: condval($condidx) : value of condition index based on state
13328: 
13329: =item *
13330: 
13331: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13332: resource's metadata, $what should be either a specific key, or either
13333: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13334: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13335: 
13336: this function automatically caches all requests
13337: 
13338: =item *
13339: 
13340: metadata_query($query,$custom,$customshow) : make a metadata query against the
13341: network of library servers; returns file handle of where SQL and regex results
13342: will be stored for query
13343: 
13344: =item *
13345: 
13346: symbread($filename) : return symbolic list entry (filename argument optional);
13347: returns the data handle
13348: 
13349: =item *
13350: 
13351: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13352: and is a possible symb for the URL in $thisfn, and if is an encrypted
13353: resource that the user accessed using /enc/ returns a 1 on success, 0
13354: on failure, user must be in a course, as it assumes the existence of
13355: the course initial hash, and uses $env('request.course.id'}.  The third
13356: arg is an optional reference to a scalar.  If this arg is passed in the 
13357: call to symbverify, it will be set to 1 if the symb has been set to be 
13358: encrypted; otherwise it will be null.  
13359: 
13360: =item *
13361: 
13362: symbclean($symb) : removes versions numbers from a symb, returns the
13363: cleaned symb
13364: 
13365: =item *
13366: 
13367: is_on_map($uri) : checks if the $uri is somewhere on the current
13368: course map, user must be in a course for it to work.
13369: 
13370: =item *
13371: 
13372: numval($salt) : return random seed value (addend for rndseed)
13373: 
13374: =item *
13375: 
13376: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13377: a random seed, all arguments are optional, if they aren't sent it uses the
13378: environment to derive them. Note: if symb isn't sent and it can't get one
13379: from &symbread it will use the current time as its return value
13380: 
13381: =item *
13382: 
13383: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13384: unfakeable, receipt
13385: 
13386: =item *
13387: 
13388: receipt() : API to ireceipt working off of env values; given out to users
13389: 
13390: =item *
13391: 
13392: countacc($url) : count the number of accesses to a given URL
13393: 
13394: =item *
13395: 
13396: 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
13397: 
13398: =item *
13399: 
13400: 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)
13401: 
13402: =item *
13403: 
13404: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13405: 
13406: =item *
13407: 
13408: devalidate($symb) : devalidate temporary spreadsheet calculations,
13409: forcing spreadsheet to reevaluate the resource scores next time.
13410: 
13411: =item * 
13412: 
13413: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13414: when viewing in course context.
13415: 
13416:  input: six args -- filename (decluttered), course number, course domain,
13417:                     url, symb (if registered) and group (if this is a 
13418:                     group item -- e.g., bulletin board, group page etc.).
13419: 
13420:  output: array of five scalars --
13421:          $cfile -- url for file editing if editable on current server
13422:          $home -- homeserver of resource (i.e., for author if published,
13423:                                           or course if uploaded.).
13424:          $switchserver --  1 if server switch will be needed.
13425:          $forceedit -- 1 if icon/link should be to go to edit mode 
13426:          $forceview -- 1 if icon/link should be to go to view mode
13427: 
13428: =item *
13429: 
13430: is_course_upload($file,$cnum,$cdom)
13431: 
13432: Used in course context to determine if current file was uploaded to 
13433: the course (i.e., would be found in /userfiles/docs on the course's 
13434: homeserver.
13435: 
13436:   input: 3 args -- filename (decluttered), course number and course domain.
13437:   output: boolean -- 1 if file was uploaded.
13438: 
13439: =back
13440: 
13441: =head2 Storing/Retreiving Data
13442: 
13443: =over 4
13444: 
13445: =item *
13446: 
13447: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13448: permanently for this url; hashref needs to be given and should be a \%hashname;
13449: the remaining args aren't required and if they aren't passed or are '' they will
13450: be derived from the env (with the exception of $laststore, which is an 
13451: optional arg used when a user's submission is stored in grading).
13452: $laststore is $version=$timestamp, where $version is the most recent version
13453: number retrieved for the corresponding $symb in the $namespace db file, and
13454: $timestamp is the timestamp for that transaction (UNIX time).
13455: $laststore is currently only passed when cstore() is called by 
13456: structuretags::finalize_storage().
13457: 
13458: =item *
13459: 
13460: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13461: but uses critical subroutine
13462: 
13463: =item *
13464: 
13465: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13466: all args are optional
13467: 
13468: =item *
13469: 
13470: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13471: dumps the complete (or key matching regexp) namespace into a hash
13472: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13473: normally &store()ed into
13474: 
13475: $range should be either an integer '100' (give me the first 100
13476:                                            matching records)
13477:               or be  two integers sperated by a - with no spaces
13478:                  '30-50' (give me the 30th through the 50th matching
13479:                           records)
13480: 
13481: 
13482: =item *
13483: 
13484: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
13485: replaces a &store() version of data with a replacement set of data
13486: for a particular resource in a namespace passed in the $storehash hash 
13487: reference. If $tolog is true, the transaction is logged in the courselog
13488: with an action=PUTSTORE.
13489: 
13490: =item *
13491: 
13492: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13493: works very similar to store/cstore, but all data is stored in a
13494: temporary location and can be reset using tmpreset, $storehash should
13495: be a hash reference, returns nothing on success
13496: 
13497: =item *
13498: 
13499: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13500: similar to restore, but all data is stored in a temporary location and
13501: can be reset using tmpreset. Returns a hash of values on success,
13502: error string otherwise.
13503: 
13504: =item *
13505: 
13506: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13507: deltes all keys for $symb form the temporary storage hash.
13508: 
13509: =item *
13510: 
13511: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13512: reference filled in from namesp ($udom and $uname are optional)
13513: 
13514: =item *
13515: 
13516: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13517: namesp ($udom and $uname are optional)
13518: 
13519: =item *
13520: 
13521: dump($namespace,$udom,$uname,$regexp,$range) : 
13522: dumps the complete (or key matching regexp) namespace into a hash
13523: ($udom, $uname, $regexp, $range are optional)
13524: 
13525: $range should be either an integer '100' (give me the first 100
13526:                                            matching records)
13527:               or be  two integers sperated by a - with no spaces
13528:                  '30-50' (give me the 30th through the 50th matching
13529:                           records)
13530: =item *
13531: 
13532: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13533: $store can be a scalar, an array reference, or if the amount to be 
13534: incremented is > 1, a hash reference.
13535: 
13536: ($udom and $uname are optional)
13537: 
13538: =item *
13539: 
13540: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13541: ($udom and $uname are optional)
13542: 
13543: =item *
13544: 
13545: cput($namespace,$storehash,$udom,$uname) : critical put
13546: ($udom and $uname are optional)
13547: 
13548: =item *
13549: 
13550: newput($namespace,$storehash,$udom,$uname) :
13551: 
13552: Attempts to store the items in the $storehash, but only if they don't
13553: currently exist, if this succeeds you can be certain that you have 
13554: successfully created a new key value pair in the $namespace db.
13555: 
13556: 
13557: Args:
13558:  $namespace: name of database to store values to
13559:  $storehash: hashref to store to the db
13560:  $udom: (optional) domain of user containing the db
13561:  $uname: (optional) name of user caontaining the db
13562: 
13563: Returns:
13564:  'ok' -> succeeded in storing all keys of $storehash
13565:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13566:                         least <key> already existed in the db (other
13567:                         requested keys may also already exist)
13568:  'error: <msg>' -> unable to tie the DB or other error occurred
13569:  'con_lost' -> unable to contact request server
13570:  'refused' -> action was not allowed by remote machine
13571: 
13572: 
13573: =item *
13574: 
13575: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13576: reference filled in from namesp (encrypts the return communication)
13577: ($udom and $uname are optional)
13578: 
13579: =item *
13580: 
13581: log($udom,$name,$home,$message) : write to permanent log for user; use
13582: critical subroutine
13583: 
13584: =item *
13585: 
13586: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13587: array reference filled in from namespace found in domain level on either
13588: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13589: 
13590: =item *
13591: 
13592: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13593: domain level either on specified domain server ($uhome) or primary domain 
13594: server ($udom and $uhome are optional)
13595: 
13596: =item * 
13597: 
13598: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13599: for: authentication, language, quotas, timezone, date locale, and portal URL in
13600: the target domain.
13601: 
13602: May also include additional key => value pairs for the following groups:
13603: 
13604: =over
13605: 
13606: =item
13607: disk quotas (MB allocated by default to portfolios and authoring spaces).
13608: 
13609: =over
13610: 
13611: =item defaultquota, authorquota
13612: 
13613: =back
13614: 
13615: =item
13616: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13617: portfolio for users).
13618: 
13619: =over
13620: 
13621: =item
13622: aboutme, blog, webdav, portfolio
13623: 
13624: =back
13625: 
13626: =item
13627: requestcourses: ability to request courses, and how requests are processed.
13628: 
13629: =over
13630: 
13631: =item
13632: official, unofficial, community, textbook
13633: 
13634: =back
13635: 
13636: =item
13637: inststatus: types of institutional affiliation, and order in which they are displayed.
13638: 
13639: =over
13640: 
13641: =item
13642: inststatustypes, inststatusorder, inststatusguest
13643: 
13644: =back
13645: 
13646: =item
13647: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13648: for course's uploaded content.
13649: 
13650: =over
13651: 
13652: =item
13653: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
13654: communityquota, textbookquota
13655: 
13656: =back
13657: 
13658: =item
13659: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13660: on your servers.
13661: 
13662: =over
13663: 
13664: =item 
13665: remotesessions, hostedsessions
13666: 
13667: =back
13668: 
13669: =back
13670: 
13671: In cases where a domain coordinator has never used the "Set Domain Configuration"
13672: utility to create a configuration.db file on a domain's primary library server 
13673: only the following domain defaults: auth_def, auth_arg_def, lang_def
13674: -- corresponding values are authentication type (internal, krb4, krb5,
13675: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13676: will be available. Values are retrieved from cache (if current), unless the
13677: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13678: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13679: 
13680: Typical usage:
13681: 
13682: %domdefaults = &get_domain_defaults($target_domain);
13683: 
13684: =back
13685: 
13686: =head2 Network Status Functions
13687: 
13688: =over 4
13689: 
13690: =item *
13691: 
13692: dirlist() : return directory list based on URI (first arg).
13693: 
13694: Inputs: 1 required, 5 optional.
13695: 
13696: =over
13697: 
13698: =item 
13699: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13700: 
13701: =item
13702: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13703: 
13704: =item
13705: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13706: 
13707: =item
13708: $getpropath - boolean: 1 if prepend path using &propath(). 
13709: 
13710: =item
13711: $getuserdir - boolean: 1 if prepend path for "userfiles".
13712: 
13713: =item 
13714: $alternateRoot - path to prepend in place of path from $uri.
13715: 
13716: =back
13717: 
13718: Returns: Array of up to two items.
13719: 
13720: =over
13721: 
13722: a reference to an array of files/subdirectories
13723: 
13724: =over
13725: 
13726: Each element in the array of files/subdirectories is a & separated list of
13727: item name and the result of running stat on the item.  If dirlist was requested
13728: for a file instead of a directory, the item name will be ''. For a directory 
13729: listing, if the item is a metadata file, the element will end &N&M 
13730: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13731: default copyright set (1).  
13732: 
13733: =back
13734: 
13735: a scalar containing error condition (if encountered).
13736: 
13737: =over
13738: 
13739: =item 
13740: no_host (no homeserver identified for $username:$domain).
13741: 
13742: =item 
13743: no_such_host (server contacted for listing not identified as valid host).
13744: 
13745: =item 
13746: con_lost (connection to remote server failed).
13747: 
13748: =item 
13749: refused (invalid $username:$domain received on lond side).
13750: 
13751: =item 
13752: no_such_dir (directory at specified path on lond side does not exist). 
13753: 
13754: =item 
13755: empty (directory at specified path on lond side is empty).
13756: 
13757: =over
13758: 
13759: This is currently not encountered because the &ls3, &ls2, 
13760: &ls (_handler) routines on the lond side do not filter out
13761: . and .. from a directory listing. 
13762: 
13763: =back
13764: 
13765: =back
13766: 
13767: =back
13768: 
13769: =item *
13770: 
13771: spareserver() : find server with least workload from spare.tab
13772: 
13773: 
13774: =item *
13775: 
13776: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13777: if there is no corresponding loncapa host.
13778: 
13779: =back
13780: 
13781: 
13782: =head2 Apache Request
13783: 
13784: =over 4
13785: 
13786: =item *
13787: 
13788: ssi($url,%hash) : server side include, does a complete request cycle on url to
13789: localhost, posts hash
13790: 
13791: =back
13792: 
13793: =head2 Data to String to Data
13794: 
13795: =over 4
13796: 
13797: =item *
13798: 
13799: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13800: and '&' separators, supports elements that are arrayrefs and hashrefs
13801: 
13802: =item *
13803: 
13804: hashref2str($hashref) : convert a hashref into a string complete with
13805: escaping and '=' and '&' separators, supports elements that are
13806: arrayrefs and hashrefs
13807: 
13808: =item *
13809: 
13810: arrayref2str($arrayref) : convert an arrayref into a string complete
13811: with escaping and '&' separators, supports elements that are arrayrefs
13812: and hashrefs
13813: 
13814: =item *
13815: 
13816: str2hash($string) : convert string to hash using unescaping and
13817: splitting on '=' and '&', supports elements that are arrayrefs and
13818: hashrefs
13819: 
13820: =item *
13821: 
13822: str2array($string) : convert string to hash using unescaping and
13823: splitting on '&', supports elements that are arrayrefs and hashrefs
13824: 
13825: =back
13826: 
13827: =head2 Logging Routines
13828: 
13829: 
13830: These routines allow one to make log messages in the lonnet.log and
13831: lonnet.perm logfiles.
13832: 
13833: =over 4
13834: 
13835: =item *
13836: 
13837: logtouch() : make sure the logfile, lonnet.log, exists
13838: 
13839: =item *
13840: 
13841: logthis() : append message to the normal lonnet.log file, it gets
13842: preiodically rolled over and deleted.
13843: 
13844: =item *
13845: 
13846: logperm() : append a permanent message to lonnet.perm.log, this log
13847: file never gets deleted by any automated portion of the system, only
13848: messages of critical importance should go in here.
13849: 
13850: 
13851: =back
13852: 
13853: =head2 General File Helper Routines
13854: 
13855: =over 4
13856: 
13857: =item *
13858: 
13859: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13860: (a) files in /uploaded
13861:   (i) If a local copy of the file exists - 
13862:       compares modification date of local copy with last-modified date for 
13863:       definitive version stored on home server for course. If local copy is 
13864:       stale, requests a new version from the home server and stores it. 
13865:       If the original has been removed from the home server, then local copy 
13866:       is unlinked.
13867:   (ii) If local copy does not exist -
13868:       requests the file from the home server and stores it. 
13869:   
13870:   If $caller is 'uploadrep':  
13871:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13872:     for request for files originally uploaded via DOCS. 
13873:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13874:   
13875:   Otherwise:
13876:      This indicates a call from the content generation phase of the request.
13877:      -  returns the entire contents of the file or -1.
13878:      
13879: (b) files in /res
13880:    - returns the entire contents of a file or -1; 
13881:    it properly subscribes to and replicates the file if neccessary.
13882: 
13883: 
13884: =item *
13885: 
13886: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13887:                   reference
13888: 
13889: returns either a stat() list of data about the file or an empty list
13890: if the file doesn't exist or couldn't find out about it (connection
13891: problems or user unknown)
13892: 
13893: =item *
13894: 
13895: filelocation($dir,$file) : returns file system location of a file
13896: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13897: directory that relative $file lookups are to looked in ($dir of /a/dir
13898: and a file of ../bob will become /a/bob)
13899: 
13900: =item *
13901: 
13902: hreflocation($dir,$file) : returns file system location or a URL; same as
13903: filelocation except for hrefs
13904: 
13905: =item *
13906: 
13907: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13908: also removes beginning /home/httpd/html unless /priv/ follows it.
13909: 
13910: =back
13911: 
13912: =head2 Usererfile file routines (/uploaded*)
13913: 
13914: =over 4
13915: 
13916: =item *
13917: 
13918: userfileupload(): main rotine for putting a file in a user or course's
13919:                   filespace, arguments are,
13920: 
13921:  formname - required - this is the name of the element in $env where the
13922:            filename, and the contents of the file to create/modifed exist
13923:            the filename is in $env{'form.'.$formname.'.filename'} and the
13924:            contents of the file is located in $env{'form.'.$formname}
13925:  context - if coursedoc, store the file in the course of the active role
13926:              of the current user; 
13927:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13928:            if 'canceloverwrite': delete file in tmp/overwrites directory
13929:  subdir - required - subdirectory to put the file in under ../userfiles/
13930:          if undefined, it will be placed in "unknown"
13931: 
13932:  (This routine calls clean_filename() to remove any dangerous
13933:  characters from the filename, and then calls finuserfileupload() to
13934:  complete the transaction)
13935: 
13936:  returns either the url of the uploaded file (/uploaded/....) if successful
13937:  and /adm/notfound.html if unsuccessful
13938: 
13939: =item *
13940: 
13941: clean_filename(): routine for cleaing a filename up for storage in
13942:                  userfile space, argument is:
13943: 
13944:  filename - proposed filename
13945: 
13946: returns: the new clean filename
13947: 
13948: =item *
13949: 
13950: finishuserfileupload(): routine that creates and sends the file to
13951: userspace, probably shouldn't be called directly
13952: 
13953:   docuname: username or courseid of destination for the file
13954:   docudom: domain of user/course of destination for the file
13955:   formname: same as for userfileupload()
13956:   fname: filename (including subdirectories) for the file
13957:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13958:   allfiles: reference to hash used to store objects found by parser
13959:   codebase: reference to hash used for codebases of java objects found by parser
13960:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13961:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13962:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13963:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13964:   context: if 'overwrite', will move the uploaded file from its temporary location to
13965:             userfiles to facilitate overwriting a previously uploaded file with same name.
13966:   mimetype: reference to scalar to accommodate mime type determined
13967:             from File::MMagic if $parser = parse.
13968: 
13969:  returns either the url of the uploaded file (/uploaded/....) if successful
13970:  and /adm/notfound.html if unsuccessful (or an error message if context 
13971:  was 'overwrite').
13972:  
13973: 
13974: =item *
13975: 
13976: renameuserfile(): renames an existing userfile to a new name
13977: 
13978:   Args:
13979:    docuname: username or courseid of destination for the file
13980:    docudom: domain of user/course of destination for the file
13981:    old: current file name (including any subdirs under userfiles)
13982:    new: desired file name (including any subdirs under userfiles)
13983: 
13984: =item *
13985: 
13986: mkdiruserfile(): creates a directory is a userfiles dir
13987: 
13988:   Args:
13989:    docuname: username or courseid of destination for the file
13990:    docudom: domain of user/course of destination for the file
13991:    dir: dir to create (including any subdirs under userfiles)
13992: 
13993: =item *
13994: 
13995: removeuserfile(): removes a file that exists in userfiles
13996: 
13997:   Args:
13998:    docuname: username or courseid of destination for the file
13999:    docudom: domain of user/course of destination for the file
14000:    fname: filname to delete (including any subdirs under userfiles)
14001: 
14002: =item *
14003: 
14004: removeuploadedurl(): convience function for removeuserfile()
14005: 
14006:   Args:
14007:    url:  a full /uploaded/... url to delete
14008: 
14009: =item * 
14010: 
14011: get_portfile_permissions():
14012:   Args:
14013:     domain: domain of user or course contain the portfolio files
14014:     user: name of user or num of course contain the portfolio files
14015:   Returns:
14016:     hashref of a dump of the proper file_permissions.db
14017:    
14018: 
14019: =item * 
14020: 
14021: get_access_controls():
14022: 
14023: Args:
14024:   current_permissions: the hash ref returned from get_portfile_permissions()
14025:   group: (optional) the group you want the files associated with
14026:   file: (optional) the file you want access info on
14027: 
14028: Returns:
14029:     a hash (keys are file names) of hashes containing
14030:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14031:         values are XML containing access control settings (see below) 
14032: 
14033: Internal notes:
14034: 
14035:  access controls are stored in file_permissions.db as key=value pairs.
14036:     key -> path to file/file_name\0uniqueID:scope_end_start
14037:         where scope -> public,guest,course,group,domains or users.
14038:               end -> UNIX time for end of access (0 -> no end date)
14039:               start -> UNIX time for start of access
14040: 
14041:     value -> XML description of access control
14042:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14043:             <start></start>
14044:             <end></end>
14045: 
14046:             <password></password>  for scope type = guest
14047: 
14048:             <domain></domain>     for scope type = course or group
14049:             <number></number>
14050:             <roles id="">
14051:              <role></role>
14052:              <access></access>
14053:              <section></section>
14054:              <group></group>
14055:             </roles>
14056: 
14057:             <dom></dom>         for scope type = domains
14058: 
14059:             <users>             for scope type = users
14060:              <user>
14061:               <uname></uname>
14062:               <udom></udom>
14063:              </user>
14064:             </users>
14065:            </scope> 
14066:               
14067:  Access data is also aggregated for each file in an additional key=value pair:
14068:  key -> path to file/file_name\0accesscontrol 
14069:  value -> reference to hash
14070:           hash contains key = value pairs
14071:           where key = uniqueID:scope_end_start
14072:                 value = UNIX time record was last updated
14073: 
14074:           Used to improve speed of look-ups of access controls for each file.  
14075:  
14076:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14077: 
14078: =item *
14079: 
14080: modify_access_controls():
14081: 
14082: Modifies access controls for a portfolio file
14083: Args
14084: 1. file name
14085: 2. reference to hash of required changes,
14086: 3. domain
14087: 4. username
14088:   where domain,username are the domain of the portfolio owner 
14089:   (either a user or a course) 
14090: 
14091: Returns:
14092: 1. result of additions or updates ('ok' or 'error', with error message). 
14093: 2. result of deletions ('ok' or 'error', with error message).
14094: 3. reference to hash of any new or updated access controls.
14095: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14096:    key = integer (inbound ID)
14097:    value = uniqueID
14098: 
14099: =item *
14100: 
14101: get_timebased_id():
14102: 
14103: Attempts to get a unique timestamp-based suffix for use with items added to a 
14104: course via the Course Editor (e.g., folders, composite pages, 
14105: group bulletin boards).
14106: 
14107: Args: (first three required; six others optional)
14108: 
14109: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14110:    docssequence, or name of group
14111: 
14112: 2. keyid (alphanumeric): name of temporary locking key in hash,
14113:    e.g., num, boardids
14114: 
14115: 3. namespace: name of gdbm file used to store suffixes already assigned;  
14116:    file will be named nohist_namespace.db
14117: 
14118: 4. cdom: domain of course; default is current course domain from %env
14119: 
14120: 5. cnum: course number; default is current course number from %env
14121: 
14122: 6. idtype: set to concat if an additional digit is to be appended to the 
14123:    unix timestamp to form the suffix, if the plain timestamp is already
14124:    in use.  Default is to not do this, but simply increment the unix 
14125:    timestamp by 1 until a unique key is obtained.
14126: 
14127: 7. who: holder of locking key; defaults to user:domain for user.
14128: 
14129: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
14130:    retrying); default is 3.
14131: 
14132: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
14133: 
14134: Returns:
14135: 
14136: 1. suffix obtained (numeric)
14137: 
14138: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14139: 
14140: 3. error: contains (localized) error message if an error occurred.
14141: 
14142: 
14143: =back
14144: 
14145: =head2 HTTP Helper Routines
14146: 
14147: =over 4
14148: 
14149: =item *
14150: 
14151: escape() : unpack non-word characters into CGI-compatible hex codes
14152: 
14153: =item *
14154: 
14155: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14156: 
14157: =back
14158: 
14159: =head1 PRIVATE SUBROUTINES
14160: 
14161: =head2 Underlying communication routines (Shouldn't call)
14162: 
14163: =over 4
14164: 
14165: =item *
14166: 
14167: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14168: 
14169: =item *
14170: 
14171: reply() : uses subreply to send a message to remote machine, logs all failures
14172: 
14173: =item *
14174: 
14175: critical() : passes a critical message to another server; if cannot
14176: get through then place message in connection buffer directory and
14177: returns con_delayed, if incapable of saving message, returns
14178: con_failed
14179: 
14180: =item *
14181: 
14182: reconlonc() : tries to reconnect lonc client processes.
14183: 
14184: =back
14185: 
14186: =head2 Resource Access Logging
14187: 
14188: =over 4
14189: 
14190: =item *
14191: 
14192: flushcourselogs() : flush (save) buffer logs and access logs
14193: 
14194: =item *
14195: 
14196: courselog($what) : save message for course in hash
14197: 
14198: =item *
14199: 
14200: courseacclog($what) : save message for course using &courselog().  Perform
14201: special processing for specific resource types (problems, exams, quizzes, etc).
14202: 
14203: =item *
14204: 
14205: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14206: as a PerlChildExitHandler
14207: 
14208: =back
14209: 
14210: =head2 Other
14211: 
14212: =over 4
14213: 
14214: =item *
14215: 
14216: symblist($mapname,%newhash) : update symbolic storage links
14217: 
14218: =back
14219: 
14220: =cut
14221: 

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