File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1166: download - view: text, annotated - select for diffs
Wed Apr 25 21:22:15 2012 UTC (12 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- lond uses client's LON-CAPA version to determine whether checking a user's
  course roles for version requirements needs to occur -- will be skipped
  on 2.10 and later, as it occurs client-side in rolesinit when building
  roles/courses display.
- No longer require sixth arg for lonnet::dump
    (frozen hash containing skipcheck => 1).
  - Reverse changes in loncommon.pm 1.982, longroup.pm rev 1.26, 1.27
    loncreateuser.pm rev 1.350, lonuserutils.pm 1.127, 1.137,
    lonnet.pm rev 1.1086, 1.1078 which used the "$extra" sixth arg.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1166 2012/04/25 21:22:15 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: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   80:             %managerstab);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use File::MMagic;
   97: use LONCAPA qw(:DEFAULT :match);
   98: use LONCAPA::Configuration;
   99: use LONCAPA::lonmetadata;
  100: 
  101: use File::Copy;
  102: 
  103: my $readit;
  104: my $max_connection_retries = 10;     # Or some such value.
  105: 
  106: require Exporter;
  107: 
  108: our @ISA = qw (Exporter);
  109: our @EXPORT = qw(%env);
  110: 
  111: 
  112: # --------------------------------------------------------------------- Logging
  113: {
  114:     my $logid;
  115:     sub instructor_log {
  116: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  117:         if (($cnum eq '') || ($cdom eq '')) {
  118:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  119:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  120:         }
  121: 	$logid++;
  122:         my $now = time();
  123: 	my $id=$now.'00000'.$$.'00000'.$logid;
  124: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  125: 				    { $id => {
  126: 					'exe_uname' => $env{'user.name'},
  127: 					'exe_udom'  => $env{'user.domain'},
  128: 					'exe_time'  => $now,
  129: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  130: 					'delflag'   => $delflag,
  131: 					'logentry'  => $storehash,
  132: 					'uname'     => $uname,
  133: 					'udom'      => $udom,
  134: 				    }
  135: 				  },$cdom,$cnum);
  136:     }
  137: }
  138: 
  139: sub logtouch {
  140:     my $execdir=$perlvar{'lonDaemons'};
  141:     unless (-e "$execdir/logs/lonnet.log") {	
  142: 	open(my $fh,">>$execdir/logs/lonnet.log");
  143: 	close $fh;
  144:     }
  145:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  146:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  147: }
  148: 
  149: sub logthis {
  150:     my $message=shift;
  151:     my $execdir=$perlvar{'lonDaemons'};
  152:     my $now=time;
  153:     my $local=localtime($now);
  154:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  155: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  156: 	print $fh $logstring;
  157: 	close($fh);
  158:     }
  159:     return 1;
  160: }
  161: 
  162: sub logperm {
  163:     my $message=shift;
  164:     my $execdir=$perlvar{'lonDaemons'};
  165:     my $now=time;
  166:     my $local=localtime($now);
  167:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  168: 	print $fh "$now:$message:$local\n";
  169: 	close($fh);
  170:     }
  171:     return 1;
  172: }
  173: 
  174: sub create_connection {
  175:     my ($hostname,$lonid) = @_;
  176:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  177: 				     Type    => SOCK_STREAM,
  178: 				     Timeout => 10);
  179:     return 0 if (!$client);
  180:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  181:     my $result = <$client>;
  182:     chomp($result);
  183:     return 1 if ($result eq 'done');
  184:     return 0;
  185: }
  186: 
  187: sub get_server_timezone {
  188:     my ($cnum,$cdom) = @_;
  189:     my $home=&homeserver($cnum,$cdom);
  190:     if ($home ne 'no_host') {
  191:         my $cachetime = 24*3600;
  192:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  193:         if (defined($cached)) {
  194:             return $timezone;
  195:         } else {
  196:             my $timezone = &reply('servertimezone',$home);
  197:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  198:         }
  199:     }
  200: }
  201: 
  202: sub get_server_distarch {
  203:     my ($lonhost,$ignore_cache) = @_;
  204:     if (defined($lonhost)) {
  205:         if (!defined(&hostname($lonhost))) {
  206:             return;
  207:         }
  208:         my $cachetime = 12*3600;
  209:         if (!$ignore_cache) {
  210:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  211:             if (defined($cached)) {
  212:                 return $distarch;
  213:             }
  214:         }
  215:         my $rep = &reply('serverdistarch',$lonhost);
  216:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  217:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  218:                 $rep eq '') {
  219:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  220:         }
  221:     }
  222:     return;
  223: }
  224: 
  225: sub get_server_loncaparev {
  226:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  227:     if (defined($lonhost)) {
  228:         if (!defined(&hostname($lonhost))) {
  229:             undef($lonhost);
  230:         }
  231:     }
  232:     if (!defined($lonhost)) {
  233:         if (defined(&domain($dom,'primary'))) {
  234:             $lonhost=&domain($dom,'primary');
  235:             if ($lonhost eq 'no_host') {
  236:                 undef($lonhost);
  237:             }
  238:         }
  239:     }
  240:     if (defined($lonhost)) {
  241:         my $cachetime = 12*3600;
  242:         if (!$ignore_cache) {
  243:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  244:             if (defined($cached)) {
  245:                 return $loncaparev;
  246:             }
  247:         }
  248:         my ($answer,$loncaparev);
  249:         my @ids=&current_machine_ids();
  250:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  251:             $answer = $perlvar{'lonVersion'};
  252:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  253:                 $loncaparev = $1;
  254:             }
  255:         } else {
  256:             $answer = &reply('serverloncaparev',$lonhost);
  257:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  258:                 if ($caller eq 'loncron') {
  259:                     my $ua=new LWP::UserAgent;
  260:                     $ua->timeout(4);
  261:                     my $protocol = $protocol{$lonhost};
  262:                     $protocol = 'http' if ($protocol ne 'https');
  263:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  264:                     my $request=new HTTP::Request('GET',$url);
  265:                     my $response=$ua->request($request);
  266:                     unless ($response->is_error()) {
  267:                         my $content = $response->content;
  268:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  269:                             $loncaparev = $1;
  270:                         }
  271:                     }
  272:                 } else {
  273:                     $loncaparev = $loncaparevs{$lonhost};
  274:                 }
  275:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  276:                 $loncaparev = $1;
  277:             }
  278:         }
  279:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  280:     }
  281: }
  282: 
  283: sub get_server_homeID {
  284:     my ($hostname,$ignore_cache,$caller) = @_;
  285:     unless ($ignore_cache) {
  286:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  287:         if (defined($cached)) {
  288:             return $serverhomeID;
  289:         }
  290:     }
  291:     my $cachetime = 12*3600;
  292:     my $serverhomeID;
  293:     if ($caller eq 'loncron') { 
  294:         my @machine_ids = &machine_ids($hostname);
  295:         foreach my $id (@machine_ids) {
  296:             my $response = &reply('serverhomeID',$id);
  297:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  298:                 $serverhomeID = $response;
  299:                 last;
  300:             }
  301:         }
  302:         if ($serverhomeID eq '') {
  303:             $serverhomeID = $machine_ids[-1];
  304:         }
  305:     } else {
  306:         $serverhomeID = $serverhomeIDs{$hostname};
  307:     }
  308:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  309: }
  310: 
  311: sub get_remote_globals {
  312:     my ($lonhost,$whathash,$ignore_cache) = @_;
  313:     my ($result,%returnhash,%whatneeded);
  314:     if (ref($whathash) eq 'HASH') {
  315:         foreach my $what (sort(keys(%{$whathash}))) {
  316:             my $hashid = $lonhost.'-'.$what;
  317:             my ($response,$cached);
  318:             unless ($ignore_cache) {
  319:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  320:             }
  321:             if (defined($cached)) {
  322:                 $returnhash{$what} = $response;
  323:             } else {
  324:                 $whatneeded{$what} = 1;
  325:             }
  326:         }
  327:         if (keys(%whatneeded) == 0) {
  328:             $result = 'ok';
  329:         } else {
  330:             my $requested = &freeze_escape(\%whatneeded);
  331:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  332:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  333:                 ($rep eq 'unknown_cmd')) {
  334:                 $result = $rep;
  335:             } else {
  336:                 $result = 'ok';
  337:                 my @pairs=split(/\&/,$rep);
  338:                 foreach my $item (@pairs) {
  339:                     my ($key,$value)=split(/=/,$item,2);
  340:                     my $what = &unescape($key);
  341:                     my $hashid = $lonhost.'-'.$what;
  342:                     $returnhash{$what}=&thaw_unescape($value);
  343:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  344:                 }
  345:             }
  346:         }
  347:     }
  348:     return ($result,\%returnhash);
  349: }
  350: 
  351: sub remote_devalidate_cache {
  352:     my ($lonhost,$name,$id) = @_;
  353:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  354:     return $response;
  355: }
  356: 
  357: # -------------------------------------------------- Non-critical communication
  358: sub subreply {
  359:     my ($cmd,$server)=@_;
  360:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  361:     #
  362:     #  With loncnew process trimming, there's a timing hole between lonc server
  363:     #  process exit and the master server picking up the listen on the AF_UNIX
  364:     #  socket.  In that time interval, a lock file will exist:
  365: 
  366:     my $lockfile=$peerfile.".lock";
  367:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  368: 	sleep(1);
  369:     }
  370:     # At this point, either a loncnew parent is listening or an old lonc
  371:     # or loncnew child is listening so we can connect or everything's dead.
  372:     #
  373:     #   We'll give the connection a few tries before abandoning it.  If
  374:     #   connection is not possible, we'll con_lost back to the client.
  375:     #   
  376:     my $client;
  377:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  378: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  379: 				      Type    => SOCK_STREAM,
  380: 				      Timeout => 10);
  381: 	if ($client) {
  382: 	    last;		# Connected!
  383: 	} else {
  384: 	    &create_connection(&hostname($server),$server);
  385: 	}
  386:         sleep(1);		# Try again later if failed connection.
  387:     }
  388:     my $answer;
  389:     if ($client) {
  390: 	print $client "sethost:$server:$cmd\n";
  391: 	$answer=<$client>;
  392: 	if (!$answer) { $answer="con_lost"; }
  393: 	chomp($answer);
  394:     } else {
  395: 	$answer = 'con_lost';	# Failed connection.
  396:     }
  397:     return $answer;
  398: }
  399: 
  400: sub reply {
  401:     my ($cmd,$server)=@_;
  402:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  403:     my $answer=subreply($cmd,$server);
  404:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  405:        &logthis("<font color=\"blue\">WARNING:".
  406:                 " $cmd to $server returned $answer</font>");
  407:     }
  408:     return $answer;
  409: }
  410: 
  411: # ----------------------------------------------------------- Send USR1 to lonc
  412: 
  413: sub reconlonc {
  414:     my ($lonid) = @_;
  415:     my $hostname = &hostname($lonid);
  416:     if ($lonid) {
  417: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  418: 	if ($hostname && -e $peerfile) {
  419: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  420: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  421: 					     Type    => SOCK_STREAM,
  422: 					     Timeout => 10);
  423: 	    if ($client) {
  424: 		print $client ("reset_retries\n");
  425: 		my $answer=<$client>;
  426: 		#reset just this one.
  427: 	    }
  428: 	}
  429: 	return;
  430:     }
  431: 
  432:     &logthis("Trying to reconnect lonc");
  433:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  434:     if (open(my $fh,"<$loncfile")) {
  435: 	my $loncpid=<$fh>;
  436:         chomp($loncpid);
  437:         if (kill 0 => $loncpid) {
  438: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  439:             kill USR1 => $loncpid;
  440:             sleep 1;
  441:          } else {
  442: 	    &logthis(
  443:                "<font color=\"blue\">WARNING:".
  444:                " lonc at pid $loncpid not responding, giving up</font>");
  445:         }
  446:     } else {
  447: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  448:     }
  449: }
  450: 
  451: # ------------------------------------------------------ Critical communication
  452: 
  453: sub critical {
  454:     my ($cmd,$server)=@_;
  455:     unless (&hostname($server)) {
  456:         &logthis("<font color=\"blue\">WARNING:".
  457:                " Critical message to unknown server ($server)</font>");
  458:         return 'no_such_host';
  459:     }
  460:     my $answer=reply($cmd,$server);
  461:     if ($answer eq 'con_lost') {
  462: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  463: 	my $answer=reply($cmd,$server);
  464:         if ($answer eq 'con_lost') {
  465:             my $now=time;
  466:             my $middlename=$cmd;
  467:             $middlename=substr($middlename,0,16);
  468:             $middlename=~s/\W//g;
  469:             my $dfilename=
  470:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  471:             $dumpcount++;
  472:             {
  473: 		my $dfh;
  474: 		if (open($dfh,">$dfilename")) {
  475: 		    print $dfh "$cmd\n"; 
  476: 		    close($dfh);
  477: 		}
  478:             }
  479:             sleep 2;
  480:             my $wcmd='';
  481:             {
  482: 		my $dfh;
  483: 		if (open($dfh,"<$dfilename")) {
  484: 		    $wcmd=<$dfh>; 
  485: 		    close($dfh);
  486: 		}
  487:             }
  488:             chomp($wcmd);
  489:             if ($wcmd eq $cmd) {
  490: 		&logthis("<font color=\"blue\">WARNING: ".
  491:                          "Connection buffer $dfilename: $cmd</font>");
  492:                 &logperm("D:$server:$cmd");
  493: 	        return 'con_delayed';
  494:             } else {
  495:                 &logthis("<font color=\"red\">CRITICAL:"
  496:                         ." Critical connection failed: $server $cmd</font>");
  497:                 &logperm("F:$server:$cmd");
  498:                 return 'con_failed';
  499:             }
  500:         }
  501:     }
  502:     return $answer;
  503: }
  504: 
  505: # ------------------------------------------- check if return value is an error
  506: 
  507: sub error {
  508:     my ($result) = @_;
  509:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  510: 	if ($2 == 2) { return undef; }
  511: 	return $1;
  512:     }
  513:     return undef;
  514: }
  515: 
  516: sub convert_and_load_session_env {
  517:     my ($lonidsdir,$handle)=@_;
  518:     my @profile;
  519:     {
  520: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  521: 	if (!$opened) {
  522: 	    return 0;
  523: 	}
  524: 	flock($idf,LOCK_SH);
  525: 	@profile=<$idf>;
  526: 	close($idf);
  527:     }
  528:     my %temp_env;
  529:     foreach my $line (@profile) {
  530: 	if ($line !~ m/=/) {
  531: 	    return 0;
  532: 	}
  533: 	chomp($line);
  534: 	my ($envname,$envvalue)=split(/=/,$line,2);
  535: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  536:     }
  537:     unlink("$lonidsdir/$handle.id");
  538:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  539: 	    0640)) {
  540: 	%disk_env = %temp_env;
  541: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  542: 	untie(%disk_env);
  543:     }
  544:     return 1;
  545: }
  546: 
  547: # ------------------------------------------- Transfer profile into environment
  548: my $env_loaded;
  549: sub transfer_profile_to_env {
  550:     my ($lonidsdir,$handle,$force_transfer) = @_;
  551:     if (!$force_transfer && $env_loaded) { return; } 
  552: 
  553:     if (!defined($lonidsdir)) {
  554: 	$lonidsdir = $perlvar{'lonIDsDir'};
  555:     }
  556:     if (!defined($handle)) {
  557:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  558:     }
  559: 
  560:     my $convert;
  561:     {
  562:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  563: 	if (!$opened) {
  564: 	    return;
  565: 	}
  566: 	flock($idf,LOCK_SH);
  567: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  568: 		&GDBM_READER(),0640)) {
  569: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  570: 	    untie(%disk_env);
  571: 	} else {
  572: 	    $convert = 1;
  573: 	}
  574:     }
  575:     if ($convert) {
  576: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  577: 	    &logthis("Failed to load session, or convert session.");
  578: 	}
  579:     }
  580: 
  581:     my %remove;
  582:     while ( my $envname = each(%env) ) {
  583:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  584:             if ($time < time-300) {
  585:                 $remove{$key}++;
  586:             }
  587:         }
  588:     }
  589: 
  590:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  591:     $env_loaded=1;
  592:     foreach my $expired_key (keys(%remove)) {
  593:         &delenv($expired_key);
  594:     }
  595: }
  596: 
  597: # ---------------------------------------------------- Check for valid session 
  598: sub check_for_valid_session {
  599:     my ($r,$name) = @_;
  600:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  601:     if ($name eq '') {
  602:         $name = 'lonID';
  603:     }
  604:     my $lonid=$cookies{$name};
  605:     return undef if (!$lonid);
  606: 
  607:     my $handle=&LONCAPA::clean_handle($lonid->value);
  608:     my $lonidsdir;
  609:     if ($name eq 'lonDAV') {
  610:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  611:     } else {
  612:         $lonidsdir=$r->dir_config('lonIDsDir');
  613:     }
  614:     return undef if (!-e "$lonidsdir/$handle.id");
  615: 
  616:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  617:     return undef if (!$opened);
  618: 
  619:     flock($idf,LOCK_SH);
  620:     my %disk_env;
  621:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  622: 	    &GDBM_READER(),0640)) {
  623: 	return undef;	
  624:     }
  625: 
  626:     if (!defined($disk_env{'user.name'})
  627: 	|| !defined($disk_env{'user.domain'})) {
  628: 	return undef;
  629:     }
  630:     return $handle;
  631: }
  632: 
  633: sub timed_flock {
  634:     my ($file,$lock_type) = @_;
  635:     my $failed=0;
  636:     eval {
  637: 	local $SIG{__DIE__}='DEFAULT';
  638: 	local $SIG{ALRM}=sub {
  639: 	    $failed=1;
  640: 	    die("failed lock");
  641: 	};
  642: 	alarm(13);
  643: 	flock($file,$lock_type);
  644: 	alarm(0);
  645:     };
  646:     if ($failed) {
  647: 	return undef;
  648:     } else {
  649: 	return 1;
  650:     }
  651: }
  652: 
  653: # ---------------------------------------------------------- Append Environment
  654: 
  655: sub appenv {
  656:     my ($newenv,$roles) = @_;
  657:     if (ref($newenv) eq 'HASH') {
  658:         foreach my $key (keys(%{$newenv})) {
  659:             my $refused = 0;
  660: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  661:                 $refused = 1;
  662:                 if (ref($roles) eq 'ARRAY') {
  663:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  664:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  665:                         $refused = 0;
  666:                     }
  667:                 }
  668:             }
  669:             if ($refused) {
  670:                 &logthis("<font color=\"blue\">WARNING: ".
  671:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  672:                          .'</font>');
  673: 	        delete($newenv->{$key});
  674:             } else {
  675:                 $env{$key}=$newenv->{$key};
  676:             }
  677:         }
  678:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  679:         if ($opened
  680: 	    && &timed_flock($env_file,LOCK_EX)
  681: 	    &&
  682: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  683: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  684: 	    while (my ($key,$value) = each(%{$newenv})) {
  685: 	        $disk_env{$key} = $value;
  686: 	    }
  687: 	    untie(%disk_env);
  688:         }
  689:     }
  690:     return 'ok';
  691: }
  692: # ----------------------------------------------------- Delete from Environment
  693: 
  694: sub delenv {
  695:     my ($delthis,$regexp,$roles) = @_;
  696:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  697:         my $refused = 1;
  698:         if (ref($roles) eq 'ARRAY') {
  699:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  700:             if (grep(/^\Q$role\E$/,@{$roles})) {
  701:                 $refused = 0;
  702:             }
  703:         }
  704:         if ($refused) {
  705:             &logthis("<font color=\"blue\">WARNING: ".
  706:                      "Attempt to delete from environment ".$delthis);
  707:             return 'error';
  708:         }
  709:     }
  710:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  711:     if ($opened
  712: 	&& &timed_flock($env_file,LOCK_EX)
  713: 	&&
  714: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  715: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  716: 	foreach my $key (keys(%disk_env)) {
  717: 	    if ($regexp) {
  718:                 if ($key=~/^$delthis/) {
  719:                     delete($env{$key});
  720:                     delete($disk_env{$key});
  721:                 } 
  722:             } else {
  723:                 if ($key=~/^\Q$delthis\E/) {
  724: 		    delete($env{$key});
  725: 		    delete($disk_env{$key});
  726: 	        }
  727:             }
  728: 	}
  729: 	untie(%disk_env);
  730:     }
  731:     return 'ok';
  732: }
  733: 
  734: sub get_env_multiple {
  735:     my ($name) = @_;
  736:     my @values;
  737:     if (defined($env{$name})) {
  738:         # exists is it an array
  739:         if (ref($env{$name})) {
  740:             @values=@{ $env{$name} };
  741:         } else {
  742:             $values[0]=$env{$name};
  743:         }
  744:     }
  745:     return(@values);
  746: }
  747: 
  748: # ------------------------------------------------------------------- Locking
  749: 
  750: sub set_lock {
  751:     my ($text)=@_;
  752:     $locknum++;
  753:     my $id=$$.'-'.$locknum;
  754:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  755:              'session.lock.'.$id => $text});
  756:     return $id;
  757: }
  758: 
  759: sub get_locks {
  760:     my $num=0;
  761:     my %texts=();
  762:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  763:        if ($lock=~/\w/) {
  764:           $num++;
  765:           $texts{$lock}=$env{'session.lock.'.$lock};
  766:        }
  767:    }
  768:    return ($num,%texts);
  769: }
  770: 
  771: sub remove_lock {
  772:     my ($id)=@_;
  773:     my $newlocks='';
  774:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  775:        if (($lock=~/\w/) && ($lock ne $id)) {
  776:           $newlocks.=','.$lock;
  777:        }
  778:     }
  779:     &appenv({'session.locks' => $newlocks});
  780:     &delenv('session.lock.'.$id);
  781: }
  782: 
  783: sub remove_all_locks {
  784:     my $activelocks=$env{'session.locks'};
  785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  786:        if ($lock=~/\w/) {
  787:           &remove_lock($lock);
  788:        }
  789:     }
  790: }
  791: 
  792: 
  793: # ------------------------------------------ Find out current server userload
  794: sub userload {
  795:     my $numusers=0;
  796:     {
  797: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  798: 	my $filename;
  799: 	my $curtime=time;
  800: 	while ($filename=readdir(LONIDS)) {
  801: 	    next if ($filename eq '.' || $filename eq '..');
  802: 	    next if ($filename =~ /publicuser_\d+\.id/);
  803: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  804: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  805: 	}
  806: 	closedir(LONIDS);
  807:     }
  808:     my $userloadpercent=0;
  809:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  810:     if ($maxuserload) {
  811: 	$userloadpercent=100*$numusers/$maxuserload;
  812:     }
  813:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  814:     return $userloadpercent;
  815: }
  816: 
  817: # ------------------------------ Find server with least workload from spare.tab
  818: 
  819: sub spareserver {
  820:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  821:     my $spare_server;
  822:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  823:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  824:                                                      :  $userloadpercent;
  825:     my ($uint_dom,$remotesessions);
  826:     if (($udom ne '') && (&domain($udom) ne '')) {
  827:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  828:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  829:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  830:         $remotesessions = $udomdefaults{'remotesessions'};
  831:     }
  832:     my $spareshash = &this_host_spares($udom);
  833:     if (ref($spareshash) eq 'HASH') {
  834:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  835:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  836:                 if ($uint_dom) {
  837:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  838:                                                  $try_server));
  839:                 }
  840: 	        ($spare_server, $lowest_load) =
  841: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  842:             }
  843:         }
  844: 
  845:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  846: 
  847:         if (!$found_server) {
  848:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  849: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  850:                     if ($uint_dom) {
  851:                         next unless (&spare_can_host($udom,$uint_dom,
  852:                                                      $remotesessions,$try_server));
  853:                     }
  854: 	            ($spare_server, $lowest_load) =
  855: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  856:                 }
  857: 	    }
  858:         }
  859:     }
  860: 
  861:     if (!$want_server_name) {
  862:         my $protocol = 'http';
  863:         if ($protocol{$spare_server} eq 'https') {
  864:             $protocol = $protocol{$spare_server};
  865:         }
  866:         if (defined($spare_server)) {
  867:             my $hostname = &hostname($spare_server);
  868:             if (defined($hostname)) {
  869: 	        $spare_server = $protocol.'://'.$hostname;
  870:             }
  871:         }
  872:     }
  873:     return $spare_server;
  874: }
  875: 
  876: sub compare_server_load {
  877:     my ($try_server, $spare_server, $lowest_load) = @_;
  878: 
  879:     my $loadans     = &reply('load',    $try_server);
  880:     my $userloadans = &reply('userload',$try_server);
  881: 
  882:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  883: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  884:     }
  885: 
  886:     my $load;
  887:     if ($loadans =~ /\d/) {
  888: 	if ($userloadans =~ /\d/) {
  889: 	    #both are numbers, pick the bigger one
  890: 	    $load = ($loadans > $userloadans) ? $loadans 
  891: 		                              : $userloadans;
  892: 	} else {
  893: 	    $load = $loadans;
  894: 	}
  895:     } else {
  896: 	$load = $userloadans;
  897:     }
  898: 
  899:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  900: 	$spare_server = $try_server;
  901: 	$lowest_load  = $load;
  902:     }
  903:     return ($spare_server,$lowest_load);
  904: }
  905: 
  906: # --------------------------- ask offload servers if user already has a session
  907: sub find_existing_session {
  908:     my ($udom,$uname) = @_;
  909:     my $spareshash = &this_host_spares($udom);
  910:     if (ref($spareshash) eq 'HASH') {
  911:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  912:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  913:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  914:             }
  915:         }
  916:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  917:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  918:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  919:             }
  920:         }
  921:     }
  922:     return;
  923: }
  924: 
  925: # -------------------------------- ask if server already has a session for user
  926: sub has_user_session {
  927:     my ($lonid,$udom,$uname) = @_;
  928:     my $result = &reply(join(':','userhassession',
  929: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  930:     return 1 if ($result eq 'ok');
  931: 
  932:     return 0;
  933: }
  934: 
  935: # --------- determine least loaded server in a user's domain which allows login
  936: 
  937: sub choose_server {
  938:     my ($udom,$checkloginvia) = @_;
  939:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  940:     my %servers = &get_servers($udom);
  941:     my $lowest_load = 30000;
  942:     my ($login_host,$hostname,$portal_path,$isredirect);
  943:     foreach my $lonhost (keys(%servers)) {
  944:         my $loginvia;
  945:         if ($checkloginvia) {
  946:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  947:             if ($loginvia) {
  948:                 my ($server,$path) = split(/:/,$loginvia);
  949:                 ($login_host, $lowest_load) =
  950:                     &compare_server_load($server, $login_host, $lowest_load);
  951:                 if ($login_host eq $server) {
  952:                     $portal_path = $path;
  953:                     $isredirect = 1;
  954:                 }
  955:             } else {
  956:                 ($login_host, $lowest_load) =
  957:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  958:                 if ($login_host eq $lonhost) {
  959:                     $portal_path = '';
  960:                     $isredirect = ''; 
  961:                 }
  962:             }
  963:         } else {
  964:             ($login_host, $lowest_load) =
  965:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  966:         }
  967:     }
  968:     if ($login_host ne '') {
  969:         $hostname = &hostname($login_host);
  970:     }
  971:     return ($login_host,$hostname,$portal_path,$isredirect);
  972: }
  973: 
  974: # --------------------------------------------- Try to change a user's password
  975: 
  976: sub changepass {
  977:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  978:     $currentpass = &escape($currentpass);
  979:     $newpass     = &escape($newpass);
  980:     my $lonhost = $perlvar{'lonHostID'};
  981:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  982: 		       $server);
  983:     if (! $answer) {
  984: 	&logthis("No reply on password change request to $server ".
  985: 		 "by $uname in domain $udom.");
  986:     } elsif ($answer =~ "^ok") {
  987:         &logthis("$uname in $udom successfully changed their password ".
  988: 		 "on $server.");
  989:     } elsif ($answer =~ "^pwchange_failure") {
  990: 	&logthis("$uname in $udom was unable to change their password ".
  991: 		 "on $server.  The action was blocked by either lcpasswd ".
  992: 		 "or pwchange");
  993:     } elsif ($answer =~ "^non_authorized") {
  994:         &logthis("$uname in $udom did not get their password correct when ".
  995: 		 "attempting to change it on $server.");
  996:     } elsif ($answer =~ "^auth_mode_error") {
  997:         &logthis("$uname in $udom attempted to change their password despite ".
  998: 		 "not being locally or internally authenticated on $server.");
  999:     } elsif ($answer =~ "^unknown_user") {
 1000:         &logthis("$uname in $udom attempted to change their password ".
 1001: 		 "on $server but were unable to because $server is not ".
 1002: 		 "their home server.");
 1003:     } elsif ($answer =~ "^refused") {
 1004: 	&logthis("$server refused to change $uname in $udom password because ".
 1005: 		 "it was sent an unencrypted request to change the password.");
 1006:     } elsif ($answer =~ "invalid_client") {
 1007:         &logthis("$server refused to change $uname in $udom password because ".
 1008:                  "it was a reset by e-mail originating from an invalid server.");
 1009:     }
 1010:     return $answer;
 1011: }
 1012: 
 1013: # ----------------------- Try to determine user's current authentication scheme
 1014: 
 1015: sub queryauthenticate {
 1016:     my ($uname,$udom)=@_;
 1017:     my $uhome=&homeserver($uname,$udom);
 1018:     if (!$uhome) {
 1019: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1020: 	return 'no_host';
 1021:     }
 1022:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1023:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1024: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1025:     }
 1026:     return $answer;
 1027: }
 1028: 
 1029: # --------- Try to authenticate user from domain's lib servers (first this one)
 1030: 
 1031: sub authenticate {
 1032:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1033:     $upass=&escape($upass);
 1034:     $uname= &LONCAPA::clean_username($uname);
 1035:     my $uhome=&homeserver($uname,$udom,1);
 1036:     my $newhome;
 1037:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1038: # Maybe the machine was offline and only re-appeared again recently?
 1039:         &reconlonc();
 1040: # One more
 1041: 	$uhome=&homeserver($uname,$udom,1);
 1042:         if (($uhome eq 'no_host') && $checkdefauth) {
 1043:             if (defined(&domain($udom,'primary'))) {
 1044:                 $newhome=&domain($udom,'primary');
 1045:             }
 1046:             if ($newhome ne '') {
 1047:                 $uhome = $newhome;
 1048:             }
 1049:         }
 1050: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1051: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1052: 	    return 'no_host';
 1053:         }
 1054:     }
 1055:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1056:     if ($answer eq 'authorized') {
 1057:         if ($newhome) {
 1058:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1059:             return 'no_account_on_host'; 
 1060:         } else {
 1061:             &logthis("User $uname at $udom authorized by $uhome");
 1062:             return $uhome;
 1063:         }
 1064:     }
 1065:     if ($answer eq 'non_authorized') {
 1066: 	&logthis("User $uname at $udom rejected by $uhome");
 1067: 	return 'no_host'; 
 1068:     }
 1069:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1070:     return 'no_host';
 1071: }
 1072: 
 1073: sub can_host_session {
 1074:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1075:     my $canhost = 1;
 1076:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1077:     if (ref($remotesessions) eq 'HASH') {
 1078:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1079:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1080:                 $canhost = 0;
 1081:             } else {
 1082:                 $canhost = 1;
 1083:             }
 1084:         }
 1085:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1086:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1087:                 $canhost = 1;
 1088:             } else {
 1089:                 $canhost = 0;
 1090:             }
 1091:         }
 1092:         if ($canhost) {
 1093:             if ($remotesessions->{'version'} ne '') {
 1094:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1095:                 if ($reqmajor ne '' && $reqminor ne '') {
 1096:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1097:                         my $major = $1;
 1098:                         my $minor = $2;
 1099:                         if (($major < $reqmajor ) ||
 1100:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1101:                             $canhost = 0;
 1102:                         }
 1103:                     } else {
 1104:                         $canhost = 0;
 1105:                     }
 1106:                 }
 1107:             }
 1108:         }
 1109:     }
 1110:     if ($canhost) {
 1111:         if (ref($hostedsessions) eq 'HASH') {
 1112:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1113:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1114:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1115:                 if (($uint_dom ne '') && 
 1116:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1117:                     $canhost = 0;
 1118:                 } else {
 1119:                     $canhost = 1;
 1120:                 }
 1121:             }
 1122:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1123:                 if (($uint_dom ne '') && 
 1124:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1125:                     $canhost = 1;
 1126:                 } else {
 1127:                     $canhost = 0;
 1128:                 }
 1129:             }
 1130:         }
 1131:     }
 1132:     return $canhost;
 1133: }
 1134: 
 1135: sub spare_can_host {
 1136:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1137:     my $canhost=1;
 1138:     my @intdoms;
 1139:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1140:     if (ref($internet_names) eq 'ARRAY') {
 1141:         @intdoms = @{$internet_names};
 1142:     }
 1143:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1144:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1145:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1146:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1147:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1148:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1149:                                      $remotesessions,
 1150:                                      $defdomdefaults{'hostedsessions'});
 1151:     }
 1152:     return $canhost;
 1153: }
 1154: 
 1155: sub this_host_spares {
 1156:     my ($dom) = @_;
 1157:     my ($dom_in_use,$lonhost_in_use,$result);
 1158:     my @hosts = &current_machine_ids();
 1159:     foreach my $lonhost (@hosts) {
 1160:         if (&host_domain($lonhost) eq $dom) {
 1161:             $dom_in_use = $dom;
 1162:             $lonhost_in_use = $lonhost;
 1163:             last;
 1164:         }
 1165:     }
 1166:     if ($dom_in_use ne '') {
 1167:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1168:     }
 1169:     if (ref($result) ne 'HASH') {
 1170:         $lonhost_in_use = $perlvar{'lonHostID'};
 1171:         $dom_in_use = &host_domain($lonhost_in_use);
 1172:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1173:         if (ref($result) ne 'HASH') {
 1174:             $result = \%spareid;
 1175:         }
 1176:     }
 1177:     return $result;
 1178: }
 1179: 
 1180: sub spares_for_offload  {
 1181:     my ($dom_in_use,$lonhost_in_use) = @_;
 1182:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1183:     if (defined($cached)) {
 1184:         return $result;
 1185:     } else {
 1186:         my $cachetime = 60*60*24;
 1187:         my %domconfig =
 1188:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1189:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1190:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1191:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1192:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1193:                 }
 1194:             }
 1195:         }
 1196:     }
 1197:     return;
 1198: }
 1199: 
 1200: sub get_lonbalancer_config {
 1201:     my ($servers) = @_;
 1202:     my ($currbalancer,$currtargets);
 1203:     if (ref($servers) eq 'HASH') {
 1204:         foreach my $server (keys(%{$servers})) {
 1205:             my %what = (
 1206:                          spareid => 1,
 1207:                          perlvar => 1,
 1208:                        );
 1209:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1210:             if ($result eq 'ok') {
 1211:                 if (ref($returnhash) eq 'HASH') {
 1212:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1213:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1214:                             $currbalancer = $server;
 1215:                             $currtargets = {};
 1216:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1217:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1218:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1219:                                 }
 1220:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1221:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1222:                                 }
 1223:                             }
 1224:                             last;
 1225:                         }
 1226:                     }
 1227:                 }
 1228:             }
 1229:         }
 1230:     }
 1231:     return ($currbalancer,$currtargets);
 1232: }
 1233: 
 1234: sub check_loadbalancing {
 1235:     my ($uname,$udom) = @_;
 1236:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
 1237:         $offloadto,$otherserver);
 1238:     my $lonhost = $perlvar{'lonHostID'};
 1239:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1240:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1241:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1242:     my $serverhomedom = &host_domain($lonhost);
 1243: 
 1244:     my $cachetime = 60*60*24;
 1245: 
 1246:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1247:         $dom_in_use = $udom;
 1248:         $homeintdom = 1;
 1249:     } else {
 1250:         $dom_in_use = $serverhomedom;
 1251:     }
 1252:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1253:     unless (defined($cached)) {
 1254:         my %domconfig =
 1255:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1256:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1257:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1258:         }
 1259:     }
 1260:     if (ref($result) eq 'HASH') {
 1261:         my $currbalancer = $result->{'lonhost'};
 1262:         my $currtargets = $result->{'targets'};
 1263:         my $currrules = $result->{'rules'};
 1264:         if ($currbalancer ne '') {
 1265:             my @hosts = &current_machine_ids();
 1266:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1267:                 $is_balancer = 1;
 1268:             }
 1269:         }
 1270:         if ($is_balancer) {
 1271:             if (ref($currrules) eq 'HASH') {
 1272:                 if ($homeintdom) {
 1273:                     if ($uname ne '') {
 1274:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1275:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1276:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1277:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1278:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1279:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1280:                             }
 1281:                         }
 1282:                         if ($rule_in_effect eq '') {
 1283:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1284:                             if ($userenv{'inststatus'} ne '') {
 1285:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1286:                                 my ($othertitle,$usertypes,$types) =
 1287:                                     &Apache::loncommon::sorted_inst_types($udom);
 1288:                                 if (ref($types) eq 'ARRAY') {
 1289:                                     foreach my $type (@{$types}) {
 1290:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1291:                                             if (exists($currrules->{$type})) {
 1292:                                                 $rule_in_effect = $currrules->{$type};
 1293:                                             }
 1294:                                         }
 1295:                                     }
 1296:                                 }
 1297:                             } else {
 1298:                                 if (exists($currrules->{'default'})) {
 1299:                                     $rule_in_effect = $currrules->{'default'};
 1300:                                 }
 1301:                             }
 1302:                         }
 1303:                     } else {
 1304:                         if (exists($currrules->{'default'})) {
 1305:                             $rule_in_effect = $currrules->{'default'};
 1306:                         }
 1307:                     }
 1308:                 } else {
 1309:                     if ($currrules->{'_LC_external'} ne '') {
 1310:                         $rule_in_effect = $currrules->{'_LC_external'};
 1311:                     }
 1312:                 }
 1313:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1314:                                                        $uname,$udom);
 1315:             }
 1316:         }
 1317:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1318:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1319:         unless (defined($cached)) {
 1320:             my %domconfig =
 1321:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1322:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1323:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1324:             }
 1325:         }
 1326:         if (ref($result) eq 'HASH') {
 1327:             my $currbalancer = $result->{'lonhost'};
 1328:             my $currtargets = $result->{'targets'};
 1329:             my $currrules = $result->{'rules'};
 1330: 
 1331:             if ($currbalancer eq $lonhost) {
 1332:                 $is_balancer = 1;
 1333:                 if (ref($currrules) eq 'HASH') {
 1334:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1335:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1336:                     }
 1337:                 }
 1338:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1339:                                                        $uname,$udom);
 1340:             }
 1341:         } else {
 1342:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1343:                 $is_balancer = 1;
 1344:                 $offloadto = &this_host_spares($dom_in_use);
 1345:             }
 1346:         }
 1347:     } else {
 1348:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1349:             $is_balancer = 1;
 1350:             $offloadto = &this_host_spares($dom_in_use);
 1351:         }
 1352:     }
 1353:     my $lowest_load = 30000;
 1354:     if (ref($offloadto) eq 'HASH') {
 1355:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1356:             foreach my $try_server (@{$offloadto->{'primary'}}) {
 1357:                 ($otherserver,$lowest_load) =
 1358:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1359:             }
 1360:         }
 1361:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1362: 
 1363:         if (!$found_server) {
 1364:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1365:                 foreach my $try_server (@{$offloadto->{'default'}}) {
 1366:                     ($otherserver,$lowest_load) =
 1367:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1368:                 }
 1369:             }
 1370:         }
 1371:     } elsif (ref($offloadto) eq 'ARRAY') {
 1372:         if (@{$offloadto} == 1) {
 1373:             $otherserver = $offloadto->[0];
 1374:         } elsif (@{$offloadto} > 1) {
 1375:             foreach my $try_server (@{$offloadto}) {
 1376:                 ($otherserver,$lowest_load) =
 1377:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1378:             }
 1379:         }
 1380:     }
 1381:     return ($is_balancer,$otherserver);
 1382: }
 1383: 
 1384: sub get_loadbalancer_targets {
 1385:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1386:     my $offloadto;
 1387:     if ($rule_in_effect eq '') {
 1388:         $offloadto = $currtargets;
 1389:     } else {
 1390:         if ($rule_in_effect eq 'homeserver') {
 1391:             my $homeserver = &homeserver($uname,$udom);
 1392:             if ($homeserver ne 'no_host') {
 1393:                 $offloadto = [$homeserver];
 1394:             }
 1395:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1396:             my %domconfig =
 1397:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1398:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1399:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1400:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1401:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1402:                     }
 1403:                 }
 1404:             } else {
 1405:                 my %servers = &dom_servers($udom);
 1406:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1407:                 if (&hostname($remotebalancer) ne '') {
 1408:                     $offloadto = [$remotebalancer];
 1409:                 }
 1410:             }
 1411:         } elsif (&hostname($rule_in_effect) ne '') {
 1412:             $offloadto = [$rule_in_effect];
 1413:         }
 1414:     }
 1415:     return $offloadto;
 1416: }
 1417: 
 1418: sub internet_dom_servers {
 1419:     my ($dom) = @_;
 1420:     my (%uniqservers,%servers);
 1421:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1422:     my @machinedoms = &machine_domains($primaryserver);
 1423:     foreach my $mdom (@machinedoms) {
 1424:         my %currservers = %servers;
 1425:         my %server = &get_servers($mdom);
 1426:         %servers = (%currservers,%server);
 1427:     }
 1428:     my %by_hostname;
 1429:     foreach my $id (keys(%servers)) {
 1430:         push(@{$by_hostname{$servers{$id}}},$id);
 1431:     }
 1432:     foreach my $hostname (sort(keys(%by_hostname))) {
 1433:         if (@{$by_hostname{$hostname}} > 1) {
 1434:             my $match = 0;
 1435:             foreach my $id (@{$by_hostname{$hostname}}) {
 1436:                 if (&host_domain($id) eq $dom) {
 1437:                     $uniqservers{$id} = $hostname;
 1438:                     $match = 1;
 1439:                 }
 1440:             }
 1441:             unless ($match) {
 1442:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1443:             }
 1444:         } else {
 1445:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1446:         }
 1447:     }
 1448:     return %uniqservers;
 1449: }
 1450: 
 1451: # ---------------------- Find the homebase for a user from domain's lib servers
 1452: 
 1453: my %homecache;
 1454: sub homeserver {
 1455:     my ($uname,$udom,$ignoreBadCache)=@_;
 1456:     my $index="$uname:$udom";
 1457: 
 1458:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1459: 
 1460:     my %servers = &get_servers($udom,'library');
 1461:     foreach my $tryserver (keys(%servers)) {
 1462:         next if ($ignoreBadCache ne 'true' && 
 1463: 		 exists($badServerCache{$tryserver}));
 1464: 
 1465: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1466: 	if ($answer eq 'found') {
 1467: 	    delete($badServerCache{$tryserver}); 
 1468: 	    return $homecache{$index}=$tryserver;
 1469: 	} elsif ($answer eq 'no_host') {
 1470: 	    $badServerCache{$tryserver}=1;
 1471: 	}
 1472:     }    
 1473:     return 'no_host';
 1474: }
 1475: 
 1476: # ------------------------------------- Find the usernames behind a list of IDs
 1477: 
 1478: sub idget {
 1479:     my ($udom,@ids)=@_;
 1480:     my %returnhash=();
 1481:     
 1482:     my %servers = &get_servers($udom,'library');
 1483:     foreach my $tryserver (keys(%servers)) {
 1484: 	my $idlist=join('&',@ids);
 1485: 	$idlist=~tr/A-Z/a-z/; 
 1486: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1487: 	my @answer=();
 1488: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1489: 	    @answer=split(/\&/,$reply);
 1490: 	}                    ;
 1491: 	my $i;
 1492: 	for ($i=0;$i<=$#ids;$i++) {
 1493: 	    if ($answer[$i]) {
 1494: 		$returnhash{$ids[$i]}=$answer[$i];
 1495: 	    } 
 1496: 	}
 1497:     } 
 1498:     return %returnhash;
 1499: }
 1500: 
 1501: # ------------------------------------- Find the IDs behind a list of usernames
 1502: 
 1503: sub idrget {
 1504:     my ($udom,@unames)=@_;
 1505:     my %returnhash=();
 1506:     foreach my $uname (@unames) {
 1507:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1508:     }
 1509:     return %returnhash;
 1510: }
 1511: 
 1512: # ------------------------------- Store away a list of names and associated IDs
 1513: 
 1514: sub idput {
 1515:     my ($udom,%ids)=@_;
 1516:     my %servers=();
 1517:     foreach my $uname (keys(%ids)) {
 1518: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1519:         my $uhom=&homeserver($uname,$udom);
 1520:         if ($uhom ne 'no_host') {
 1521:             my $id=&escape($ids{$uname});
 1522:             $id=~tr/A-Z/a-z/;
 1523:             my $esc_unam=&escape($uname);
 1524: 	    if ($servers{$uhom}) {
 1525: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1526:             } else {
 1527:                 $servers{$uhom}=$id.'='.$esc_unam;
 1528:             }
 1529:         }
 1530:     }
 1531:     foreach my $server (keys(%servers)) {
 1532:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1533:     }
 1534: }
 1535: 
 1536: # ------------------------------dump from db file owned by domainconfig user
 1537: sub dump_dom {
 1538:     my ($namespace, $udom, $regexp) = @_;
 1539: 
 1540:     $udom ||= $env{'user.domain'};
 1541: 
 1542:     return () unless $udom;
 1543: 
 1544:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1545: }
 1546: 
 1547: # ------------------------------------------ get items from domain db files   
 1548: 
 1549: sub get_dom {
 1550:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1551:     my $items='';
 1552:     foreach my $item (@$storearr) {
 1553:         $items.=&escape($item).'&';
 1554:     }
 1555:     $items=~s/\&$//;
 1556:     if (!$udom) {
 1557:         $udom=$env{'user.domain'};
 1558:         if (defined(&domain($udom,'primary'))) {
 1559:             $uhome=&domain($udom,'primary');
 1560:         } else {
 1561:             undef($uhome);
 1562:         }
 1563:     } else {
 1564:         if (!$uhome) {
 1565:             if (defined(&domain($udom,'primary'))) {
 1566:                 $uhome=&domain($udom,'primary');
 1567:             }
 1568:         }
 1569:     }
 1570:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1571:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1572:         my %returnhash;
 1573:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1574:             return %returnhash;
 1575:         }
 1576:         my @pairs=split(/\&/,$rep);
 1577:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1578:             return @pairs;
 1579:         }
 1580:         my $i=0;
 1581:         foreach my $item (@$storearr) {
 1582:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1583:             $i++;
 1584:         }
 1585:         return %returnhash;
 1586:     } else {
 1587:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1588:     }
 1589: }
 1590: 
 1591: # -------------------------------------------- put items in domain db files 
 1592: 
 1593: sub put_dom {
 1594:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1595:     if (!$udom) {
 1596:         $udom=$env{'user.domain'};
 1597:         if (defined(&domain($udom,'primary'))) {
 1598:             $uhome=&domain($udom,'primary');
 1599:         } else {
 1600:             undef($uhome);
 1601:         }
 1602:     } else {
 1603:         if (!$uhome) {
 1604:             if (defined(&domain($udom,'primary'))) {
 1605:                 $uhome=&domain($udom,'primary');
 1606:             }
 1607:         }
 1608:     } 
 1609:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1610:         my $items='';
 1611:         foreach my $item (keys(%$storehash)) {
 1612:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1613:         }
 1614:         $items=~s/\&$//;
 1615:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1616:     } else {
 1617:         &logthis("put_dom failed - no homeserver and/or domain");
 1618:     }
 1619: }
 1620: 
 1621: # --------------------- newput for items in db file owned by domainconfig user
 1622: sub newput_dom {
 1623:     my ($namespace,$storehash,$udom) = @_;
 1624:     my $result;
 1625:     if (!$udom) {
 1626:         $udom=$env{'user.domain'};
 1627:     }
 1628:     if ($udom) {
 1629:         my $uname = &get_domainconfiguser($udom);
 1630:         $result = &newput($namespace,$storehash,$udom,$uname);
 1631:     }
 1632:     return $result;
 1633: }
 1634: 
 1635: # --------------------- delete for items in db file owned by domainconfig user
 1636: sub del_dom {
 1637:     my ($namespace,$storearr,$udom)=@_;
 1638:     if (ref($storearr) eq 'ARRAY') {
 1639:         if (!$udom) {
 1640:             $udom=$env{'user.domain'};
 1641:         }
 1642:         if ($udom) {
 1643:             my $uname = &get_domainconfiguser($udom); 
 1644:             return &del($namespace,$storearr,$udom,$uname);
 1645:         }
 1646:     }
 1647: }
 1648: 
 1649: # ----------------------------------construct domainconfig user for a domain 
 1650: sub get_domainconfiguser {
 1651:     my ($udom) = @_;
 1652:     return $udom.'-domainconfig';
 1653: }
 1654: 
 1655: sub retrieve_inst_usertypes {
 1656:     my ($udom) = @_;
 1657:     my (%returnhash,@order);
 1658:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1659:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1660:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1661:         %returnhash = %{$domdefs{'inststatustypes'}};
 1662:         @order = @{$domdefs{'inststatusorder'}};
 1663:     } else {
 1664:         if (defined(&domain($udom,'primary'))) {
 1665:             my $uhome=&domain($udom,'primary');
 1666:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1667:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1668:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1669:                 return (\%returnhash,\@order);
 1670:             }
 1671:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1672:             my @pairs=split(/\&/,$hashitems);
 1673:             foreach my $item (@pairs) {
 1674:                 my ($key,$value)=split(/=/,$item,2);
 1675:                 $key = &unescape($key);
 1676:                 next if ($key =~ /^error: 2 /);
 1677:                 $returnhash{$key}=&thaw_unescape($value);
 1678:             }
 1679:             my @esc_order = split(/\&/,$orderitems);
 1680:             foreach my $item (@esc_order) {
 1681:                 push(@order,&unescape($item));
 1682:             }
 1683:         } else {
 1684:             &logthis("get_dom failed - no primary domain server for $udom");
 1685:         }
 1686:     }
 1687:     return (\%returnhash,\@order);
 1688: }
 1689: 
 1690: sub is_domainimage {
 1691:     my ($url) = @_;
 1692:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1693:         if (&domain($1) ne '') {
 1694:             return '1';
 1695:         }
 1696:     }
 1697:     return;
 1698: }
 1699: 
 1700: sub inst_directory_query {
 1701:     my ($srch) = @_;
 1702:     my $udom = $srch->{'srchdomain'};
 1703:     my %results;
 1704:     my $homeserver = &domain($udom,'primary');
 1705:     my $outcome;
 1706:     if ($homeserver ne '') {
 1707: 	my $queryid=&reply("querysend:instdirsearch:".
 1708: 			   &escape($srch->{'srchby'}).':'.
 1709: 			   &escape($srch->{'srchterm'}).':'.
 1710: 			   &escape($srch->{'srchtype'}),$homeserver);
 1711: 	my $host=&hostname($homeserver);
 1712: 	if ($queryid !~/^\Q$host\E\_/) {
 1713: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1714: 	    return;
 1715: 	}
 1716: 	my $response = &get_query_reply($queryid);
 1717: 	my $maxtries = 5;
 1718: 	my $tries = 1;
 1719: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1720: 	    $response = &get_query_reply($queryid);
 1721: 	    $tries ++;
 1722: 	}
 1723: 
 1724:         if (!&error($response) && $response ne 'refused') {
 1725:             if ($response eq 'unavailable') {
 1726:                 $outcome = $response;
 1727:             } else {
 1728:                 $outcome = 'ok';
 1729:                 my @matches = split(/\n/,$response);
 1730:                 foreach my $match (@matches) {
 1731:                     my ($key,$value) = split(/=/,$match);
 1732:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1733:                 }
 1734:             }
 1735:         }
 1736:     }
 1737:     return ($outcome,%results);
 1738: }
 1739: 
 1740: sub usersearch {
 1741:     my ($srch) = @_;
 1742:     my $dom = $srch->{'srchdomain'};
 1743:     my %results;
 1744:     my %libserv = &all_library();
 1745:     my $query = 'usersearch';
 1746:     foreach my $tryserver (keys(%libserv)) {
 1747:         if (&host_domain($tryserver) eq $dom) {
 1748:             my $host=&hostname($tryserver);
 1749:             my $queryid=
 1750:                 &reply("querysend:".&escape($query).':'.
 1751:                        &escape($srch->{'srchby'}).':'.
 1752:                        &escape($srch->{'srchtype'}).':'.
 1753:                        &escape($srch->{'srchterm'}),$tryserver);
 1754:             if ($queryid !~/^\Q$host\E\_/) {
 1755:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1756:                 next;
 1757:             }
 1758:             my $reply = &get_query_reply($queryid);
 1759:             my $maxtries = 1;
 1760:             my $tries = 1;
 1761:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1762:                 $reply = &get_query_reply($queryid);
 1763:                 $tries ++;
 1764:             }
 1765:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1766:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1767:             } else {
 1768:                 my @matches;
 1769:                 if ($reply =~ /\n/) {
 1770:                     @matches = split(/\n/,$reply);
 1771:                 } else {
 1772:                     @matches = split(/\&/,$reply);
 1773:                 }
 1774:                 foreach my $match (@matches) {
 1775:                     my ($uname,$udom,%userhash);
 1776:                     foreach my $entry (split(/:/,$match)) {
 1777:                         my ($key,$value) =
 1778:                             map {&unescape($_);} split(/=/,$entry);
 1779:                         $userhash{$key} = $value;
 1780:                         if ($key eq 'username') {
 1781:                             $uname = $value;
 1782:                         } elsif ($key eq 'domain') {
 1783:                             $udom = $value;
 1784:                         }
 1785:                     }
 1786:                     $results{$uname.':'.$udom} = \%userhash;
 1787:                 }
 1788:             }
 1789:         }
 1790:     }
 1791:     return %results;
 1792: }
 1793: 
 1794: sub get_instuser {
 1795:     my ($udom,$uname,$id) = @_;
 1796:     my $homeserver = &domain($udom,'primary');
 1797:     my ($outcome,%results);
 1798:     if ($homeserver ne '') {
 1799:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1800:                            &escape($id).':'.&escape($udom),$homeserver);
 1801:         my $host=&hostname($homeserver);
 1802:         if ($queryid !~/^\Q$host\E\_/) {
 1803:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1804:             return;
 1805:         }
 1806:         my $response = &get_query_reply($queryid);
 1807:         my $maxtries = 5;
 1808:         my $tries = 1;
 1809:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1810:             $response = &get_query_reply($queryid);
 1811:             $tries ++;
 1812:         }
 1813:         if (!&error($response) && $response ne 'refused') {
 1814:             if ($response eq 'unavailable') {
 1815:                 $outcome = $response;
 1816:             } else {
 1817:                 $outcome = 'ok';
 1818:                 my @matches = split(/\n/,$response);
 1819:                 foreach my $match (@matches) {
 1820:                     my ($key,$value) = split(/=/,$match);
 1821:                     $results{&unescape($key)} = &thaw_unescape($value);
 1822:                 }
 1823:             }
 1824:         }
 1825:     }
 1826:     my %userinfo;
 1827:     if (ref($results{$uname}) eq 'HASH') {
 1828:         %userinfo = %{$results{$uname}};
 1829:     } 
 1830:     return ($outcome,%userinfo);
 1831: }
 1832: 
 1833: sub inst_rulecheck {
 1834:     my ($udom,$uname,$id,$item,$rules) = @_;
 1835:     my %returnhash;
 1836:     if ($udom ne '') {
 1837:         if (ref($rules) eq 'ARRAY') {
 1838:             @{$rules} = map {&escape($_);} (@{$rules});
 1839:             my $rulestr = join(':',@{$rules});
 1840:             my $homeserver=&domain($udom,'primary');
 1841:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1842:                 my $response;
 1843:                 if ($item eq 'username') {                
 1844:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1845:                                               ':'.&escape($uname).':'.$rulestr,
 1846:                                               $homeserver));
 1847:                 } elsif ($item eq 'id') {
 1848:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1849:                                               ':'.&escape($id).':'.$rulestr,
 1850:                                               $homeserver));
 1851:                 } elsif ($item eq 'selfcreate') {
 1852:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1853:                                                &escape($udom).':'.&escape($uname).
 1854:                                               ':'.$rulestr,$homeserver));
 1855:                 }
 1856:                 if ($response ne 'refused') {
 1857:                     my @pairs=split(/\&/,$response);
 1858:                     foreach my $item (@pairs) {
 1859:                         my ($key,$value)=split(/=/,$item,2);
 1860:                         $key = &unescape($key);
 1861:                         next if ($key =~ /^error: 2 /);
 1862:                         $returnhash{$key}=&thaw_unescape($value);
 1863:                     }
 1864:                 }
 1865:             }
 1866:         }
 1867:     }
 1868:     return %returnhash;
 1869: }
 1870: 
 1871: sub inst_userrules {
 1872:     my ($udom,$check) = @_;
 1873:     my (%ruleshash,@ruleorder);
 1874:     if ($udom ne '') {
 1875:         my $homeserver=&domain($udom,'primary');
 1876:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1877:             my $response;
 1878:             if ($check eq 'id') {
 1879:                 $response=&reply('instidrules:'.&escape($udom),
 1880:                                  $homeserver);
 1881:             } elsif ($check eq 'email') {
 1882:                 $response=&reply('instemailrules:'.&escape($udom),
 1883:                                  $homeserver);
 1884:             } else {
 1885:                 $response=&reply('instuserrules:'.&escape($udom),
 1886:                                  $homeserver);
 1887:             }
 1888:             if (($response ne 'refused') && ($response ne 'error') && 
 1889:                 ($response ne 'unknown_cmd') && 
 1890:                 ($response ne 'no_such_host')) {
 1891:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1892:                 my @pairs=split(/\&/,$hashitems);
 1893:                 foreach my $item (@pairs) {
 1894:                     my ($key,$value)=split(/=/,$item,2);
 1895:                     $key = &unescape($key);
 1896:                     next if ($key =~ /^error: 2 /);
 1897:                     $ruleshash{$key}=&thaw_unescape($value);
 1898:                 }
 1899:                 my @esc_order = split(/\&/,$orderitems);
 1900:                 foreach my $item (@esc_order) {
 1901:                     push(@ruleorder,&unescape($item));
 1902:                 }
 1903:             }
 1904:         }
 1905:     }
 1906:     return (\%ruleshash,\@ruleorder);
 1907: }
 1908: 
 1909: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1910: 
 1911: sub get_domain_defaults {
 1912:     my ($domain) = @_;
 1913:     my $cachetime = 60*60*24;
 1914:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1915:     if (defined($cached)) {
 1916:         if (ref($result) eq 'HASH') {
 1917:             return %{$result};
 1918:         }
 1919:     }
 1920:     my %domdefaults;
 1921:     my %domconfig =
 1922:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1923:                                   'requestcourses','inststatus',
 1924:                                   'coursedefaults','usersessions'],$domain);
 1925:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1926:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1927:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1928:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1929:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1930:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1931:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1932:     } else {
 1933:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1934:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1935:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1936:     }
 1937:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1938:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1939:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1940:         } else {
 1941:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1942:         } 
 1943:         my @usertools = ('aboutme','blog','portfolio');
 1944:         foreach my $item (@usertools) {
 1945:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1946:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1947:             }
 1948:         }
 1949:     }
 1950:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1951:         foreach my $item ('official','unofficial','community') {
 1952:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1953:         }
 1954:     }
 1955:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1956:         foreach my $item ('inststatustypes','inststatusorder') {
 1957:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1958:         }
 1959:     }
 1960:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1961:         foreach my $item ('canuse_pdfforms') {
 1962:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1963:         }
 1964:     }
 1965:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1966:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1967:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1968:         }
 1969:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1970:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1971:         }
 1972:     }
 1973:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1974:                                   $cachetime);
 1975:     return %domdefaults;
 1976: }
 1977: 
 1978: # --------------------------------------------------- Assign a key to a student
 1979: 
 1980: sub assign_access_key {
 1981: #
 1982: # a valid key looks like uname:udom#comments
 1983: # comments are being appended
 1984: #
 1985:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1986:     $kdom=
 1987:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1988:     $knum=
 1989:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1990:     $cdom=
 1991:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1992:     $cnum=
 1993:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1994:     $udom=$env{'user.name'} unless (defined($udom));
 1995:     $uname=$env{'user.domain'} unless (defined($uname));
 1996:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1997:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1998:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1999:                                                   # assigned to this person
 2000:                                                   # - this should not happen,
 2001:                                                   # unless something went wrong
 2002:                                                   # the first time around
 2003: # ready to assign
 2004:         $logentry=$1.'; '.$logentry;
 2005:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2006:                                                  $kdom,$knum) eq 'ok') {
 2007: # key now belongs to user
 2008: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2009:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2010:                 &appenv({'environment.'.$envkey => $ckey});
 2011:                 return 'ok';
 2012:             } else {
 2013:                 return 
 2014:   'error: Count not permanently assign key, will need to be re-entered later.';
 2015: 	    }
 2016:         } else {
 2017:             return 'error: Could not assign key, try again later.';
 2018:         }
 2019:     } elsif (!$existing{$ckey}) {
 2020: # the key does not exist
 2021: 	return 'error: The key does not exist';
 2022:     } else {
 2023: # the key is somebody else's
 2024: 	return 'error: The key is already in use';
 2025:     }
 2026: }
 2027: 
 2028: # ------------------------------------------ put an additional comment on a key
 2029: 
 2030: sub comment_access_key {
 2031: #
 2032: # a valid key looks like uname:udom#comments
 2033: # comments are being appended
 2034: #
 2035:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2036:     $cdom=
 2037:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2038:     $cnum=
 2039:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2040:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2041:     if ($existing{$ckey}) {
 2042:         $existing{$ckey}.='; '.$logentry;
 2043: # ready to assign
 2044:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2045:                                                  $cdom,$cnum) eq 'ok') {
 2046: 	    return 'ok';
 2047:         } else {
 2048: 	    return 'error: Count not store comment.';
 2049:         }
 2050:     } else {
 2051: # the key does not exist
 2052: 	return 'error: The key does not exist';
 2053:     }
 2054: }
 2055: 
 2056: # ------------------------------------------------------ Generate a set of keys
 2057: 
 2058: sub generate_access_keys {
 2059:     my ($number,$cdom,$cnum,$logentry)=@_;
 2060:     $cdom=
 2061:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2062:     $cnum=
 2063:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2064:     unless (&allowed('mky',$cdom)) { return 0; }
 2065:     unless (($cdom) && ($cnum)) { return 0; }
 2066:     if ($number>10000) { return 0; }
 2067:     sleep(2); # make sure don't get same seed twice
 2068:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2069:     my $total=0;
 2070:     for (my $i=1;$i<=$number;$i++) {
 2071:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2072:                   sprintf("%lx",int(100000*rand)).'-'.
 2073:                   sprintf("%lx",int(100000*rand));
 2074:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2075:        $newkey=~s/0/h/g; # and also 0 and O
 2076:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2077:        if ($existing{$newkey}) {
 2078:            $i--;
 2079:        } else {
 2080: 	  if (&put('accesskeys',
 2081:               { $newkey => '# generated '.localtime().
 2082:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2083:                            '; '.$logentry },
 2084: 		   $cdom,$cnum) eq 'ok') {
 2085:               $total++;
 2086: 	  }
 2087:        }
 2088:     }
 2089:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2090:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2091:     return $total;
 2092: }
 2093: 
 2094: # ------------------------------------------------------- Validate an accesskey
 2095: 
 2096: sub validate_access_key {
 2097:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2098:     $cdom=
 2099:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2100:     $cnum=
 2101:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2102:     $udom=$env{'user.domain'} unless (defined($udom));
 2103:     $uname=$env{'user.name'} unless (defined($uname));
 2104:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2105:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2106: }
 2107: 
 2108: # ------------------------------------- Find the section of student in a course
 2109: sub devalidate_getsection_cache {
 2110:     my ($udom,$unam,$courseid)=@_;
 2111:     my $hashid="$udom:$unam:$courseid";
 2112:     &devalidate_cache_new('getsection',$hashid);
 2113: }
 2114: 
 2115: sub courseid_to_courseurl {
 2116:     my ($courseid) = @_;
 2117:     #already url style courseid
 2118:     return $courseid if ($courseid =~ m{^/});
 2119: 
 2120:     if (exists($env{'course.'.$courseid.'.num'})) {
 2121: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2122: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2123: 	return "/$cdom/$cnum";
 2124:     }
 2125: 
 2126:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2127:     if (exists($courseinfo{'num'})) {
 2128: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2129:     }
 2130: 
 2131:     return undef;
 2132: }
 2133: 
 2134: sub getsection {
 2135:     my ($udom,$unam,$courseid)=@_;
 2136:     my $cachetime=1800;
 2137: 
 2138:     my $hashid="$udom:$unam:$courseid";
 2139:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2140:     if (defined($cached)) { return $result; }
 2141: 
 2142:     my %Pending; 
 2143:     my %Expired;
 2144:     #
 2145:     # Each role can either have not started yet (pending), be active, 
 2146:     #    or have expired.
 2147:     #
 2148:     # If there is an active role, we are done.
 2149:     #
 2150:     # If there is more than one role which has not started yet, 
 2151:     #     choose the one which will start sooner
 2152:     # If there is one role which has not started yet, return it.
 2153:     #
 2154:     # If there is more than one expired role, choose the one which ended last.
 2155:     # If there is a role which has expired, return it.
 2156:     #
 2157:     $courseid = &courseid_to_courseurl($courseid);
 2158:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2159:     foreach my $key (keys(%roleshash)) {
 2160:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2161:         my $section=$1;
 2162:         if ($key eq $courseid.'_st') { $section=''; }
 2163:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2164:         my $now=time;
 2165:         if (defined($end) && $end && ($now > $end)) {
 2166:             $Expired{$end}=$section;
 2167:             next;
 2168:         }
 2169:         if (defined($start) && $start && ($now < $start)) {
 2170:             $Pending{$start}=$section;
 2171:             next;
 2172:         }
 2173:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2174:     }
 2175:     #
 2176:     # Presumedly there will be few matching roles from the above
 2177:     # loop and the sorting time will be negligible.
 2178:     if (scalar(keys(%Pending))) {
 2179:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2180:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2181:     } 
 2182:     if (scalar(keys(%Expired))) {
 2183:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2184:         my $time = pop(@sorted);
 2185:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2186:     }
 2187:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2188: }
 2189: 
 2190: sub save_cache {
 2191:     &purge_remembered();
 2192:     #&Apache::loncommon::validate_page();
 2193:     undef(%env);
 2194:     undef($env_loaded);
 2195: }
 2196: 
 2197: my $to_remember=-1;
 2198: my %remembered;
 2199: my %accessed;
 2200: my $kicks=0;
 2201: my $hits=0;
 2202: sub make_key {
 2203:     my ($name,$id) = @_;
 2204:     if (length($id) > 65 
 2205: 	&& length(&escape($id)) > 200) {
 2206: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2207:     }
 2208:     return &escape($name.':'.$id);
 2209: }
 2210: 
 2211: sub devalidate_cache_new {
 2212:     my ($name,$id,$debug) = @_;
 2213:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2214:     $id=&make_key($name,$id);
 2215:     $memcache->delete($id);
 2216:     delete($remembered{$id});
 2217:     delete($accessed{$id});
 2218: }
 2219: 
 2220: sub is_cached_new {
 2221:     my ($name,$id,$debug) = @_;
 2222:     $id=&make_key($name,$id);
 2223:     if (exists($remembered{$id})) {
 2224: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2225: 	$accessed{$id}=[&gettimeofday()];
 2226: 	$hits++;
 2227: 	return ($remembered{$id},1);
 2228:     }
 2229:     my $value = $memcache->get($id);
 2230:     if (!(defined($value))) {
 2231: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2232: 	return (undef,undef);
 2233:     }
 2234:     if ($value eq '__undef__') {
 2235: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2236: 	$value=undef;
 2237:     }
 2238:     &make_room($id,$value,$debug);
 2239:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2240:     return ($value,1);
 2241: }
 2242: 
 2243: sub do_cache_new {
 2244:     my ($name,$id,$value,$time,$debug) = @_;
 2245:     $id=&make_key($name,$id);
 2246:     my $setvalue=$value;
 2247:     if (!defined($setvalue)) {
 2248: 	$setvalue='__undef__';
 2249:     }
 2250:     if (!defined($time) ) {
 2251: 	$time=600;
 2252:     }
 2253:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2254:     my $result = $memcache->set($id,$setvalue,$time);
 2255:     if (! $result) {
 2256: 	&logthis("caching of id -> $id  failed");
 2257: 	$memcache->disconnect_all();
 2258:     }
 2259:     # need to make a copy of $value
 2260:     &make_room($id,$value,$debug);
 2261:     return $value;
 2262: }
 2263: 
 2264: sub make_room {
 2265:     my ($id,$value,$debug)=@_;
 2266: 
 2267:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2268:                                     : $value;
 2269:     if ($to_remember<0) { return; }
 2270:     $accessed{$id}=[&gettimeofday()];
 2271:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2272:     my $to_kick;
 2273:     my $max_time=0;
 2274:     foreach my $other (keys(%accessed)) {
 2275: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2276: 	    $to_kick=$other;
 2277: 	    $max_time=&tv_interval($accessed{$other});
 2278: 	}
 2279:     }
 2280:     delete($remembered{$to_kick});
 2281:     delete($accessed{$to_kick});
 2282:     $kicks++;
 2283:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2284:     return;
 2285: }
 2286: 
 2287: sub purge_remembered {
 2288:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2289:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2290:     undef(%remembered);
 2291:     undef(%accessed);
 2292: }
 2293: # ------------------------------------- Read an entry from a user's environment
 2294: 
 2295: sub userenvironment {
 2296:     my ($udom,$unam,@what)=@_;
 2297:     my $items;
 2298:     foreach my $item (@what) {
 2299:         $items.=&escape($item).'&';
 2300:     }
 2301:     $items=~s/\&$//;
 2302:     my %returnhash=();
 2303:     my $uhome = &homeserver($unam,$udom);
 2304:     unless ($uhome eq 'no_host') {
 2305:         my @answer=split(/\&/, 
 2306:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2307:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2308:             return %returnhash;
 2309:         }
 2310:         my $i;
 2311:         for ($i=0;$i<=$#what;$i++) {
 2312: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2313:         }
 2314:     }
 2315:     return %returnhash;
 2316: }
 2317: 
 2318: # ---------------------------------------------------------- Get a studentphoto
 2319: sub studentphoto {
 2320:     my ($udom,$unam,$ext) = @_;
 2321:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2322:     if (defined($env{'request.course.id'})) {
 2323:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2324:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2325:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2326:             } else {
 2327:                 my ($result,$perm_reqd)=
 2328: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2329:                 if ($result eq 'ok') {
 2330:                     if (!($perm_reqd eq 'yes')) {
 2331:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2332:                     }
 2333:                 }
 2334:             }
 2335:         }
 2336:     } else {
 2337:         my ($result,$perm_reqd) = 
 2338: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2339:         if ($result eq 'ok') {
 2340:             if (!($perm_reqd eq 'yes')) {
 2341:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2342:             }
 2343:         }
 2344:     }
 2345:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2346: }
 2347: 
 2348: sub retrievestudentphoto {
 2349:     my ($udom,$unam,$ext,$type) = @_;
 2350:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2351:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2352:     if ($ret eq 'ok') {
 2353:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2354:         if ($type eq 'thumbnail') {
 2355:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2356:         }
 2357:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2358:         return $tokenurl;
 2359:     } else {
 2360:         if ($type eq 'thumbnail') {
 2361:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2362:         } else { 
 2363:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2364:         }
 2365:     }
 2366: }
 2367: 
 2368: # -------------------------------------------------------------------- New chat
 2369: 
 2370: sub chatsend {
 2371:     my ($newentry,$anon,$group)=@_;
 2372:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2373:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2374:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2375:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2376: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2377: 		   &escape($newentry)).':'.$group,$chome);
 2378: }
 2379: 
 2380: # ------------------------------------------ Find current version of a resource
 2381: 
 2382: sub getversion {
 2383:     my $fname=&clutter(shift);
 2384:     unless ($fname=~/^\/res\//) { return -1; }
 2385:     return &currentversion(&filelocation('',$fname));
 2386: }
 2387: 
 2388: sub currentversion {
 2389:     my $fname=shift;
 2390:     my $author=$fname;
 2391:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2392:     my ($udom,$uname)=split(/\//,$author);
 2393:     my $home=&homeserver($uname,$udom);
 2394:     if ($home eq 'no_host') { 
 2395:         return -1; 
 2396:     }
 2397:     my $answer=&reply("currentversion:$fname",$home);
 2398:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2399: 	return -1;
 2400:     }
 2401:     return $answer;
 2402: }
 2403: 
 2404: #
 2405: # Return special version number of resource if set by override, empty otherwise
 2406: #
 2407: sub usedversion {
 2408:     my $fname=shift;
 2409:     unless ($fname) { $fname=$env{'request.uri'}; }
 2410:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2411:     if ($urlversion) { return $urlversion; }
 2412:     return '';
 2413: }
 2414: 
 2415: # ----------------------------- Subscribe to a resource, return URL if possible
 2416: 
 2417: sub subscribe {
 2418:     my $fname=shift;
 2419:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2420:     $fname=~s/[\n\r]//g;
 2421:     my $author=$fname;
 2422:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2423:     my ($udom,$uname)=split(/\//,$author);
 2424:     my $home=homeserver($uname,$udom);
 2425:     if ($home eq 'no_host') {
 2426:         return 'not_found';
 2427:     }
 2428:     my $answer=reply("sub:$fname",$home);
 2429:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2430: 	$answer.=' by '.$home;
 2431:     }
 2432:     return $answer;
 2433: }
 2434:     
 2435: # -------------------------------------------------------------- Replicate file
 2436: 
 2437: sub repcopy {
 2438:     my $filename=shift;
 2439:     $filename=~s/\/+/\//g;
 2440:     my $londocroot = $perlvar{'lonDocRoot'};
 2441:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2442:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2443:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2444: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2445: 	return &repcopy_userfile($filename);
 2446:     }
 2447:     $filename=~s/[\n\r]//g;
 2448:     my $transname="$filename.in.transfer";
 2449: # FIXME: this should flock
 2450:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2451:     my $remoteurl=subscribe($filename);
 2452:     if ($remoteurl =~ /^con_lost by/) {
 2453: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2454:            return 'unavailable';
 2455:     } elsif ($remoteurl eq 'not_found') {
 2456: 	   #&logthis("Subscribe returned not_found: $filename");
 2457: 	   return 'not_found';
 2458:     } elsif ($remoteurl =~ /^rejected by/) {
 2459: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2460:            return 'forbidden';
 2461:     } elsif ($remoteurl eq 'directory') {
 2462:            return 'ok';
 2463:     } else {
 2464:         my $author=$filename;
 2465:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2466:         my ($udom,$uname)=split(/\//,$author);
 2467:         my $home=homeserver($uname,$udom);
 2468:         unless ($home eq $perlvar{'lonHostID'}) {
 2469:            my @parts=split(/\//,$filename);
 2470:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2471:            if ($path ne "$londocroot/res") {
 2472:                &logthis("Malconfiguration for replication: $filename");
 2473: 	       return 'bad_request';
 2474:            }
 2475:            my $count;
 2476:            for ($count=5;$count<$#parts;$count++) {
 2477:                $path.="/$parts[$count]";
 2478:                if ((-e $path)!=1) {
 2479: 		   mkdir($path,0777);
 2480:                }
 2481:            }
 2482:            my $ua=new LWP::UserAgent;
 2483:            my $request=new HTTP::Request('GET',"$remoteurl");
 2484:            my $response=$ua->request($request,$transname);
 2485:            if ($response->is_error()) {
 2486: 	       unlink($transname);
 2487:                my $message=$response->status_line;
 2488:                &logthis("<font color=\"blue\">WARNING:"
 2489:                        ." LWP get: $message: $filename</font>");
 2490:                return 'unavailable';
 2491:            } else {
 2492: 	       if ($remoteurl!~/\.meta$/) {
 2493:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2494:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2495:                   if ($mresponse->is_error()) {
 2496: 		      unlink($filename.'.meta');
 2497:                       &logthis(
 2498:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2499:                   }
 2500: 	       }
 2501:                rename($transname,$filename);
 2502:                return 'ok';
 2503:            }
 2504:        }
 2505:     }
 2506: }
 2507: 
 2508: # ------------------------------------------------ Get server side include body
 2509: sub ssi_body {
 2510:     my ($filelink,%form)=@_;
 2511:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2512:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2513:     }
 2514:     my $output='';
 2515:     my $response;
 2516:     if ($filelink=~/^https?\:/) {
 2517:        ($output,$response)=&externalssi($filelink);
 2518:     } else {
 2519:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2520:        $filelink .= 'inhibitmenu=yes';
 2521:        ($output,$response)=&ssi($filelink,%form);
 2522:     }
 2523:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2524:     $output=~s/^.*?\<body[^\>]*\>//si;
 2525:     $output=~s/\<\/body\s*\>.*?$//si;
 2526:     if (wantarray) {
 2527:         return ($output, $response);
 2528:     } else {
 2529:         return $output;
 2530:     }
 2531: }
 2532: 
 2533: # --------------------------------------------------------- Server Side Include
 2534: 
 2535: sub absolute_url {
 2536:     my ($host_name) = @_;
 2537:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2538:     if ($host_name eq '') {
 2539: 	$host_name = $ENV{'SERVER_NAME'};
 2540:     }
 2541:     return $protocol.$host_name;
 2542: }
 2543: 
 2544: #
 2545: #   Server side include.
 2546: # Parameters:
 2547: #  fn     Possibly encrypted resource name/id.
 2548: #  form   Hash that describes how the rendering should be done
 2549: #         and other things.
 2550: # Returns:
 2551: #   Scalar context: The content of the response.
 2552: #   Array context:  2 element list of the content and the full response object.
 2553: #     
 2554: sub ssi {
 2555: 
 2556:     my ($fn,%form)=@_;
 2557:     my $ua=new LWP::UserAgent;
 2558:     my $request;
 2559: 
 2560:     $form{'no_update_last_known'}=1;
 2561:     &Apache::lonenc::check_encrypt(\$fn);
 2562:     if (%form) {
 2563:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2564:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2565:     } else {
 2566:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2567:     }
 2568: 
 2569:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2570:     my $response=$ua->request($request);
 2571: 
 2572:     if (wantarray) {
 2573: 	return ($response->content, $response);
 2574:     } else {
 2575: 	return $response->content;
 2576:     }
 2577: }
 2578: 
 2579: sub externalssi {
 2580:     my ($url)=@_;
 2581:     my $ua=new LWP::UserAgent;
 2582:     my $request=new HTTP::Request('GET',$url);
 2583:     my $response=$ua->request($request);
 2584:     if (wantarray) {
 2585:         return ($response->content, $response);
 2586:     } else {
 2587:         return $response->content;
 2588:     }
 2589: }
 2590: 
 2591: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2592: 
 2593: sub allowuploaded {
 2594:     my ($srcurl,$url)=@_;
 2595:     $url=&clutter(&declutter($url));
 2596:     my $dir=$url;
 2597:     $dir=~s/\/[^\/]+$//;
 2598:     my %httpref=();
 2599:     my $httpurl=&hreflocation('',$url);
 2600:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2601:     &Apache::lonnet::appenv(\%httpref);
 2602: }
 2603: 
 2604: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2605: # input: action, courseID, current domain, intended
 2606: #        path to file, source of file, instruction to parse file for objects,
 2607: #        ref to hash for embedded objects,
 2608: #        ref to hash for codebase of java objects.
 2609: #        reference to scalar to accommodate mime type determined
 2610: #          from File::MMagic if $parser = parse.
 2611: #
 2612: # output: url to file (if action was uploaddoc), 
 2613: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2614: #
 2615: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2616: # course.
 2617: #
 2618: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2619: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2620: #          course's home server.
 2621: #
 2622: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2623: #          be copied from $source (current location) to 
 2624: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2625: #         and will then be copied to
 2626: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2627: #         course's home server.
 2628: #
 2629: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2630: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2631: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2632: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2633: #         in course's home server.
 2634: #
 2635: 
 2636: sub process_coursefile {
 2637:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2638:         $mimetype)=@_;
 2639:     my $fetchresult;
 2640:     my $home=&homeserver($docuname,$docudom);
 2641:     if ($action eq 'propagate') {
 2642:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2643: 			     $home);
 2644:     } else {
 2645:         my $fpath = '';
 2646:         my $fname = $file;
 2647:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2648:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2649:         my $filepath = &build_filepath($fpath);
 2650:         if ($action eq 'copy') {
 2651:             if ($source eq '') {
 2652:                 $fetchresult = 'no source file';
 2653:                 return $fetchresult;
 2654:             } else {
 2655:                 my $destination = $filepath.'/'.$fname;
 2656:                 rename($source,$destination);
 2657:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2658:                                  $home);
 2659:             }
 2660:         } elsif ($action eq 'uploaddoc') {
 2661:             open(my $fh,'>'.$filepath.'/'.$fname);
 2662:             print $fh $env{'form.'.$source};
 2663:             close($fh);
 2664:             if ($parser eq 'parse') {
 2665:                 my $mm = new File::MMagic;
 2666:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2667:                 if ($type eq 'text/html') {
 2668:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2669:                     unless ($parse_result eq 'ok') {
 2670:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2671:                     }
 2672:                 }
 2673:                 if (ref($mimetype)) {
 2674:                     $$mimetype = $type;
 2675:                 } 
 2676:             }
 2677:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2678:                                  $home);
 2679:             if ($fetchresult eq 'ok') {
 2680:                 return '/uploaded/'.$fpath.'/'.$fname;
 2681:             } else {
 2682:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2683:                         ' to host '.$home.': '.$fetchresult);
 2684:                 return '/adm/notfound.html';
 2685:             }
 2686:         }
 2687:     }
 2688:     unless ( $fetchresult eq 'ok') {
 2689:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2690:              ' to host '.$home.': '.$fetchresult);
 2691:     }
 2692:     return $fetchresult;
 2693: }
 2694: 
 2695: sub build_filepath {
 2696:     my ($fpath) = @_;
 2697:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2698:     unless ($fpath eq '') {
 2699:         my @parts=split('/',$fpath);
 2700:         foreach my $part (@parts) {
 2701:             $filepath.= '/'.$part;
 2702:             if ((-e $filepath)!=1) {
 2703:                 mkdir($filepath,0777);
 2704:             }
 2705:         }
 2706:     }
 2707:     return $filepath;
 2708: }
 2709: 
 2710: sub store_edited_file {
 2711:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2712:     my $file = $primary_url;
 2713:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2714:     my $fpath = '';
 2715:     my $fname = $file;
 2716:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2717:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2718:     my $filepath = &build_filepath($fpath);
 2719:     open(my $fh,'>'.$filepath.'/'.$fname);
 2720:     print $fh $content;
 2721:     close($fh);
 2722:     my $home=&homeserver($docuname,$docudom);
 2723:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2724: 			  $home);
 2725:     if ($$fetchresult eq 'ok') {
 2726:         return '/uploaded/'.$fpath.'/'.$fname;
 2727:     } else {
 2728:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2729: 		 ' to host '.$home.': '.$$fetchresult);
 2730:         return '/adm/notfound.html';
 2731:     }
 2732: }
 2733: 
 2734: sub clean_filename {
 2735:     my ($fname,$args)=@_;
 2736: # Replace Windows backslashes by forward slashes
 2737:     $fname=~s/\\/\//g;
 2738:     if (!$args->{'keep_path'}) {
 2739:         # Get rid of everything but the actual filename
 2740: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2741:     }
 2742: # Replace spaces by underscores
 2743:     $fname=~s/\s+/\_/g;
 2744: # Replace all other weird characters by nothing
 2745:     $fname=~s{[^/\w\.\-]}{}g;
 2746: # Replace all .\d. sequences with _\d. so they no longer look like version
 2747: # numbers
 2748:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2749:     return $fname;
 2750: }
 2751: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2752: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2753: # image with the same aspect ratio as the original, but with dimensions which do 
 2754: # not exceed $resizewidth and $resizeheight.
 2755:  
 2756: sub resizeImage {
 2757:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2758:     my $ima = Image::Magick->new;
 2759:     my $resized;
 2760:     if (-e $img_path) {
 2761:         $ima->Read($img_path);
 2762:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2763:             my $width = $ima->Get('width');
 2764:             my $height = $ima->Get('height');
 2765:             if ($width > $resizewidth) {
 2766: 	        my $factor = $width/$resizewidth;
 2767:                 my $newheight = $height/$factor;
 2768:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2769:                 $resized = 1;
 2770:             }
 2771:         }
 2772:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2773:             my $width = $ima->Get('width');
 2774:             my $height = $ima->Get('height');
 2775:             if ($height > $resizeheight) {
 2776:                 my $factor = $height/$resizeheight;
 2777:                 my $newwidth = $width/$factor;
 2778:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2779:                 $resized = 1;
 2780:             }
 2781:         }
 2782:         if ($resized) {
 2783:             $ima->Write($img_path);
 2784:         }
 2785:     }
 2786:     return;
 2787: }
 2788: 
 2789: # --------------- Take an uploaded file and put it into the userfiles directory
 2790: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2791: #                    the desired filename is in $env{"form.$formname.filename"}
 2792: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2793: #                                    canceloverwrite, or ''. 
 2794: #                   if 'coursedoc': upload to the current course
 2795: #                   if 'existingfile': write file to tmp/overwrites directory 
 2796: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2797: #                   $context is passed as argument to &finishuserfileupload
 2798: #        $subdir - directory in userfile to store the file into
 2799: #        $parser - instruction to parse file for objects ($parser = parse)    
 2800: #        $allfiles - reference to hash for embedded objects
 2801: #        $codebase - reference to hash for codebase of java objects
 2802: #        $desuname - username for permanent storage of uploaded file
 2803: #        $dsetudom - domain for permanaent storage of uploaded file
 2804: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2805: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2806: #        $resizewidth - width (pixels) to which to resize uploaded image
 2807: #        $resizeheight - height (pixels) to which to resize uploaded image
 2808: #        $mimetype - reference to scalar to accommodate mime type determined
 2809: #                    from File::MMagic.
 2810: # 
 2811: # output: url of file in userspace, or error: <message> 
 2812: #             or /adm/notfound.html if failure to upload occurse
 2813: 
 2814: sub userfileupload {
 2815:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2816:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2817:     if (!defined($subdir)) { $subdir='unknown'; }
 2818:     my $fname=$env{'form.'.$formname.'.filename'};
 2819:     $fname=&clean_filename($fname);
 2820:     # See if there is anything left
 2821:     unless ($fname) { return 'error: no uploaded file'; }
 2822:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2823:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2824:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2825:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2826:         my $now = time;
 2827:         my $filepath;
 2828:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2829:              $filepath = 'tmp/helprequests/'.$now;
 2830:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2831:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2832:                          '_'.$env{'user.domain'}.'/pending';
 2833:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2834:             my ($docuname,$docudom);
 2835:             if ($destudom) {
 2836:                 $docudom = $destudom;
 2837:             } else {
 2838:                 $docudom = $env{'user.domain'};
 2839:             }
 2840:             if ($destuname) {
 2841:                 $docuname = $destuname;
 2842:             } else {
 2843:                 $docuname = $env{'user.name'};
 2844:             }
 2845:             if (exists($env{'form.group'})) {
 2846:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2847:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2848:             }
 2849:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2850:             if ($context eq 'canceloverwrite') {
 2851:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2852:                 if (-e  $tempfile) {
 2853:                     my @info = stat($tempfile);
 2854:                     if ($info[9] eq $env{'form.timestamp'}) {
 2855:                         unlink($tempfile);
 2856:                     }
 2857:                 }
 2858:                 return;
 2859:             }
 2860:         }
 2861:         # Create the directory if not present
 2862:         my @parts=split(/\//,$filepath);
 2863:         my $fullpath = $perlvar{'lonDaemons'};
 2864:         for (my $i=0;$i<@parts;$i++) {
 2865:             $fullpath .= '/'.$parts[$i];
 2866:             if ((-e $fullpath)!=1) {
 2867:                 mkdir($fullpath,0777);
 2868:             }
 2869:         }
 2870:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2871:         print $fh $env{'form.'.$formname};
 2872:         close($fh);
 2873:         if ($context eq 'existingfile') {
 2874:             my @info = stat($fullpath.'/'.$fname);
 2875:             return ($fullpath.'/'.$fname,$info[9]);
 2876:         } else {
 2877:             return $fullpath.'/'.$fname;
 2878:         }
 2879:     }
 2880:     if ($subdir eq 'scantron') {
 2881:         $fname = 'scantron_orig_'.$fname;
 2882:     } else {
 2883:         $fname="$subdir/$fname";
 2884:     }
 2885:     if ($context eq 'coursedoc') {
 2886: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2887: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2888:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2889:             return &finishuserfileupload($docuname,$docudom,
 2890: 					 $formname,$fname,$parser,$allfiles,
 2891: 					 $codebase,$thumbwidth,$thumbheight,
 2892:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2893:         } else {
 2894:             $fname=$env{'form.folder'}.'/'.$fname;
 2895:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2896: 				       $fname,$formname,$parser,
 2897: 				       $allfiles,$codebase,$mimetype);
 2898:         }
 2899:     } elsif (defined($destuname)) {
 2900:         my $docuname=$destuname;
 2901:         my $docudom=$destudom;
 2902: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2903: 				     $parser,$allfiles,$codebase,
 2904:                                      $thumbwidth,$thumbheight,
 2905:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2906:     } else {
 2907:         my $docuname=$env{'user.name'};
 2908:         my $docudom=$env{'user.domain'};
 2909:         if (exists($env{'form.group'})) {
 2910:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2911:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2912:         }
 2913: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2914: 				     $parser,$allfiles,$codebase,
 2915:                                      $thumbwidth,$thumbheight,
 2916:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2917:     }
 2918: }
 2919: 
 2920: sub finishuserfileupload {
 2921:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2922:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2923:     my $path=$docudom.'/'.$docuname.'/';
 2924:     my $filepath=$perlvar{'lonDocRoot'};
 2925:   
 2926:     my ($fnamepath,$file,$fetchthumb);
 2927:     $file=$fname;
 2928:     if ($fname=~m|/|) {
 2929:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2930: 	$path.=$fnamepath.'/';
 2931:     }
 2932:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2933:     my $count;
 2934:     for ($count=4;$count<=$#parts;$count++) {
 2935:         $filepath.="/$parts[$count]";
 2936:         if ((-e $filepath)!=1) {
 2937: 	    mkdir($filepath,0777);
 2938:         }
 2939:     }
 2940: 
 2941: # Save the file
 2942:     {
 2943: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2944: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2945: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2946: 	    return '/adm/notfound.html';
 2947: 	}
 2948:         if ($context eq 'overwrite') {
 2949:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2950:             my $target = $filepath.'/'.$file;
 2951:             if (-e $source) {
 2952:                 my @info = stat($source);
 2953:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2954:                     unless (&File::Copy::move($source,$target)) {
 2955:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 2956:                         return "Moving from $source failed";
 2957:                     }
 2958:                 } else {
 2959:                     return "Temporary file: $source had unexpected date/time for last modification";
 2960:                 }
 2961:             } else {
 2962:                 return "Temporary file: $source missing";
 2963:             }
 2964:         } elsif (!print FH ($env{'form.'.$formname})) {
 2965: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2966: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2967: 	    return '/adm/notfound.html';
 2968: 	}
 2969: 	close(FH);
 2970:         if ($resizewidth && $resizeheight) {
 2971:             my $mm = new File::MMagic;
 2972:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2973:             if ($mime_type =~ m{^image/}) {
 2974: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2975:             }  
 2976: 	}
 2977:     }
 2978:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 2979:         if (ref($mimetype)) {
 2980:             if ($$mimetype eq '') {
 2981:                 my $mm = new File::MMagic;
 2982:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 2983:                 $$mimetype = $type;
 2984:             }
 2985:         }
 2986:     }
 2987:     if ($parser eq 'parse') {
 2988:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 2989:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2990:                                                        $allfiles,$codebase);
 2991:             unless ($parse_result eq 'ok') {
 2992:                 &logthis('Failed to parse '.$filepath.$file.
 2993: 	   	         ' for embedded media: '.$parse_result); 
 2994:             }
 2995:         }
 2996:     }
 2997:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2998:         my $input = $filepath.'/'.$file;
 2999:         my $output = $filepath.'/'.'tn-'.$file;
 3000:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3001:         system("convert -sample $thumbsize $input $output");
 3002:         if (-e $filepath.'/'.'tn-'.$file) {
 3003:             $fetchthumb  = 1; 
 3004:         }
 3005:     }
 3006:  
 3007: # Notify homeserver to grep it
 3008: #
 3009:     my $docuhome=&homeserver($docuname,$docudom);	
 3010:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3011:     if ($fetchresult eq 'ok') {
 3012:         if ($fetchthumb) {
 3013:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3014:             if ($thumbresult ne 'ok') {
 3015:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3016:                          $docuhome.': '.$thumbresult);
 3017:             }
 3018:         }
 3019: #
 3020: # Return the URL to it
 3021:         return '/uploaded/'.$path.$file;
 3022:     } else {
 3023:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3024: 		 ': '.$fetchresult);
 3025:         return '/adm/notfound.html';
 3026:     }
 3027: }
 3028: 
 3029: sub extract_embedded_items {
 3030:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3031:     my @state = ();
 3032:     my (%lastids,%related,%shockwave,%flashvars);
 3033:     my %javafiles = (
 3034:                       codebase => '',
 3035:                       code => '',
 3036:                       archive => ''
 3037:                     );
 3038:     my %mediafiles = (
 3039:                       src => '',
 3040:                       movie => '',
 3041:                      );
 3042:     my $p;
 3043:     if ($content) {
 3044:         $p = HTML::LCParser->new($content);
 3045:     } else {
 3046:         $p = HTML::LCParser->new($fullpath);
 3047:     }
 3048:     while (my $t=$p->get_token()) {
 3049: 	if ($t->[0] eq 'S') {
 3050: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3051: 	    push(@state, $tagname);
 3052:             if (lc($tagname) eq 'allow') {
 3053:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3054:             }
 3055: 	    if (lc($tagname) eq 'img') {
 3056: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3057: 	    }
 3058: 	    if (lc($tagname) eq 'a') {
 3059: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3060: 	    }
 3061:             if (lc($tagname) eq 'script') {
 3062:                 my $src;
 3063:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3064:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3065:                 } else {
 3066:                     if ($attr->{'src'} ne '') {
 3067:                         $src = $attr->{'src'};
 3068:                         &add_filetype($allfiles,$src,'src');
 3069:                     }
 3070:                 }
 3071:                 my $text = $p->get_trimmed_text();
 3072:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3073:                     my @swfargs = split(/,/,$1);
 3074:                     foreach my $item (@swfargs) {
 3075:                         $item =~ s/["']//g;
 3076:                         $item =~ s/^\s+//;
 3077:                         $item =~ s/\s+$//;
 3078:                     }
 3079:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3080:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3081:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3082:                         } else {
 3083:                             $related{$swfargs[0]} = [$swfargs[2]];
 3084:                         }
 3085:                     }
 3086:                 }
 3087:             }
 3088:             if (lc($tagname) eq 'link') {
 3089:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3090:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3091:                 }
 3092:             }
 3093: 	    if (lc($tagname) eq 'object' ||
 3094: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3095: 		foreach my $item (keys(%javafiles)) {
 3096: 		    $javafiles{$item} = '';
 3097: 		}
 3098:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3099:                     $lastids{lc($tagname)} = $attr->{'id'};
 3100:                 }
 3101: 	    }
 3102: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3103: 		my $name = lc($attr->{'name'});
 3104: 		foreach my $item (keys(%javafiles)) {
 3105: 		    if ($name eq $item) {
 3106: 			$javafiles{$item} = $attr->{'value'};
 3107: 			last;
 3108: 		    }
 3109: 		}
 3110:                 my $pathfrom;
 3111: 		foreach my $item (keys(%mediafiles)) {
 3112: 		    if ($name eq $item) {
 3113:                         $pathfrom = $attr->{'value'};
 3114:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3115: 			&add_filetype($allfiles,$pathfrom,$name);
 3116: 			last;
 3117: 		    }
 3118: 		}
 3119:                 if ($name eq 'flashvars') {
 3120:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3121:                 }
 3122:                 if ($pathfrom ne '') {
 3123:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3124:                                          $pathfrom);
 3125:                 }
 3126: 	    }
 3127: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3128: 		foreach my $item (keys(%javafiles)) {
 3129: 		    if ($attr->{$item}) {
 3130: 			$javafiles{$item} = $attr->{$item};
 3131: 			last;
 3132: 		    }
 3133: 		}
 3134: 		foreach my $item (keys(%mediafiles)) {
 3135: 		    if ($attr->{$item}) {
 3136: 			&add_filetype($allfiles,$attr->{$item},$item);
 3137: 			last;
 3138: 		    }
 3139: 		}
 3140:                 if (lc($tagname) eq 'embed') {
 3141:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3142:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3143:                                              $attr->{'src'});
 3144:                     }
 3145:                 }
 3146: 	    }
 3147:             if ($t->[4] =~ m{/>$}) {
 3148:                 pop(@state);  
 3149:             }
 3150: 	} elsif ($t->[0] eq 'E') {
 3151: 	    my ($tagname) = ($t->[1]);
 3152: 	    if ($javafiles{'codebase'} ne '') {
 3153: 		$javafiles{'codebase'} .= '/';
 3154: 	    }  
 3155: 	    if (lc($tagname) eq 'applet' ||
 3156: 		lc($tagname) eq 'object' ||
 3157: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3158: 		) {
 3159: 		foreach my $item (keys(%javafiles)) {
 3160: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3161: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3162: 			&add_filetype($allfiles,$file,$item);
 3163: 		    }
 3164: 		}
 3165: 	    } 
 3166: 	    pop @state;
 3167: 	}
 3168:     }
 3169:     foreach my $id (sort(keys(%flashvars))) {
 3170:         if ($shockwave{$id} ne '') {
 3171:             my @pairs = split(/\&/,$flashvars{$id});
 3172:             foreach my $pair (@pairs) {
 3173:                 my ($key,$value) = split(/\=/,$pair);
 3174:                 if ($key eq 'thumb') {
 3175:                     &add_filetype($allfiles,$value,$key);
 3176:                 } elsif ($key eq 'content') {
 3177:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3178:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3179:                     if ($ext ne '') {
 3180:                         &add_filetype($allfiles,$path.$value,$ext);
 3181:                     }
 3182:                 }
 3183:             }
 3184:         }
 3185:     }
 3186:     return 'ok';
 3187: }
 3188: 
 3189: sub add_filetype {
 3190:     my ($allfiles,$file,$type)=@_;
 3191:     if (exists($allfiles->{$file})) {
 3192: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3193: 	    push(@{$allfiles->{$file}}, &escape($type));
 3194: 	}
 3195:     } else {
 3196: 	@{$allfiles->{$file}} = (&escape($type));
 3197:     }
 3198: }
 3199: 
 3200: sub embedded_dependency {
 3201:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3202:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3203:         if (($identifier ne '') &&
 3204:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3205:             ($pathfrom ne '')) {
 3206:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3207:             foreach my $dep (@{$related->{$identifier}}) {
 3208:                 &add_filetype($allfiles,$path.$dep,'object');
 3209:             }
 3210:         }
 3211:     }
 3212:     return;
 3213: }
 3214: 
 3215: sub removeuploadedurl {
 3216:     my ($url)=@_;	
 3217:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3218:     return &removeuserfile($uname,$udom,$fname);
 3219: }
 3220: 
 3221: sub removeuserfile {
 3222:     my ($docuname,$docudom,$fname)=@_;
 3223:     my $home=&homeserver($docuname,$docudom);    
 3224:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3225:     if ($result eq 'ok') {	
 3226:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3227:             my $metafile = $fname.'.meta';
 3228:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3229: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3230:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3231:             my $sqlresult = 
 3232:                 &update_portfolio_table($docuname,$docudom,$file,
 3233:                                         'portfolio_metadata',$group,
 3234:                                         'delete');
 3235:         }
 3236:     }
 3237:     return $result;
 3238: }
 3239: 
 3240: sub mkdiruserfile {
 3241:     my ($docuname,$docudom,$dir)=@_;
 3242:     my $home=&homeserver($docuname,$docudom);
 3243:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3244: }
 3245: 
 3246: sub renameuserfile {
 3247:     my ($docuname,$docudom,$old,$new)=@_;
 3248:     my $home=&homeserver($docuname,$docudom);
 3249:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3250:                         &escape("$old").':'.&escape("$new"),$home);
 3251:     if ($result eq 'ok') {
 3252:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3253:             my $oldmeta = $old.'.meta';
 3254:             my $newmeta = $new.'.meta';
 3255:             my $metaresult = 
 3256:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3257: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3258:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3259:             my $sqlresult = 
 3260:                 &update_portfolio_table($docuname,$docudom,$file,
 3261:                                         'portfolio_metadata',$group,
 3262:                                         'delete');
 3263:         }
 3264:     }
 3265:     return $result;
 3266: }
 3267: 
 3268: # ------------------------------------------------------------------------- Log
 3269: 
 3270: sub log {
 3271:     my ($dom,$nam,$hom,$what)=@_;
 3272:     return critical("log:$dom:$nam:$what",$hom);
 3273: }
 3274: 
 3275: # ------------------------------------------------------------------ Course Log
 3276: #
 3277: # This routine flushes several buffers of non-mission-critical nature
 3278: #
 3279: 
 3280: sub flushcourselogs {
 3281:     &logthis('Flushing log buffers');
 3282: #
 3283: # course logs
 3284: # This is a log of all transactions in a course, which can be used
 3285: # for data mining purposes
 3286: #
 3287: # It also collects the courseid database, which lists last transaction
 3288: # times and course titles for all courseids
 3289: #
 3290:     my %courseidbuffer=();
 3291:     foreach my $crsid (keys(%courselogs)) {
 3292:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3293: 		          &escape($courselogs{$crsid}),
 3294: 		          $coursehombuf{$crsid}) eq 'ok') {
 3295: 	    delete $courselogs{$crsid};
 3296:         } else {
 3297:             &logthis('Failed to flush log buffer for '.$crsid);
 3298:             if (length($courselogs{$crsid})>40000) {
 3299:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3300:                         " exceeded maximum size, deleting.</font>");
 3301:                delete $courselogs{$crsid};
 3302:             }
 3303:         }
 3304:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3305:             'description' => $coursedescrbuf{$crsid},
 3306:             'inst_code'    => $courseinstcodebuf{$crsid},
 3307:             'type'        => $coursetypebuf{$crsid},
 3308:             'owner'       => $courseownerbuf{$crsid},
 3309:         };
 3310:     }
 3311: #
 3312: # Write course id database (reverse lookup) to homeserver of courses 
 3313: # Is used in pickcourse
 3314: #
 3315:     foreach my $crs_home (keys(%courseidbuffer)) {
 3316:         my $response = &courseidput(&host_domain($crs_home),
 3317:                                     $courseidbuffer{$crs_home},
 3318:                                     $crs_home,'timeonly');
 3319:     }
 3320: #
 3321: # File accesses
 3322: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3323: #
 3324:     foreach my $entry (keys(%accesshash)) {
 3325:         if ($entry =~ /___count$/) {
 3326:             my ($dom,$name);
 3327:             ($dom,$name,undef)=
 3328: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3329:             if (! defined($dom) || $dom eq '' || 
 3330:                 ! defined($name) || $name eq '') {
 3331:                 my $cid = $env{'request.course.id'};
 3332:                 $dom  = $env{'request.'.$cid.'.domain'};
 3333:                 $name = $env{'request.'.$cid.'.num'};
 3334:             }
 3335:             my $value = $accesshash{$entry};
 3336:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3337:             my %temphash=($url => $value);
 3338:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3339:             if ($result eq 'ok') {
 3340:                 delete $accesshash{$entry};
 3341:             }
 3342:         } else {
 3343:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3344:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3345:             my %temphash=($entry => $accesshash{$entry});
 3346:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3347:                 delete $accesshash{$entry};
 3348:             }
 3349:         }
 3350:     }
 3351: #
 3352: # Roles
 3353: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3354: #
 3355:     foreach my $entry (keys(%userrolehash)) {
 3356:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3357: 	    split(/\:/,$entry);
 3358:         if (&Apache::lonnet::put('nohist_userroles',
 3359:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3360:                 $rudom,$runame) eq 'ok') {
 3361: 	    delete $userrolehash{$entry};
 3362:         }
 3363:     }
 3364: #
 3365: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3366: #
 3367:     my %domrolebuffer = ();
 3368:     foreach my $entry (keys(%domainrolehash)) {
 3369:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3370:         if ($domrolebuffer{$rudom}) {
 3371:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3372:                       '='.&escape($domainrolehash{$entry});
 3373:         } else {
 3374:             $domrolebuffer{$rudom}.=&escape($entry).
 3375:                       '='.&escape($domainrolehash{$entry});
 3376:         }
 3377:         delete $domainrolehash{$entry};
 3378:     }
 3379:     foreach my $dom (keys(%domrolebuffer)) {
 3380: 	my %servers = &get_servers($dom,'library');
 3381: 	foreach my $tryserver (keys(%servers)) {
 3382: 	    unless (&reply('domroleput:'.$dom.':'.
 3383: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3384: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3385: 	    }
 3386:         }
 3387:     }
 3388:     $dumpcount++;
 3389: }
 3390: 
 3391: sub courselog {
 3392:     my $what=shift;
 3393:     $what=time.':'.$what;
 3394:     unless ($env{'request.course.id'}) { return ''; }
 3395:     $coursedombuf{$env{'request.course.id'}}=
 3396:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3397:     $coursenumbuf{$env{'request.course.id'}}=
 3398:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3399:     $coursehombuf{$env{'request.course.id'}}=
 3400:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3401:     $coursedescrbuf{$env{'request.course.id'}}=
 3402:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3403:     $courseinstcodebuf{$env{'request.course.id'}}=
 3404:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3405:     $courseownerbuf{$env{'request.course.id'}}=
 3406:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3407:     $coursetypebuf{$env{'request.course.id'}}=
 3408:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3409:     if (defined $courselogs{$env{'request.course.id'}}) {
 3410: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3411:     } else {
 3412: 	$courselogs{$env{'request.course.id'}}.=$what;
 3413:     }
 3414:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3415: 	&flushcourselogs();
 3416:     }
 3417: }
 3418: 
 3419: sub courseacclog {
 3420:     my $fnsymb=shift;
 3421:     unless ($env{'request.course.id'}) { return ''; }
 3422:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3423:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3424:         $what.=':POST';
 3425:         # FIXME: Probably ought to escape things....
 3426: 	foreach my $key (keys(%env)) {
 3427:             if ($key=~/^form\.(.*)/) {
 3428:                 my $formitem = $1;
 3429:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3430:                     $what.=':'.$formitem.'='.$env{$key};
 3431:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3432:                     $what.=':'.$formitem.'='.$env{$key};
 3433:                 }
 3434:             }
 3435:         }
 3436:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3437:         # FIXME: We should not be depending on a form parameter that someone
 3438:         # editing lonsearchcat.pm might change in the future.
 3439:         if ($env{'form.phase'} eq 'course_search') {
 3440:             $what.= ':POST';
 3441:             # FIXME: Probably ought to escape things....
 3442:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3443:                                  'crsdiscuss') {
 3444:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3445:             }
 3446:         }
 3447:     }
 3448:     &courselog($what);
 3449: }
 3450: 
 3451: sub countacc {
 3452:     my $url=&declutter(shift);
 3453:     return if (! defined($url) || $url eq '');
 3454:     unless ($env{'request.course.id'}) { return ''; }
 3455: #
 3456: # Mark that this url was used in this course
 3457: #
 3458:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3459: #
 3460: # Increase the access count for this resource in this child process
 3461: #
 3462:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3463:     $accesshash{$key}++;
 3464: }
 3465: 
 3466: sub linklog {
 3467:     my ($from,$to)=@_;
 3468:     $from=&declutter($from);
 3469:     $to=&declutter($to);
 3470:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3471:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3472: }
 3473: 
 3474: sub statslog {
 3475:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3476:     if ($users<2) { return; }
 3477:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3478:             'course'       => $env{'request.course.id'},
 3479:             'sections'     => '"all"',
 3480:             'num_students' => $users,
 3481:             'part'         => $part,
 3482:             'symb'         => $symb,
 3483:             'mean_tries'   => $av_attempts,
 3484:             'deg_of_diff'  => $degdiff});
 3485:     foreach my $key (keys(%dynstore)) {
 3486:         $accesshash{$key}=$dynstore{$key};
 3487:     }
 3488: }
 3489:   
 3490: sub userrolelog {
 3491:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3492:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 3493:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 3494:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 3495:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 3496:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3497:        $userrolehash
 3498:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3499:                     =$tend.':'.$tstart;
 3500:     }
 3501:     if (($env{'request.role'} =~ /dc\./) &&
 3502: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 3503: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 3504: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 3505:          ($trole=~/^co/))) {
 3506:        $userrolehash
 3507:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3508:                     =$tend.':'.$tstart;
 3509:     }
 3510:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 3511:         ($trole=~/^li/) || ($trole=~/^li/) ||
 3512:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 3513:         ($trole=~/^sc/)) {
 3514:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3515:        $domainrolehash
 3516:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3517:                     = $tend.':'.$tstart;
 3518:     }
 3519: }
 3520: 
 3521: sub courserolelog {
 3522:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3523:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3524:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3525:         ($trole eq 'ta') || ($trole eq 'st') ||
 3526:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3527:         ($trole eq 'co')) {
 3528:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3529:             my $cdom = $1;
 3530:             my $cnum = $2;
 3531:             my $sec = $3;
 3532:             my $namespace = 'rolelog';
 3533:             my %storehash = (
 3534:                                role    => $trole,
 3535:                                start   => $tstart,
 3536:                                end     => $tend,
 3537:                                selfenroll => $selfenroll,
 3538:                                context    => $context,
 3539:                             );
 3540:             if ($trole eq 'gr') {
 3541:                 $namespace = 'groupslog';
 3542:                 $storehash{'group'} = $sec;
 3543:             } else {
 3544:                 $storehash{'section'} = $sec;
 3545:             }
 3546:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3547:             if (($trole ne 'st') || ($sec ne '')) {
 3548:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3549:             }
 3550:         }
 3551:     }
 3552:     return;
 3553: }
 3554: 
 3555: sub get_course_adv_roles {
 3556:     my ($cid,$codes) = @_;
 3557:     $cid=$env{'request.course.id'} unless (defined($cid));
 3558:     my %coursehash=&coursedescription($cid);
 3559:     my $crstype = &Apache::loncommon::course_type($cid);
 3560:     my %nothide=();
 3561:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3562:         if ($user !~ /:/) {
 3563: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3564:         } else {
 3565:             $nothide{$user}=1;
 3566:         }
 3567:     }
 3568:     my %returnhash=();
 3569:     my %dumphash=
 3570:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3571:     my $now=time;
 3572:     my %privileged;
 3573:     foreach my $entry (keys(%dumphash)) {
 3574: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3575:         if (($tstart) && ($tstart<0)) { next; }
 3576:         if (($tend) && ($tend<$now)) { next; }
 3577:         if (($tstart) && ($now<$tstart)) { next; }
 3578:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3579: 	if ($username eq '' || $domain eq '') { next; }
 3580:         unless (ref($privileged{$domain}) eq 'HASH') {
 3581:             my %dompersonnel =
 3582:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3583:             $privileged{$domain} = {};
 3584:             foreach my $server (keys(%dompersonnel)) {
 3585:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3586:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3587:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3588:                         $privileged{$udom}{$uname} = 1;
 3589:                     }
 3590:                 }
 3591:             }
 3592:         }
 3593:         if ((exists($privileged{$domain}{$username})) && 
 3594:             (!$nothide{$username.':'.$domain})) { next; }
 3595: 	if ($role eq 'cr') { next; }
 3596:         if ($codes) {
 3597:             if ($section) { $role .= ':'.$section; }
 3598:             if ($returnhash{$role}) {
 3599:                 $returnhash{$role}.=','.$username.':'.$domain;
 3600:             } else {
 3601:                 $returnhash{$role}=$username.':'.$domain;
 3602:             }
 3603:         } else {
 3604:             my $key=&plaintext($role,$crstype);
 3605:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3606:             if ($returnhash{$key}) {
 3607: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3608:             } else {
 3609:                 $returnhash{$key}=$username.':'.$domain;
 3610:             }
 3611:         }
 3612:     }
 3613:     return %returnhash;
 3614: }
 3615: 
 3616: sub get_my_roles {
 3617:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3618:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3619:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3620:     my (%dumphash,%nothide);
 3621:     if ($context eq 'userroles') {
 3622:         %dumphash = &dump('roles',$udom,$uname);
 3623:     } else {
 3624:         %dumphash=
 3625:             &dump('nohist_userroles',$udom,$uname);
 3626:         if ($hidepriv) {
 3627:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3628:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3629:                 if ($user !~ /:/) {
 3630:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3631:                 } else {
 3632:                     $nothide{$user} = 1;
 3633:                 }
 3634:             }
 3635:         }
 3636:     }
 3637:     my %returnhash=();
 3638:     my $now=time;
 3639:     my %privileged;
 3640:     foreach my $entry (keys(%dumphash)) {
 3641:         my ($role,$tend,$tstart);
 3642:         if ($context eq 'userroles') {
 3643:             next if ($entry =~ /^rolesdef/);
 3644: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3645:         } else {
 3646:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3647:         }
 3648:         if (($tstart) && ($tstart<0)) { next; }
 3649:         my $status = 'active';
 3650:         if (($tend) && ($tend<=$now)) {
 3651:             $status = 'previous';
 3652:         } 
 3653:         if (($tstart) && ($now<$tstart)) {
 3654:             $status = 'future';
 3655:         }
 3656:         if (ref($types) eq 'ARRAY') {
 3657:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3658:                 next;
 3659:             } 
 3660:         } else {
 3661:             if ($status ne 'active') {
 3662:                 next;
 3663:             }
 3664:         }
 3665:         my ($rolecode,$username,$domain,$section,$area);
 3666:         if ($context eq 'userroles') {
 3667:             ($area,$rolecode) = split(/_/,$entry);
 3668:             (undef,$domain,$username,$section) = split(/\//,$area);
 3669:         } else {
 3670:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3671:         }
 3672:         if (ref($roledoms) eq 'ARRAY') {
 3673:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3674:                 next;
 3675:             }
 3676:         }
 3677:         if (ref($roles) eq 'ARRAY') {
 3678:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3679:                 if ($role =~ /^cr\//) {
 3680:                     if (!grep(/^cr$/,@{$roles})) {
 3681:                         next;
 3682:                     }
 3683:                 } elsif ($role =~ /^gr\//) {
 3684:                     if (!grep(/^gr$/,@{$roles})) {
 3685:                         next;
 3686:                     }
 3687:                 } else {
 3688:                     next;
 3689:                 }
 3690:             }
 3691:         }
 3692:         if ($hidepriv) {
 3693:             if ($context eq 'userroles') {
 3694:                 if ((&privileged($username,$domain)) &&
 3695:                     (!$nothide{$username.':'.$domain})) {
 3696:                     next;
 3697:                 }
 3698:             } else {
 3699:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3700:                     my %dompersonnel =
 3701:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3702:                     $privileged{$domain} = {};
 3703:                     if (keys(%dompersonnel)) {
 3704:                         foreach my $server (keys(%dompersonnel)) {
 3705:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3706:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3707:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3708:                                     $privileged{$udom}{$uname} = $trole;
 3709:                                 }
 3710:                             }
 3711:                         }
 3712:                     }
 3713:                 }
 3714:                 if (exists($privileged{$domain}{$username})) {
 3715:                     if (!$nothide{$username.':'.$domain}) {
 3716:                         next;
 3717:                     }
 3718:                 }
 3719:             }
 3720:         }
 3721:         if ($withsec) {
 3722:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3723:                 $tstart.':'.$tend;
 3724:         } else {
 3725:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3726:         }
 3727:     }
 3728:     return %returnhash;
 3729: }
 3730: 
 3731: # ----------------------------------------------------- Frontpage Announcements
 3732: #
 3733: #
 3734: 
 3735: sub postannounce {
 3736:     my ($server,$text)=@_;
 3737:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3738:     unless ($text=~/\w/) { $text=''; }
 3739:     return &reply('setannounce:'.&escape($text),$server);
 3740: }
 3741: 
 3742: sub getannounce {
 3743: 
 3744:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3745: 	my $announcement='';
 3746: 	while (my $line = <$fh>) { $announcement .= $line; }
 3747: 	close($fh);
 3748: 	if ($announcement=~/\w/) { 
 3749: 	    return 
 3750:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3751:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3752: 	} else {
 3753: 	    return '';
 3754: 	}
 3755:     } else {
 3756: 	return '';
 3757:     }
 3758: }
 3759: 
 3760: # ---------------------------------------------------------- Course ID routines
 3761: # Deal with domain's nohist_courseid.db files
 3762: #
 3763: 
 3764: sub courseidput {
 3765:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3766:     return unless (ref($storehash) eq 'HASH');
 3767:     my $outcome;
 3768:     if ($caller eq 'timeonly') {
 3769:         my $cids = '';
 3770:         foreach my $item (keys(%$storehash)) {
 3771:             $cids.=&escape($item).'&';
 3772:         }
 3773:         $cids=~s/\&$//;
 3774:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3775:                           $coursehome);       
 3776:     } else {
 3777:         my $items = '';
 3778:         foreach my $item (keys(%$storehash)) {
 3779:             $items.= &escape($item).'='.
 3780:                      &freeze_escape($$storehash{$item}).'&';
 3781:         }
 3782:         $items=~s/\&$//;
 3783:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3784:                           $coursehome);
 3785:     }
 3786:     if ($outcome eq 'unknown_cmd') {
 3787:         my $what;
 3788:         foreach my $cid (keys(%$storehash)) {
 3789:             $what .= &escape($cid).'=';
 3790:             foreach my $item ('description','inst_code','owner','type') {
 3791:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3792:             }
 3793:             $what =~ s/\:$/&/;
 3794:         }
 3795:         $what =~ s/\&$//;  
 3796:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3797:     } else {
 3798:         return $outcome;
 3799:     }
 3800: }
 3801: 
 3802: sub courseiddump {
 3803:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3804:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3805:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3806:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3807:     my $as_hash = 1;
 3808:     my %returnhash;
 3809:     if (!$domfilter) { $domfilter=''; }
 3810:     my %libserv = &all_library();
 3811:     foreach my $tryserver (keys(%libserv)) {
 3812:         if ( (  $hostidflag == 1 
 3813: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3814: 	     || (!defined($hostidflag)) ) {
 3815: 
 3816: 	    if (($domfilter eq '') ||
 3817: 		(&host_domain($tryserver) eq $domfilter)) {
 3818:                 my $rep = 
 3819:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3820:                          $sincefilter.':'.&escape($descfilter).':'.
 3821:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3822:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3823:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3824:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3825:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3826:                          &escape($cc_clone).':'.$cloneonly.':'.
 3827:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3828:                          &escape($creationcontext).':'.$domcloner,
 3829:                          $tryserver);
 3830:                 my @pairs=split(/\&/,$rep);
 3831:                 foreach my $item (@pairs) {
 3832:                     my ($key,$value)=split(/\=/,$item,2);
 3833:                     $key = &unescape($key);
 3834:                     next if ($key =~ /^error: 2 /);
 3835:                     my $result = &thaw_unescape($value);
 3836:                     if (ref($result) eq 'HASH') {
 3837:                         $returnhash{$key}=$result;
 3838:                     } else {
 3839:                         my @responses = split(/:/,$value);
 3840:                         my @items = ('description','inst_code','owner','type');
 3841:                         for (my $i=0; $i<@responses; $i++) {
 3842:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3843:                         }
 3844:                     }
 3845:                 }
 3846:             }
 3847:         }
 3848:     }
 3849:     return %returnhash;
 3850: }
 3851: 
 3852: sub courselastaccess {
 3853:     my ($cdom,$cnum,$hostidref) = @_;
 3854:     my %returnhash;
 3855:     if ($cdom && $cnum) {
 3856:         my $chome = &homeserver($cnum,$cdom);
 3857:         if ($chome ne 'no_host') {
 3858:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3859:             &extract_lastaccess(\%returnhash,$rep);
 3860:         }
 3861:     } else {
 3862:         if (!$cdom) { $cdom=''; }
 3863:         my %libserv = &all_library();
 3864:         foreach my $tryserver (keys(%libserv)) {
 3865:             if (ref($hostidref) eq 'ARRAY') {
 3866:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3867:             } 
 3868:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3869:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3870:                 &extract_lastaccess(\%returnhash,$rep);
 3871:             }
 3872:         }
 3873:     }
 3874:     return %returnhash;
 3875: }
 3876: 
 3877: sub extract_lastaccess {
 3878:     my ($returnhash,$rep) = @_;
 3879:     if (ref($returnhash) eq 'HASH') {
 3880:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3881:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3882:                  $rep eq '') {
 3883:             my @pairs=split(/\&/,$rep);
 3884:             foreach my $item (@pairs) {
 3885:                 my ($key,$value)=split(/\=/,$item,2);
 3886:                 $key = &unescape($key);
 3887:                 next if ($key =~ /^error: 2 /);
 3888:                 $returnhash->{$key} = &thaw_unescape($value);
 3889:             }
 3890:         }
 3891:     }
 3892:     return;
 3893: }
 3894: 
 3895: # ---------------------------------------------------------- DC e-mail
 3896: 
 3897: sub dcmailput {
 3898:     my ($domain,$msgid,$message,$server)=@_;
 3899:     my $status = &Apache::lonnet::critical(
 3900:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3901:        &escape($message),$server);
 3902:     return $status;
 3903: }
 3904: 
 3905: sub dcmaildump {
 3906:     my ($dom,$startdate,$enddate,$senders) = @_;
 3907:     my %returnhash=();
 3908: 
 3909:     if (defined(&domain($dom,'primary'))) {
 3910:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3911:                                                          &escape($enddate).':';
 3912: 	my @esc_senders=map { &escape($_)} @$senders;
 3913: 	$cmd.=&escape(join('&',@esc_senders));
 3914: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3915:             my ($key,$value) = split(/\=/,$line,2);
 3916:             if (($key) && ($value)) {
 3917:                 $returnhash{&unescape($key)} = &unescape($value);
 3918:             }
 3919:         }
 3920:     }
 3921:     return %returnhash;
 3922: }
 3923: # ---------------------------------------------------------- Domain roles
 3924: 
 3925: sub get_domain_roles {
 3926:     my ($dom,$roles,$startdate,$enddate)=@_;
 3927:     if ((!defined($startdate)) || ($startdate eq '')) {
 3928:         $startdate = '.';
 3929:     }
 3930:     if ((!defined($enddate)) || ($enddate eq '')) {
 3931:         $enddate = '.';
 3932:     }
 3933:     my $rolelist;
 3934:     if (ref($roles) eq 'ARRAY') {
 3935:         $rolelist = join(':',@{$roles});
 3936:     }
 3937:     my %personnel = ();
 3938: 
 3939:     my %servers = &get_servers($dom,'library');
 3940:     foreach my $tryserver (keys(%servers)) {
 3941: 	%{$personnel{$tryserver}}=();
 3942: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3943: 					    &escape($startdate).':'.
 3944: 					    &escape($enddate).':'.
 3945: 					    &escape($rolelist), $tryserver))) {
 3946: 	    my ($key,$value) = split(/\=/,$line,2);
 3947: 	    if (($key) && ($value)) {
 3948: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3949: 	    }
 3950: 	}
 3951:     }
 3952:     return %personnel;
 3953: }
 3954: 
 3955: # ----------------------------------------------------------- Interval timing 
 3956: 
 3957: {
 3958: # Caches needed for speedup of navmaps
 3959: # We don't want to cache this for very long at all (5 seconds at most)
 3960: # 
 3961: # The user for whom we cache
 3962: my $cachedkey='';
 3963: # The cached times for this user
 3964: my %cachedtimes=();
 3965: # When this was last done
 3966: my $cachedtime=();
 3967: 
 3968: sub load_all_first_access {
 3969:     my ($uname,$udom)=@_;
 3970:     if (($cachedkey eq $uname.':'.$udom) &&
 3971:         (abs($cachedtime-time)<5)) {
 3972:         return;
 3973:     }
 3974:     $cachedtime=time;
 3975:     $cachedkey=$uname.':'.$udom;
 3976:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 3977: }
 3978: 
 3979: sub get_first_access {
 3980:     my ($type,$argsymb,$argmap)=@_;
 3981:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3982:     if ($argsymb) { $symb=$argsymb; }
 3983:     my ($map,$id,$res)=&decode_symb($symb);
 3984:     if ($argmap) { $map = $argmap; }
 3985:     if ($type eq 'course') {
 3986: 	$res='course';
 3987:     } elsif ($type eq 'map') {
 3988: 	$res=&symbread($map);
 3989:     } else {
 3990: 	$res=$symb;
 3991:     }
 3992:     &load_all_first_access($uname,$udom);
 3993:     return $cachedtimes{"$courseid\0$res"};
 3994: }
 3995: 
 3996: sub set_first_access {
 3997:     my ($type,$interval)=@_;
 3998:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3999:     my ($map,$id,$res)=&decode_symb($symb);
 4000:     if ($type eq 'course') {
 4001: 	$res='course';
 4002:     } elsif ($type eq 'map') {
 4003: 	$res=&symbread($map);
 4004:     } else {
 4005: 	$res=$symb;
 4006:     }
 4007:     $cachedkey='';
 4008:     my $firstaccess=&get_first_access($type,$symb,$map);
 4009:     if (!$firstaccess) {
 4010:         my $start = time;
 4011: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4012:                           $udom,$uname);
 4013:         if ($putres eq 'ok') {
 4014:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4015:                  $udom,$uname); 
 4016:             &appenv(
 4017:                      {
 4018:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4019:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4020:                      }
 4021:                   );
 4022:         }
 4023:         return $putres;
 4024:     }
 4025:     return 'already_set';
 4026: }
 4027: }
 4028: # --------------------------------------------- Set Expire Date for Spreadsheet
 4029: 
 4030: sub expirespread {
 4031:     my ($uname,$udom,$stype,$usymb)=@_;
 4032:     my $cid=$env{'request.course.id'}; 
 4033:     if ($cid) {
 4034:        my $now=time;
 4035:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4036:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4037:                             $env{'course.'.$cid.'.num'}.
 4038: 	        	    ':nohist_expirationdates:'.
 4039:                             &escape($key).'='.$now,
 4040:                             $env{'course.'.$cid.'.home'})
 4041:     }
 4042:     return 'ok';
 4043: }
 4044: 
 4045: # ----------------------------------------------------- Devalidate Spreadsheets
 4046: 
 4047: sub devalidate {
 4048:     my ($symb,$uname,$udom)=@_;
 4049:     my $cid=$env{'request.course.id'}; 
 4050:     if ($cid) {
 4051:         # delete the stored spreadsheets for
 4052:         # - the student level sheet of this user in course's homespace
 4053:         # - the assessment level sheet for this resource 
 4054:         #   for this user in user's homespace
 4055: 	# - current conditional state info
 4056: 	my $key=$uname.':'.$udom.':';
 4057:         my $status=
 4058: 	    &del('nohist_calculatedsheets',
 4059: 		 [$key.'studentcalc:'],
 4060: 		 $env{'course.'.$cid.'.domain'},
 4061: 		 $env{'course.'.$cid.'.num'})
 4062: 		.' '.
 4063: 	    &del('nohist_calculatedsheets_'.$cid,
 4064: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4065:         unless ($status eq 'ok ok') {
 4066:            &logthis('Could not devalidate spreadsheet '.
 4067:                     $uname.' at '.$udom.' for '.
 4068: 		    $symb.': '.$status);
 4069:         }
 4070: 	&delenv('user.state.'.$cid);
 4071:     }
 4072: }
 4073: 
 4074: sub get_scalar {
 4075:     my ($string,$end) = @_;
 4076:     my $value;
 4077:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4078: 	$value = $1;
 4079:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4080: 	$value = $1;
 4081:     }
 4082:     return &unescape($value);
 4083: }
 4084: 
 4085: sub array2str {
 4086:   my (@array) = @_;
 4087:   my $result=&arrayref2str(\@array);
 4088:   $result=~s/^__ARRAY_REF__//;
 4089:   $result=~s/__END_ARRAY_REF__$//;
 4090:   return $result;
 4091: }
 4092: 
 4093: sub arrayref2str {
 4094:   my ($arrayref) = @_;
 4095:   my $result='__ARRAY_REF__';
 4096:   foreach my $elem (@$arrayref) {
 4097:     if(ref($elem) eq 'ARRAY') {
 4098:       $result.=&arrayref2str($elem).'&';
 4099:     } elsif(ref($elem) eq 'HASH') {
 4100:       $result.=&hashref2str($elem).'&';
 4101:     } elsif(ref($elem)) {
 4102:       #print("Got a ref of ".(ref($elem))." skipping.");
 4103:     } else {
 4104:       $result.=&escape($elem).'&';
 4105:     }
 4106:   }
 4107:   $result=~s/\&$//;
 4108:   $result .= '__END_ARRAY_REF__';
 4109:   return $result;
 4110: }
 4111: 
 4112: sub hash2str {
 4113:   my (%hash) = @_;
 4114:   my $result=&hashref2str(\%hash);
 4115:   $result=~s/^__HASH_REF__//;
 4116:   $result=~s/__END_HASH_REF__$//;
 4117:   return $result;
 4118: }
 4119: 
 4120: sub hashref2str {
 4121:   my ($hashref)=@_;
 4122:   my $result='__HASH_REF__';
 4123:   foreach my $key (sort(keys(%$hashref))) {
 4124:     if (ref($key) eq 'ARRAY') {
 4125:       $result.=&arrayref2str($key).'=';
 4126:     } elsif (ref($key) eq 'HASH') {
 4127:       $result.=&hashref2str($key).'=';
 4128:     } elsif (ref($key)) {
 4129:       $result.='=';
 4130:       #print("Got a ref of ".(ref($key))." skipping.");
 4131:     } else {
 4132: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4133:     }
 4134: 
 4135:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4136:       $result.=&arrayref2str($hashref->{$key}).'&';
 4137:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4138:       $result.=&hashref2str($hashref->{$key}).'&';
 4139:     } elsif(ref($hashref->{$key})) {
 4140:        $result.='&';
 4141:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4142:     } else {
 4143:       $result.=&escape($hashref->{$key}).'&';
 4144:     }
 4145:   }
 4146:   $result=~s/\&$//;
 4147:   $result .= '__END_HASH_REF__';
 4148:   return $result;
 4149: }
 4150: 
 4151: sub str2hash {
 4152:     my ($string)=@_;
 4153:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4154:     return %$hash;
 4155: }
 4156: 
 4157: sub str2hashref {
 4158:   my ($string) = @_;
 4159: 
 4160:   my %hash;
 4161: 
 4162:   if($string !~ /^__HASH_REF__/) {
 4163:       if (! ($string eq '' || !defined($string))) {
 4164: 	  $hash{'error'}='Not hash reference';
 4165:       }
 4166:       return (\%hash, $string);
 4167:   }
 4168: 
 4169:   $string =~ s/^__HASH_REF__//;
 4170: 
 4171:   while($string !~ /^__END_HASH_REF__/) {
 4172:       #key
 4173:       my $key='';
 4174:       if($string =~ /^__HASH_REF__/) {
 4175:           ($key, $string)=&str2hashref($string);
 4176:           if(defined($key->{'error'})) {
 4177:               $hash{'error'}='Bad data';
 4178:               return (\%hash, $string);
 4179:           }
 4180:       } elsif($string =~ /^__ARRAY_REF__/) {
 4181:           ($key, $string)=&str2arrayref($string);
 4182:           if($key->[0] eq 'Array reference error') {
 4183:               $hash{'error'}='Bad data';
 4184:               return (\%hash, $string);
 4185:           }
 4186:       } else {
 4187:           $string =~ s/^(.*?)=//;
 4188: 	  $key=&unescape($1);
 4189:       }
 4190:       $string =~ s/^=//;
 4191: 
 4192:       #value
 4193:       my $value='';
 4194:       if($string =~ /^__HASH_REF__/) {
 4195:           ($value, $string)=&str2hashref($string);
 4196:           if(defined($value->{'error'})) {
 4197:               $hash{'error'}='Bad data';
 4198:               return (\%hash, $string);
 4199:           }
 4200:       } elsif($string =~ /^__ARRAY_REF__/) {
 4201:           ($value, $string)=&str2arrayref($string);
 4202:           if($value->[0] eq 'Array reference error') {
 4203:               $hash{'error'}='Bad data';
 4204:               return (\%hash, $string);
 4205:           }
 4206:       } else {
 4207: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4208:       }
 4209:       $string =~ s/^&//;
 4210: 
 4211:       $hash{$key}=$value;
 4212:   }
 4213: 
 4214:   $string =~ s/^__END_HASH_REF__//;
 4215: 
 4216:   return (\%hash, $string);
 4217: }
 4218: 
 4219: sub str2array {
 4220:     my ($string)=@_;
 4221:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4222:     return @$array;
 4223: }
 4224: 
 4225: sub str2arrayref {
 4226:   my ($string) = @_;
 4227:   my @array;
 4228: 
 4229:   if($string !~ /^__ARRAY_REF__/) {
 4230:       if (! ($string eq '' || !defined($string))) {
 4231: 	  $array[0]='Array reference error';
 4232:       }
 4233:       return (\@array, $string);
 4234:   }
 4235: 
 4236:   $string =~ s/^__ARRAY_REF__//;
 4237: 
 4238:   while($string !~ /^__END_ARRAY_REF__/) {
 4239:       my $value='';
 4240:       if($string =~ /^__HASH_REF__/) {
 4241:           ($value, $string)=&str2hashref($string);
 4242:           if(defined($value->{'error'})) {
 4243:               $array[0] ='Array reference error';
 4244:               return (\@array, $string);
 4245:           }
 4246:       } elsif($string =~ /^__ARRAY_REF__/) {
 4247:           ($value, $string)=&str2arrayref($string);
 4248:           if($value->[0] eq 'Array reference error') {
 4249:               $array[0] ='Array reference error';
 4250:               return (\@array, $string);
 4251:           }
 4252:       } else {
 4253: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4254:       }
 4255:       $string =~ s/^&//;
 4256: 
 4257:       push(@array, $value);
 4258:   }
 4259: 
 4260:   $string =~ s/^__END_ARRAY_REF__//;
 4261: 
 4262:   return (\@array, $string);
 4263: }
 4264: 
 4265: # -------------------------------------------------------------------Temp Store
 4266: 
 4267: sub tmpreset {
 4268:   my ($symb,$namespace,$domain,$stuname) = @_;
 4269:   if (!$symb) {
 4270:     $symb=&symbread();
 4271:     if (!$symb) { $symb= $env{'request.url'}; }
 4272:   }
 4273:   $symb=escape($symb);
 4274: 
 4275:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4276:   $namespace=~s/\//\_/g;
 4277:   $namespace=~s/\W//g;
 4278: 
 4279:   if (!$domain) { $domain=$env{'user.domain'}; }
 4280:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4281:   if ($domain eq 'public' && $stuname eq 'public') {
 4282:       $stuname=$ENV{'REMOTE_ADDR'};
 4283:   }
 4284:   my $path=LONCAPA::tempdir();
 4285:   my %hash;
 4286:   if (tie(%hash,'GDBM_File',
 4287: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4288: 	  &GDBM_WRCREAT(),0640)) {
 4289:     foreach my $key (keys(%hash)) {
 4290:       if ($key=~ /:$symb/) {
 4291: 	delete($hash{$key});
 4292:       }
 4293:     }
 4294:   }
 4295: }
 4296: 
 4297: sub tmpstore {
 4298:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4299: 
 4300:   if (!$symb) {
 4301:     $symb=&symbread();
 4302:     if (!$symb) { $symb= $env{'request.url'}; }
 4303:   }
 4304:   $symb=escape($symb);
 4305: 
 4306:   if (!$namespace) {
 4307:     # I don't think we would ever want to store this for a course.
 4308:     # it seems this will only be used if we don't have a course.
 4309:     #$namespace=$env{'request.course.id'};
 4310:     #if (!$namespace) {
 4311:       $namespace=$env{'request.state'};
 4312:     #}
 4313:   }
 4314:   $namespace=~s/\//\_/g;
 4315:   $namespace=~s/\W//g;
 4316:   if (!$domain) { $domain=$env{'user.domain'}; }
 4317:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4318:   if ($domain eq 'public' && $stuname eq 'public') {
 4319:       $stuname=$ENV{'REMOTE_ADDR'};
 4320:   }
 4321:   my $now=time;
 4322:   my %hash;
 4323:   my $path=LONCAPA::tempdir();
 4324:   if (tie(%hash,'GDBM_File',
 4325: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4326: 	  &GDBM_WRCREAT(),0640)) {
 4327:     $hash{"version:$symb"}++;
 4328:     my $version=$hash{"version:$symb"};
 4329:     my $allkeys=''; 
 4330:     foreach my $key (keys(%$storehash)) {
 4331:       $allkeys.=$key.':';
 4332:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4333:     }
 4334:     $hash{"$version:$symb:timestamp"}=$now;
 4335:     $allkeys.='timestamp';
 4336:     $hash{"$version:keys:$symb"}=$allkeys;
 4337:     if (untie(%hash)) {
 4338:       return 'ok';
 4339:     } else {
 4340:       return "error:$!";
 4341:     }
 4342:   } else {
 4343:     return "error:$!";
 4344:   }
 4345: }
 4346: 
 4347: # -----------------------------------------------------------------Temp Restore
 4348: 
 4349: sub tmprestore {
 4350:   my ($symb,$namespace,$domain,$stuname) = @_;
 4351: 
 4352:   if (!$symb) {
 4353:     $symb=&symbread();
 4354:     if (!$symb) { $symb= $env{'request.url'}; }
 4355:   }
 4356:   $symb=escape($symb);
 4357: 
 4358:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4359: 
 4360:   if (!$domain) { $domain=$env{'user.domain'}; }
 4361:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4362:   if ($domain eq 'public' && $stuname eq 'public') {
 4363:       $stuname=$ENV{'REMOTE_ADDR'};
 4364:   }
 4365:   my %returnhash;
 4366:   $namespace=~s/\//\_/g;
 4367:   $namespace=~s/\W//g;
 4368:   my %hash;
 4369:   my $path=LONCAPA::tempdir();
 4370:   if (tie(%hash,'GDBM_File',
 4371: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4372: 	  &GDBM_READER(),0640)) {
 4373:     my $version=$hash{"version:$symb"};
 4374:     $returnhash{'version'}=$version;
 4375:     my $scope;
 4376:     for ($scope=1;$scope<=$version;$scope++) {
 4377:       my $vkeys=$hash{"$scope:keys:$symb"};
 4378:       my @keys=split(/:/,$vkeys);
 4379:       my $key;
 4380:       $returnhash{"$scope:keys"}=$vkeys;
 4381:       foreach $key (@keys) {
 4382: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4383: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4384:       }
 4385:     }
 4386:     if (!(untie(%hash))) {
 4387:       return "error:$!";
 4388:     }
 4389:   } else {
 4390:     return "error:$!";
 4391:   }
 4392:   return %returnhash;
 4393: }
 4394: 
 4395: # ----------------------------------------------------------------------- Store
 4396: 
 4397: sub store {
 4398:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4399:     my $home='';
 4400: 
 4401:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4402: 
 4403:     $symb=&symbclean($symb);
 4404:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4405: 
 4406:     if (!$domain) { $domain=$env{'user.domain'}; }
 4407:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4408: 
 4409:     &devalidate($symb,$stuname,$domain);
 4410: 
 4411:     $symb=escape($symb);
 4412:     if (!$namespace) { 
 4413:        unless ($namespace=$env{'request.course.id'}) { 
 4414:           return ''; 
 4415:        } 
 4416:     }
 4417:     if (!$home) { $home=$env{'user.home'}; }
 4418: 
 4419:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4420:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4421: 
 4422:     my $namevalue='';
 4423:     foreach my $key (keys(%$storehash)) {
 4424:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4425:     }
 4426:     $namevalue=~s/\&$//;
 4427:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4428:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4429: }
 4430: 
 4431: # -------------------------------------------------------------- Critical Store
 4432: 
 4433: sub cstore {
 4434:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4435:     my $home='';
 4436: 
 4437:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4438: 
 4439:     $symb=&symbclean($symb);
 4440:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4441: 
 4442:     if (!$domain) { $domain=$env{'user.domain'}; }
 4443:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4444: 
 4445:     &devalidate($symb,$stuname,$domain);
 4446: 
 4447:     $symb=escape($symb);
 4448:     if (!$namespace) { 
 4449:        unless ($namespace=$env{'request.course.id'}) { 
 4450:           return ''; 
 4451:        } 
 4452:     }
 4453:     if (!$home) { $home=$env{'user.home'}; }
 4454: 
 4455:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4456:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4457: 
 4458:     my $namevalue='';
 4459:     foreach my $key (keys(%$storehash)) {
 4460:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4461:     }
 4462:     $namevalue=~s/\&$//;
 4463:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4464:     return critical
 4465:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4466: }
 4467: 
 4468: # --------------------------------------------------------------------- Restore
 4469: 
 4470: sub restore {
 4471:     my ($symb,$namespace,$domain,$stuname) = @_;
 4472:     my $home='';
 4473: 
 4474:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4475: 
 4476:     if (!$symb) {
 4477:       unless ($symb=escape(&symbread())) { return ''; }
 4478:     } else {
 4479:       $symb=&escape(&symbclean($symb));
 4480:     }
 4481:     if (!$namespace) { 
 4482:        unless ($namespace=$env{'request.course.id'}) { 
 4483:           return ''; 
 4484:        } 
 4485:     }
 4486:     if (!$domain) { $domain=$env{'user.domain'}; }
 4487:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4488:     if (!$home) { $home=$env{'user.home'}; }
 4489:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4490: 
 4491:     my %returnhash=();
 4492:     foreach my $line (split(/\&/,$answer)) {
 4493: 	my ($name,$value)=split(/\=/,$line);
 4494:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4495:     }
 4496:     my $version;
 4497:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4498:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4499:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4500:        }
 4501:     }
 4502:     return %returnhash;
 4503: }
 4504: 
 4505: # ---------------------------------------------------------- Course Description
 4506: #
 4507: #  
 4508: 
 4509: sub coursedescription {
 4510:     my ($courseid,$args)=@_;
 4511:     $courseid=~s/^\///;
 4512:     $courseid=~s/\_/\//g;
 4513:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4514:     my $chome=&homeserver($cnum,$cdomain);
 4515:     my $normalid=$cdomain.'_'.$cnum;
 4516:     # need to always cache even if we get errors otherwise we keep 
 4517:     # trying and trying and trying to get the course description.
 4518:     my %envhash=();
 4519:     my %returnhash=();
 4520:     
 4521:     my $expiretime=600;
 4522:     if ($env{'request.course.id'} eq $normalid) {
 4523: 	$expiretime=120;
 4524:     }
 4525: 
 4526:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4527:     if (!$args->{'freshen_cache'}
 4528: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4529: 	foreach my $key (keys(%env)) {
 4530: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4531: 	    my ($setting) = $1;
 4532: 	    $returnhash{$setting} = $env{$key};
 4533: 	}
 4534: 	return %returnhash;
 4535:     }
 4536: 
 4537:     # get the data again
 4538: 
 4539:     if (!$args->{'one_time'}) {
 4540: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4541:     }
 4542: 
 4543:     if ($chome ne 'no_host') {
 4544:        %returnhash=&dump('environment',$cdomain,$cnum);
 4545:        if (!exists($returnhash{'con_lost'})) {
 4546: 	   my $username = $env{'user.name'}; # Defult username
 4547: 	   if(defined $args->{'user'}) {
 4548: 	       $username = $args->{'user'};
 4549: 	   }
 4550:            $returnhash{'home'}= $chome;
 4551: 	   $returnhash{'domain'} = $cdomain;
 4552: 	   $returnhash{'num'} = $cnum;
 4553:            if (!defined($returnhash{'type'})) {
 4554:                $returnhash{'type'} = 'Course';
 4555:            }
 4556:            while (my ($name,$value) = each %returnhash) {
 4557:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4558:            }
 4559:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4560:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4561: 	       $username.'_'.$cdomain.'_'.$cnum;
 4562:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4563:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4564:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4565:        }
 4566:     }
 4567:     if (!$args->{'one_time'}) {
 4568: 	&appenv(\%envhash);
 4569:     }
 4570:     return %returnhash;
 4571: }
 4572: 
 4573: sub update_released_required {
 4574:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4575:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4576:         $cid = $env{'request.course.id'};
 4577:         $cdom = $env{'course.'.$cid.'.domain'};
 4578:         $cnum = $env{'course.'.$cid.'.num'};
 4579:         $chome = $env{'course.'.$cid.'.home'};
 4580:     }
 4581:     if ($needsrelease) {
 4582:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4583:         my $needsupdate;
 4584:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4585:             $needsupdate = 1;
 4586:         } else {
 4587:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4588:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4589:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4590:                 $needsupdate = 1;
 4591:             }
 4592:         }
 4593:         if ($needsupdate) {
 4594:             my %needshash = (
 4595:                              'internal.releaserequired' => $needsrelease,
 4596:                             );
 4597:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4598:             if ($putresult eq 'ok') {
 4599:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4600:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4601:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4602:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4603:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4604:                 }
 4605:             }
 4606:         }
 4607:     }
 4608:     return;
 4609: }
 4610: 
 4611: # -------------------------------------------------See if a user is privileged
 4612: 
 4613: sub privileged {
 4614:     my ($username,$domain)=@_;
 4615:     my $rolesdump=&reply("dump:$domain:$username:roles",
 4616: 			&homeserver($username,$domain));
 4617:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4618:         ($rolesdump =~ /^error:/)) {
 4619:         return 0;
 4620:     }
 4621:     my $now=time;
 4622:     if ($rolesdump ne '') {
 4623:         foreach my $entry (split(/&/,$rolesdump)) {
 4624: 	    if ($entry!~/^rolesdef_/) {
 4625: 		my ($area,$role)=split(/=/,$entry);
 4626: 		$area=~s/\_\w\w$//;
 4627: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 4628: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 4629: 		    my $active=1;
 4630: 		    if ($tend) {
 4631: 			if ($tend<$now) { $active=0; }
 4632: 		    }
 4633: 		    if ($tstart) {
 4634: 			if ($tstart>$now) { $active=0; }
 4635: 		    }
 4636: 		    if ($active) { return 1; }
 4637: 		}
 4638: 	    }
 4639: 	}
 4640:     }
 4641:     return 0;
 4642: }
 4643: 
 4644: # -------------------------------------------------------- Get user privileges
 4645: 
 4646: sub rolesinit {
 4647:     my ($domain,$username,$authhost)=@_;
 4648:     my $now=time;
 4649:     my %userroles = ('user.login.time' => $now);
 4650:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 4651:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4652:         ($rolesdump =~ /^error:/)) {
 4653:         return \%userroles;
 4654:     }
 4655:     my %firstaccess = &dump('firstaccesstimes',$domain,$username);
 4656:     my %timerinterval = &dump('timerinterval',$domain,$username);
 4657:     my (%coursetimerstarts,%firstaccchk,%firstaccenv,
 4658:         %coursetimerintervals,%timerintchk,%timerintenv);
 4659:     foreach my $key (keys(%firstaccess)) {
 4660:         my ($cid,$rest) = split(/\0/,$key);
 4661:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4662:     }
 4663:     foreach my $key (keys(%timerinterval)) {
 4664:         my ($cid,$rest) = split(/\0/,$key);
 4665:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4666:     }
 4667:     my %allroles=();
 4668:     my %allgroups=();
 4669: 
 4670:     if ($rolesdump ne '') {
 4671:         foreach my $entry (split(/&/,$rolesdump)) {
 4672: 	  if ($entry!~/^rolesdef_/) {
 4673:             my ($area,$role)=split(/=/,$entry);
 4674: 	    $area=~s/\_\w\w$//;
 4675:             my ($trole,$tend,$tstart,$group_privs);
 4676: 	    if ($role=~/^cr/) { 
 4677: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4678: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 4679: 		    ($tend,$tstart)=split('_',$trest);
 4680: 		} else {
 4681: 		    $trole=$role;
 4682: 		}
 4683:             } elsif ($role =~ m|^gr/|) {
 4684:                 ($trole,$tend,$tstart) = split(/_/,$role);
 4685:                 next if ($tstart eq '-1');
 4686:                 ($trole,$group_privs) = split(/\//,$trole);
 4687:                 $group_privs = &unescape($group_privs);
 4688: 	    } else {
 4689: 		($trole,$tend,$tstart)=split(/_/,$role);
 4690: 	    }
 4691: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4692: 					 $username);
 4693: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4694:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 4695:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 4696:             if (($area ne '') && ($trole ne '')) {
 4697: 		my $spec=$trole.'.'.$area;
 4698: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 4699: 		if ($trole =~ /^cr\//) {
 4700:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4701:                 } elsif ($trole eq 'gr') {
 4702:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4703: 		} else {
 4704:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4705: 		}
 4706:                 if ($trole ne 'gr') {
 4707:                     my $cid = $tdomain.'_'.$trest;
 4708:                     unless ($firstaccchk{$cid}) {
 4709:                         if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 4710:                             foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 4711:                                 $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 4712:                                     $coursetimerstarts{$cid}{$item}; 
 4713:                             }
 4714:                         }
 4715:                         $firstaccchk{$cid} = 1;
 4716:                     }
 4717:                     unless ($timerintchk{$cid}) {
 4718:                         if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 4719:                             foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 4720:                                 $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 4721:                                    $coursetimerintervals{$cid}{$item};
 4722:                             }
 4723:                         }
 4724:                         $timerintchk{$cid} = 1;
 4725:                     }
 4726:                 }
 4727:             }
 4728:           }
 4729:         }
 4730:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4731:         $userroles{'user.adv'}    = $adv;
 4732: 	$userroles{'user.author'} = $author;
 4733:         $env{'user.adv'}=$adv;
 4734:     }
 4735:     return (\%userroles,\%firstaccenv,\%timerintenv);
 4736: }
 4737: 
 4738: sub set_arearole {
 4739:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4740: # log the associated role with the area
 4741:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4742:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4743: }
 4744: 
 4745: sub custom_roleprivs {
 4746:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4747:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4748:     my $homsvr=homeserver($rauthor,$rdomain);
 4749:     if (&hostname($homsvr) ne '') {
 4750:         my ($rdummy,$roledef)=
 4751:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4752:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4753:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4754:             if (defined($syspriv)) {
 4755:                 if ($trest =~ /^$match_community$/) {
 4756:                     $syspriv =~ s/bre\&S//; 
 4757:                 }
 4758:                 $$allroles{'cm./'}.=':'.$syspriv;
 4759:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4760:             }
 4761:             if ($tdomain ne '') {
 4762:                 if (defined($dompriv)) {
 4763:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4764:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4765:                 }
 4766:                 if (($trest ne '') && (defined($coursepriv))) {
 4767:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4768:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4769:                 }
 4770:             }
 4771:         }
 4772:     }
 4773: }
 4774: 
 4775: sub group_roleprivs {
 4776:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4777:     my $access = 1;
 4778:     my $now = time;
 4779:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4780:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4781:     if ($access) {
 4782:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4783:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4784:     }
 4785: }
 4786: 
 4787: sub standard_roleprivs {
 4788:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4789:     if (defined($pr{$trole.':s'})) {
 4790:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4791:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4792:     }
 4793:     if ($tdomain ne '') {
 4794:         if (defined($pr{$trole.':d'})) {
 4795:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4796:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4797:         }
 4798:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4799:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4800:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4801:         }
 4802:     }
 4803: }
 4804: 
 4805: sub set_userprivs {
 4806:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4807:     my $author=0;
 4808:     my $adv=0;
 4809:     my %grouproles = ();
 4810:     if (keys(%{$allgroups}) > 0) {
 4811:         my @groupkeys; 
 4812:         foreach my $role (keys(%{$allroles})) {
 4813:             push(@groupkeys,$role);
 4814:         }
 4815:         if (ref($groups_roles) eq 'HASH') {
 4816:             foreach my $key (keys(%{$groups_roles})) {
 4817:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4818:                     push(@groupkeys,$key);
 4819:                 }
 4820:             }
 4821:         }
 4822:         if (@groupkeys > 0) {
 4823:             foreach my $role (@groupkeys) {
 4824:                 my ($trole,$area,$sec,$extendedarea);
 4825:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4826:                     $trole = $1;
 4827:                     $area = $2;
 4828:                     $sec = $3;
 4829:                     $extendedarea = $area.$sec;
 4830:                     if (exists($$allgroups{$area})) {
 4831:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4832:                             my $spec = $trole.'.'.$extendedarea;
 4833:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4834:                                                 $$allgroups{$area}{$group};
 4835:                         }
 4836:                     }
 4837:                 }
 4838:             }
 4839:         }
 4840:     }
 4841:     foreach my $group (keys(%grouproles)) {
 4842:         $$allroles{$group} = $grouproles{$group};
 4843:     }
 4844:     foreach my $role (keys(%{$allroles})) {
 4845:         my %thesepriv;
 4846:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4847:         foreach my $item (split(/:/,$$allroles{$role})) {
 4848:             if ($item ne '') {
 4849:                 my ($privilege,$restrictions)=split(/&/,$item);
 4850:                 if ($restrictions eq '') {
 4851:                     $thesepriv{$privilege}='F';
 4852:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4853:                     $thesepriv{$privilege}.=$restrictions;
 4854:                 }
 4855:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4856:             }
 4857:         }
 4858:         my $thesestr='';
 4859:         foreach my $priv (sort(keys(%thesepriv))) {
 4860: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4861: 	}
 4862:         $userroles->{'user.priv.'.$role} = $thesestr;
 4863:     }
 4864:     return ($author,$adv);
 4865: }
 4866: 
 4867: sub role_status {
 4868:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4869:     my @pwhere = ();
 4870:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4871:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4872:         unless (!defined($$role) || $$role eq '') {
 4873:             $$where=join('.',@pwhere);
 4874:             $$trolecode=$$role.'.'.$$where;
 4875:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4876:             $$tstatus='is';
 4877:             if ($$tstart && $$tstart>$update) {
 4878:                 $$tstatus='future';
 4879:                 if ($$tstart<$now) {
 4880:                     if ($$tstart && $$tstart>$refresh) {
 4881:                         if (($$where ne '') && ($$role ne '')) {
 4882:                             my (%allroles,%allgroups,$group_privs,
 4883:                                 %groups_roles,@rolecodes);
 4884:                             my %userroles = (
 4885:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4886:                             );
 4887:                             @rolecodes = ('cm'); 
 4888:                             my $spec=$$role.'.'.$$where;
 4889:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4890:                             if ($$role =~ /^cr\//) {
 4891:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4892:                                 push(@rolecodes,'cr');
 4893:                             } elsif ($$role eq 'gr') {
 4894:                                 push(@rolecodes,$$role);
 4895:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4896:                                                     $env{'user.name'});
 4897:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4898:                                 (undef,my $group_privs) = split(/\//,$trole);
 4899:                                 $group_privs = &unescape($group_privs);
 4900:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4901:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4902:                                 &get_groups_roles($tdomain,$trest,
 4903:                                                   \%course_roles,\@rolecodes,
 4904:                                                   \%groups_roles);
 4905:                             } else {
 4906:                                 push(@rolecodes,$$role);
 4907:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4908:                             }
 4909:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4910:                             &appenv(\%userroles,\@rolecodes);
 4911:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4912:                         }
 4913:                     }
 4914:                     $$tstatus = 'is';
 4915:                 }
 4916:             }
 4917:             if ($$tend) {
 4918:                 if ($$tend<$update) {
 4919:                     $$tstatus='expired';
 4920:                 } elsif ($$tend<$now) {
 4921:                     $$tstatus='will_not';
 4922:                 }
 4923:             }
 4924:         }
 4925:     }
 4926: }
 4927: 
 4928: sub get_groups_roles {
 4929:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4930:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4931:                   (ref($rolecodes) eq 'ARRAY') && 
 4932:                   (ref($groups_roles) eq 'HASH')); 
 4933:     if (keys(%{$cdom_courseroles}) > 0) {
 4934:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4935:         if ($cdom ne '' && $cnum ne '') {
 4936:             foreach my $key (keys(%{$cdom_courseroles})) {
 4937:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4938:                     my $crsrole = $1;
 4939:                     my $crssec = $2;
 4940:                     if ($crsrole =~ /^cr/) {
 4941:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4942:                             push(@{$rolecodes},'cr');
 4943:                         }
 4944:                     } else {
 4945:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4946:                             push(@{$rolecodes},$crsrole);
 4947:                         }
 4948:                     }
 4949:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4950:                     if ($crssec ne '') {
 4951:                         $rolekey .= "/$crssec";
 4952:                     }
 4953:                     $rolekey .= './';
 4954:                     $groups_roles->{$rolekey} = $rolecodes;
 4955:                 }
 4956:             }
 4957:         }
 4958:     }
 4959:     return;
 4960: }
 4961: 
 4962: sub delete_env_groupprivs {
 4963:     my ($where,$courseroles,$possroles) = @_;
 4964:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4965:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4966:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4967:         %{$courseroles->{$udom}} =
 4968:             &get_my_roles('','','userroles',['active'],
 4969:                           $possroles,[$udom],1);
 4970:     }
 4971:     if (ref($courseroles->{$udom}) eq 'HASH') {
 4972:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 4973:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 4974:             my $area = '/'.$cdom.'/'.$cnum;
 4975:             my $privkey = "user.priv.$crsrole.$area";
 4976:             if ($crssec ne '') {
 4977:                 $privkey .= '/'.$crssec;
 4978:             }
 4979:             $privkey .= ".$area/$group";
 4980:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 4981:         }
 4982:     }
 4983:     return;
 4984: }
 4985: 
 4986: sub check_adhoc_privs {
 4987:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 4988:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4989:     if ($env{$cckey}) {
 4990:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4991:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4992:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4993:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4994:         }
 4995:     } else {
 4996:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4997:     }
 4998: }
 4999: 
 5000: sub set_adhoc_privileges {
 5001: # role can be cc or ca
 5002:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5003:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5004:     my $spec = $role.'.'.$area;
 5005:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5006:                                   $env{'user.name'});
 5007:     my %ccrole = ();
 5008:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5009:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5010:     &appenv(\%userroles,[$role,'cm']);
 5011:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5012:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5013:         &appenv( {'request.role'        => $spec,
 5014:                   'request.role.domain' => $dcdom,
 5015:                   'request.course.sec'  => ''
 5016:                  }
 5017:                );
 5018:         my $tadv=0;
 5019:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5020:         &appenv({'request.role.adv'    => $tadv});
 5021:     }
 5022: }
 5023: 
 5024: # --------------------------------------------------------------- get interface
 5025: 
 5026: sub get {
 5027:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5028:    my $items='';
 5029:    foreach my $item (@$storearr) {
 5030:        $items.=&escape($item).'&';
 5031:    }
 5032:    $items=~s/\&$//;
 5033:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5034:    if (!$uname) { $uname=$env{'user.name'}; }
 5035:    my $uhome=&homeserver($uname,$udomain);
 5036: 
 5037:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5038:    my @pairs=split(/\&/,$rep);
 5039:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5040:      return @pairs;
 5041:    }
 5042:    my %returnhash=();
 5043:    my $i=0;
 5044:    foreach my $item (@$storearr) {
 5045:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5046:       $i++;
 5047:    }
 5048:    return %returnhash;
 5049: }
 5050: 
 5051: # --------------------------------------------------------------- del interface
 5052: 
 5053: sub del {
 5054:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5055:    my $items='';
 5056:    foreach my $item (@$storearr) {
 5057:        $items.=&escape($item).'&';
 5058:    }
 5059: 
 5060:    $items=~s/\&$//;
 5061:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5062:    if (!$uname) { $uname=$env{'user.name'}; }
 5063:    my $uhome=&homeserver($uname,$udomain);
 5064:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5065: }
 5066: 
 5067: # -------------------------------------------------------------- dump interface
 5068: 
 5069: sub dump {
 5070:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5071:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5072:     if (!$uname) { $uname=$env{'user.name'}; }
 5073:     my $uhome=&homeserver($uname,$udomain);
 5074:     if ($regexp) {
 5075: 	$regexp=&escape($regexp);
 5076:     } else {
 5077: 	$regexp='.';
 5078:     }
 5079:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5080:     my @pairs=split(/\&/,$rep);
 5081:     my %returnhash=();
 5082:     if (!($rep =~ /^error/ )) {
 5083: 	foreach my $item (@pairs) {
 5084: 	    my ($key,$value)=split(/=/,$item,2);
 5085: 	    $key = &unescape($key);
 5086: 	    next if ($key =~ /^error: 2 /);
 5087: 	    $returnhash{$key}=&thaw_unescape($value);
 5088: 	}
 5089:     }
 5090:     return %returnhash;
 5091: }
 5092: 
 5093: 
 5094: # --------------------------------------------------------- dumpstore interface
 5095: 
 5096: sub dumpstore {
 5097:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5098:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5099:    if (!$uname) { $uname=$env{'user.name'}; }
 5100:    my $uhome=&homeserver($uname,$udomain);
 5101:    if ($regexp) {
 5102:        $regexp=&escape($regexp);
 5103:    } else {
 5104:        $regexp='.';
 5105:    }
 5106:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5107:    my @pairs=split(/\&/,$rep);
 5108:    my %returnhash=();
 5109:    foreach my $item (@pairs) {
 5110:        my ($key,$value)=split(/=/,$item,2);
 5111:        next if ($key =~ /^error: 2 /);
 5112:        $returnhash{$key}=&thaw_unescape($value);
 5113:    }
 5114:    return %returnhash;
 5115: }
 5116: 
 5117: # -------------------------------------------------------------- keys interface
 5118: 
 5119: sub getkeys {
 5120:    my ($namespace,$udomain,$uname)=@_;
 5121:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5122:    if (!$uname) { $uname=$env{'user.name'}; }
 5123:    my $uhome=&homeserver($uname,$udomain);
 5124:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5125:    my @keyarray=();
 5126:    foreach my $key (split(/\&/,$rep)) {
 5127:       next if ($key =~ /^error: 2 /);
 5128:       push(@keyarray,&unescape($key));
 5129:    }
 5130:    return @keyarray;
 5131: }
 5132: 
 5133: # --------------------------------------------------------------- currentdump
 5134: sub currentdump {
 5135:    my ($courseid,$sdom,$sname)=@_;
 5136:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5137:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5138:    $sname    = $env{'user.name'}         if (! defined($sname));
 5139:    my $uhome = &homeserver($sname,$sdom);
 5140:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5141:    return if ($rep =~ /^(error:|no_such_host)/);
 5142:    #
 5143:    my %returnhash=();
 5144:    #
 5145:    if ($rep eq "unknown_cmd") { 
 5146:        # an old lond will not know currentdump
 5147:        # Do a dump and make it look like a currentdump
 5148:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5149:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5150:        my %hash = @tmp;
 5151:        @tmp=();
 5152:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5153:    } else {
 5154:        my @pairs=split(/\&/,$rep);
 5155:        foreach my $pair (@pairs) {
 5156:            my ($key,$value)=split(/=/,$pair,2);
 5157:            my ($symb,$param) = split(/:/,$key);
 5158:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5159:                                                         &thaw_unescape($value);
 5160:        }
 5161:    }
 5162:    return %returnhash;
 5163: }
 5164: 
 5165: sub convert_dump_to_currentdump{
 5166:     my %hash = %{shift()};
 5167:     my %returnhash;
 5168:     # Code ripped from lond, essentially.  The only difference
 5169:     # here is the unescaping done by lonnet::dump().  Conceivably
 5170:     # we might run in to problems with parameter names =~ /^v\./
 5171:     while (my ($key,$value) = each(%hash)) {
 5172:         my ($v,$symb,$param) = split(/:/,$key);
 5173: 	$symb  = &unescape($symb);
 5174: 	$param = &unescape($param);
 5175:         next if ($v eq 'version' || $symb eq 'keys');
 5176:         next if (exists($returnhash{$symb}) &&
 5177:                  exists($returnhash{$symb}->{$param}) &&
 5178:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5179:         $returnhash{$symb}->{$param}=$value;
 5180:         $returnhash{$symb}->{'v.'.$param}=$v;
 5181:     }
 5182:     #
 5183:     # Remove all of the keys in the hashes which keep track of
 5184:     # the version of the parameter.
 5185:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5186:         # use a foreach because we are going to delete from the hash.
 5187:         foreach my $key (keys(%$param_hash)) {
 5188:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5189:         }
 5190:     }
 5191:     return \%returnhash;
 5192: }
 5193: 
 5194: # ------------------------------------------------------ critical inc interface
 5195: 
 5196: sub cinc {
 5197:     return &inc(@_,'critical');
 5198: }
 5199: 
 5200: # --------------------------------------------------------------- inc interface
 5201: 
 5202: sub inc {
 5203:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5204:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5205:     if (!$uname) { $uname=$env{'user.name'}; }
 5206:     my $uhome=&homeserver($uname,$udomain);
 5207:     my $items='';
 5208:     if (! ref($store)) {
 5209:         # got a single value, so use that instead
 5210:         $items = &escape($store).'=&';
 5211:     } elsif (ref($store) eq 'SCALAR') {
 5212:         $items = &escape($$store).'=&';        
 5213:     } elsif (ref($store) eq 'ARRAY') {
 5214:         $items = join('=&',map {&escape($_);} @{$store});
 5215:     } elsif (ref($store) eq 'HASH') {
 5216:         while (my($key,$value) = each(%{$store})) {
 5217:             $items.= &escape($key).'='.&escape($value).'&';
 5218:         }
 5219:     }
 5220:     $items=~s/\&$//;
 5221:     if ($critical) {
 5222: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5223:     } else {
 5224: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5225:     }
 5226: }
 5227: 
 5228: # --------------------------------------------------------------- put interface
 5229: 
 5230: sub put {
 5231:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5232:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5233:    if (!$uname) { $uname=$env{'user.name'}; }
 5234:    my $uhome=&homeserver($uname,$udomain);
 5235:    my $items='';
 5236:    foreach my $item (keys(%$storehash)) {
 5237:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5238:    }
 5239:    $items=~s/\&$//;
 5240:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5241: }
 5242: 
 5243: # ------------------------------------------------------------ newput interface
 5244: 
 5245: sub newput {
 5246:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5247:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5248:    if (!$uname) { $uname=$env{'user.name'}; }
 5249:    my $uhome=&homeserver($uname,$udomain);
 5250:    my $items='';
 5251:    foreach my $key (keys(%$storehash)) {
 5252:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5253:    }
 5254:    $items=~s/\&$//;
 5255:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5256: }
 5257: 
 5258: # ---------------------------------------------------------  putstore interface
 5259: 
 5260: sub putstore {
 5261:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5262:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5263:    if (!$uname) { $uname=$env{'user.name'}; }
 5264:    my $uhome=&homeserver($uname,$udomain);
 5265:    my $items='';
 5266:    foreach my $key (keys(%$storehash)) {
 5267:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5268:    }
 5269:    $items=~s/\&$//;
 5270:    my $esc_symb=&escape($symb);
 5271:    my $esc_v=&escape($version);
 5272:    my $reply =
 5273:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5274: 	      $uhome);
 5275:    if ($reply eq 'unknown_cmd') {
 5276:        # gfall back to way things use to be done
 5277:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5278: 			    $uname);
 5279:    }
 5280:    return $reply;
 5281: }
 5282: 
 5283: sub old_putstore {
 5284:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5285:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5286:     if (!$uname) { $uname=$env{'user.name'}; }
 5287:     my $uhome=&homeserver($uname,$udomain);
 5288:     my %newstorehash;
 5289:     foreach my $item (keys(%$storehash)) {
 5290: 	my $key = $version.':'.&escape($symb).':'.$item;
 5291: 	$newstorehash{$key} = $storehash->{$item};
 5292:     }
 5293:     my $items='';
 5294:     my %allitems = ();
 5295:     foreach my $item (keys(%newstorehash)) {
 5296: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5297: 	    my $key = $1.':keys:'.$2;
 5298: 	    $allitems{$key} .= $3.':';
 5299: 	}
 5300: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5301:     }
 5302:     foreach my $item (keys(%allitems)) {
 5303: 	$allitems{$item} =~ s/\:$//;
 5304: 	$items.= $item.'='.$allitems{$item}.'&';
 5305:     }
 5306:     $items=~s/\&$//;
 5307:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5308: }
 5309: 
 5310: # ------------------------------------------------------ critical put interface
 5311: 
 5312: sub cput {
 5313:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5314:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5315:    if (!$uname) { $uname=$env{'user.name'}; }
 5316:    my $uhome=&homeserver($uname,$udomain);
 5317:    my $items='';
 5318:    foreach my $item (keys(%$storehash)) {
 5319:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5320:    }
 5321:    $items=~s/\&$//;
 5322:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5323: }
 5324: 
 5325: # -------------------------------------------------------------- eget interface
 5326: 
 5327: sub eget {
 5328:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5329:    my $items='';
 5330:    foreach my $item (@$storearr) {
 5331:        $items.=&escape($item).'&';
 5332:    }
 5333:    $items=~s/\&$//;
 5334:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5335:    if (!$uname) { $uname=$env{'user.name'}; }
 5336:    my $uhome=&homeserver($uname,$udomain);
 5337:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5338:    my @pairs=split(/\&/,$rep);
 5339:    my %returnhash=();
 5340:    my $i=0;
 5341:    foreach my $item (@$storearr) {
 5342:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5343:       $i++;
 5344:    }
 5345:    return %returnhash;
 5346: }
 5347: 
 5348: # ------------------------------------------------------------ tmpput interface
 5349: sub tmpput {
 5350:     my ($storehash,$server,$context)=@_;
 5351:     my $items='';
 5352:     foreach my $item (keys(%$storehash)) {
 5353: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5354:     }
 5355:     $items=~s/\&$//;
 5356:     if (defined($context)) {
 5357:         $items .= ':'.&escape($context);
 5358:     }
 5359:     return &reply("tmpput:$items",$server);
 5360: }
 5361: 
 5362: # ------------------------------------------------------------ tmpget interface
 5363: sub tmpget {
 5364:     my ($token,$server)=@_;
 5365:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5366:     my $rep=&reply("tmpget:$token",$server);
 5367:     my %returnhash;
 5368:     foreach my $item (split(/\&/,$rep)) {
 5369: 	my ($key,$value)=split(/=/,$item);
 5370:         next if ($key =~ /^error: 2 /);
 5371: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5372:     }
 5373:     return %returnhash;
 5374: }
 5375: 
 5376: # ------------------------------------------------------------ tmpdel interface
 5377: sub tmpdel {
 5378:     my ($token,$server)=@_;
 5379:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5380:     return &reply("tmpdel:$token",$server);
 5381: }
 5382: 
 5383: # -------------------------------------------------- portfolio access checking
 5384: 
 5385: sub portfolio_access {
 5386:     my ($requrl) = @_;
 5387:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5388:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5389:     if ($result) {
 5390:         my %setters;
 5391:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5392:             my ($startblock,$endblock) =
 5393:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5394:             if ($startblock && $endblock) {
 5395:                 return 'B';
 5396:             }
 5397:         } else {
 5398:             my ($startblock,$endblock) =
 5399:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5400:             if ($startblock && $endblock) {
 5401:                 return 'B';
 5402:             }
 5403:         }
 5404:     }
 5405:     if ($result eq 'ok') {
 5406:        return 'F';
 5407:     } elsif ($result =~ /^[^:]+:guest_/) {
 5408:        return 'A';
 5409:     }
 5410:     return '';
 5411: }
 5412: 
 5413: sub get_portfolio_access {
 5414:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5415: 
 5416:     if (!ref($access_hash)) {
 5417: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5418: 	my %access_controls = &get_access_controls($current_perms,$group,
 5419: 						   $file_name);
 5420: 	$access_hash = $access_controls{$file_name};
 5421:     }
 5422: 
 5423:     my ($public,$guest,@domains,@users,@courses,@groups);
 5424:     my $now = time;
 5425:     if (ref($access_hash) eq 'HASH') {
 5426:         foreach my $key (keys(%{$access_hash})) {
 5427:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5428:             if ($start > $now) {
 5429:                 next;
 5430:             }
 5431:             if ($end && $end<$now) {
 5432:                 next;
 5433:             }
 5434:             if ($scope eq 'public') {
 5435:                 $public = $key;
 5436:                 last;
 5437:             } elsif ($scope eq 'guest') {
 5438:                 $guest = $key;
 5439:             } elsif ($scope eq 'domains') {
 5440:                 push(@domains,$key);
 5441:             } elsif ($scope eq 'users') {
 5442:                 push(@users,$key);
 5443:             } elsif ($scope eq 'course') {
 5444:                 push(@courses,$key);
 5445:             } elsif ($scope eq 'group') {
 5446:                 push(@groups,$key);
 5447:             }
 5448:         }
 5449:         if ($public) {
 5450:             return 'ok';
 5451:         }
 5452:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5453:             if ($guest) {
 5454:                 return $guest;
 5455:             }
 5456:         } else {
 5457:             if (@domains > 0) {
 5458:                 foreach my $domkey (@domains) {
 5459:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5460:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5461:                             return 'ok';
 5462:                         }
 5463:                     }
 5464:                 }
 5465:             }
 5466:             if (@users > 0) {
 5467:                 foreach my $userkey (@users) {
 5468:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5469:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5470:                             if (ref($item) eq 'HASH') {
 5471:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5472:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5473:                                     return 'ok';
 5474:                                 }
 5475:                             }
 5476:                         }
 5477:                     } 
 5478:                 }
 5479:             }
 5480:             my %roleshash;
 5481:             my @courses_and_groups = @courses;
 5482:             push(@courses_and_groups,@groups); 
 5483:             if (@courses_and_groups > 0) {
 5484:                 my (%allgroups,%allroles); 
 5485:                 my ($start,$end,$role,$sec,$group);
 5486:                 foreach my $envkey (%env) {
 5487:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5488:                         my $cid = $2.'_'.$3; 
 5489:                         if ($1 eq 'gr') {
 5490:                             $group = $4;
 5491:                             $allgroups{$cid}{$group} = $env{$envkey};
 5492:                         } else {
 5493:                             if ($4 eq '') {
 5494:                                 $sec = 'none';
 5495:                             } else {
 5496:                                 $sec = $4;
 5497:                             }
 5498:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5499:                         }
 5500:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5501:                         my $cid = $2.'_'.$3;
 5502:                         if ($4 eq '') {
 5503:                             $sec = 'none';
 5504:                         } else {
 5505:                             $sec = $4;
 5506:                         }
 5507:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5508:                     }
 5509:                 }
 5510:                 if (keys(%allroles) == 0) {
 5511:                     return;
 5512:                 }
 5513:                 foreach my $key (@courses_and_groups) {
 5514:                     my %content = %{$$access_hash{$key}};
 5515:                     my $cnum = $content{'number'};
 5516:                     my $cdom = $content{'domain'};
 5517:                     my $cid = $cdom.'_'.$cnum;
 5518:                     if (!exists($allroles{$cid})) {
 5519:                         next;
 5520:                     }    
 5521:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5522:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5523:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5524:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5525:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5526:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5527:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5528:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5529:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5530:                                         if (grep/^all$/,@sections) {
 5531:                                             return 'ok';
 5532:                                         } else {
 5533:                                             if (grep/^$sec$/,@sections) {
 5534:                                                 return 'ok';
 5535:                                             }
 5536:                                         }
 5537:                                     }
 5538:                                 }
 5539:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5540:                                     if (grep/^none$/,@groups) {
 5541:                                         return 'ok';
 5542:                                     }
 5543:                                 } else {
 5544:                                     if (grep/^all$/,@groups) {
 5545:                                         return 'ok';
 5546:                                     } 
 5547:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5548:                                         if (grep/^$group$/,@groups) {
 5549:                                             return 'ok';
 5550:                                         }
 5551:                                     }
 5552:                                 } 
 5553:                             }
 5554:                         }
 5555:                     }
 5556:                 }
 5557:             }
 5558:             if ($guest) {
 5559:                 return $guest;
 5560:             }
 5561:         }
 5562:     }
 5563:     return;
 5564: }
 5565: 
 5566: sub course_group_datechecker {
 5567:     my ($dates,$now,$status) = @_;
 5568:     my ($start,$end) = split(/\./,$dates);
 5569:     if (!$start && !$end) {
 5570:         return 'ok';
 5571:     }
 5572:     if (grep/^active$/,@{$status}) {
 5573:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5574:             return 'ok';
 5575:         }
 5576:     }
 5577:     if (grep/^previous$/,@{$status}) {
 5578:         if ($end > $now ) {
 5579:             return 'ok';
 5580:         }
 5581:     }
 5582:     if (grep/^future$/,@{$status}) {
 5583:         if ($start > $now) {
 5584:             return 'ok';
 5585:         }
 5586:     }
 5587:     return; 
 5588: }
 5589: 
 5590: sub parse_portfolio_url {
 5591:     my ($url) = @_;
 5592: 
 5593:     my ($type,$udom,$unum,$group,$file_name);
 5594:     
 5595:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5596: 	$type = 1;
 5597:         $udom = $1;
 5598:         $unum = $2;
 5599:         $file_name = $3;
 5600:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5601: 	$type = 2;
 5602:         $udom = $1;
 5603:         $unum = $2;
 5604:         $group = $3;
 5605:         $file_name = $3.'/'.$4;
 5606:     }
 5607:     if (wantarray) {
 5608: 	return ($type,$udom,$unum,$file_name,$group);
 5609:     }
 5610:     return $type;
 5611: }
 5612: 
 5613: sub is_portfolio_url {
 5614:     my ($url) = @_;
 5615:     return scalar(&parse_portfolio_url($url));
 5616: }
 5617: 
 5618: sub is_portfolio_file {
 5619:     my ($file) = @_;
 5620:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5621:         return 1;
 5622:     }
 5623:     return;
 5624: }
 5625: 
 5626: sub usertools_access {
 5627:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5628:     my ($access,%tools);
 5629:     if ($context eq '') {
 5630:         $context = 'tools';
 5631:     }
 5632:     if ($context eq 'requestcourses') {
 5633:         %tools = (
 5634:                       official   => 1,
 5635:                       unofficial => 1,
 5636:                       community  => 1,
 5637:                  );
 5638:     } else {
 5639:         %tools = (
 5640:                       aboutme   => 1,
 5641:                       blog      => 1,
 5642:                       portfolio => 1,
 5643:                  );
 5644:     }
 5645:     return if (!defined($tools{$tool}));
 5646: 
 5647:     if ((!defined($udom)) || (!defined($uname))) {
 5648:         $udom = $env{'user.domain'};
 5649:         $uname = $env{'user.name'};
 5650:     }
 5651: 
 5652:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5653:         if ($action ne 'reload') {
 5654:             if ($context eq 'requestcourses') {
 5655:                 return $env{'environment.canrequest.'.$tool};
 5656:             } else {
 5657:                 return $env{'environment.availabletools.'.$tool};
 5658:             }
 5659:         }
 5660:     }
 5661: 
 5662:     my ($toolstatus,$inststatus);
 5663: 
 5664:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5665:          ($action ne 'reload')) {
 5666:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 5667:         $inststatus = $env{'environment.inststatus'};
 5668:     } else {
 5669:         if (ref($userenvref) eq 'HASH') {
 5670:             $toolstatus = $userenvref->{$context.'.'.$tool};
 5671:             $inststatus = $userenvref->{'inststatus'};
 5672:         } else {
 5673:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 5674:             $toolstatus = $userenv{$context.'.'.$tool};
 5675:             $inststatus = $userenv{'inststatus'};
 5676:         }
 5677:     }
 5678: 
 5679:     if ($toolstatus ne '') {
 5680:         if ($toolstatus) {
 5681:             $access = 1;
 5682:         } else {
 5683:             $access = 0;
 5684:         }
 5685:         return $access;
 5686:     }
 5687: 
 5688:     my ($is_adv,%domdef);
 5689:     if (ref($is_advref) eq 'HASH') {
 5690:         $is_adv = $is_advref->{'is_adv'};
 5691:     } else {
 5692:         $is_adv = &is_advanced_user($udom,$uname);
 5693:     }
 5694:     if (ref($domdefref) eq 'HASH') {
 5695:         %domdef = %{$domdefref};
 5696:     } else {
 5697:         %domdef = &get_domain_defaults($udom);
 5698:     }
 5699:     if (ref($domdef{$tool}) eq 'HASH') {
 5700:         if ($is_adv) {
 5701:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5702:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5703:                     $access = 1;
 5704:                 } else {
 5705:                     $access = 0;
 5706:                 }
 5707:                 return $access;
 5708:             }
 5709:         }
 5710:         if ($inststatus ne '') {
 5711:             my ($hasaccess,$hasnoaccess);
 5712:             foreach my $affiliation (split(/:/,$inststatus)) {
 5713:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5714:                     if ($domdef{$tool}{$affiliation}) {
 5715:                         $hasaccess = 1;
 5716:                     } else {
 5717:                         $hasnoaccess = 1;
 5718:                     }
 5719:                 }
 5720:             }
 5721:             if ($hasaccess || $hasnoaccess) {
 5722:                 if ($hasaccess) {
 5723:                     $access = 1;
 5724:                 } elsif ($hasnoaccess) {
 5725:                     $access = 0; 
 5726:                 }
 5727:                 return $access;
 5728:             }
 5729:         } else {
 5730:             if ($domdef{$tool}{'default'} ne '') {
 5731:                 if ($domdef{$tool}{'default'}) {
 5732:                     $access = 1;
 5733:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5734:                     $access = 0;
 5735:                 }
 5736:                 return $access;
 5737:             }
 5738:         }
 5739:     } else {
 5740:         if ($context eq 'tools') {
 5741:             $access = 1;
 5742:         } else {
 5743:             $access = 0;
 5744:         }
 5745:         return $access;
 5746:     }
 5747: }
 5748: 
 5749: sub is_course_owner {
 5750:     my ($cdom,$cnum,$udom,$uname) = @_;
 5751:     if (($udom eq '') || ($uname eq '')) {
 5752:         $udom = $env{'user.domain'};
 5753:         $uname = $env{'user.name'};
 5754:     }
 5755:     unless (($udom eq '') || ($uname eq '')) {
 5756:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5757:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5758:                 return 1;
 5759:             } else {
 5760:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5761:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5762:                     return 1;
 5763:                 }
 5764:             }
 5765:         }
 5766:     }
 5767:     return;
 5768: }
 5769: 
 5770: sub is_advanced_user {
 5771:     my ($udom,$uname) = @_;
 5772:     if ($udom ne '' && $uname ne '') {
 5773:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5774:             if (wantarray) {
 5775:                 return ($env{'user.adv'},$env{'user.author'});
 5776:             } else {
 5777:                 return $env{'user.adv'};
 5778:             }
 5779:         }
 5780:     }
 5781:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5782:     my %allroles;
 5783:     my ($is_adv,$is_author);
 5784:     foreach my $role (keys(%roleshash)) {
 5785:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5786:         my $area = '/'.$tdomain.'/'.$trest;
 5787:         if ($sec ne '') {
 5788:             $area .= '/'.$sec;
 5789:         }
 5790:         if (($area ne '') && ($trole ne '')) {
 5791:             my $spec=$trole.'.'.$area;
 5792:             if ($trole =~ /^cr\//) {
 5793:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5794:             } elsif ($trole ne 'gr') {
 5795:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5796:             }
 5797:             if ($trole eq 'au') {
 5798:                 $is_author = 1;
 5799:             }
 5800:         }
 5801:     }
 5802:     foreach my $role (keys(%allroles)) {
 5803:         last if ($is_adv);
 5804:         foreach my $item (split(/:/,$allroles{$role})) {
 5805:             if ($item ne '') {
 5806:                 my ($privilege,$restrictions)=split(/&/,$item);
 5807:                 if ($privilege eq 'adv') {
 5808:                     $is_adv = 1;
 5809:                     last;
 5810:                 }
 5811:             }
 5812:         }
 5813:     }
 5814:     if (wantarray) {
 5815:         return ($is_adv,$is_author);
 5816:     }
 5817:     return $is_adv;
 5818: }
 5819: 
 5820: sub check_can_request {
 5821:     my ($dom,$can_request,$request_domains) = @_;
 5822:     my $canreq = 0;
 5823:     my ($types,$typename) = &Apache::loncommon::course_types();
 5824:     my @options = ('approval','validate','autolimit');
 5825:     my $optregex = join('|',@options);
 5826:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5827:         foreach my $type (@{$types}) {
 5828:             if (&usertools_access($env{'user.name'},
 5829:                                   $env{'user.domain'},
 5830:                                   $type,undef,'requestcourses')) {
 5831:                 $canreq ++;
 5832:                 if (ref($request_domains) eq 'HASH') {
 5833:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5834:                 }
 5835:                 if ($dom eq $env{'user.domain'}) {
 5836:                     $can_request->{$type} = 1;
 5837:                 }
 5838:             }
 5839:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5840:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5841:                 if (@curr > 0) {
 5842:                     foreach my $item (@curr) {
 5843:                         if (ref($request_domains) eq 'HASH') {
 5844:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5845:                             if ($otherdom ne '') {
 5846:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5847:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5848:                                         push(@{$request_domains->{$type}},$otherdom);
 5849:                                     }
 5850:                                 } else {
 5851:                                     push(@{$request_domains->{$type}},$otherdom);
 5852:                                 }
 5853:                             }
 5854:                         }
 5855:                     }
 5856:                     unless($dom eq $env{'user.domain'}) {
 5857:                         $canreq ++;
 5858:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5859:                             $can_request->{$type} = 1;
 5860:                         }
 5861:                     }
 5862:                 }
 5863:             }
 5864:         }
 5865:     }
 5866:     return $canreq;
 5867: }
 5868: 
 5869: # ---------------------------------------------- Custom access rule evaluation
 5870: 
 5871: sub customaccess {
 5872:     my ($priv,$uri)=@_;
 5873:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5874:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5875:     $udom = &LONCAPA::clean_domain($udom);
 5876:     $ucrs = &LONCAPA::clean_username($ucrs);
 5877:     my $access=0;
 5878:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5879: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5880: 	if ($type eq 'user') {
 5881: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5882: 		my ($tdom,$tuname)=split(m{/},$scope);
 5883: 		if ($tdom) {
 5884: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5885: 		}
 5886: 		if ($tuname) {
 5887: 		    if ($tuname ne $env{'user.name'}) { next; }
 5888: 		}
 5889: 		$access=($effect eq 'allow');
 5890: 		last;
 5891: 	    }
 5892: 	} else {
 5893: 	    if ($role) {
 5894: 		if ($role ne $urole) { next; }
 5895: 	    }
 5896: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5897: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5898: 		if ($tdom) {
 5899: 		    if ($tdom ne $udom) { next; }
 5900: 		}
 5901: 		if ($tcrs) {
 5902: 		    if ($tcrs ne $ucrs) { next; }
 5903: 		}
 5904: 		if ($tsec) {
 5905: 		    if ($tsec ne $usec) { next; }
 5906: 		}
 5907: 		$access=($effect eq 'allow');
 5908: 		last;
 5909: 	    }
 5910: 	    if ($realm eq '' && $role eq '') {
 5911: 		$access=($effect eq 'allow');
 5912: 	    }
 5913: 	}
 5914:     }
 5915:     return $access;
 5916: }
 5917: 
 5918: # ------------------------------------------------- Check for a user privilege
 5919: 
 5920: sub allowed {
 5921:     my ($priv,$uri,$symb,$role)=@_;
 5922:     my $ver_orguri=$uri;
 5923:     $uri=&deversion($uri);
 5924:     my $orguri=$uri;
 5925:     $uri=&declutter($uri);
 5926: 
 5927:     if ($priv eq 'evb') {
 5928: # Evade communication block restrictions for specified role in a course
 5929:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5930:             return $1;
 5931:         } else {
 5932:             return;
 5933:         }
 5934:     }
 5935: 
 5936:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5937: # Free bre access to adm and meta resources
 5938:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5939: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5940: 	&& ($priv eq 'bre')) {
 5941: 	return 'F';
 5942:     }
 5943: 
 5944: # Free bre access to user's own portfolio contents
 5945:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5946:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5947: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5948:         my %setters;
 5949:         my ($startblock,$endblock) = 
 5950:             &Apache::loncommon::blockcheck(\%setters,'port');
 5951:         if ($startblock && $endblock) {
 5952:             return 'B';
 5953:         } else {
 5954:             return 'F';
 5955:         }
 5956:     }
 5957: 
 5958: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5959:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5960:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5961:         if (exists($env{'request.course.id'})) {
 5962:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5963:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5964:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5965:                 my $courseprivid=$env{'request.course.id'};
 5966:                 $courseprivid=~s/\_/\//;
 5967:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5968:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5969:                     return $1; 
 5970:                 } else {
 5971:                     if ($env{'request.course.sec'}) {
 5972:                         $courseprivid.='/'.$env{'request.course.sec'};
 5973:                     }
 5974:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5975:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5976:                         return $2;
 5977:                     }
 5978:                 }
 5979:             }
 5980:         }
 5981:     }
 5982: 
 5983: # Free bre to public access
 5984: 
 5985:     if ($priv eq 'bre') {
 5986:         my $copyright=&metadata($uri,'copyright');
 5987: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5988:            return 'F'; 
 5989:         }
 5990:         if ($copyright eq 'priv') {
 5991:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5992: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5993: 		return '';
 5994:             }
 5995:         }
 5996:         if ($copyright eq 'domain') {
 5997:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5998: 	    unless (($env{'user.domain'} eq $1) ||
 5999:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6000: 		return '';
 6001:             }
 6002:         }
 6003:         if ($env{'request.role'}=~ /li\.\//) {
 6004:             # Library role, so allow browsing of resources in this domain.
 6005:             return 'F';
 6006:         }
 6007:         if ($copyright eq 'custom') {
 6008: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6009:         }
 6010:     }
 6011:     # Domain coordinator is trying to create a course
 6012:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6013:         # uri is the requested domain in this case.
 6014:         # comparison to 'request.role.domain' shows if the user has selected
 6015:         # a role of dc for the domain in question.
 6016:         return 'F' if ($uri eq $env{'request.role.domain'});
 6017:     }
 6018: 
 6019:     my $thisallowed='';
 6020:     my $statecond=0;
 6021:     my $courseprivid='';
 6022: 
 6023:     my $ownaccess;
 6024:     # Community Coordinator or Assistant Co-author browsing resource space.
 6025:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6026:         if ($uri eq '') {
 6027:             $ownaccess = 1;
 6028:         } else {
 6029:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6030:                 my $udom = $env{'user.domain'};
 6031:                 my $uname = $env{'user.name'};
 6032:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6033:                     $ownaccess = 1;
 6034:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6035:                     unless ($uri =~ m{\.\./}) {
 6036:                         $ownaccess = 1;
 6037:                     }
 6038:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6039:                     my $now = time;
 6040:                     if ($uri =~ m{^([^/]+)/?$}) {
 6041:                         my $adom = $1;
 6042:                         foreach my $key (keys(%env)) {
 6043:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6044:                                 my ($start,$end) = split('.',$env{$key});
 6045:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6046:                                     $ownaccess = 1;
 6047:                                     last;
 6048:                                 }
 6049:                             }
 6050:                         }
 6051:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6052:                         my $adom = $1;
 6053:                         my $aname = $2;
 6054:                         foreach my $role ('ca','aa') { 
 6055:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6056:                                 my ($start,$end) =
 6057:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6058:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6059:                                     $ownaccess = 1;
 6060:                                     last;
 6061:                                 }
 6062:                             }
 6063:                         }
 6064:                     }
 6065:                 }
 6066:             }
 6067:         }
 6068:     }
 6069: 
 6070: # Course
 6071: 
 6072:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6073:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6074:             $thisallowed.=$1;
 6075:         }
 6076:     }
 6077: 
 6078: # Domain
 6079: 
 6080:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6081:        =~/\Q$priv\E\&([^\:]*)/) {
 6082:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6083:             $thisallowed.=$1;
 6084:         }
 6085:     }
 6086: 
 6087: # User who is not author or co-author might still be able to edit
 6088: # resource of an author in the domain (e.g., if Domain Coordinator).
 6089:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6090:         (&allowed('mdc',$env{'request.course.id'}))) {
 6091:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6092:             $thisallowed.=$1;
 6093:         }
 6094:     }
 6095: 
 6096: # Course: uri itself is a course
 6097:     my $courseuri=$uri;
 6098:     $courseuri=~s/\_(\d)/\/$1/;
 6099:     $courseuri=~s/^([^\/])/\/$1/;
 6100: 
 6101:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6102:        =~/\Q$priv\E\&([^\:]*)/) {
 6103:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6104:             $thisallowed.=$1;
 6105:         }
 6106:     }
 6107: 
 6108: # URI is an uploaded document for this course, default permissions don't matter
 6109: # not allowing 'edit' access (editupload) to uploaded course docs
 6110:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6111: 	$thisallowed='';
 6112:         my ($match)=&is_on_map($uri);
 6113:         if ($match) {
 6114:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6115:                   =~/\Q$priv\E\&([^\:]*)/) {
 6116:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6117:                 if (@blockers > 0) {
 6118:                     $thisallowed = 'B';
 6119:                 } else {
 6120:                     $thisallowed.=$1;
 6121:                 }
 6122:             }
 6123:         } else {
 6124:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6125:             if ($refuri) {
 6126:                 if ($refuri =~ m|^/adm/|) {
 6127:                     $thisallowed='F';
 6128:                 } else {
 6129:                     $refuri=&declutter($refuri);
 6130:                     my ($match) = &is_on_map($refuri);
 6131:                     if ($match) {
 6132:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6133:                         if (@blockers > 0) {
 6134:                             $thisallowed = 'B';
 6135:                         } else {
 6136:                             $thisallowed='F';
 6137:                         }
 6138:                     }
 6139:                 }
 6140:             }
 6141:         }
 6142:     }
 6143: 
 6144:     if ($priv eq 'bre'
 6145: 	&& $thisallowed ne 'F' 
 6146: 	&& $thisallowed ne '2'
 6147: 	&& &is_portfolio_url($uri)) {
 6148: 	$thisallowed = &portfolio_access($uri);
 6149:     }
 6150:     
 6151: # Full access at system, domain or course-wide level? Exit.
 6152:     if ($thisallowed=~/F/) {
 6153: 	return 'F';
 6154:     }
 6155: 
 6156: # If this is generating or modifying users, exit with special codes
 6157: 
 6158:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6159: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6160: 	    my ($audom,$auname)=split('/',$uri);
 6161: # no author name given, so this just checks on the general right to make a co-author in this domain
 6162: 	    unless ($auname) { return $thisallowed; }
 6163: # an author name is given, so we are about to actually make a co-author for a certain account
 6164: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6165: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6166: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6167: 	}
 6168: 	return $thisallowed;
 6169:     }
 6170: #
 6171: # Gathered so far: system, domain and course wide privileges
 6172: #
 6173: # Course: See if uri or referer is an individual resource that is part of 
 6174: # the course
 6175: 
 6176:     if ($env{'request.course.id'}) {
 6177: 
 6178:        $courseprivid=$env{'request.course.id'};
 6179:        if ($env{'request.course.sec'}) {
 6180:           $courseprivid.='/'.$env{'request.course.sec'};
 6181:        }
 6182:        $courseprivid=~s/\_/\//;
 6183:        my $checkreferer=1;
 6184:        my ($match,$cond)=&is_on_map($uri);
 6185:        if ($match) {
 6186:            $statecond=$cond;
 6187:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6188:                =~/\Q$priv\E\&([^\:]*)/) {
 6189:                my $value = $1;
 6190:                if ($priv eq 'bre') {
 6191:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6192:                    if (@blockers > 0) {
 6193:                        $thisallowed = 'B';
 6194:                    } else {
 6195:                        $thisallowed.=$value;
 6196:                    }
 6197:                } else {
 6198:                    $thisallowed.=$value;
 6199:                }
 6200:                $checkreferer=0;
 6201:            }
 6202:        }
 6203:        
 6204:        if ($checkreferer) {
 6205: 	  my $refuri=$env{'httpref.'.$orguri};
 6206:             unless ($refuri) {
 6207:                 foreach my $key (keys(%env)) {
 6208: 		    if ($key=~/^httpref\..*\*/) {
 6209: 			my $pattern=$key;
 6210:                         $pattern=~s/^httpref\.\/res\///;
 6211:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6212:                         $pattern=~s/\//\\\//g;
 6213:                         if ($orguri=~/$pattern/) {
 6214: 			    $refuri=$env{$key};
 6215:                         }
 6216:                     }
 6217:                 }
 6218:             }
 6219: 
 6220:          if ($refuri) { 
 6221: 	  $refuri=&declutter($refuri);
 6222:           my ($match,$cond)=&is_on_map($refuri);
 6223:             if ($match) {
 6224:               my $refstatecond=$cond;
 6225:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6226:                   =~/\Q$priv\E\&([^\:]*)/) {
 6227:                   my $value = $1;
 6228:                   if ($priv eq 'bre') {
 6229:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6230:                       if (@blockers > 0) {
 6231:                           $thisallowed = 'B';
 6232:                       } else {
 6233:                           $thisallowed.=$value;
 6234:                       }
 6235:                   } else {
 6236:                       $thisallowed.=$value;
 6237:                   }
 6238:                   $uri=$refuri;
 6239:                   $statecond=$refstatecond;
 6240:               }
 6241:           }
 6242:         }
 6243:        }
 6244:    }
 6245: 
 6246: #
 6247: # Gathered now: all privileges that could apply, and condition number
 6248: # 
 6249: #
 6250: # Full or no access?
 6251: #
 6252: 
 6253:     if ($thisallowed=~/F/) {
 6254: 	return 'F';
 6255:     }
 6256: 
 6257:     unless ($thisallowed) {
 6258:         return '';
 6259:     }
 6260: 
 6261: # Restrictions exist, deal with them
 6262: #
 6263: #   C:according to course preferences
 6264: #   R:according to resource settings
 6265: #   L:unless locked
 6266: #   X:according to user session state
 6267: #
 6268: 
 6269: # Possibly locked functionality, check all courses
 6270: # Locks might take effect only after 10 minutes cache expiration for other
 6271: # courses, and 2 minutes for current course
 6272: 
 6273:     my $envkey;
 6274:     if ($thisallowed=~/L/) {
 6275:         foreach $envkey (keys(%env)) {
 6276:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6277:                my $courseid=$2;
 6278:                my $roleid=$1.'.'.$2;
 6279:                $courseid=~s/^\///;
 6280:                my $expiretime=600;
 6281:                if ($env{'request.role'} eq $roleid) {
 6282: 		  $expiretime=120;
 6283:                }
 6284: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6285:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6286:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6287: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6288:                }
 6289:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6290:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6291: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6292:                        &log($env{'user.domain'},$env{'user.name'},
 6293:                             $env{'user.home'},
 6294:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6295:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6296:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6297: 		       return '';
 6298:                    }
 6299:                }
 6300:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6301:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6302: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6303:                        &log($env{'user.domain'},$env{'user.name'},
 6304:                             $env{'user.home'},
 6305:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6306:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6307:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6308: 		       return '';
 6309:                    }
 6310:                }
 6311: 	   }
 6312:        }
 6313:     }
 6314:    
 6315: #
 6316: # Rest of the restrictions depend on selected course
 6317: #
 6318: 
 6319:     unless ($env{'request.course.id'}) {
 6320: 	if ($thisallowed eq 'A') {
 6321: 	    return 'A';
 6322:         } elsif ($thisallowed eq 'B') {
 6323:             return 'B';
 6324: 	} else {
 6325: 	    return '1';
 6326: 	}
 6327:     }
 6328: 
 6329: #
 6330: # Now user is definitely in a course
 6331: #
 6332: 
 6333: 
 6334: # Course preferences
 6335: 
 6336:    if ($thisallowed=~/C/) {
 6337:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6338:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6339:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6340: 	   =~/\Q$rolecode\E/) {
 6341: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6342: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6343: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6344: 			$env{'request.course.id'});
 6345: 	   }
 6346:            return '';
 6347:        }
 6348: 
 6349:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6350: 	   =~/\Q$unamedom\E/) {
 6351: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6352: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6353: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6354: 			$env{'request.course.id'});
 6355: 	   }
 6356:            return '';
 6357:        }
 6358:    }
 6359: 
 6360: # Resource preferences
 6361: 
 6362:    if ($thisallowed=~/R/) {
 6363:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6364:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6365: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6366: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6367: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6368: 	   }
 6369: 	   return '';
 6370:        }
 6371:    }
 6372: 
 6373: # Restricted by state or randomout?
 6374: 
 6375:    if ($thisallowed=~/X/) {
 6376:       if ($env{'acc.randomout'}) {
 6377: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6378:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6379:             return ''; 
 6380:          }
 6381:       }
 6382:       if (&condval($statecond)) {
 6383: 	 return '2';
 6384:       } else {
 6385:          return '';
 6386:       }
 6387:    }
 6388: 
 6389:     if ($thisallowed eq 'A') {
 6390: 	return 'A';
 6391:     } elsif ($thisallowed eq 'B') {
 6392:         return 'B';
 6393:     }
 6394:    return 'F';
 6395: }
 6396: 
 6397: sub get_comm_blocks {
 6398:     my ($cdom,$cnum) = @_;
 6399:     if ($cdom eq '' || $cnum eq '') {
 6400:         return unless ($env{'request.course.id'});
 6401:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6402:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6403:     }
 6404:     my %commblocks;
 6405:     my $hashid=$cdom.'_'.$cnum;
 6406:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6407:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6408:         %commblocks = %{$blocksref};
 6409:     } else {
 6410:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6411:         my $cachetime = 600;
 6412:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6413:     }
 6414:     return %commblocks;
 6415: }
 6416: 
 6417: sub has_comm_blocking {
 6418:     my ($priv,$symb,$uri,$blocks) = @_;
 6419:     return unless ($env{'request.course.id'});
 6420:     return unless ($priv eq 'bre');
 6421:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6422:     my %commblocks;
 6423:     if (ref($blocks) eq 'HASH') {
 6424:         %commblocks = %{$blocks};
 6425:     } else {
 6426:         %commblocks = &get_comm_blocks();
 6427:     }
 6428:     return unless (keys(%commblocks) > 0);
 6429:     if (!$symb) { $symb=&symbread($uri,1); }
 6430:     my ($map,$resid,undef)=&decode_symb($symb);
 6431:     my %tocheck = (
 6432:                     maps      => $map,
 6433:                     resources => $symb,
 6434:                   );
 6435:     my @blockers;
 6436:     my $now = time;
 6437:     my $navmap = Apache::lonnavmaps::navmap->new();
 6438:     foreach my $block (keys(%commblocks)) {
 6439:         if ($block =~ /^(\d+)____(\d+)$/) {
 6440:             my ($start,$end) = ($1,$2);
 6441:             if ($start <= $now && $end >= $now) {
 6442:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6443:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6444:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6445:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6446:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6447:                                     push(@blockers,$block);
 6448:                                 }
 6449:                             }
 6450:                         }
 6451:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6452:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6453:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6454:                                     push(@blockers,$block);
 6455:                                 }
 6456:                             }
 6457:                         }
 6458:                     }
 6459:                 }
 6460:             }
 6461:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6462:             my $item = $1;
 6463:             my @to_test;
 6464:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6465:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6466:                     my $check_interval;
 6467:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6468:                         my @interval;
 6469:                         my $type = 'map';
 6470:                         if ($item eq 'course') {
 6471:                             $type = 'course';
 6472:                             @interval=&EXT("resource.0.interval");
 6473:                         } else {
 6474:                             if ($item =~ /___\d+___/) {
 6475:                                 $type = 'resource';
 6476:                                 @interval=&EXT("resource.0.interval",$item);
 6477:                                 if (ref($navmap)) {                        
 6478:                                     my $res = $navmap->getBySymb($item); 
 6479:                                     push(@to_test,$res);
 6480:                                 }
 6481:                             } else {
 6482:                                 my $mapsymb = &symbread($item,1);
 6483:                                 if ($mapsymb) {
 6484:                                     if (ref($navmap)) {
 6485:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6486:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6487:                                         foreach my $res (@to_test) {
 6488:                                             my $symb = $res->symb();
 6489:                                             next if ($symb eq $mapsymb);
 6490:                                             if ($symb ne '') {
 6491:                                                 @interval=&EXT("resource.0.interval",$symb);
 6492:                                                 last;
 6493:                                             }
 6494:                                         }
 6495:                                     }
 6496:                                 }
 6497:                             }
 6498:                         }
 6499:                         if ($interval[0] =~ /\d+/) {
 6500:                             my $first_access;
 6501:                             if ($type eq 'resource') {
 6502:                                 $first_access=&get_first_access($interval[1],$item);
 6503:                             } elsif ($type eq 'map') {
 6504:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6505:                             } else {
 6506:                                 $first_access=&get_first_access($interval[1]);
 6507:                             }
 6508:                             if ($first_access) {
 6509:                                 my $timesup = $first_access+$interval[0];
 6510:                                 if ($timesup > $now) {
 6511:                                     foreach my $res (@to_test) {
 6512:                                         if ($res->is_problem()) {
 6513:                                             if ($res->completable()) {
 6514:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6515:                                                     push(@blockers,$block);
 6516:                                                 }
 6517:                                                 last;
 6518:                                             }
 6519:                                         }
 6520:                                     }
 6521:                                 }
 6522:                             }
 6523:                         }
 6524:                     }
 6525:                 }
 6526:             }
 6527:         }
 6528:     }
 6529:     return @blockers;
 6530: }
 6531: 
 6532: sub check_docs_block {
 6533:     my ($docsblock,$tocheck) =@_;
 6534:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 6535:         return;
 6536:     }
 6537:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 6538:         if ($tocheck->{'maps'}) {
 6539:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 6540:                 return 1;
 6541:             }
 6542:         }
 6543:     }
 6544:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 6545:         if ($tocheck->{'resources'}) {
 6546:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 6547:                 return 1;
 6548:             }
 6549:         }
 6550:     }
 6551:     return;
 6552: }
 6553: 
 6554: #
 6555: #   Removes the versino from a URI and
 6556: #   splits it in to its filename and path to the filename.
 6557: #   Seems like File::Basename could have done this more clearly.
 6558: #   Parameters:
 6559: #      $uri   - input URI
 6560: #   Returns:
 6561: #     Two element list consisting of 
 6562: #     $pathname  - the URI up to and excluding the trailing /
 6563: #     $filename  - The part of the URI following the last /
 6564: #  NOTE:
 6565: #    Another realization of this is simply:
 6566: #    use File::Basename;
 6567: #    ...
 6568: #    $uri = shift;
 6569: #    $filename = basename($uri);
 6570: #    $path     = dirname($uri);
 6571: #    return ($filename, $path);
 6572: #
 6573: #     The implementation below is probably faster however.
 6574: #
 6575: sub split_uri_for_cond {
 6576:     my $uri=&deversion(&declutter(shift));
 6577:     my @uriparts=split(/\//,$uri);
 6578:     my $filename=pop(@uriparts);
 6579:     my $pathname=join('/',@uriparts);
 6580:     return ($pathname,$filename);
 6581: }
 6582: # --------------------------------------------------- Is a resource on the map?
 6583: 
 6584: sub is_on_map {
 6585:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6586:     #Trying to find the conditional for the file
 6587:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6588: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6589:     if ($match) {
 6590: 	return (1,$1);
 6591:     } else {
 6592: 	return (0,0);
 6593:     }
 6594: }
 6595: 
 6596: # --------------------------------------------------------- Get symb from alias
 6597: 
 6598: sub get_symb_from_alias {
 6599:     my $symb=shift;
 6600:     my ($map,$resid,$url)=&decode_symb($symb);
 6601: # Already is a symb
 6602:     if ($url) { return $symb; }
 6603: # Must be an alias
 6604:     my $aliassymb='';
 6605:     my %bighash;
 6606:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6607:                             &GDBM_READER(),0640)) {
 6608:         my $rid=$bighash{'mapalias_'.$symb};
 6609: 	if ($rid) {
 6610: 	    my ($mapid,$resid)=split(/\./,$rid);
 6611: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6612: 				    $resid,$bighash{'src_'.$rid});
 6613: 	}
 6614:         untie %bighash;
 6615:     }
 6616:     return $aliassymb;
 6617: }
 6618: 
 6619: # ----------------------------------------------------------------- Define Role
 6620: 
 6621: sub definerole {
 6622:   if (allowed('mcr','/')) {
 6623:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6624:     foreach my $role (split(':',$sysrole)) {
 6625: 	my ($crole,$cqual)=split(/\&/,$role);
 6626:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6627:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6628: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6629:                return "refused:s:$crole&$cqual"; 
 6630:             }
 6631:         }
 6632:     }
 6633:     foreach my $role (split(':',$domrole)) {
 6634: 	my ($crole,$cqual)=split(/\&/,$role);
 6635:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6636:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6637: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6638:                return "refused:d:$crole&$cqual"; 
 6639:             }
 6640:         }
 6641:     }
 6642:     foreach my $role (split(':',$courole)) {
 6643: 	my ($crole,$cqual)=split(/\&/,$role);
 6644:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6645:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6646: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6647:                return "refused:c:$crole&$cqual"; 
 6648:             }
 6649:         }
 6650:     }
 6651:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6652:                 "$env{'user.domain'}:$env{'user.name'}:".
 6653: 	        "rolesdef_$rolename=".
 6654:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6655:     return reply($command,$env{'user.home'});
 6656:   } else {
 6657:     return 'refused';
 6658:   }
 6659: }
 6660: 
 6661: # ---------------- Make a metadata query against the network of library servers
 6662: 
 6663: sub metadata_query {
 6664:     my ($query,$custom,$customshow,$server_array)=@_;
 6665:     my %rhash;
 6666:     my %libserv = &all_library();
 6667:     my @server_list = (defined($server_array) ? @$server_array
 6668:                                               : keys(%libserv) );
 6669:     for my $server (@server_list) {
 6670: 	unless ($custom or $customshow) {
 6671: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6672: 	    $rhash{$server}=$reply;
 6673: 	}
 6674: 	else {
 6675: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6676: 			     &escape($custom).':'.&escape($customshow),
 6677: 			     $server);
 6678: 	    $rhash{$server}=$reply;
 6679: 	}
 6680:     }
 6681:     return \%rhash;
 6682: }
 6683: 
 6684: # ----------------------------------------- Send log queries and wait for reply
 6685: 
 6686: sub log_query {
 6687:     my ($uname,$udom,$query,%filters)=@_;
 6688:     my $uhome=&homeserver($uname,$udom);
 6689:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6690:     my $uhost=&hostname($uhome);
 6691:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6692:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6693:                        $uhome);
 6694:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6695:     return get_query_reply($queryid);
 6696: }
 6697: 
 6698: # -------------------------- Update MySQL table for portfolio file
 6699: 
 6700: sub update_portfolio_table {
 6701:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6702:     if ($group ne '') {
 6703:         $file_name =~s /^\Q$group\E//;
 6704:     }
 6705:     my $homeserver = &homeserver($uname,$udom);
 6706:     my $queryid=
 6707:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6708:                ':'.&escape($file_name).':'.$action,$homeserver);
 6709:     my $reply = &get_query_reply($queryid);
 6710:     return $reply;
 6711: }
 6712: 
 6713: # -------------------------- Update MySQL allusers table
 6714: 
 6715: sub update_allusers_table {
 6716:     my ($uname,$udom,$names) = @_;
 6717:     my $homeserver = &homeserver($uname,$udom);
 6718:     my $queryid=
 6719:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6720:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6721:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6722:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6723:                'generation='.&escape($names->{'generation'}).'%%'.
 6724:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6725:                'id='.&escape($names->{'id'}),$homeserver);
 6726:     return;
 6727: }
 6728: 
 6729: # ------- Request retrieval of institutional classlists for course(s)
 6730: 
 6731: sub fetch_enrollment_query {
 6732:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6733:     my $homeserver;
 6734:     my $maxtries = 1;
 6735:     if ($context eq 'automated') {
 6736:         $homeserver = $perlvar{'lonHostID'};
 6737:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6738:     } else {
 6739:         $homeserver = &homeserver($cnum,$dom);
 6740:     }
 6741:     my $host=&hostname($homeserver);
 6742:     my $cmd = '';
 6743:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6744:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6745:     }
 6746:     $cmd =~ s/%%$//;
 6747:     $cmd = &escape($cmd);
 6748:     my $query = 'fetchenrollment';
 6749:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6750:     unless ($queryid=~/^\Q$host\E\_/) { 
 6751:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6752:         return 'error: '.$queryid;
 6753:     }
 6754:     my $reply = &get_query_reply($queryid);
 6755:     my $tries = 1;
 6756:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6757:         $reply = &get_query_reply($queryid);
 6758:         $tries ++;
 6759:     }
 6760:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6761:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6762:     } else {
 6763:         my @responses = split(/:/,$reply);
 6764:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6765:             foreach my $line (@responses) {
 6766:                 my ($key,$value) = split(/=/,$line,2);
 6767:                 $$replyref{$key} = $value;
 6768:             }
 6769:         } else {
 6770:             my $pathname = LONCAPA::tempdir();
 6771:             foreach my $line (@responses) {
 6772:                 my ($key,$value) = split(/=/,$line);
 6773:                 $$replyref{$key} = $value;
 6774:                 if ($value > 0) {
 6775:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6776:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6777:                         my $destname = $pathname.'/'.$filename;
 6778:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6779:                         if ($xml_classlist =~ /^error/) {
 6780:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6781:                         } else {
 6782:                             if ( open(FILE,">$destname") ) {
 6783:                                 print FILE &unescape($xml_classlist);
 6784:                                 close(FILE);
 6785:                             } else {
 6786:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6787:                             }
 6788:                         }
 6789:                     }
 6790:                 }
 6791:             }
 6792:         }
 6793:         return 'ok';
 6794:     }
 6795:     return 'error';
 6796: }
 6797: 
 6798: sub get_query_reply {
 6799:     my $queryid=shift;
 6800:     my $replyfile=LONCAPA::tempdir().$queryid;
 6801:     my $reply='';
 6802:     for (1..100) {
 6803: 	sleep 2;
 6804:         if (-e $replyfile.'.end') {
 6805: 	    if (open(my $fh,$replyfile)) {
 6806: 		$reply = join('',<$fh>);
 6807: 		close($fh);
 6808: 	   } else { return 'error: reply_file_error'; }
 6809:            return &unescape($reply);
 6810: 	}
 6811:     }
 6812:     return 'timeout:'.$queryid;
 6813: }
 6814: 
 6815: sub courselog_query {
 6816: #
 6817: # possible filters:
 6818: # url: url or symb
 6819: # username
 6820: # domain
 6821: # action: view, submit, grade
 6822: # start: timestamp
 6823: # end: timestamp
 6824: #
 6825:     my (%filters)=@_;
 6826:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6827:     if ($filters{'url'}) {
 6828: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6829:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6830:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6831:     }
 6832:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6833:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6834:     return &log_query($cname,$cdom,'courselog',%filters);
 6835: }
 6836: 
 6837: sub userlog_query {
 6838: #
 6839: # possible filters:
 6840: # action: log check role
 6841: # start: timestamp
 6842: # end: timestamp
 6843: #
 6844:     my ($uname,$udom,%filters)=@_;
 6845:     return &log_query($uname,$udom,'userlog',%filters);
 6846: }
 6847: 
 6848: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6849: 
 6850: sub auto_run {
 6851:     my ($cnum,$cdom) = @_;
 6852:     my $response = 0;
 6853:     my $settings;
 6854:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6855:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6856:         $settings = $domconfig{'autoenroll'};
 6857:         if ($settings->{'run'} eq '1') {
 6858:             $response = 1;
 6859:         }
 6860:     } else {
 6861:         my $homeserver;
 6862:         if (&is_course($cdom,$cnum)) {
 6863:             $homeserver = &homeserver($cnum,$cdom);
 6864:         } else {
 6865:             $homeserver = &domain($cdom,'primary');
 6866:         }
 6867:         if ($homeserver ne 'no_host') {
 6868:             $response = &reply('autorun:'.$cdom,$homeserver);
 6869:         }
 6870:     }
 6871:     return $response;
 6872: }
 6873: 
 6874: sub auto_get_sections {
 6875:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6876:     my $homeserver;
 6877:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6878:         $homeserver = &homeserver($cnum,$cdom);
 6879:     }
 6880:     if (!defined($homeserver)) { 
 6881:         if ($cdom =~ /^$match_domain$/) {
 6882:             $homeserver = &domain($cdom,'primary');
 6883:         }
 6884:     }
 6885:     my @secs;
 6886:     if (defined($homeserver)) {
 6887:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6888:         unless ($response eq 'refused') {
 6889:             @secs = split(/:/,$response);
 6890:         }
 6891:     }
 6892:     return @secs;
 6893: }
 6894: 
 6895: sub auto_new_course {
 6896:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6897:     my $homeserver = &homeserver($cnum,$cdom);
 6898:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6899:     return $response;
 6900: }
 6901: 
 6902: sub auto_validate_courseID {
 6903:     my ($cnum,$cdom,$inst_course_id) = @_;
 6904:     my $homeserver = &homeserver($cnum,$cdom);
 6905:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6906:     return $response;
 6907: }
 6908: 
 6909: sub auto_validate_instcode {
 6910:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6911:     my ($homeserver,$response);
 6912:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6913:         $homeserver = &homeserver($cnum,$cdom);
 6914:     }
 6915:     if (!defined($homeserver)) {
 6916:         if ($cdom =~ /^$match_domain$/) {
 6917:             $homeserver = &domain($cdom,'primary');
 6918:         }
 6919:     }
 6920:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6921:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6922:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6923:     return ($outcome,$description);
 6924: }
 6925: 
 6926: sub auto_create_password {
 6927:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6928:     my ($homeserver,$response);
 6929:     my $create_passwd = 0;
 6930:     my $authchk = '';
 6931:     if ($udom =~ /^$match_domain$/) {
 6932:         $homeserver = &domain($udom,'primary');
 6933:     }
 6934:     if ($homeserver eq '') {
 6935:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6936:             $homeserver = &homeserver($cnum,$cdom);
 6937:         }
 6938:     }
 6939:     if ($homeserver eq '') {
 6940:         $authchk = 'nodomain';
 6941:     } else {
 6942:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 6943:         if ($response eq 'refused') {
 6944:             $authchk = 'refused';
 6945:         } else {
 6946:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 6947:         }
 6948:     }
 6949:     return ($authparam,$create_passwd,$authchk);
 6950: }
 6951: 
 6952: sub auto_photo_permission {
 6953:     my ($cnum,$cdom,$students) = @_;
 6954:     my $homeserver = &homeserver($cnum,$cdom);
 6955:     my ($outcome,$perm_reqd,$conditions) = 
 6956: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 6957:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6958: 	return (undef,undef);
 6959:     }
 6960:     return ($outcome,$perm_reqd,$conditions);
 6961: }
 6962: 
 6963: sub auto_checkphotos {
 6964:     my ($uname,$udom,$pid) = @_;
 6965:     my $homeserver = &homeserver($uname,$udom);
 6966:     my ($result,$resulttype);
 6967:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 6968: 				   &escape($uname).':'.&escape($pid),
 6969: 				   $homeserver));
 6970:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6971: 	return (undef,undef);
 6972:     }
 6973:     if ($outcome) {
 6974:         ($result,$resulttype) = split(/:/,$outcome);
 6975:     } 
 6976:     return ($result,$resulttype);
 6977: }
 6978: 
 6979: sub auto_photochoice {
 6980:     my ($cnum,$cdom) = @_;
 6981:     my $homeserver = &homeserver($cnum,$cdom);
 6982:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 6983: 						       &escape($cdom),
 6984: 						       $homeserver)));
 6985:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6986: 	return (undef,undef);
 6987:     }
 6988:     return ($update,$comment);
 6989: }
 6990: 
 6991: sub auto_photoupdate {
 6992:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 6993:     my $homeserver = &homeserver($cnum,$dom);
 6994:     my $host=&hostname($homeserver);
 6995:     my $cmd = '';
 6996:     my $maxtries = 1;
 6997:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6998:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6999:     }
 7000:     $cmd =~ s/%%$//;
 7001:     $cmd = &escape($cmd);
 7002:     my $query = 'institutionalphotos';
 7003:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7004:     unless ($queryid=~/^\Q$host\E\_/) {
 7005:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7006:         return 'error: '.$queryid;
 7007:     }
 7008:     my $reply = &get_query_reply($queryid);
 7009:     my $tries = 1;
 7010:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7011:         $reply = &get_query_reply($queryid);
 7012:         $tries ++;
 7013:     }
 7014:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7015:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7016:     } else {
 7017:         my @responses = split(/:/,$reply);
 7018:         my $outcome = shift(@responses); 
 7019:         foreach my $item (@responses) {
 7020:             my ($key,$value) = split(/=/,$item);
 7021:             $$photo{$key} = $value;
 7022:         }
 7023:         return $outcome;
 7024:     }
 7025:     return 'error';
 7026: }
 7027: 
 7028: sub auto_instcode_format {
 7029:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7030: 	$cat_order) = @_;
 7031:     my $courses = '';
 7032:     my @homeservers;
 7033:     if ($caller eq 'global') {
 7034: 	my %servers = &get_servers($codedom,'library');
 7035: 	foreach my $tryserver (keys(%servers)) {
 7036: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7037: 		push(@homeservers,$tryserver);
 7038: 	    }
 7039:         }
 7040:     } elsif ($caller eq 'requests') {
 7041:         if ($codedom =~ /^$match_domain$/) {
 7042:             my $chome = &domain($codedom,'primary');
 7043:             unless ($chome eq 'no_host') {
 7044:                 push(@homeservers,$chome);
 7045:             }
 7046:         }
 7047:     } else {
 7048:         push(@homeservers,&homeserver($caller,$codedom));
 7049:     }
 7050:     foreach my $code (keys(%{$instcodes})) {
 7051:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7052:     }
 7053:     chop($courses);
 7054:     my $ok_response = 0;
 7055:     my $response;
 7056:     while (@homeservers > 0 && $ok_response == 0) {
 7057:         my $server = shift(@homeservers); 
 7058:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7059:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7060:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7061: 		split(/:/,$response);
 7062:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7063:             push(@{$codetitles},&str2array($codetitles_str));
 7064:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7065:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7066:             $ok_response = 1;
 7067:         }
 7068:     }
 7069:     if ($ok_response) {
 7070:         return 'ok';
 7071:     } else {
 7072:         return $response;
 7073:     }
 7074: }
 7075: 
 7076: sub auto_instcode_defaults {
 7077:     my ($domain,$returnhash,$code_order) = @_;
 7078:     my @homeservers;
 7079: 
 7080:     my %servers = &get_servers($domain,'library');
 7081:     foreach my $tryserver (keys(%servers)) {
 7082: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7083: 	    push(@homeservers,$tryserver);
 7084: 	}
 7085:     }
 7086: 
 7087:     my $response;
 7088:     foreach my $server (@homeservers) {
 7089:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7090:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7091: 	
 7092: 	foreach my $pair (split(/\&/,$response)) {
 7093: 	    my ($name,$value)=split(/\=/,$pair);
 7094: 	    if ($name eq 'code_order') {
 7095: 		@{$code_order} = split(/\&/,&unescape($value));
 7096: 	    } else {
 7097: 		$returnhash->{&unescape($name)}=&unescape($value);
 7098: 	    }
 7099: 	}
 7100: 	return 'ok';
 7101:     }
 7102: 
 7103:     return $response;
 7104: }
 7105: 
 7106: sub auto_possible_instcodes {
 7107:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7108:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7109:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7110:         return;
 7111:     }
 7112:     my (@homeservers,$uhome);
 7113:     if (defined(&domain($domain,'primary'))) {
 7114:         $uhome=&domain($domain,'primary');
 7115:         push(@homeservers,&domain($domain,'primary'));
 7116:     } else {
 7117:         my %servers = &get_servers($domain,'library');
 7118:         foreach my $tryserver (keys(%servers)) {
 7119:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7120:                 push(@homeservers,$tryserver);
 7121:             }
 7122:         }
 7123:     }
 7124:     my $response;
 7125:     foreach my $server (@homeservers) {
 7126:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7127:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7128:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7129:             split(':',$response);
 7130:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7131:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7132:         foreach my $item (split('&',$cat_title)) {   
 7133:             my ($name,$value)=split('=',$item);
 7134:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7135:         }
 7136:         foreach my $item (split('&',$cat_order)) {
 7137:             my ($name,$value)=split('=',$item);
 7138:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7139:         }
 7140:         return 'ok';
 7141:     }
 7142:     return $response;
 7143: }
 7144: 
 7145: sub auto_courserequest_checks {
 7146:     my ($dom) = @_;
 7147:     my ($homeserver,%validations);
 7148:     if ($dom =~ /^$match_domain$/) {
 7149:         $homeserver = &domain($dom,'primary');
 7150:     }
 7151:     unless ($homeserver eq 'no_host') {
 7152:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7153:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7154:             my @items = split(/&/,$response);
 7155:             foreach my $item (@items) {
 7156:                 my ($key,$value) = split('=',$item);
 7157:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7158:             }
 7159:         }
 7160:     }
 7161:     return %validations; 
 7162: }
 7163: 
 7164: sub auto_courserequest_validation {
 7165:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7166:     my ($homeserver,$response);
 7167:     if ($dom =~ /^$match_domain$/) {
 7168:         $homeserver = &domain($dom,'primary');
 7169:     }
 7170:     unless ($homeserver eq 'no_host') {  
 7171:           
 7172:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7173:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7174:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7175:                                     $homeserver));
 7176:     }
 7177:     return $response;
 7178: }
 7179: 
 7180: sub auto_validate_class_sec {
 7181:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7182:     my $homeserver = &homeserver($cnum,$cdom);
 7183:     my $ownerlist;
 7184:     if (ref($owners) eq 'ARRAY') {
 7185:         $ownerlist = join(',',@{$owners});
 7186:     } else {
 7187:         $ownerlist = $owners;
 7188:     }
 7189:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7190:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7191:     return $response;
 7192: }
 7193: 
 7194: # ------------------------------------------------------- Course Group routines
 7195: 
 7196: sub get_coursegroups {
 7197:     my ($cdom,$cnum,$group,$namespace) = @_;
 7198:     return(&dump($namespace,$cdom,$cnum,$group));
 7199: }
 7200: 
 7201: sub modify_coursegroup {
 7202:     my ($cdom,$cnum,$groupsettings) = @_;
 7203:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7204: }
 7205: 
 7206: sub toggle_coursegroup_status {
 7207:     my ($cdom,$cnum,$group,$action) = @_;
 7208:     my ($from_namespace,$to_namespace);
 7209:     if ($action eq 'delete') {
 7210:         $from_namespace = 'coursegroups';
 7211:         $to_namespace = 'deleted_groups';
 7212:     } else {
 7213:         $from_namespace = 'deleted_groups';
 7214:         $to_namespace = 'coursegroups';
 7215:     }
 7216:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7217:     if (my $tmp = &error(%curr_group)) {
 7218:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7219:         return ('read error',$tmp);
 7220:     } else {
 7221:         my %savedsettings = %curr_group; 
 7222:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7223:         my $deloutcome;
 7224:         if ($result eq 'ok') {
 7225:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7226:         } else {
 7227:             return ('write error',$result);
 7228:         }
 7229:         if ($deloutcome eq 'ok') {
 7230:             return 'ok';
 7231:         } else {
 7232:             return ('delete error',$deloutcome);
 7233:         }
 7234:     }
 7235: }
 7236: 
 7237: sub modify_group_roles {
 7238:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7239:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7240:     my $role = 'gr/'.&escape($userprivs);
 7241:     my ($uname,$udom) = split(/:/,$user);
 7242:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7243:     if ($result eq 'ok') {
 7244:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7245:     }
 7246:     return $result;
 7247: }
 7248: 
 7249: sub modify_coursegroup_membership {
 7250:     my ($cdom,$cnum,$membership) = @_;
 7251:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7252:     return $result;
 7253: }
 7254: 
 7255: sub get_active_groups {
 7256:     my ($udom,$uname,$cdom,$cnum) = @_;
 7257:     my $now = time;
 7258:     my %groups = ();
 7259:     foreach my $key (keys(%env)) {
 7260:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7261:             my ($start,$end) = split(/\./,$env{$key});
 7262:             if (($end!=0) && ($end<$now)) { next; }
 7263:             if (($start!=0) && ($start>$now)) { next; }
 7264:             if ($1 eq $cdom && $2 eq $cnum) {
 7265:                 $groups{$3} = $env{$key} ;
 7266:             }
 7267:         }
 7268:     }
 7269:     return %groups;
 7270: }
 7271: 
 7272: sub get_group_membership {
 7273:     my ($cdom,$cnum,$group) = @_;
 7274:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7275: }
 7276: 
 7277: sub get_users_groups {
 7278:     my ($udom,$uname,$courseid) = @_;
 7279:     my @usersgroups;
 7280:     my $cachetime=1800;
 7281: 
 7282:     my $hashid="$udom:$uname:$courseid";
 7283:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7284:     if (defined($cached)) {
 7285:         @usersgroups = split(/:/,$grouplist);
 7286:     } else {  
 7287:         $grouplist = '';
 7288:         my $courseurl = &courseid_to_courseurl($courseid);
 7289:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7290:         my $access_end = $env{'course.'.$courseid.
 7291:                               '.default_enrollment_end_date'};
 7292:         my $now = time;
 7293:         foreach my $key (keys(%roleshash)) {
 7294:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7295:                 my $group = $1;
 7296:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7297:                     my $start = $2;
 7298:                     my $end = $1;
 7299:                     if ($start == -1) { next; } # deleted from group
 7300:                     if (($start!=0) && ($start>$now)) { next; }
 7301:                     if (($end!=0) && ($end<$now)) {
 7302:                         if ($access_end && $access_end < $now) {
 7303:                             if ($access_end - $end < 86400) {
 7304:                                 push(@usersgroups,$group);
 7305:                             }
 7306:                         }
 7307:                         next;
 7308:                     }
 7309:                     push(@usersgroups,$group);
 7310:                 }
 7311:             }
 7312:         }
 7313:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7314:         $grouplist = join(':',@usersgroups);
 7315:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7316:     }
 7317:     return @usersgroups;
 7318: }
 7319: 
 7320: sub devalidate_getgroups_cache {
 7321:     my ($udom,$uname,$cdom,$cnum)=@_;
 7322:     my $courseid = $cdom.'_'.$cnum;
 7323: 
 7324:     my $hashid="$udom:$uname:$courseid";
 7325:     &devalidate_cache_new('getgroups',$hashid);
 7326: }
 7327: 
 7328: # ------------------------------------------------------------------ Plain Text
 7329: 
 7330: sub plaintext {
 7331:     my ($short,$type,$cid,$forcedefault) = @_;
 7332:     if ($short =~ m{^cr/}) {
 7333: 	return (split('/',$short))[-1];
 7334:     }
 7335:     if (!defined($cid)) {
 7336:         $cid = $env{'request.course.id'};
 7337:     }
 7338:     my %rolenames = (
 7339:                       Course    => 'std',
 7340:                       Community => 'alt1',
 7341:                     );
 7342:     if ($cid ne '') {
 7343:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7344:             unless ($forcedefault) {
 7345:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7346:                 &Apache::lonlocal::mt_escape(\$roletext);
 7347:                 return &Apache::lonlocal::mt($roletext);
 7348:             }
 7349:         }
 7350:     }
 7351:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7352:         (defined($rolenames{$type})) && 
 7353:         (defined($prp{$short}{$rolenames{$type}}))) {
 7354:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7355:     } elsif ($cid ne '') {
 7356:         my $crstype = $env{'course.'.$cid.'.type'};
 7357:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7358:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7359:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7360:         }
 7361:     }
 7362:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7363: }
 7364: 
 7365: # ----------------------------------------------------------------- Assign Role
 7366: 
 7367: sub assignrole {
 7368:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7369:         $context)=@_;
 7370:     my $mrole;
 7371:     if ($role =~ /^cr\//) {
 7372:         my $cwosec=$url;
 7373:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7374: 	unless (&allowed('ccr',$cwosec)) {
 7375:            my $refused = 1;
 7376:            if ($context eq 'requestcourses') {
 7377:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7378:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7379:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7380:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7381:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7382:                            if ($crsenv{'internal.courseowner'} eq
 7383:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7384:                                $refused = '';
 7385:                            }
 7386:                        }
 7387:                    }
 7388:                }
 7389:            }
 7390:            if ($refused) {
 7391:                &logthis('Refused custom assignrole: '.
 7392:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7393:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7394:                return 'refused';
 7395:            }
 7396:         }
 7397:         $mrole='cr';
 7398:     } elsif ($role =~ /^gr\//) {
 7399:         my $cwogrp=$url;
 7400:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7401:         unless (&allowed('mdg',$cwogrp)) {
 7402:             &logthis('Refused group assignrole: '.
 7403:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7404:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7405:             return 'refused';
 7406:         }
 7407:         $mrole='gr';
 7408:     } else {
 7409:         my $cwosec=$url;
 7410:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7411:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7412:             my $refused;
 7413:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7414:                 if (!(&allowed('c'.$role,$url))) {
 7415:                     $refused = 1;
 7416:                 }
 7417:             } else {
 7418:                 $refused = 1;
 7419:             }
 7420:             if ($refused) {
 7421:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7422:                 if (!$selfenroll && $context eq 'course') {
 7423:                     my %crsenv;
 7424:                     if ($role eq 'cc' || $role eq 'co') {
 7425:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7426:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7427:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7428:                                 if ($crsenv{'internal.courseowner'} eq 
 7429:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7430:                                     $refused = '';
 7431:                                 }
 7432:                             }
 7433:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7434:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7435:                                 if ($crsenv{'internal.courseowner'} eq 
 7436:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7437:                                     $refused = '';
 7438:                                 }
 7439:                             }
 7440:                         }
 7441:                     }
 7442:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7443:                     $refused = '';
 7444:                 } elsif ($context eq 'requestcourses') {
 7445:                     my @possroles = ('st','ta','ep','in','cc','co');
 7446:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7447:                         my $wrongcc;
 7448:                         if ($cnum =~ /^$match_community$/) {
 7449:                             $wrongcc = 1 if ($role eq 'cc');
 7450:                         } else {
 7451:                             $wrongcc = 1 if ($role eq 'co');
 7452:                         }
 7453:                         unless ($wrongcc) {
 7454:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7455:                             if ($crsenv{'internal.courseowner'} eq 
 7456:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7457:                                 $refused = '';
 7458:                             }
 7459:                         }
 7460:                     }
 7461:                 }
 7462:                 if ($refused) {
 7463:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7464:                              ' '.$role.' '.$end.' '.$start.' by '.
 7465: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7466:                     return 'refused';
 7467:                 }
 7468:             }
 7469:         } elsif ($role eq 'au') {
 7470:             if ($url ne '/'.$udom.'/') {
 7471:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7472:                          ' to assign author role for '.$uname.':'.$udom.
 7473:                          ' in domain: '.$url.' refused (wrong domain).');
 7474:                 return 'refused';
 7475:             }
 7476:         }
 7477:         $mrole=$role;
 7478:     }
 7479:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7480:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7481:     if ($end) { $command.='_'.$end; }
 7482:     if ($start) {
 7483: 	if ($end) { 
 7484:            $command.='_'.$start; 
 7485:         } else {
 7486:            $command.='_0_'.$start;
 7487:         }
 7488:     }
 7489:     my $origstart = $start;
 7490:     my $origend = $end;
 7491:     my $delflag;
 7492: # actually delete
 7493:     if ($deleteflag) {
 7494: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7495: # modify command to delete the role
 7496:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7497:                 "$udom:$uname:$url".'_'."$mrole";
 7498: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7499: # set start and finish to negative values for userrolelog
 7500:            $start=-1;
 7501:            $end=-1;
 7502:            $delflag = 1;
 7503:         }
 7504:     }
 7505: # send command
 7506:     my $answer=&reply($command,&homeserver($uname,$udom));
 7507: # log new user role if status is ok
 7508:     if ($answer eq 'ok') {
 7509: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7510: # for course roles, perform group memberships changes triggered by role change.
 7511:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7512:         unless ($role =~ /^gr/) {
 7513:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7514:                                              $origstart,$selfenroll,$context);
 7515:         }
 7516:         if ($role eq 'cc') {
 7517:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7518:         }
 7519:     }
 7520:     return $answer;
 7521: }
 7522: 
 7523: sub autoupdate_coowners {
 7524:     my ($url,$end,$start,$uname,$udom) = @_;
 7525:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7526:     if (($cdom ne '') && ($cnum ne '')) {
 7527:         my $now = time;
 7528:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7529:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7530:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7531:             my $instcode = $coursehash{'internal.coursecode'};
 7532:             if ($instcode ne '') {
 7533:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7534:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7535:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7536:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7537:                         if ($result eq 'valid') {
 7538:                             if ($coursehash{'internal.co-owners'}) {
 7539:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7540:                                     push(@newcoowners,$coowner);
 7541:                                 }
 7542:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7543:                                     push(@newcoowners,$uname.':'.$udom);
 7544:                                 }
 7545:                                 @newcoowners = sort(@newcoowners);
 7546:                             } else {
 7547:                                 push(@newcoowners,$uname.':'.$udom);
 7548:                             }
 7549:                         } else {
 7550:                             if ($coursehash{'internal.co-owners'}) {
 7551:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7552:                                     unless ($coowner eq $uname.':'.$udom) {
 7553:                                         push(@newcoowners,$coowner);
 7554:                                     }
 7555:                                 }
 7556:                                 unless (@newcoowners > 0) {
 7557:                                     $delcoowners = 1;
 7558:                                     $coowners = '';
 7559:                                 }
 7560:                             }
 7561:                         }
 7562:                         if (@newcoowners || $delcoowners) {
 7563:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7564:                                             $delcoowners,@newcoowners);
 7565:                         }
 7566:                     }
 7567:                 }
 7568:             }
 7569:         }
 7570:     }
 7571: }
 7572: 
 7573: sub store_coowners {
 7574:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7575:     my $cid = $cdom.'_'.$cnum;
 7576:     my ($coowners,$delresult,$putresult);
 7577:     if (@newcoowners) {
 7578:         $coowners = join(',',@newcoowners);
 7579:         my %coownershash = (
 7580:                             'internal.co-owners' => $coowners,
 7581:                            );
 7582:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7583:         if ($putresult eq 'ok') {
 7584:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7585:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7586:             }
 7587:         }
 7588:     }
 7589:     if ($delcoowners) {
 7590:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7591:         if ($delresult eq 'ok') {
 7592:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7593:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7594:             }
 7595:         }
 7596:     }
 7597:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7598:         my %crsinfo =
 7599:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7600:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7601:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7602:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7603:         }
 7604:     }
 7605: }
 7606: 
 7607: # -------------------------------------------------- Modify user authentication
 7608: # Overrides without validation
 7609: 
 7610: sub modifyuserauth {
 7611:     my ($udom,$uname,$umode,$upass)=@_;
 7612:     my $uhome=&homeserver($uname,$udom);
 7613:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7614:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7615:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7616:              ' in domain '.$env{'request.role.domain'});  
 7617:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7618: 		     &escape($upass),$uhome);
 7619:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7620:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7621:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7622:     &log($udom,,$uname,$uhome,
 7623:         'Authentication changed by '.$env{'user.domain'}.', '.
 7624:                                      $env{'user.name'}.', '.$umode.
 7625:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7626:     unless ($reply eq 'ok') {
 7627:         &logthis('Authentication mode error: '.$reply);
 7628: 	return 'error: '.$reply;
 7629:     }   
 7630:     return 'ok';
 7631: }
 7632: 
 7633: # --------------------------------------------------------------- Modify a user
 7634: 
 7635: sub modifyuser {
 7636:     my ($udom,    $uname, $uid,
 7637:         $umode,   $upass, $first,
 7638:         $middle,  $last,  $gene,
 7639:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7640:     $udom= &LONCAPA::clean_domain($udom);
 7641:     $uname=&LONCAPA::clean_username($uname);
 7642:     my $showcandelete = 'none';
 7643:     if (ref($candelete) eq 'ARRAY') {
 7644:         if (@{$candelete} > 0) {
 7645:             $showcandelete = join(', ',@{$candelete});
 7646:         }
 7647:     }
 7648:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7649:              $umode.', '.$first.', '.$middle.', '.
 7650: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7651:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7652:                                      ' desiredhome not specified'). 
 7653:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7654:              ' in domain '.$env{'request.role.domain'});
 7655:     my $uhome=&homeserver($uname,$udom,'true');
 7656:     my $newuser;
 7657:     if ($uhome eq 'no_host') {
 7658:         $newuser = 1;
 7659:     }
 7660: # ----------------------------------------------------------------- Create User
 7661:     if (($uhome eq 'no_host') && 
 7662: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7663:         my $unhome='';
 7664:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7665:             $unhome = $desiredhome;
 7666: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7667: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7668:         } else { # load balancing routine for determining $unhome
 7669:             my $loadm=10000000;
 7670: 	    my %servers = &get_servers($udom,'library');
 7671: 	    foreach my $tryserver (keys(%servers)) {
 7672: 		my $answer=reply('load',$tryserver);
 7673: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7674: 		    $loadm=$answer;
 7675: 		    $unhome=$tryserver;
 7676: 		}
 7677: 	    }
 7678:         }
 7679:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7680: 	    return 'error: unable to find a home server for '.$uname.
 7681:                    ' in domain '.$udom;
 7682:         }
 7683:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7684:                          &escape($upass),$unhome);
 7685: 	unless ($reply eq 'ok') {
 7686:             return 'error: '.$reply;
 7687:         }   
 7688:         $uhome=&homeserver($uname,$udom,'true');
 7689:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7690: 	    return 'error: unable verify users home machine.';
 7691:         }
 7692:     }   # End of creation of new user
 7693: # ---------------------------------------------------------------------- Add ID
 7694:     if ($uid) {
 7695:        $uid=~tr/A-Z/a-z/;
 7696:        my %uidhash=&idrget($udom,$uname);
 7697:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7698:          && (!$forceid)) {
 7699: 	  unless ($uid eq $uidhash{$uname}) {
 7700: 	      return 'error: user id "'.$uid.'" does not match '.
 7701:                   'current user id "'.$uidhash{$uname}.'".';
 7702:           }
 7703:        } else {
 7704: 	  &idput($udom,($uname => $uid));
 7705:        }
 7706:     }
 7707: # -------------------------------------------------------------- Add names, etc
 7708:     my @tmp=&get('environment',
 7709: 		   ['firstname','middlename','lastname','generation','id',
 7710:                     'permanentemail','inststatus'],
 7711: 		   $udom,$uname);
 7712:     my (%names,%oldnames);
 7713:     if ($tmp[0] =~ m/^error:.*/) { 
 7714:         %names=(); 
 7715:     } else {
 7716:         %names = @tmp;
 7717:         %oldnames = %names;
 7718:     }
 7719: #
 7720: # If name, email and/or uid are blank (e.g., because an uploaded file
 7721: # of users did not contain them), do not overwrite existing values
 7722: # unless field is in $candelete array ref.  
 7723: #
 7724: 
 7725:     my @fields = ('firstname','middlename','lastname','generation',
 7726:                   'permanentemail','id');
 7727:     my %newvalues;
 7728:     if (ref($candelete) eq 'ARRAY') {
 7729:         foreach my $field (@fields) {
 7730:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7731:                 if ($field eq 'firstname') {
 7732:                     $names{$field} = $first;
 7733:                 } elsif ($field eq 'middlename') {
 7734:                     $names{$field} = $middle;
 7735:                 } elsif ($field eq 'lastname') {
 7736:                     $names{$field} = $last;
 7737:                 } elsif ($field eq 'generation') { 
 7738:                     $names{$field} = $gene;
 7739:                 } elsif ($field eq 'permanentemail') {
 7740:                     $names{$field} = $email;
 7741:                 } elsif ($field eq 'id') {
 7742:                     $names{$field}  = $uid;
 7743:                 }
 7744:             }
 7745:         }
 7746:     }
 7747:     if ($first)  { $names{'firstname'}  = $first; }
 7748:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7749:     if ($last)   { $names{'lastname'}   = $last; }
 7750:     if (defined($gene))   { $names{'generation'} = $gene; }
 7751:     if ($email) {
 7752:        $email=~s/[^\w\@\.\-\,]//gs;
 7753:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7754:     }
 7755:     if ($uid) { $names{'id'}  = $uid; }
 7756:     if (defined($inststatus)) {
 7757:         $names{'inststatus'} = '';
 7758:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7759:         if (ref($usertypes) eq 'HASH') {
 7760:             my @okstatuses; 
 7761:             foreach my $item (split(/:/,$inststatus)) {
 7762:                 if (defined($usertypes->{$item})) {
 7763:                     push(@okstatuses,$item);  
 7764:                 }
 7765:             }
 7766:             if (@okstatuses) {
 7767:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7768:             }
 7769:         }
 7770:     }
 7771:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7772:                  $umode.', '.$first.', '.$middle.', '.
 7773:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7774:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7775:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7776:     } else {
 7777:         $logmsg .= ' during self creation';
 7778:     }
 7779:     my $changed;
 7780:     if ($newuser) {
 7781:         $changed = 1;
 7782:     } else {
 7783:         foreach my $field (@fields) {
 7784:             if ($names{$field} ne $oldnames{$field}) {
 7785:                 $changed = 1;
 7786:                 last;
 7787:             }
 7788:         }
 7789:     }
 7790:     unless ($changed) {
 7791:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7792:         &logthis($logmsg);
 7793:         return 'ok';
 7794:     }
 7795:     my $reply = &put('environment', \%names, $udom,$uname);
 7796:     if ($reply ne 'ok') { 
 7797:         return 'error: '.$reply;
 7798:     }
 7799:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7800:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7801:     }
 7802:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7803:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7804:     $logmsg = 'Success modifying user '.$logmsg;
 7805:     &logthis($logmsg);
 7806:     return 'ok';
 7807: }
 7808: 
 7809: # -------------------------------------------------------------- Modify student
 7810: 
 7811: sub modifystudent {
 7812:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7813:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7814:         $selfenroll,$context,$inststatus)=@_;
 7815:     if (!$cid) {
 7816: 	unless ($cid=$env{'request.course.id'}) {
 7817: 	    return 'not_in_class';
 7818: 	}
 7819:     }
 7820: # --------------------------------------------------------------- Make the user
 7821:     my $reply=&modifyuser
 7822: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7823:          $desiredhome,$email,$inststatus);
 7824:     unless ($reply eq 'ok') { return $reply; }
 7825:     # This will cause &modify_student_enrollment to get the uid from the
 7826:     # students environment
 7827:     $uid = undef if (!$forceid);
 7828:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7829: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7830:     return $reply;
 7831: }
 7832: 
 7833: sub modify_student_enrollment {
 7834:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7835:     my ($cdom,$cnum,$chome);
 7836:     if (!$cid) {
 7837: 	unless ($cid=$env{'request.course.id'}) {
 7838: 	    return 'not_in_class';
 7839: 	}
 7840: 	$cdom=$env{'course.'.$cid.'.domain'};
 7841: 	$cnum=$env{'course.'.$cid.'.num'};
 7842:     } else {
 7843: 	($cdom,$cnum)=split(/_/,$cid);
 7844:     }
 7845:     $chome=$env{'course.'.$cid.'.home'};
 7846:     if (!$chome) {
 7847: 	$chome=&homeserver($cnum,$cdom);
 7848:     }
 7849:     if (!$chome) { return 'unknown_course'; }
 7850:     # Make sure the user exists
 7851:     my $uhome=&homeserver($uname,$udom);
 7852:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7853: 	return 'error: no such user';
 7854:     }
 7855:     # Get student data if we were not given enough information
 7856:     if (!defined($first)  || $first  eq '' || 
 7857:         !defined($last)   || $last   eq '' || 
 7858:         !defined($uid)    || $uid    eq '' || 
 7859:         !defined($middle) || $middle eq '' || 
 7860:         !defined($gene)   || $gene   eq '') {
 7861:         # They did not supply us with enough data to enroll the student, so
 7862:         # we need to pick up more information.
 7863:         my %tmp = &get('environment',
 7864:                        ['firstname','middlename','lastname', 'generation','id']
 7865:                        ,$udom,$uname);
 7866: 
 7867:         #foreach my $key (keys(%tmp)) {
 7868:         #    &logthis("key $key = ".$tmp{$key});
 7869:         #}
 7870:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7871:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7872:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7873:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7874:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7875:     }
 7876:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7877:     my $user = "$uname:$udom";
 7878:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 7879:     my $reply=cput('classlist',
 7880: 		   {$user => 
 7881: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7882: 		   $cdom,$cnum);
 7883:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 7884:         &devalidate_getsection_cache($udom,$uname,$cid);
 7885:     } else { 
 7886: 	return 'error: '.$reply;
 7887:     }
 7888:     # Add student role to user
 7889:     my $uurl='/'.$cid;
 7890:     $uurl=~s/\_/\//g;
 7891:     if ($usec) {
 7892: 	$uurl.='/'.$usec;
 7893:     }
 7894:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 7895:                              $selfenroll,$context);
 7896:     if ($result ne 'ok') {
 7897:         if ($old_entry{$user} ne '') {
 7898:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 7899:         } else {
 7900:             $reply = &del('classlist',[$user],$cdom,$cnum);
 7901:         }
 7902:     }
 7903:     return $result; 
 7904: }
 7905: 
 7906: sub format_name {
 7907:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 7908:     my $name;
 7909:     if ($first ne 'lastname') {
 7910: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 7911:     } else {
 7912: 	if ($lastname=~/\S/) {
 7913: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 7914: 	    $name=~s/\s+,/,/;
 7915: 	} else {
 7916: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 7917: 	}
 7918:     }
 7919:     $name=~s/^\s+//;
 7920:     $name=~s/\s+$//;
 7921:     $name=~s/\s+/ /g;
 7922:     return $name;
 7923: }
 7924: 
 7925: # ------------------------------------------------- Write to course preferences
 7926: 
 7927: sub writecoursepref {
 7928:     my ($courseid,%prefs)=@_;
 7929:     $courseid=~s/^\///;
 7930:     $courseid=~s/\_/\//g;
 7931:     my ($cdomain,$cnum)=split(/\//,$courseid);
 7932:     my $chome=homeserver($cnum,$cdomain);
 7933:     if (($chome eq '') || ($chome eq 'no_host')) { 
 7934: 	return 'error: no such course';
 7935:     }
 7936:     my $cstring='';
 7937:     foreach my $pref (keys(%prefs)) {
 7938: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 7939:     }
 7940:     $cstring=~s/\&$//;
 7941:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 7942: }
 7943: 
 7944: # ---------------------------------------------------------- Make/modify course
 7945: 
 7946: sub createcourse {
 7947:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 7948:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 7949:     $url=&declutter($url);
 7950:     my $cid='';
 7951:     if ($context eq 'requestcourses') {
 7952:         my $can_create = 0;
 7953:         my ($ownername,$ownerdom) = split(':',$course_owner);
 7954:         if ($udom eq $ownerdom) {
 7955:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 7956:                                   $context)) {
 7957:                 $can_create = 1;
 7958:             }
 7959:         } else {
 7960:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 7961:                                            $category);
 7962:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 7963:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 7964:                 if (@curr > 0) {
 7965:                     my @options = qw(approval validate autolimit);
 7966:                     my $optregex = join('|',@options);
 7967:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 7968:                         $can_create = 1;
 7969:                     }
 7970:                 }
 7971:             }
 7972:         }
 7973:         if ($can_create) {
 7974:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 7975:                 unless (&allowed('ccc',$udom)) {
 7976:                     return 'refused'; 
 7977:                 }
 7978:             }
 7979:         } else {
 7980:             return 'refused';
 7981:         }
 7982:     } elsif (!&allowed('ccc',$udom)) {
 7983:         return 'refused';
 7984:     }
 7985: # --------------------------------------------------------------- Get Unique ID
 7986:     my $uname;
 7987:     if ($cnum =~ /^$match_courseid$/) {
 7988:         my $chome=&homeserver($cnum,$udom,'true');
 7989:         if (($chome eq '') || ($chome eq 'no_host')) {
 7990:             $uname = $cnum;
 7991:         } else {
 7992:             $uname = &generate_coursenum($udom,$crstype);
 7993:         }
 7994:     } else {
 7995:         $uname = &generate_coursenum($udom,$crstype);
 7996:     }
 7997:     return $uname if ($uname =~ /^error/);
 7998: # -------------------------------------------------- Check supplied server name
 7999:     if (!defined($course_server)) {
 8000:         if (defined(&domain($udom,'primary'))) {
 8001:             $course_server = &domain($udom,'primary');
 8002:         } else {
 8003:             $course_server = $env{'user.home'}; 
 8004:         }
 8005:     }
 8006:     my %host_servers =
 8007:         &Apache::lonnet::get_servers($udom,'library');
 8008:     unless ($host_servers{$course_server}) {
 8009:         return 'error: invalid home server for course: '.$course_server;
 8010:     }
 8011: # ------------------------------------------------------------- Make the course
 8012:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8013:                       $course_server);
 8014:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8015:     my $uhome=&homeserver($uname,$udom,'true');
 8016:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8017: 	return 'error: no such course';
 8018:     }
 8019: # ----------------------------------------------------------------- Course made
 8020: # log existence
 8021:     my $now = time;
 8022:     my $newcourse = {
 8023:                     $udom.'_'.$uname => {
 8024:                                      description => $description,
 8025:                                      inst_code   => $inst_code,
 8026:                                      owner       => $course_owner,
 8027:                                      type        => $crstype,
 8028:                                      creator     => $env{'user.name'}.':'.
 8029:                                                     $env{'user.domain'},
 8030:                                      created     => $now,
 8031:                                      context     => $context,
 8032:                                                 },
 8033:                     };
 8034:     &courseidput($udom,$newcourse,$uhome,'notime');
 8035: # set toplevel url
 8036:     my $topurl=$url;
 8037:     unless ($nonstandard) {
 8038: # ------------------------------------------ For standard courses, make top url
 8039:         my $mapurl=&clutter($url);
 8040:         if ($mapurl eq '/res/') { $mapurl=''; }
 8041:         $env{'form.initmap'}=(<<ENDINITMAP);
 8042: <map>
 8043: <resource id="1" type="start"></resource>
 8044: <resource id="2" src="$mapurl"></resource>
 8045: <resource id="3" type="finish"></resource>
 8046: <link index="1" from="1" to="2"></link>
 8047: <link index="2" from="2" to="3"></link>
 8048: </map>
 8049: ENDINITMAP
 8050:         $topurl=&declutter(
 8051:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8052:                           );
 8053:     }
 8054: # ----------------------------------------------------------- Write preferences
 8055:     &writecoursepref($udom.'_'.$uname,
 8056:                      ('description'              => $description,
 8057:                       'url'                      => $topurl,
 8058:                       'internal.creator'         => $env{'user.name'}.':'.
 8059:                                                     $env{'user.domain'},
 8060:                       'internal.created'         => $now,
 8061:                       'internal.creationcontext' => $context)
 8062:                     );
 8063:     return '/'.$udom.'/'.$uname;
 8064: }
 8065: 
 8066: # ------------------------------------------------------------------- Create ID
 8067: sub generate_coursenum {
 8068:     my ($udom,$crstype) = @_;
 8069:     my $domdesc = &domain($udom);
 8070:     return 'error: invalid domain' if ($domdesc eq '');
 8071:     my $first;
 8072:     if ($crstype eq 'Community') {
 8073:         $first = '0';
 8074:     } else {
 8075:         $first = int(1+rand(9)); 
 8076:     } 
 8077:     my $uname=$first.
 8078:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8079:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8080:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8081: # ----------------------------------------------- Make sure that does not exist
 8082:     my $uhome=&homeserver($uname,$udom,'true');
 8083:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8084:         if ($crstype eq 'Community') {
 8085:             $first = '0';
 8086:         } else {
 8087:             $first = int(1+rand(9));
 8088:         }
 8089:         $uname=$first.
 8090:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8091:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8092:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8093:         $uhome=&homeserver($uname,$udom,'true');
 8094:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8095:             return 'error: unable to generate unique course-ID';
 8096:         }
 8097:     }
 8098:     return $uname;
 8099: }
 8100: 
 8101: sub is_course {
 8102:     my ($cdom,$cnum) = @_;
 8103:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 8104: 				undef,'.');
 8105:     if (exists($courses{$cdom.'_'.$cnum})) {
 8106:         return 1;
 8107:     }
 8108:     return 0;
 8109: }
 8110: 
 8111: sub store_userdata {
 8112:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8113:     my $result;
 8114:     if ($datakey ne '') {
 8115:         if (ref($storehash) eq 'HASH') {
 8116:             if ($udom eq '' || $uname eq '') {
 8117:                 $udom = $env{'user.domain'};
 8118:                 $uname = $env{'user.name'};
 8119:             }
 8120:             my $uhome=&homeserver($uname,$udom);
 8121:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8122:                 $result = 'error: no_host';
 8123:             } else {
 8124:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8125:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8126: 
 8127:                 my $namevalue='';
 8128:                 foreach my $key (keys(%{$storehash})) {
 8129:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8130:                 }
 8131:                 $namevalue=~s/\&$//;
 8132:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8133:                                   $namevalue,$uhome);
 8134:             }
 8135:         } else {
 8136:             $result = 'error: data to store was not a hash reference'; 
 8137:         }
 8138:     } else {
 8139:         $result= 'error: invalid requestkey'; 
 8140:     }
 8141:     return $result;
 8142: }
 8143: 
 8144: # ---------------------------------------------------------- Assign Custom Role
 8145: 
 8146: sub assigncustomrole {
 8147:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8148:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8149:                        $end,$start,$deleteflag,$selfenroll,$context);
 8150: }
 8151: 
 8152: # ----------------------------------------------------------------- Revoke Role
 8153: 
 8154: sub revokerole {
 8155:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8156:     my $now=time;
 8157:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8158: }
 8159: 
 8160: # ---------------------------------------------------------- Revoke Custom Role
 8161: 
 8162: sub revokecustomrole {
 8163:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8164:     my $now=time;
 8165:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8166:            $deleteflag,$selfenroll,$context);
 8167: }
 8168: 
 8169: # ------------------------------------------------------------ Disk usage
 8170: sub diskusage {
 8171:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8172:     $directorypath =~ s/\/$//;
 8173:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8174:                        .&escape($getpropath).':'.&escape($uname).':'
 8175:                        .&escape($udom),homeserver($uname,$udom));
 8176:     if ($listing eq 'unknown_cmd') {
 8177:         if ($getpropath) {
 8178:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8179:         }
 8180:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8181:     }
 8182:     return $listing;
 8183: }
 8184: 
 8185: sub is_locked {
 8186:     my ($file_name, $domain, $user, $which) = @_;
 8187:     my @check;
 8188:     my $is_locked;
 8189:     push (@check,$file_name);
 8190:     my %locked = &get('file_permissions',\@check,
 8191: 		      $env{'user.domain'},$env{'user.name'});
 8192:     my ($tmp)=keys(%locked);
 8193:     if ($tmp=~/^error:/) { undef(%locked); }
 8194:     
 8195:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8196:         $is_locked = 'false';
 8197:         foreach my $entry (@{$locked{$file_name}}) {
 8198:            if (ref($entry) eq 'ARRAY') {
 8199:                $is_locked = 'true';
 8200:                if (ref($which) eq 'ARRAY') {
 8201:                    push(@{$which},$entry);
 8202:                } else {
 8203:                    last;
 8204:                }
 8205:            }
 8206:        }
 8207:     } else {
 8208:         $is_locked = 'false';
 8209:     }
 8210:     return $is_locked;
 8211: }
 8212: 
 8213: sub declutter_portfile {
 8214:     my ($file) = @_;
 8215:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8216:     return $file;
 8217: }
 8218: 
 8219: # ------------------------------------------------------------- Mark as Read Only
 8220: 
 8221: sub mark_as_readonly {
 8222:     my ($domain,$user,$files,$what) = @_;
 8223:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8224:     my ($tmp)=keys(%current_permissions);
 8225:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8226:     foreach my $file (@{$files}) {
 8227: 	$file = &declutter_portfile($file);
 8228:         push(@{$current_permissions{$file}},$what);
 8229:     }
 8230:     &put('file_permissions',\%current_permissions,$domain,$user);
 8231:     return;
 8232: }
 8233: 
 8234: # ------------------------------------------------------------Save Selected Files
 8235: 
 8236: sub save_selected_files {
 8237:     my ($user, $path, @files) = @_;
 8238:     my $filename = $user."savedfiles";
 8239:     my @other_files = &files_not_in_path($user, $path);
 8240:     open (OUT, '>'.$tmpdir.$filename);
 8241:     foreach my $file (@files) {
 8242:         print (OUT $env{'form.currentpath'}.$file."\n");
 8243:     }
 8244:     foreach my $file (@other_files) {
 8245:         print (OUT $file."\n");
 8246:     }
 8247:     close (OUT);
 8248:     return 'ok';
 8249: }
 8250: 
 8251: sub clear_selected_files {
 8252:     my ($user) = @_;
 8253:     my $filename = $user."savedfiles";
 8254:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8255:     print (OUT undef);
 8256:     close (OUT);
 8257:     return ("ok");    
 8258: }
 8259: 
 8260: sub files_in_path {
 8261:     my ($user, $path) = @_;
 8262:     my $filename = $user."savedfiles";
 8263:     my %return_files;
 8264:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8265:     while (my $line_in = <IN>) {
 8266:         chomp ($line_in);
 8267:         my @paths_and_file = split (m!/!, $line_in);
 8268:         my $file_part = pop (@paths_and_file);
 8269:         my $path_part = join ('/', @paths_and_file);
 8270:         $path_part.='/';
 8271:         my $path_and_file = $path_part.$file_part;
 8272:         if ($path_part eq $path) {
 8273:             $return_files{$file_part}= 'selected';
 8274:         }
 8275:     }
 8276:     close (IN);
 8277:     return (\%return_files);
 8278: }
 8279: 
 8280: # called in portfolio select mode, to show files selected NOT in current directory
 8281: sub files_not_in_path {
 8282:     my ($user, $path) = @_;
 8283:     my $filename = $user."savedfiles";
 8284:     my @return_files;
 8285:     my $path_part;
 8286:     open(IN, '<'.LONCAPA::.$filename);
 8287:     while (my $line = <IN>) {
 8288:         #ok, I know it's clunky, but I want it to work
 8289:         my @paths_and_file = split(m|/|, $line);
 8290:         my $file_part = pop(@paths_and_file);
 8291:         chomp($file_part);
 8292:         my $path_part = join('/', @paths_and_file);
 8293:         $path_part .= '/';
 8294:         my $path_and_file = $path_part.$file_part;
 8295:         if ($path_part ne $path) {
 8296:             push(@return_files, ($path_and_file));
 8297:         }
 8298:     }
 8299:     close(OUT);
 8300:     return (@return_files);
 8301: }
 8302: 
 8303: #----------------------------------------------Get portfolio file permissions
 8304: 
 8305: sub get_portfile_permissions {
 8306:     my ($domain,$user) = @_;
 8307:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8308:     my ($tmp)=keys(%current_permissions);
 8309:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8310:     return \%current_permissions;
 8311: }
 8312: 
 8313: #---------------------------------------------Get portfolio file access controls
 8314: 
 8315: sub get_access_controls {
 8316:     my ($current_permissions,$group,$file) = @_;
 8317:     my %access;
 8318:     my $real_file = $file;
 8319:     $file =~ s/\.meta$//;
 8320:     if (defined($file)) {
 8321:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8322:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8323:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8324:             }
 8325:         }
 8326:     } else {
 8327:         foreach my $key (keys(%{$current_permissions})) {
 8328:             if ($key =~ /\0accesscontrol$/) {
 8329:                 if (defined($group)) {
 8330:                     if ($key !~ m-^\Q$group\E/-) {
 8331:                         next;
 8332:                     }
 8333:                 }
 8334:                 my ($fullpath) = split(/\0/,$key);
 8335:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8336:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8337:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8338:                     }
 8339:                 }
 8340:             }
 8341:         }
 8342:     }
 8343:     return %access;
 8344: }
 8345: 
 8346: sub modify_access_controls {
 8347:     my ($file_name,$changes,$domain,$user)=@_;
 8348:     my ($outcome,$deloutcome);
 8349:     my %store_permissions;
 8350:     my %new_values;
 8351:     my %new_control;
 8352:     my %translation;
 8353:     my @deletions = ();
 8354:     my $now = time;
 8355:     if (exists($$changes{'activate'})) {
 8356:         if (ref($$changes{'activate'}) eq 'HASH') {
 8357:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8358:             my $numnew = scalar(@newitems);
 8359:             for (my $i=0; $i<$numnew; $i++) {
 8360:                 my $newkey = $newitems[$i];
 8361:                 my $newid = &Apache::loncommon::get_cgi_id();
 8362:                 if ($newkey =~ /^\d+:/) { 
 8363:                     $newkey =~ s/^(\d+)/$newid/;
 8364:                     $translation{$1} = $newid;
 8365:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8366:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8367:                     $translation{$1} = $newid;
 8368:                 }
 8369:                 $new_values{$file_name."\0".$newkey} = 
 8370:                                           $$changes{'activate'}{$newitems[$i]};
 8371:                 $new_control{$newkey} = $now;
 8372:             }
 8373:         }
 8374:     }
 8375:     my %todelete;
 8376:     my %changed_items;
 8377:     foreach my $action ('delete','update') {
 8378:         if (exists($$changes{$action})) {
 8379:             if (ref($$changes{$action}) eq 'HASH') {
 8380:                 foreach my $key (keys(%{$$changes{$action}})) {
 8381:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8382:                     if ($action eq 'delete') { 
 8383:                         $todelete{$itemnum} = 1;
 8384:                     } else {
 8385:                         $changed_items{$itemnum} = $key;
 8386:                     }
 8387:                 }
 8388:             }
 8389:         }
 8390:     }
 8391:     # get lock on access controls for file.
 8392:     my $lockhash = {
 8393:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8394:                                                        ':'.$env{'user.domain'},
 8395:                    }; 
 8396:     my $tries = 0;
 8397:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8398:    
 8399:     while (($gotlock ne 'ok') && $tries <3) {
 8400:         $tries ++;
 8401:         sleep 1;
 8402:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8403:     }
 8404:     if ($gotlock eq 'ok') {
 8405:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8406:         my ($tmp)=keys(%curr_permissions);
 8407:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8408:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8409:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8410:             if (ref($curr_controls) eq 'HASH') {
 8411:                 foreach my $control_item (keys(%{$curr_controls})) {
 8412:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8413:                     if (defined($todelete{$itemnum})) {
 8414:                         push(@deletions,$file_name."\0".$control_item);
 8415:                     } else {
 8416:                         if (defined($changed_items{$itemnum})) {
 8417:                             $new_control{$changed_items{$itemnum}} = $now;
 8418:                             push(@deletions,$file_name."\0".$control_item);
 8419:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8420:                         } else {
 8421:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8422:                         }
 8423:                     }
 8424:                 }
 8425:             }
 8426:         }
 8427:         my ($group);
 8428:         if (&is_course($domain,$user)) {
 8429:             ($group,my $file) = split(/\//,$file_name,2);
 8430:         }
 8431:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8432:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8433:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8434:         #  remove lock
 8435:         my @del_lock = ($file_name."\0".'locked_access_records');
 8436:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8437:         my $sqlresult =
 8438:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8439:                                     $group);
 8440:     } else {
 8441:         $outcome = "error: could not obtain lockfile\n";  
 8442:     }
 8443:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8444: }
 8445: 
 8446: sub make_public_indefinitely {
 8447:     my ($requrl) = @_;
 8448:     my $now = time;
 8449:     my $action = 'activate';
 8450:     my $aclnum = 0;
 8451:     if (&is_portfolio_url($requrl)) {
 8452:         my (undef,$udom,$unum,$file_name,$group) =
 8453:             &parse_portfolio_url($requrl);
 8454:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8455:         my %access_controls = &get_access_controls($current_perms,
 8456:                                                    $group,$file_name);
 8457:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8458:             my ($num,$scope,$end,$start) = 
 8459:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8460:             if ($scope eq 'public') {
 8461:                 if ($start <= $now && $end == 0) {
 8462:                     $action = 'none';
 8463:                 } else {
 8464:                     $action = 'update';
 8465:                     $aclnum = $num;
 8466:                 }
 8467:                 last;
 8468:             }
 8469:         }
 8470:         if ($action eq 'none') {
 8471:              return 'ok';
 8472:         } else {
 8473:             my %changes;
 8474:             my $newend = 0;
 8475:             my $newstart = $now;
 8476:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8477:             $changes{$action}{$newkey} = {
 8478:                 type => 'public',
 8479:                 time => {
 8480:                     start => $newstart,
 8481:                     end   => $newend,
 8482:                 },
 8483:             };
 8484:             my ($outcome,$deloutcome,$new_values,$translation) =
 8485:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8486:             return $outcome;
 8487:         }
 8488:     } else {
 8489:         return 'invalid';
 8490:     }
 8491: }
 8492: 
 8493: #------------------------------------------------------Get Marked as Read Only
 8494: 
 8495: sub get_marked_as_readonly {
 8496:     my ($domain,$user,$what,$group) = @_;
 8497:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8498:     my @readonly_files;
 8499:     my $cmp1=$what;
 8500:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8501:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8502:         if (defined($group)) {
 8503:             if ($file_name !~ m-^\Q$group\E/-) {
 8504:                 next;
 8505:             }
 8506:         }
 8507:         if (ref($value) eq "ARRAY"){
 8508:             foreach my $stored_what (@{$value}) {
 8509:                 my $cmp2=$stored_what;
 8510:                 if (ref($stored_what) eq 'ARRAY') {
 8511:                     $cmp2=join('',@{$stored_what});
 8512:                 }
 8513:                 if ($cmp1 eq $cmp2) {
 8514:                     push(@readonly_files, $file_name);
 8515:                     last;
 8516:                 } elsif (!defined($what)) {
 8517:                     push(@readonly_files, $file_name);
 8518:                     last;
 8519:                 }
 8520:             }
 8521:         }
 8522:     }
 8523:     return @readonly_files;
 8524: }
 8525: #-----------------------------------------------------------Get Marked as Read Only Hash
 8526: 
 8527: sub get_marked_as_readonly_hash {
 8528:     my ($current_permissions,$group,$what) = @_;
 8529:     my %readonly_files;
 8530:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8531:         if (defined($group)) {
 8532:             if ($file_name !~ m-^\Q$group\E/-) {
 8533:                 next;
 8534:             }
 8535:         }
 8536:         if (ref($value) eq "ARRAY"){
 8537:             foreach my $stored_what (@{$value}) {
 8538:                 if (ref($stored_what) eq 'ARRAY') {
 8539:                     foreach my $lock_descriptor(@{$stored_what}) {
 8540:                         if ($lock_descriptor eq 'graded') {
 8541:                             $readonly_files{$file_name} = 'graded';
 8542:                         } elsif ($lock_descriptor eq 'handback') {
 8543:                             $readonly_files{$file_name} = 'handback';
 8544:                         } else {
 8545:                             if (!exists($readonly_files{$file_name})) {
 8546:                                 $readonly_files{$file_name} = 'locked';
 8547:                             }
 8548:                         }
 8549:                     }
 8550:                 } 
 8551:             }
 8552:         } 
 8553:     }
 8554:     return %readonly_files;
 8555: }
 8556: # ------------------------------------------------------------ Unmark as Read Only
 8557: 
 8558: sub unmark_as_readonly {
 8559:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8560:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8561:     my ($domain,$user,$what,$file_name,$group) = @_;
 8562:     $file_name = &declutter_portfile($file_name);
 8563:     my $symb_crs = $what;
 8564:     if (ref($what)) { $symb_crs=join('',@$what); }
 8565:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8566:     my ($tmp)=keys(%current_permissions);
 8567:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8568:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8569:     foreach my $file (@readonly_files) {
 8570: 	my $clean_file = &declutter_portfile($file);
 8571: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8572: 	my $current_locks = $current_permissions{$file};
 8573:         my @new_locks;
 8574:         my @del_keys;
 8575:         if (ref($current_locks) eq "ARRAY"){
 8576:             foreach my $locker (@{$current_locks}) {
 8577:                 my $compare=$locker;
 8578:                 if (ref($locker) eq 'ARRAY') {
 8579:                     $compare=join('',@{$locker});
 8580:                     if ($compare ne $symb_crs) {
 8581:                         push(@new_locks, $locker);
 8582:                     }
 8583:                 }
 8584:             }
 8585:             if (scalar(@new_locks) > 0) {
 8586:                 $current_permissions{$file} = \@new_locks;
 8587:             } else {
 8588:                 push(@del_keys, $file);
 8589:                 &del('file_permissions',\@del_keys, $domain, $user);
 8590:                 delete($current_permissions{$file});
 8591:             }
 8592:         }
 8593:     }
 8594:     &put('file_permissions',\%current_permissions,$domain,$user);
 8595:     return;
 8596: }
 8597: 
 8598: # ------------------------------------------------------------ Directory lister
 8599: 
 8600: sub dirlist {
 8601:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8602:     $uri=~s/^\///;
 8603:     $uri=~s/\/$//;
 8604:     my ($udom, $uname);
 8605:     if ($getuserdir) {
 8606:         $udom = $userdomain;
 8607:         $uname = $username;
 8608:     } else {
 8609:         (undef,$udom,$uname)=split(/\//,$uri);
 8610:         if(defined($userdomain)) {
 8611:             $udom = $userdomain;
 8612:         }
 8613:         if(defined($username)) {
 8614:             $uname = $username;
 8615:         }
 8616:     }
 8617:     my ($dirRoot,$listing,@listing_results);
 8618: 
 8619:     $dirRoot = $perlvar{'lonDocRoot'};
 8620:     if (defined($getpropath)) {
 8621:         $dirRoot = &propath($udom,$uname);
 8622:         $dirRoot =~ s/\/$//;
 8623:     } elsif (defined($getuserdir)) {
 8624:         my $subdir=$uname.'__';
 8625:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8626:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8627:                    ."/$udom/$subdir/$uname";
 8628:     } elsif (defined($alternateRoot)) {
 8629:         $dirRoot = $alternateRoot;
 8630:     }
 8631: 
 8632:     if($udom) {
 8633:         if($uname) {
 8634:             my $uhome = &homeserver($uname,$udom);
 8635:             if ($uhome eq 'no_host') {
 8636:                 return ([],'no_host');
 8637:             }
 8638:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8639:                               .$getuserdir.':'.&escape($dirRoot)
 8640:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8641:             if ($listing eq 'unknown_cmd') {
 8642:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8643:             } else {
 8644:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8645:             }
 8646:             if ($listing eq 'unknown_cmd') {
 8647:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8648:                 @listing_results = split(/:/,$listing);
 8649:             } else {
 8650:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8651:             }
 8652:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8653:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8654:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8655:                 return ([],$listing);
 8656:             } else {
 8657:                 return (\@listing_results);
 8658:             }
 8659:         } elsif(!$alternateRoot) {
 8660:             my (%allusers,%listerror);
 8661: 	    my %servers = &get_servers($udom,'library');
 8662:  	    foreach my $tryserver (keys(%servers)) {
 8663:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8664:                                   &escape($udom),$tryserver);
 8665:                 if ($listing eq 'unknown_cmd') {
 8666: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8667: 				      $udom, $tryserver);
 8668:                 } else {
 8669:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8670:                 }
 8671: 		if ($listing eq 'unknown_cmd') {
 8672: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8673: 				      $udom, $tryserver);
 8674: 		    @listing_results = split(/:/,$listing);
 8675: 		} else {
 8676: 		    @listing_results =
 8677: 			map { &unescape($_); } split(/:/,$listing);
 8678: 		}
 8679:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8680:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8681:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8682:                     $listerror{$tryserver} = $listing;
 8683:                 } else {
 8684: 		    foreach my $line (@listing_results) {
 8685: 			my ($entry) = split(/&/,$line,2);
 8686: 			$allusers{$entry} = 1;
 8687: 		    }
 8688: 		}
 8689:             }
 8690:             my @alluserslist=();
 8691:             foreach my $user (sort(keys(%allusers))) {
 8692:                 push(@alluserslist,$user.'&user');
 8693:             }
 8694:             return (\@alluserslist);
 8695:         } else {
 8696:             return ([],'missing username');
 8697:         }
 8698:     } elsif(!defined($getpropath)) {
 8699:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8700:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8701:         return (\@all_domains);
 8702:     } else {
 8703:         return ([],'missing domain');
 8704:     }
 8705: }
 8706: 
 8707: # --------------------------------------------- GetFileTimestamp
 8708: # This function utilizes dirlist and returns the date stamp for
 8709: # when it was last modified.  It will also return an error of -1
 8710: # if an error occurs
 8711: 
 8712: sub GetFileTimestamp {
 8713:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8714:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8715:     $studentName   = &LONCAPA::clean_username($studentName);
 8716:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8717:                                     undef,$getuserdir);
 8718:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8719:         return -1;
 8720:     }
 8721:     if (ref($fileref) eq 'ARRAY') {
 8722:         my @stats = split('&',$fileref->[0]);
 8723:         # @stats contains first the filename, then the stat output
 8724:         return $stats[10]; # so this is 10 instead of 9.
 8725:     } else {
 8726:         return -1;
 8727:     }
 8728: }
 8729: 
 8730: sub stat_file {
 8731:     my ($uri) = @_;
 8732:     $uri = &clutter_with_no_wrapper($uri);
 8733: 
 8734:     my ($udom,$uname,$file);
 8735:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8736: 	($udom,$uname,$file) =
 8737: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8738: 	$file = 'userfiles/'.$file;
 8739:     }
 8740:     if ($uri =~ m-^/res/-) {
 8741: 	($udom,$uname) = 
 8742: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8743: 	$file = $uri;
 8744:     }
 8745: 
 8746:     if (!$udom || !$uname || !$file) {
 8747: 	# unable to handle the uri
 8748: 	return ();
 8749:     }
 8750:     my $getpropath;
 8751:     if ($file =~ /^userfiles\//) {
 8752:         $getpropath = 1;
 8753:     }
 8754:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8755:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8756:         return ();
 8757:     } else {
 8758:         if (ref($listref) eq 'ARRAY') {
 8759:             my @stats = split('&',$listref->[0]);
 8760: 	    shift(@stats); #filename is first
 8761: 	    return @stats;
 8762:         }
 8763:     }
 8764:     return ();
 8765: }
 8766: 
 8767: # -------------------------------------------------------- Value of a Condition
 8768: 
 8769: # gets the value of a specific preevaluated condition
 8770: #    stored in the string  $env{user.state.<cid>}
 8771: # or looks up a condition reference in the bighash and if if hasn't
 8772: # already been evaluated recurses into docondval to get the value of
 8773: # the condition, then memoizing it to 
 8774: #   $env{user.state.<cid>.<condition>}
 8775: sub directcondval {
 8776:     my $number=shift;
 8777:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8778: 	&Apache::lonuserstate::evalstate();
 8779:     }
 8780:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8781: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8782:     } elsif ($number =~ /^_/) {
 8783: 	my $sub_condition;
 8784: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8785: 		&GDBM_READER(),0640)) {
 8786: 	    $sub_condition=$bighash{'conditions'.$number};
 8787: 	    untie(%bighash);
 8788: 	}
 8789: 	my $value = &docondval($sub_condition);
 8790: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8791: 	return $value;
 8792:     }
 8793:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8794:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8795:     } else {
 8796:        return 2;
 8797:     }
 8798: }
 8799: 
 8800: # get the collection of conditions for this resource
 8801: sub condval {
 8802:     my $condidx=shift;
 8803:     my $allpathcond='';
 8804:     foreach my $cond (split(/\|/,$condidx)) {
 8805: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8806: 	    $allpathcond.=
 8807: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8808: 	}
 8809:     }
 8810:     $allpathcond=~s/\|$//;
 8811:     return &docondval($allpathcond);
 8812: }
 8813: 
 8814: #evaluates an expression of conditions
 8815: sub docondval {
 8816:     my ($allpathcond) = @_;
 8817:     my $result=0;
 8818:     if ($env{'request.course.id'}
 8819: 	&& defined($allpathcond)) {
 8820: 	my $operand='|';
 8821: 	my @stack;
 8822: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8823: 	    if ($chunk eq '(') {
 8824: 		push @stack,($operand,$result);
 8825: 	    } elsif ($chunk eq ')') {
 8826: 		my $before=pop @stack;
 8827: 		if (pop @stack eq '&') {
 8828: 		    $result=$result>$before?$before:$result;
 8829: 		} else {
 8830: 		    $result=$result>$before?$result:$before;
 8831: 		}
 8832: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8833: 		$operand=$chunk;
 8834: 	    } else {
 8835: 		my $new=directcondval($chunk);
 8836: 		if ($operand eq '&') {
 8837: 		    $result=$result>$new?$new:$result;
 8838: 		} else {
 8839: 		    $result=$result>$new?$result:$new;
 8840: 		}
 8841: 	    }
 8842: 	}
 8843:     }
 8844:     return $result;
 8845: }
 8846: 
 8847: # ---------------------------------------------------- Devalidate courseresdata
 8848: 
 8849: sub devalidatecourseresdata {
 8850:     my ($coursenum,$coursedomain)=@_;
 8851:     my $hashid=$coursenum.':'.$coursedomain;
 8852:     &devalidate_cache_new('courseres',$hashid);
 8853: }
 8854: 
 8855: 
 8856: # --------------------------------------------------- Course Resourcedata Query
 8857: #
 8858: #  Parameters:
 8859: #      $coursenum    - Number of the course.
 8860: #      $coursedomain - Domain at which the course was created.
 8861: #  Returns:
 8862: #     A hash of the course parameters along (I think) with timestamps
 8863: #     and version info.
 8864: 
 8865: sub get_courseresdata {
 8866:     my ($coursenum,$coursedomain)=@_;
 8867:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8868:     my $hashid=$coursenum.':'.$coursedomain;
 8869:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8870:     my %dumpreply;
 8871:     unless (defined($cached)) {
 8872: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8873: 	$result=\%dumpreply;
 8874: 	my ($tmp) = keys(%dumpreply);
 8875: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8876: 	    &do_cache_new('courseres',$hashid,$result,600);
 8877: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8878: 	    return $tmp;
 8879: 	} elsif ($tmp =~ /^(error)/) {
 8880: 	    $result=undef;
 8881: 	    &do_cache_new('courseres',$hashid,$result,600);
 8882: 	}
 8883:     }
 8884:     return $result;
 8885: }
 8886: 
 8887: sub devalidateuserresdata {
 8888:     my ($uname,$udom)=@_;
 8889:     my $hashid="$udom:$uname";
 8890:     &devalidate_cache_new('userres',$hashid);
 8891: }
 8892: 
 8893: sub get_userresdata {
 8894:     my ($uname,$udom)=@_;
 8895:     #most student don\'t have any data set, check if there is some data
 8896:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8897: 
 8898:     my $hashid="$udom:$uname";
 8899:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8900:     if (!defined($cached)) {
 8901: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 8902: 	$result=\%resourcedata;
 8903: 	&do_cache_new('userres',$hashid,$result,600);
 8904:     }
 8905:     my ($tmp)=keys(%$result);
 8906:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 8907: 	return $result;
 8908:     }
 8909:     #error 2 occurs when the .db doesn't exist
 8910:     if ($tmp!~/error: 2 /) {
 8911: 	&logthis("<font color=\"blue\">WARNING:".
 8912: 		 " Trying to get resource data for ".
 8913: 		 $uname." at ".$udom.": ".
 8914: 		 $tmp."</font>");
 8915:     } elsif ($tmp=~/error: 2 /) {
 8916: 	#&EXT_cache_set($udom,$uname);
 8917: 	&do_cache_new('userres',$hashid,undef,600);
 8918: 	undef($tmp); # not really an error so don't send it back
 8919:     }
 8920:     return $tmp;
 8921: }
 8922: #----------------------------------------------- resdata - return resource data
 8923: #  Purpose:
 8924: #    Return resource data for either users or for a course.
 8925: #  Parameters:
 8926: #     $name      - Course/user name.
 8927: #     $domain    - Name of the domain the user/course is registered on.
 8928: #     $type      - Type of thing $name is (must be 'course' or 'user'
 8929: #     @which     - Array of names of resources desired.
 8930: #  Returns:
 8931: #     The value of the first reasource in @which that is found in the
 8932: #     resource hash.
 8933: #  Exceptional Conditions:
 8934: #     If the $type passed in is not valid (not the string 'course' or 
 8935: #     'user', an undefined  reference is returned.
 8936: #     If none of the resources are found, an undef is returned
 8937: sub resdata {
 8938:     my ($name,$domain,$type,@which)=@_;
 8939:     my $result;
 8940:     if ($type eq 'course') {
 8941: 	$result=&get_courseresdata($name,$domain);
 8942:     } elsif ($type eq 'user') {
 8943: 	$result=&get_userresdata($name,$domain);
 8944:     }
 8945:     if (!ref($result)) { return $result; }    
 8946:     foreach my $item (@which) {
 8947: 	if (defined($result->{$item->[0]})) {
 8948: 	    return [$result->{$item->[0]},$item->[1]];
 8949: 	}
 8950:     }
 8951:     return undef;
 8952: }
 8953: 
 8954: #
 8955: # EXT resource caching routines
 8956: #
 8957: 
 8958: sub clear_EXT_cache_status {
 8959:     &delenv('cache.EXT.');
 8960: }
 8961: 
 8962: sub EXT_cache_status {
 8963:     my ($target_domain,$target_user) = @_;
 8964:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8965:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 8966:         # We know already the user has no data
 8967:         return 1;
 8968:     } else {
 8969:         return 0;
 8970:     }
 8971: }
 8972: 
 8973: sub EXT_cache_set {
 8974:     my ($target_domain,$target_user) = @_;
 8975:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8976:     #&appenv({$cachename => time});
 8977: }
 8978: 
 8979: # --------------------------------------------------------- Value of a Variable
 8980: sub EXT {
 8981: 
 8982:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 8983:     unless ($varname) { return ''; }
 8984:     #get real user name/domain, courseid and symb
 8985:     my $courseid;
 8986:     my $publicuser;
 8987:     if ($symbparm) {
 8988: 	$symbparm=&get_symb_from_alias($symbparm);
 8989:     }
 8990:     if (!($uname && $udom)) {
 8991:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 8992:       if (!$symbparm) {	$symbparm=$cursymb; }
 8993:     } else {
 8994: 	$courseid=$env{'request.course.id'};
 8995:     }
 8996:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 8997:     my $rest;
 8998:     if (defined($therest[0])) {
 8999:        $rest=join('.',@therest);
 9000:     } else {
 9001:        $rest='';
 9002:     }
 9003: 
 9004:     my $qualifierrest=$qualifier;
 9005:     if ($rest) { $qualifierrest.='.'.$rest; }
 9006:     my $spacequalifierrest=$space;
 9007:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9008:     if ($realm eq 'user') {
 9009: # --------------------------------------------------------------- user.resource
 9010: 	if ($space eq 'resource') {
 9011: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9012: 		  || defined($Apache::lonhomework::parsing_a_task))
 9013: 		 &&
 9014: 		 ($symbparm eq &symbread()) ) {	
 9015: 		# if we are in the middle of processing the resource the
 9016: 		# get the value we are planning on committing
 9017:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9018:                     return $Apache::lonhomework::results{$qualifierrest};
 9019:                 } else {
 9020:                     return $Apache::lonhomework::history{$qualifierrest};
 9021:                 }
 9022: 	    } else {
 9023: 		my %restored;
 9024: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9025: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9026: 		} else {
 9027: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9028: 		}
 9029: 		return $restored{$qualifierrest};
 9030: 	    }
 9031: # ----------------------------------------------------------------- user.access
 9032:         } elsif ($space eq 'access') {
 9033: 	    # FIXME - not supporting calls for a specific user
 9034:             return &allowed($qualifier,$rest);
 9035: # ------------------------------------------ user.preferences, user.environment
 9036:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9037: 	    if (($uname eq $env{'user.name'}) &&
 9038: 		($udom eq $env{'user.domain'})) {
 9039: 		return $env{join('.',('environment',$qualifierrest))};
 9040: 	    } else {
 9041: 		my %returnhash;
 9042: 		if (!$publicuser) {
 9043: 		    %returnhash=&userenvironment($udom,$uname,
 9044: 						 $qualifierrest);
 9045: 		}
 9046: 		return $returnhash{$qualifierrest};
 9047: 	    }
 9048: # ----------------------------------------------------------------- user.course
 9049:         } elsif ($space eq 'course') {
 9050: 	    # FIXME - not supporting calls for a specific user
 9051:             return $env{join('.',('request.course',$qualifier))};
 9052: # ------------------------------------------------------------------- user.role
 9053:         } elsif ($space eq 'role') {
 9054: 	    # FIXME - not supporting calls for a specific user
 9055:             my ($role,$where)=split(/\./,$env{'request.role'});
 9056:             if ($qualifier eq 'value') {
 9057: 		return $role;
 9058:             } elsif ($qualifier eq 'extent') {
 9059:                 return $where;
 9060:             }
 9061: # ----------------------------------------------------------------- user.domain
 9062:         } elsif ($space eq 'domain') {
 9063:             return $udom;
 9064: # ------------------------------------------------------------------- user.name
 9065:         } elsif ($space eq 'name') {
 9066:             return $uname;
 9067: # ---------------------------------------------------- Any other user namespace
 9068:         } else {
 9069: 	    my %reply;
 9070: 	    if (!$publicuser) {
 9071: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9072: 	    }
 9073: 	    return $reply{$qualifierrest};
 9074:         }
 9075:     } elsif ($realm eq 'query') {
 9076: # ---------------------------------------------- pull stuff out of query string
 9077:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9078: 						[$spacequalifierrest]);
 9079: 	return $env{'form.'.$spacequalifierrest}; 
 9080:    } elsif ($realm eq 'request') {
 9081: # ------------------------------------------------------------- request.browser
 9082:         if ($space eq 'browser') {
 9083:             return $env{'browser.'.$qualifier};
 9084: # ------------------------------------------------------------ request.filename
 9085:         } else {
 9086:             return $env{'request.'.$spacequalifierrest};
 9087:         }
 9088:     } elsif ($realm eq 'course') {
 9089: # ---------------------------------------------------------- course.description
 9090:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9091:     } elsif ($realm eq 'resource') {
 9092: 
 9093: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9094: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9095: 	}
 9096: 
 9097: 	if ($space eq 'title') {
 9098: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9099: 	    return &gettitle($symbparm);
 9100: 	}
 9101: 	
 9102: 	if ($space eq 'map') {
 9103: 	    my ($map) = &decode_symb($symbparm);
 9104: 	    return &symbread($map);
 9105: 	}
 9106: 	if ($space eq 'filename') {
 9107: 	    if ($symbparm) {
 9108: 		return &clutter((&decode_symb($symbparm))[2]);
 9109: 	    }
 9110: 	    return &hreflocation('',$env{'request.filename'});
 9111: 	}
 9112: 
 9113: 	my ($section, $group, @groups);
 9114: 	my ($courselevelm,$courselevel);
 9115: 	if ($symbparm && defined($courseid) && 
 9116: 	    $courseid eq $env{'request.course.id'}) {
 9117: 
 9118: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9119: 
 9120: # ----------------------------------------------------- Cascading lookup scheme
 9121: 	    my $symbp=$symbparm;
 9122: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9123: 
 9124: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9125: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9126: 
 9127: 	    if (($env{'user.name'} eq $uname) &&
 9128: 		($env{'user.domain'} eq $udom)) {
 9129: 		$section=$env{'request.course.sec'};
 9130:                 @groups = split(/:/,$env{'request.course.groups'});  
 9131:                 @groups=&sort_course_groups($courseid,@groups); 
 9132: 	    } else {
 9133: 		if (! defined($usection)) {
 9134: 		    $section=&getsection($udom,$uname,$courseid);
 9135: 		} else {
 9136: 		    $section = $usection;
 9137: 		}
 9138:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9139: 	    }
 9140: 
 9141: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9142: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9143: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9144: 
 9145: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9146: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9147: 	    $courselevelm=$courseid.'.'.$mapparm;
 9148: 
 9149: # ----------------------------------------------------------- first, check user
 9150: 
 9151: 	    my $userreply=&resdata($uname,$udom,'user',
 9152: 				       ([$courselevelr,'resource'],
 9153: 					[$courselevelm,'map'     ],
 9154: 					[$courselevel, 'course'  ]));
 9155: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9156: 
 9157: # ------------------------------------------------ second, check some of course
 9158:             my $coursereply;
 9159:             if (@groups > 0) {
 9160:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9161:                                        $mapparm,$spacequalifierrest);
 9162:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9163:             }
 9164: 
 9165: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9166: 				  $env{'course.'.$courseid.'.domain'},
 9167: 				  'course',
 9168: 				  ([$seclevelr,   'resource'],
 9169: 				   [$seclevelm,   'map'     ],
 9170: 				   [$seclevel,    'course'  ],
 9171: 				   [$courselevelr,'resource']));
 9172: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9173: 
 9174: # ------------------------------------------------------ third, check map parms
 9175: 	    my %parmhash=();
 9176: 	    my $thisparm='';
 9177: 	    if (tie(%parmhash,'GDBM_File',
 9178: 		    $env{'request.course.fn'}.'_parms.db',
 9179: 		    &GDBM_READER(),0640)) {
 9180: 		$thisparm=$parmhash{$symbparm};
 9181: 		untie(%parmhash);
 9182: 	    }
 9183: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9184: 	}
 9185: # ------------------------------------------ fourth, look in resource metadata
 9186: 
 9187: 	$spacequalifierrest=~s/\./\_/;
 9188: 	my $filename;
 9189: 	if (!$symbparm) { $symbparm=&symbread(); }
 9190: 	if ($symbparm) {
 9191: 	    $filename=(&decode_symb($symbparm))[2];
 9192: 	} else {
 9193: 	    $filename=$env{'request.filename'};
 9194: 	}
 9195: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9196: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9197: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9198: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9199: 
 9200: # ---------------------------------------------- fourth, look in rest of course
 9201: 	if ($symbparm && defined($courseid) && 
 9202: 	    $courseid eq $env{'request.course.id'}) {
 9203: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9204: 				     $env{'course.'.$courseid.'.domain'},
 9205: 				     'course',
 9206: 				     ([$courselevelm,'map'   ],
 9207: 				      [$courselevel, 'course']));
 9208: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9209: 	}
 9210: # ------------------------------------------------------------------ Cascade up
 9211: 	unless ($space eq '0') {
 9212: 	    my @parts=split(/_/,$space);
 9213: 	    my $id=pop(@parts);
 9214: 	    my $part=join('_',@parts);
 9215: 	    if ($part eq '') { $part='0'; }
 9216: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9217: 				 $symbparm,$udom,$uname,$section,1);
 9218: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9219: 	}
 9220: 	if ($recurse) { return undef; }
 9221: 	my $pack_def=&packages_tab_default($filename,$varname);
 9222: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9223: # ---------------------------------------------------- Any other user namespace
 9224:     } elsif ($realm eq 'environment') {
 9225: # ----------------------------------------------------------------- environment
 9226: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9227: 	    return $env{'environment.'.$spacequalifierrest};
 9228: 	} else {
 9229: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9230: 		return '';
 9231: 	    }
 9232: 	    my %returnhash=&userenvironment($udom,$uname,
 9233: 					    $spacequalifierrest);
 9234: 	    return $returnhash{$spacequalifierrest};
 9235: 	}
 9236:     } elsif ($realm eq 'system') {
 9237: # ----------------------------------------------------------------- system.time
 9238: 	if ($space eq 'time') {
 9239: 	    return time;
 9240:         }
 9241:     } elsif ($realm eq 'server') {
 9242: # ----------------------------------------------------------------- system.time
 9243: 	if ($space eq 'name') {
 9244: 	    return $ENV{'SERVER_NAME'};
 9245:         }
 9246:     }
 9247:     return '';
 9248: }
 9249: 
 9250: sub get_reply {
 9251:     my ($reply_value) = @_;
 9252:     if (ref($reply_value) eq 'ARRAY') {
 9253:         if (wantarray) {
 9254: 	    return @$reply_value;
 9255:         }
 9256:         return $reply_value->[0];
 9257:     } else {
 9258:         return $reply_value;
 9259:     }
 9260: }
 9261: 
 9262: sub check_group_parms {
 9263:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9264:     my @groupitems = ();
 9265:     my $resultitem;
 9266:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9267:     foreach my $group (@{$groups}) {
 9268:         foreach my $level (@levels) {
 9269:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9270:              push(@groupitems,[$item,$level->[1]]);
 9271:         }
 9272:     }
 9273:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9274:                             $env{'course.'.$courseid.'.domain'},
 9275:                                      'course',@groupitems);
 9276:     return $coursereply;
 9277: }
 9278: 
 9279: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9280:     my ($courseid,@groups) = @_;
 9281:     @groups = sort(@groups);
 9282:     return @groups;
 9283: }
 9284: 
 9285: sub packages_tab_default {
 9286:     my ($uri,$varname)=@_;
 9287:     my (undef,$part,$name)=split(/\./,$varname);
 9288: 
 9289:     my (@extension,@specifics,$do_default);
 9290:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9291: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9292: 	if ($pack_type eq 'default') {
 9293: 	    $do_default=1;
 9294: 	} elsif ($pack_type eq 'extension') {
 9295: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9296: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9297: 	    # only look at packages defaults for packages that this id is
 9298: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9299: 	}
 9300:     }
 9301:     # first look for a package that matches the requested part id
 9302:     foreach my $package (@specifics) {
 9303: 	my (undef,$pack_type,$pack_part)=@{$package};
 9304: 	next if ($pack_part ne $part);
 9305: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9306: 	    return $packagetab{"$pack_type&$name&default"};
 9307: 	}
 9308:     }
 9309:     # look for any possible matching non extension_ package
 9310:     foreach my $package (@specifics) {
 9311: 	my (undef,$pack_type,$pack_part)=@{$package};
 9312: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9313: 	    return $packagetab{"$pack_type&$name&default"};
 9314: 	}
 9315: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9316: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9317: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9318: 	}
 9319:     }
 9320:     # look for any posible extension_ match
 9321:     foreach my $package (@extension) {
 9322: 	my ($package,$pack_type)=@{$package};
 9323: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9324: 	    return $packagetab{"$pack_type&$name&default"};
 9325: 	}
 9326: 	if (defined($packagetab{$package."&$name&default"})) {
 9327: 	    return $packagetab{$package."&$name&default"};
 9328: 	}
 9329:     }
 9330:     # look for a global default setting
 9331:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9332: 	return $packagetab{"default&$name&default"};
 9333:     }
 9334:     return undef;
 9335: }
 9336: 
 9337: sub add_prefix_and_part {
 9338:     my ($prefix,$part)=@_;
 9339:     my $keyroot;
 9340:     if (defined($prefix) && $prefix !~ /^__/) {
 9341: 	# prefix that has a part already
 9342: 	$keyroot=$prefix;
 9343:     } elsif (defined($prefix)) {
 9344: 	# prefix that is missing a part
 9345: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9346:     } else {
 9347: 	# no prefix at all
 9348: 	if (defined($part)) { $keyroot='_'.$part; }
 9349:     }
 9350:     return $keyroot;
 9351: }
 9352: 
 9353: # ---------------------------------------------------------------- Get metadata
 9354: 
 9355: my %metaentry;
 9356: my %importedpartids;
 9357: sub metadata {
 9358:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9359:     $uri=&declutter($uri);
 9360:     # if it is a non metadata possible uri return quickly
 9361:     if (($uri eq '') || 
 9362: 	(($uri =~ m|^/*adm/|) && 
 9363: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9364:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9365: 	return undef;
 9366:     }
 9367:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9368: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9369: 	return undef;
 9370:     }
 9371:     my $filename=$uri;
 9372:     $uri=~s/\.meta$//;
 9373: #
 9374: # Is the metadata already cached?
 9375: # Look at timestamp of caching
 9376: # Everything is cached by the main uri, libraries are never directly cached
 9377: #
 9378:     if (!defined($liburi)) {
 9379: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9380: 	if (defined($cached)) { return $result->{':'.$what}; }
 9381:     }
 9382:     {
 9383: # Imported parts would go here
 9384:         my %importedids=();
 9385:         my @origfileimportpartids=();
 9386:         my $importedparts=0;
 9387: #
 9388: # Is this a recursive call for a library?
 9389: #
 9390: #	if (! exists($metacache{$uri})) {
 9391: #	    $metacache{$uri}={};
 9392: #	}
 9393: 	my $cachetime = 60*60;
 9394:         if ($liburi) {
 9395: 	    $liburi=&declutter($liburi);
 9396:             $filename=$liburi;
 9397:         } else {
 9398: 	    &devalidate_cache_new('meta',$uri);
 9399: 	    undef(%metaentry);
 9400: 	}
 9401:         my %metathesekeys=();
 9402:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9403: 	my $metastring;
 9404: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9405: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9406: 	    $metastring = 
 9407: 		&Apache::lonnet::ssi_body($which,
 9408: 					  ('grade_target' => 'meta'));
 9409: 	    $cachetime = 1; # only want this cached in the child not long term
 9410: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9411:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9412: 	    my $file=&filelocation('',&clutter($filename));
 9413: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9414: 	    $metastring=&getfile($file);
 9415: 	}
 9416:         my $parser=HTML::LCParser->new(\$metastring);
 9417:         my $token;
 9418:         undef %metathesekeys;
 9419:         while ($token=$parser->get_token) {
 9420: 	    if ($token->[0] eq 'S') {
 9421: 		if (defined($token->[2]->{'package'})) {
 9422: #
 9423: # This is a package - get package info
 9424: #
 9425: 		    my $package=$token->[2]->{'package'};
 9426: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9427: 		    if (defined($token->[2]->{'id'})) { 
 9428: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9429: 		    }
 9430: 		    if ($metaentry{':packages'}) {
 9431: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9432: 		    } else {
 9433: 			$metaentry{':packages'}=$package.$keyroot;
 9434: 		    }
 9435: 		    foreach my $pack_entry (keys(%packagetab)) {
 9436: 			my $part=$keyroot;
 9437: 			$part=~s/^\_//;
 9438: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9439: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9440: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9441: 			    # ignore package.tab specified default values
 9442:                             # here &package_tab_default() will fetch those
 9443: 			    if ($subp eq 'default') { next; }
 9444: 			    my $value=$packagetab{$pack_entry};
 9445: 			    my $unikey;
 9446: 			    if ($pack =~ /_0$/) {
 9447: 				$unikey='parameter_0_'.$name;
 9448: 				$part=0;
 9449: 			    } else {
 9450: 				$unikey='parameter'.$keyroot.'_'.$name;
 9451: 			    }
 9452: 			    if ($subp eq 'display') {
 9453: 				$value.=' [Part: '.$part.']';
 9454: 			    }
 9455: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9456: 			    $metathesekeys{$unikey}=1;
 9457: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9458: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9459: 			    }
 9460: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9461: 				$metaentry{':'.$unikey}=
 9462: 				    $metaentry{':'.$unikey.'.default'};
 9463: 			    }
 9464: 			}
 9465: 		    }
 9466: 		} else {
 9467: #
 9468: # This is not a package - some other kind of start tag
 9469: #
 9470: 		    my $entry=$token->[1];
 9471: 		    my $unikey='';
 9472: 
 9473: 		    if ($entry eq 'import') {
 9474: #
 9475: # Importing a library here
 9476: #
 9477:                         my $location=$parser->get_text('/import');
 9478:                         my $dir=$filename;
 9479:                         $dir=~s|[^/]*$||;
 9480:                         $location=&filelocation($dir,$location);
 9481:                        
 9482:                         my $importmode=$token->[2]->{'importmode'};
 9483:                         if ($importmode eq 'problem') {
 9484: # Import as problem/response
 9485:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9486:                         } elsif ($importmode eq 'part') {
 9487: # Import as part(s)
 9488:                            $importedparts=1;
 9489: # We need to get the original file and the imported file to get the part order correct
 9490: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9491: # Load and inspect original file
 9492:                            if ($#origfileimportpartids<0) {
 9493:                               undef(%importedpartids);
 9494:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9495:                               my $origfile=&getfile($origfilelocation);
 9496:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9497:                            }
 9498: 
 9499: # Load and inspect imported file
 9500:                            my $impfile=&getfile($location);
 9501:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9502:                            if ($#impfilepartids>=0) {
 9503: # This problem had parts
 9504:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9505:                            } else {
 9506: # Importing by turning a single problem into a problem part
 9507: # It gets the import-tags ID as part-ID
 9508:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9509:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9510:                            }
 9511:                         } else {
 9512: # Normal import
 9513:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9514:                            if (defined($token->[2]->{'id'})) {
 9515:                               $unikey.='_'.$token->[2]->{'id'};
 9516:                            }
 9517:                         }
 9518: 
 9519: 			if ($depthcount<20) {
 9520: 			    my $metadata = 
 9521: 				&metadata($uri,'keys', $location,$unikey,
 9522: 					  $depthcount+1);
 9523: 			    foreach my $meta (split(',',$metadata)) {
 9524: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9525: 				$metathesekeys{$meta}=1;
 9526: 			    }
 9527: 			
 9528:                         }
 9529: 		    } else {
 9530: #
 9531: # Not importing, some other kind of non-package, non-library start tag
 9532: # 
 9533:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9534:                         if (defined($token->[2]->{'id'})) {
 9535:                             $unikey.='_'.$token->[2]->{'id'};
 9536:                         }
 9537: 			if (defined($token->[2]->{'name'})) { 
 9538: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9539: 			}
 9540: 			$metathesekeys{$unikey}=1;
 9541: 			foreach my $param (@{$token->[3]}) {
 9542: 			    $metaentry{':'.$unikey.'.'.$param} =
 9543: 				$token->[2]->{$param};
 9544: 			}
 9545: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9546: 			my $default=$metaentry{':'.$unikey.'.default'};
 9547: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9548: 		 # only ws inside the tag, and not in default, so use default
 9549: 		 # as value
 9550: 			    $metaentry{':'.$unikey}=$default;
 9551: 			} elsif ( $internaltext =~ /\S/ ) {
 9552: 		  # something interesting inside the tag
 9553: 			    $metaentry{':'.$unikey}=$internaltext;
 9554: 			} else {
 9555: 		  # no interesting values, don't set a default
 9556: 			}
 9557: # end of not-a-package not-a-library import
 9558: 		    }
 9559: # end of not-a-package start tag
 9560: 		}
 9561: # the next is the end of "start tag"
 9562: 	    }
 9563: 	}
 9564: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9565: 	$extension = lc($extension);
 9566: 	if ($extension eq 'htm') { $extension='html'; }
 9567: 
 9568: 	foreach my $key (keys(%packagetab)) {
 9569: 	    #no specific packages #how's our extension
 9570: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9571: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9572: 					 \%metathesekeys);
 9573: 	}
 9574: 
 9575: 	if (!exists($metaentry{':packages'})
 9576: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9577: 	    foreach my $key (keys(%packagetab)) {
 9578: 		#no specific packages well let's get default then
 9579: 		if ($key!~/^default&/) { next; }
 9580: 		&metadata_create_package_def($uri,$key,'default',
 9581: 					     \%metathesekeys);
 9582: 	    }
 9583: 	}
 9584: # are there custom rights to evaluate
 9585: 	if ($metaentry{':copyright'} eq 'custom') {
 9586: 
 9587:     #
 9588:     # Importing a rights file here
 9589:     #
 9590: 	    unless ($depthcount) {
 9591: 		my $location=$metaentry{':customdistributionfile'};
 9592: 		my $dir=$filename;
 9593: 		$dir=~s|[^/]*$||;
 9594: 		$location=&filelocation($dir,$location);
 9595: 		my $rights_metadata =
 9596: 		    &metadata($uri,'keys',$location,'_rights',
 9597: 			      $depthcount+1);
 9598: 		foreach my $rights (split(',',$rights_metadata)) {
 9599: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9600: 		    $metathesekeys{$rights}=1;
 9601: 		}
 9602: 	    }
 9603: 	}
 9604: 	# uniqifiy package listing
 9605: 	my %seen;
 9606: 	my @uniq_packages =
 9607: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9608: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9609: 
 9610:         if ($importedparts) {
 9611: # We had imported parts and need to rebuild partorder
 9612:            $metaentry{':partorder'}='';
 9613:            $metathesekeys{'partorder'}=1;
 9614:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9615:                if ($origfileimportpartids[$index] eq 'part') {
 9616: # original part, part of the problem
 9617:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9618:                } else {
 9619: # we have imported parts at this position
 9620:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9621:                }
 9622:            }
 9623:            $metaentry{':partorder'}=~s/^\,//;
 9624:         }
 9625: 
 9626: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9627: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9628: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9629: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9630: # this is the end of "was not already recently cached
 9631:     }
 9632:     return $metaentry{':'.$what};
 9633: }
 9634: 
 9635: sub metadata_create_package_def {
 9636:     my ($uri,$key,$package,$metathesekeys)=@_;
 9637:     my ($pack,$name,$subp)=split(/\&/,$key);
 9638:     if ($subp eq 'default') { next; }
 9639:     
 9640:     if (defined($metaentry{':packages'})) {
 9641: 	$metaentry{':packages'}.=','.$package;
 9642:     } else {
 9643: 	$metaentry{':packages'}=$package;
 9644:     }
 9645:     my $value=$packagetab{$key};
 9646:     my $unikey;
 9647:     $unikey='parameter_0_'.$name;
 9648:     $metaentry{':'.$unikey.'.part'}=0;
 9649:     $$metathesekeys{$unikey}=1;
 9650:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9651: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9652:     }
 9653:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9654: 	$metaentry{':'.$unikey}=
 9655: 	    $metaentry{':'.$unikey.'.default'};
 9656:     }
 9657: }
 9658: 
 9659: sub metadata_generate_part0 {
 9660:     my ($metadata,$metacache,$uri) = @_;
 9661:     my %allnames;
 9662:     foreach my $metakey (keys(%$metadata)) {
 9663: 	if ($metakey=~/^parameter\_(.*)/) {
 9664: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9665: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9666: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9667: 	    $allnames{$name}=$part;
 9668: 	  }
 9669: 	}
 9670:     }
 9671:     foreach my $name (keys(%allnames)) {
 9672:       $$metadata{"parameter_0_$name"}=1;
 9673:       my $key=":parameter_0_$name";
 9674:       $$metacache{"$key.part"}='0';
 9675:       $$metacache{"$key.name"}=$name;
 9676:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9677: 					   $allnames{$name}.'_'.$name.
 9678: 					   '.type'};
 9679:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9680: 			     '.display'};
 9681:       my $expr='[Part: '.$allnames{$name}.']';
 9682:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9683:       $$metacache{"$key.display"}=$olddis;
 9684:     }
 9685: }
 9686: 
 9687: # ------------------------------------------------------ Devalidate title cache
 9688: 
 9689: sub devalidate_title_cache {
 9690:     my ($url)=@_;
 9691:     if (!$env{'request.course.id'}) { return; }
 9692:     my $symb=&symbread($url);
 9693:     if (!$symb) { return; }
 9694:     my $key=$env{'request.course.id'}."\0".$symb;
 9695:     &devalidate_cache_new('title',$key);
 9696: }
 9697: 
 9698: # ------------------------------------------------- Get the title of a course
 9699: 
 9700: sub current_course_title {
 9701:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9702: }
 9703: # ------------------------------------------------- Get the title of a resource
 9704: 
 9705: sub gettitle {
 9706:     my $urlsymb=shift;
 9707:     my $symb=&symbread($urlsymb);
 9708:     if ($symb) {
 9709: 	my $key=$env{'request.course.id'}."\0".$symb;
 9710: 	my ($result,$cached)=&is_cached_new('title',$key);
 9711: 	if (defined($cached)) { 
 9712: 	    return $result;
 9713: 	}
 9714: 	my ($map,$resid,$url)=&decode_symb($symb);
 9715: 	my $title='';
 9716: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9717: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9718: 	} else {
 9719: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9720: 		    &GDBM_READER(),0640)) {
 9721: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9722: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9723: 		untie(%bighash);
 9724: 	    }
 9725: 	}
 9726: 	$title=~s/\&colon\;/\:/gs;
 9727: 	if ($title) {
 9728: # Remember both $symb and $title for dynamic metadata
 9729:             $accesshash{$symb.'___crstitle'}=$title;
 9730:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
 9731: # Cache this title and then return it
 9732: 	    return &do_cache_new('title',$key,$title,600);
 9733: 	}
 9734: 	$urlsymb=$url;
 9735:     }
 9736:     my $title=&metadata($urlsymb,'title');
 9737:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9738:     return $title;
 9739: }
 9740: 
 9741: sub get_slot {
 9742:     my ($which,$cnum,$cdom)=@_;
 9743:     if (!$cnum || !$cdom) {
 9744: 	(undef,my $courseid)=&whichuser();
 9745: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9746: 	$cnum=$env{'course.'.$courseid.'.num'};
 9747:     }
 9748:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9749:     my %slotinfo;
 9750:     if (exists($remembered{$key})) {
 9751: 	$slotinfo{$which} = $remembered{$key};
 9752:     } else {
 9753: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9754: 	&Apache::lonhomework::showhash(%slotinfo);
 9755: 	my ($tmp)=keys(%slotinfo);
 9756: 	if ($tmp=~/^error:/) { return (); }
 9757: 	$remembered{$key} = $slotinfo{$which};
 9758:     }
 9759:     if (ref($slotinfo{$which}) eq 'HASH') {
 9760: 	return %{$slotinfo{$which}};
 9761:     }
 9762:     return $slotinfo{$which};
 9763: }
 9764: 
 9765: sub get_reservable_slots {
 9766:     my ($cnum,$cdom,$uname,$udom) = @_;
 9767:     my $now = time;
 9768:     my $reservable_info;
 9769:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
 9770:     if (exists($remembered{$key})) {
 9771:         $reservable_info = $remembered{$key};
 9772:     } else {
 9773:         my %resv;
 9774:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
 9775:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
 9776:         $reservable_info = \%resv;
 9777:         $remembered{$key} = $reservable_info;
 9778:     }
 9779:     return $reservable_info;
 9780: }
 9781: 
 9782: sub get_course_slots {
 9783:     my ($cnum,$cdom) = @_;
 9784:     my $hashid=$cnum.':'.$cdom;
 9785:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
 9786:     if (defined($cached)) {
 9787:         if (ref($result) eq 'HASH') {
 9788:             return %{$result};
 9789:         }
 9790:     } else {
 9791:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 9792:         my ($tmp) = keys(%slots);
 9793:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9794:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
 9795:             return %slots;
 9796:         }
 9797:     }
 9798:     return;
 9799: }
 9800: 
 9801: sub devalidate_slots_cache {
 9802:     my ($cnum,$cdom)=@_;
 9803:     my $hashid=$cnum.':'.$cdom;
 9804:     &devalidate_cache_new('allslots',$hashid);
 9805: }
 9806: 
 9807: # ------------------------------------------------- Update symbolic store links
 9808: 
 9809: sub symblist {
 9810:     my ($mapname,%newhash)=@_;
 9811:     $mapname=&deversion(&declutter($mapname));
 9812:     my %hash;
 9813:     if (($env{'request.course.fn'}) && (%newhash)) {
 9814:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9815:                       &GDBM_WRCREAT(),0640)) {
 9816: 	    foreach my $url (keys(%newhash)) {
 9817: 		next if ($url eq 'last_known'
 9818: 			 && $env{'form.no_update_last_known'});
 9819: 		$hash{declutter($url)}=&encode_symb($mapname,
 9820: 						    $newhash{$url}->[1],
 9821: 						    $newhash{$url}->[0]);
 9822:             }
 9823:             if (untie(%hash)) {
 9824: 		return 'ok';
 9825:             }
 9826:         }
 9827:     }
 9828:     return 'error';
 9829: }
 9830: 
 9831: # --------------------------------------------------------------- Verify a symb
 9832: 
 9833: sub symbverify {
 9834:     my ($symb,$thisurl)=@_;
 9835:     my $thisfn=$thisurl;
 9836:     $thisfn=&declutter($thisfn);
 9837: # direct jump to resource in page or to a sequence - will construct own symbs
 9838:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9839: # check URL part
 9840:     my ($map,$resid,$url)=&decode_symb($symb);
 9841: 
 9842:     unless ($url eq $thisfn) { return 0; }
 9843: 
 9844:     $symb=&symbclean($symb);
 9845:     $thisurl=&deversion($thisurl);
 9846:     $thisfn=&deversion($thisfn);
 9847: 
 9848:     my %bighash;
 9849:     my $okay=0;
 9850: 
 9851:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9852:                             &GDBM_READER(),0640)) {
 9853:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9854:             $thisurl =~ s/\?.+$//;
 9855:         }
 9856:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9857:         unless ($ids) {
 9858:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9859:             $ids=$bighash{$idkey};
 9860:         }
 9861:         if ($ids) {
 9862: # ------------------------------------------------------------------- Has ID(s)
 9863: 	    foreach my $id (split(/\,/,$ids)) {
 9864: 	       my ($mapid,$resid)=split(/\./,$id);
 9865:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 9866:                    $symb =~ s/\?.+$//;
 9867:                }
 9868:                if (
 9869:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 9870:    eq $symb) { 
 9871: 		   if (($env{'request.role.adv'}) ||
 9872: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
 9873:                        ($thisurl eq '/adm/navmaps')) {
 9874: 		       $okay=1; 
 9875: 		   }
 9876: 	       }
 9877: 	   }
 9878:         }
 9879: 	untie(%bighash);
 9880:     }
 9881:     return $okay;
 9882: }
 9883: 
 9884: # --------------------------------------------------------------- Clean-up symb
 9885: 
 9886: sub symbclean {
 9887:     my $symb=shift;
 9888:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9889: # remove version from map
 9890:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 9891: 
 9892: # remove version from URL
 9893:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 9894: 
 9895: # remove wrapper
 9896: 
 9897:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 9898:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 9899:     return $symb;
 9900: }
 9901: 
 9902: # ---------------------------------------------- Split symb to find map and url
 9903: 
 9904: sub encode_symb {
 9905:     my ($map,$resid,$url)=@_;
 9906:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 9907: }
 9908: 
 9909: sub decode_symb {
 9910:     my $symb=shift;
 9911:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9912:     my ($map,$resid,$url)=split(/___/,$symb);
 9913:     return (&fixversion($map),$resid,&fixversion($url));
 9914: }
 9915: 
 9916: sub fixversion {
 9917:     my $fn=shift;
 9918:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 9919:     my %bighash;
 9920:     my $uri=&clutter($fn);
 9921:     my $key=$env{'request.course.id'}.'_'.$uri;
 9922: # is this cached?
 9923:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 9924:     if (defined($cached)) { return $result; }
 9925: # unfortunately not cached, or expired
 9926:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9927: 	    &GDBM_READER(),0640)) {
 9928:  	if ($bighash{'version_'.$uri}) {
 9929:  	    my $version=$bighash{'version_'.$uri};
 9930:  	    unless (($version eq 'mostrecent') || 
 9931: 		    ($version==&getversion($uri))) {
 9932:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 9933:  	    }
 9934:  	}
 9935:  	untie %bighash;
 9936:     }
 9937:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 9938: }
 9939: 
 9940: sub deversion {
 9941:     my $url=shift;
 9942:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 9943:     return $url;
 9944: }
 9945: 
 9946: # ------------------------------------------------------ Return symb list entry
 9947: 
 9948: sub symbread {
 9949:     my ($thisfn,$donotrecurse)=@_;
 9950:     my $cache_str='request.symbread.cached.'.$thisfn;
 9951:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 9952: # no filename provided? try from environment
 9953:     unless ($thisfn) {
 9954:         if ($env{'request.symb'}) {
 9955: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 9956: 	}
 9957: 	$thisfn=$env{'request.filename'};
 9958:     }
 9959:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9960: # is that filename actually a symb? Verify, clean, and return
 9961:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 9962: 	if (&symbverify($thisfn,$1)) {
 9963: 	    return $env{$cache_str}=&symbclean($thisfn);
 9964: 	}
 9965:     }
 9966:     $thisfn=declutter($thisfn);
 9967:     my %hash;
 9968:     my %bighash;
 9969:     my $syval='';
 9970:     if (($env{'request.course.fn'}) && ($thisfn)) {
 9971:         my $targetfn = $thisfn;
 9972:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 9973:             $targetfn = 'adm/wrapper/'.$thisfn;
 9974:         }
 9975: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 9976: 	    $targetfn=$1;
 9977: 	}
 9978:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9979:                       &GDBM_READER(),0640)) {
 9980: 	    $syval=$hash{$targetfn};
 9981:             untie(%hash);
 9982:         }
 9983: # ---------------------------------------------------------- There was an entry
 9984:         if ($syval) {
 9985: 	    #unless ($syval=~/\_\d+$/) {
 9986: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 9987: 		    #&appenv({'request.ambiguous' => $thisfn});
 9988: 		    #return $env{$cache_str}='';
 9989: 		#}    
 9990: 		#$syval.=$1;
 9991: 	    #}
 9992:         } else {
 9993: # ------------------------------------------------------- Was not in symb table
 9994:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9995:                             &GDBM_READER(),0640)) {
 9996: # ---------------------------------------------- Get ID(s) for current resource
 9997:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 9998:               unless ($ids) { 
 9999:                  $ids=$bighash{'ids_/'.$thisfn};
10000:               }
10001:               unless ($ids) {
10002: # alias?
10003: 		  $ids=$bighash{'mapalias_'.$thisfn};
10004:               }
10005:               if ($ids) {
10006: # ------------------------------------------------------------------- Has ID(s)
10007:                  my @possibilities=split(/\,/,$ids);
10008:                  if ($#possibilities==0) {
10009: # ----------------------------------------------- There is only one possibility
10010: 		     my ($mapid,$resid)=split(/\./,$ids);
10011: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10012: 						    $resid,$thisfn);
10013:                  } elsif (!$donotrecurse) {
10014: # ------------------------------------------ There is more than one possibility
10015:                      my $realpossible=0;
10016:                      foreach my $id (@possibilities) {
10017: 			 my $file=$bighash{'src_'.$id};
10018:                          if (&allowed('bre',$file)) {
10019:          		    my ($mapid,$resid)=split(/\./,$id);
10020:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10021: 				$realpossible++;
10022:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10023: 						    $resid,$thisfn);
10024:                             }
10025: 			 }
10026:                      }
10027: 		     if ($realpossible!=1) { $syval=''; }
10028:                  } else {
10029:                      $syval='';
10030:                  }
10031: 	      }
10032:               untie(%bighash)
10033:            }
10034:         }
10035:         if ($syval) {
10036: 	    return $env{$cache_str}=$syval;
10037:         }
10038:     }
10039:     &appenv({'request.ambiguous' => $thisfn});
10040:     return $env{$cache_str}='';
10041: }
10042: 
10043: # ---------------------------------------------------------- Return random seed
10044: 
10045: sub numval {
10046:     my $txt=shift;
10047:     $txt=~tr/A-J/0-9/;
10048:     $txt=~tr/a-j/0-9/;
10049:     $txt=~tr/K-T/0-9/;
10050:     $txt=~tr/k-t/0-9/;
10051:     $txt=~tr/U-Z/0-5/;
10052:     $txt=~tr/u-z/0-5/;
10053:     $txt=~s/\D//g;
10054:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10055:     return int($txt);
10056: }
10057: 
10058: sub numval2 {
10059:     my $txt=shift;
10060:     $txt=~tr/A-J/0-9/;
10061:     $txt=~tr/a-j/0-9/;
10062:     $txt=~tr/K-T/0-9/;
10063:     $txt=~tr/k-t/0-9/;
10064:     $txt=~tr/U-Z/0-5/;
10065:     $txt=~tr/u-z/0-5/;
10066:     $txt=~s/\D//g;
10067:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10068:     my $total;
10069:     foreach my $val (@txts) { $total+=$val; }
10070:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10071:     return int($total);
10072: }
10073: 
10074: sub numval3 {
10075:     use integer;
10076:     my $txt=shift;
10077:     $txt=~tr/A-J/0-9/;
10078:     $txt=~tr/a-j/0-9/;
10079:     $txt=~tr/K-T/0-9/;
10080:     $txt=~tr/k-t/0-9/;
10081:     $txt=~tr/U-Z/0-5/;
10082:     $txt=~tr/u-z/0-5/;
10083:     $txt=~s/\D//g;
10084:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10085:     my $total;
10086:     foreach my $val (@txts) { $total+=$val; }
10087:     if ($_64bit) { $total=(($total<<32)>>32); }
10088:     return $total;
10089: }
10090: 
10091: sub digest {
10092:     my ($data)=@_;
10093:     my $digest=&Digest::MD5::md5($data);
10094:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10095:     my ($e,$f);
10096:     {
10097:         use integer;
10098:         $e=($a+$b);
10099:         $f=($c+$d);
10100:         if ($_64bit) {
10101:             $e=(($e<<32)>>32);
10102:             $f=(($f<<32)>>32);
10103:         }
10104:     }
10105:     if (wantarray) {
10106: 	return ($e,$f);
10107:     } else {
10108: 	my $g;
10109: 	{
10110: 	    use integer;
10111: 	    $g=($e+$f);
10112: 	    if ($_64bit) {
10113: 		$g=(($g<<32)>>32);
10114: 	    }
10115: 	}
10116: 	return $g;
10117:     }
10118: }
10119: 
10120: sub latest_rnd_algorithm_id {
10121:     return '64bit5';
10122: }
10123: 
10124: sub get_rand_alg {
10125:     my ($courseid)=@_;
10126:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10127:     if ($courseid) {
10128: 	return $env{"course.$courseid.rndseed"};
10129:     }
10130:     return &latest_rnd_algorithm_id();
10131: }
10132: 
10133: sub validCODE {
10134:     my ($CODE)=@_;
10135:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10136:     return 0;
10137: }
10138: 
10139: sub getCODE {
10140:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10141:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10142: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10143: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10144: 	return $Apache::lonhomework::history{'resource.CODE'};
10145:     }
10146:     return undef;
10147: }
10148: #
10149: #  Determines the random seed for a specific context:
10150: #
10151: # parameters:
10152: #   symb      - in course context the symb for the seed.
10153: #   course_id - The course id of the form domain_coursenum.
10154: #   domain    - Domain for the user.
10155: #   course    - Course for the user.
10156: #   cenv      - environment of the course.
10157: #
10158: # NOTE:
10159: #   All parameters are picked out of the environment if missing
10160: #   or not defined.
10161: #   If a symb cannot be determined the current time is used instead.
10162: #
10163: #  For a given well defined symb, courside, domain, username,
10164: #  and course environment, the seed is reproducible.
10165: #
10166: sub rndseed {
10167:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10168:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10169:     if (!defined($symb)) {
10170: 	unless ($symb=$wsymb) { return time; }
10171:     }
10172:     if (!defined $courseid) { 
10173: 	$courseid=$wcourseid; 
10174:     }
10175:     if (!defined $domain) { $domain=$wdomain; }
10176:     if (!defined $username) { $username=$wusername }
10177: 
10178:     my $which;
10179:     if (defined($cenv->{'rndseed'})) {
10180: 	$which = $cenv->{'rndseed'};
10181:     } else {
10182: 	$which =&get_rand_alg($courseid);
10183:     }
10184:     if (defined(&getCODE())) {
10185: 
10186: 	if ($which eq '64bit5') {
10187: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10188: 	} elsif ($which eq '64bit4') {
10189: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10190: 	} else {
10191: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10192: 	}
10193:     } elsif ($which eq '64bit5') {
10194: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10195:     } elsif ($which eq '64bit4') {
10196: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10197:     } elsif ($which eq '64bit3') {
10198: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10199:     } elsif ($which eq '64bit2') {
10200: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10201:     } elsif ($which eq '64bit') {
10202: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10203:     }
10204:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10205: }
10206: 
10207: sub rndseed_32bit {
10208:     my ($symb,$courseid,$domain,$username)=@_;
10209:     {
10210: 	use integer;
10211: 	my $symbchck=unpack("%32C*",$symb) << 27;
10212: 	my $symbseed=numval($symb) << 22;
10213: 	my $namechck=unpack("%32C*",$username) << 17;
10214: 	my $nameseed=numval($username) << 12;
10215: 	my $domainseed=unpack("%32C*",$domain) << 7;
10216: 	my $courseseed=unpack("%32C*",$courseid);
10217: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10218: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10219: 	#&logthis("rndseed :$num:$symb");
10220: 	if ($_64bit) { $num=(($num<<32)>>32); }
10221: 	return $num;
10222:     }
10223: }
10224: 
10225: sub rndseed_64bit {
10226:     my ($symb,$courseid,$domain,$username)=@_;
10227:     {
10228: 	use integer;
10229: 	my $symbchck=unpack("%32S*",$symb) << 21;
10230: 	my $symbseed=numval($symb) << 10;
10231: 	my $namechck=unpack("%32S*",$username);
10232: 	
10233: 	my $nameseed=numval($username) << 21;
10234: 	my $domainseed=unpack("%32S*",$domain) << 10;
10235: 	my $courseseed=unpack("%32S*",$courseid);
10236: 	
10237: 	my $num1=$symbchck+$symbseed+$namechck;
10238: 	my $num2=$nameseed+$domainseed+$courseseed;
10239: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10240: 	#&logthis("rndseed :$num:$symb");
10241: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10242: 	return "$num1,$num2";
10243:     }
10244: }
10245: 
10246: sub rndseed_64bit2 {
10247:     my ($symb,$courseid,$domain,$username)=@_;
10248:     {
10249: 	use integer;
10250: 	# strings need to be an even # of cahracters long, it it is odd the
10251:         # last characters gets thrown away
10252: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10253: 	my $symbseed=numval($symb) << 10;
10254: 	my $namechck=unpack("%32S*",$username.' ');
10255: 	
10256: 	my $nameseed=numval($username) << 21;
10257: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10258: 	my $courseseed=unpack("%32S*",$courseid.' ');
10259: 	
10260: 	my $num1=$symbchck+$symbseed+$namechck;
10261: 	my $num2=$nameseed+$domainseed+$courseseed;
10262: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10263: 	#&logthis("rndseed :$num:$symb");
10264: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10265: 	return "$num1,$num2";
10266:     }
10267: }
10268: 
10269: sub rndseed_64bit3 {
10270:     my ($symb,$courseid,$domain,$username)=@_;
10271:     {
10272: 	use integer;
10273: 	# strings need to be an even # of cahracters long, it it is odd the
10274:         # last characters gets thrown away
10275: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10276: 	my $symbseed=numval2($symb) << 10;
10277: 	my $namechck=unpack("%32S*",$username.' ');
10278: 	
10279: 	my $nameseed=numval2($username) << 21;
10280: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10281: 	my $courseseed=unpack("%32S*",$courseid.' ');
10282: 	
10283: 	my $num1=$symbchck+$symbseed+$namechck;
10284: 	my $num2=$nameseed+$domainseed+$courseseed;
10285: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10286: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10287: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10288: 	
10289: 	return "$num1:$num2";
10290:     }
10291: }
10292: 
10293: sub rndseed_64bit4 {
10294:     my ($symb,$courseid,$domain,$username)=@_;
10295:     {
10296: 	use integer;
10297: 	# strings need to be an even # of cahracters long, it it is odd the
10298:         # last characters gets thrown away
10299: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10300: 	my $symbseed=numval3($symb) << 10;
10301: 	my $namechck=unpack("%32S*",$username.' ');
10302: 	
10303: 	my $nameseed=numval3($username) << 21;
10304: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10305: 	my $courseseed=unpack("%32S*",$courseid.' ');
10306: 	
10307: 	my $num1=$symbchck+$symbseed+$namechck;
10308: 	my $num2=$nameseed+$domainseed+$courseseed;
10309: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10310: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10311: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10312: 	
10313: 	return "$num1:$num2";
10314:     }
10315: }
10316: 
10317: sub rndseed_64bit5 {
10318:     my ($symb,$courseid,$domain,$username)=@_;
10319:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10320:     return "$num1:$num2";
10321: }
10322: 
10323: sub rndseed_CODE_64bit {
10324:     my ($symb,$courseid,$domain,$username)=@_;
10325:     {
10326: 	use integer;
10327: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10328: 	my $symbseed=numval2($symb);
10329: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10330: 	my $CODEseed=numval(&getCODE());
10331: 	my $courseseed=unpack("%32S*",$courseid.' ');
10332: 	my $num1=$symbseed+$CODEchck;
10333: 	my $num2=$CODEseed+$courseseed+$symbchck;
10334: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10335: 	#&logthis("rndseed :$num1:$num2:$symb");
10336: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10337: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10338: 	return "$num1:$num2";
10339:     }
10340: }
10341: 
10342: sub rndseed_CODE_64bit4 {
10343:     my ($symb,$courseid,$domain,$username)=@_;
10344:     {
10345: 	use integer;
10346: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10347: 	my $symbseed=numval3($symb);
10348: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10349: 	my $CODEseed=numval3(&getCODE());
10350: 	my $courseseed=unpack("%32S*",$courseid.' ');
10351: 	my $num1=$symbseed+$CODEchck;
10352: 	my $num2=$CODEseed+$courseseed+$symbchck;
10353: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10354: 	#&logthis("rndseed :$num1:$num2:$symb");
10355: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10356: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10357: 	return "$num1:$num2";
10358:     }
10359: }
10360: 
10361: sub rndseed_CODE_64bit5 {
10362:     my ($symb,$courseid,$domain,$username)=@_;
10363:     my $code = &getCODE();
10364:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10365:     return "$num1:$num2";
10366: }
10367: 
10368: sub setup_random_from_rndseed {
10369:     my ($rndseed)=@_;
10370:     if ($rndseed =~/([,:])/) {
10371: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10372: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10373:     } else {
10374: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10375:     }
10376: }
10377: 
10378: sub latest_receipt_algorithm_id {
10379:     return 'receipt3';
10380: }
10381: 
10382: sub recunique {
10383:     my $fucourseid=shift;
10384:     my $unique;
10385:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10386: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10387: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10388:     } else {
10389: 	$unique=$perlvar{'lonReceipt'};
10390:     }
10391:     return unpack("%32C*",$unique);
10392: }
10393: 
10394: sub recprefix {
10395:     my $fucourseid=shift;
10396:     my $prefix;
10397:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10398: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10399: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10400:     } else {
10401: 	$prefix=$perlvar{'lonHostID'};
10402:     }
10403:     return unpack("%32C*",$prefix);
10404: }
10405: 
10406: sub ireceipt {
10407:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10408: 
10409:     my $return =&recprefix($fucourseid).'-';
10410: 
10411:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10412: 	$env{'request.state'} eq 'construct') {
10413: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10414: 	return $return;
10415:     }
10416: 
10417:     my $cuname=unpack("%32C*",$funame);
10418:     my $cudom=unpack("%32C*",$fudom);
10419:     my $cucourseid=unpack("%32C*",$fucourseid);
10420:     my $cusymb=unpack("%32C*",$fusymb);
10421:     my $cunique=&recunique($fucourseid);
10422:     my $cpart=unpack("%32S*",$part);
10423:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10424: 
10425: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10426: 			       
10427: 	$return.= ($cunique%$cuname+
10428: 		   $cunique%$cudom+
10429: 		   $cusymb%$cuname+
10430: 		   $cusymb%$cudom+
10431: 		   $cucourseid%$cuname+
10432: 		   $cucourseid%$cudom+
10433: 		   $cpart%$cuname+
10434: 		   $cpart%$cudom);
10435:     } else {
10436: 	$return.= ($cunique%$cuname+
10437: 		   $cunique%$cudom+
10438: 		   $cusymb%$cuname+
10439: 		   $cusymb%$cudom+
10440: 		   $cucourseid%$cuname+
10441: 		   $cucourseid%$cudom);
10442:     }
10443:     return $return;
10444: }
10445: 
10446: sub receipt {
10447:     my ($part)=@_;
10448:     my ($symb,$courseid,$domain,$name) = &whichuser();
10449:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10450: }
10451: 
10452: sub whichuser {
10453:     my ($passedsymb)=@_;
10454:     my ($symb,$courseid,$domain,$name,$publicuser);
10455:     if (defined($env{'form.grade_symb'})) {
10456: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10457: 	my $allowed=&allowed('vgr',$tmp_courseid);
10458: 	if (!$allowed &&
10459: 	    exists($env{'request.course.sec'}) &&
10460: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10461: 	    $allowed=&allowed('vgr',$tmp_courseid.
10462: 			      '/'.$env{'request.course.sec'});
10463: 	}
10464: 	if ($allowed) {
10465: 	    ($symb)=&get_env_multiple('form.grade_symb');
10466: 	    $courseid=$tmp_courseid;
10467: 	    ($domain)=&get_env_multiple('form.grade_domain');
10468: 	    ($name)=&get_env_multiple('form.grade_username');
10469: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10470: 	}
10471:     }
10472:     if (!$passedsymb) {
10473: 	$symb=&symbread();
10474:     } else {
10475: 	$symb=$passedsymb;
10476:     }
10477:     $courseid=$env{'request.course.id'};
10478:     $domain=$env{'user.domain'};
10479:     $name=$env{'user.name'};
10480:     if ($name eq 'public' && $domain eq 'public') {
10481: 	if (!defined($env{'form.username'})) {
10482: 	    $env{'form.username'}.=time.rand(10000000);
10483: 	}
10484: 	$name.=$env{'form.username'};
10485:     }
10486:     return ($symb,$courseid,$domain,$name,$publicuser);
10487: 
10488: }
10489: 
10490: # ------------------------------------------------------------ Serves up a file
10491: # returns either the contents of the file or 
10492: # -1 if the file doesn't exist
10493: #
10494: # if the target is a file that was uploaded via DOCS, 
10495: # a check will be made to see if a current copy exists on the local server,
10496: # if it does this will be served, otherwise a copy will be retrieved from
10497: # the home server for the course and stored in /home/httpd/html/userfiles on
10498: # the local server.   
10499: 
10500: sub getfile {
10501:     my ($file) = @_;
10502:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10503:     &repcopy($file);
10504:     return &readfile($file);
10505: }
10506: 
10507: sub repcopy_userfile {
10508:     my ($file)=@_;
10509:     my $londocroot = $perlvar{'lonDocRoot'};
10510:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10511:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10512:     my ($cdom,$cnum,$filename) = 
10513: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10514:     my $uri="/uploaded/$cdom/$cnum/$filename";
10515:     if (-e "$file") {
10516: # we already have a local copy, check it out
10517: 	my @fileinfo = stat($file);
10518: 	my $rtncode;
10519: 	my $info;
10520: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10521: 	if ($lwpresp ne 'ok') {
10522: # there is no such file anymore, even though we had a local copy
10523: 	    if ($rtncode eq '404') {
10524: 		unlink($file);
10525: 	    }
10526: 	    return -1;
10527: 	}
10528: 	if ($info < $fileinfo[9]) {
10529: # nice, the file we have is up-to-date, just say okay
10530: 	    return 'ok';
10531: 	} else {
10532: # the file is outdated, get rid of it
10533: 	    unlink($file);
10534: 	}
10535:     }
10536: # one way or the other, at this point, we don't have the file
10537: # construct the correct path for the file
10538:     my @parts = ($cdom,$cnum); 
10539:     if ($filename =~ m|^(.+)/[^/]+$|) {
10540: 	push @parts, split(/\//,$1);
10541:     }
10542:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10543:     foreach my $part (@parts) {
10544: 	$path .= '/'.$part;
10545: 	if (!-e $path) {
10546: 	    mkdir($path,0770);
10547: 	}
10548:     }
10549: # now the path exists for sure
10550: # get a user agent
10551:     my $ua=new LWP::UserAgent;
10552:     my $transferfile=$file.'.in.transfer';
10553: # FIXME: this should flock
10554:     if (-e $transferfile) { return 'ok'; }
10555:     my $request;
10556:     $uri=~s/^\///;
10557:     my $homeserver = &homeserver($cnum,$cdom);
10558:     my $protocol = $protocol{$homeserver};
10559:     $protocol = 'http' if ($protocol ne 'https');
10560:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10561:     my $response=$ua->request($request,$transferfile);
10562: # did it work?
10563:     if ($response->is_error()) {
10564: 	unlink($transferfile);
10565: 	&logthis("Userfile repcopy failed for $uri");
10566: 	return -1;
10567:     }
10568: # worked, rename the transfer file
10569:     rename($transferfile,$file);
10570:     return 'ok';
10571: }
10572: 
10573: sub tokenwrapper {
10574:     my $uri=shift;
10575:     $uri=~s|^https?\://([^/]+)||;
10576:     $uri=~s|^/||;
10577:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10578:     my $token=$1;
10579:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10580:     if ($udom && $uname && $file) {
10581: 	$file=~s|(\?\.*)*$||;
10582:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10583:         my $homeserver = &homeserver($uname,$udom);
10584:         my $protocol = $protocol{$homeserver};
10585:         $protocol = 'http' if ($protocol ne 'https');
10586:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10587:                (($uri=~/\?/)?'&':'?').'token='.$token.
10588:                                '&tokenissued='.$perlvar{'lonHostID'};
10589:     } else {
10590:         return '/adm/notfound.html';
10591:     }
10592: }
10593: 
10594: # call with reqtype HEAD: get last modification time
10595: # call with reqtype GET: get the file contents
10596: # Do not call this with reqtype GET for large files! It loads everything into memory
10597: #
10598: sub getuploaded {
10599:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10600:     $uri=~s/^\///;
10601:     my $homeserver = &homeserver($cnum,$cdom);
10602:     my $protocol = $protocol{$homeserver};
10603:     $protocol = 'http' if ($protocol ne 'https');
10604:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10605:     my $ua=new LWP::UserAgent;
10606:     my $request=new HTTP::Request($reqtype,$uri);
10607:     my $response=$ua->request($request);
10608:     $$rtncode = $response->code;
10609:     if (! $response->is_success()) {
10610: 	return 'failed';
10611:     }      
10612:     if ($reqtype eq 'HEAD') {
10613: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10614:     } elsif ($reqtype eq 'GET') {
10615: 	$$info = $response->content;
10616:     }
10617:     return 'ok';
10618: }
10619: 
10620: sub readfile {
10621:     my $file = shift;
10622:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10623:     my $fh;
10624:     open($fh,"<$file");
10625:     my $a='';
10626:     while (my $line = <$fh>) { $a .= $line; }
10627:     return $a;
10628: }
10629: 
10630: sub filelocation {
10631:     my ($dir,$file) = @_;
10632:     my $location;
10633:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10634: 
10635:     if ($file =~ m-^/adm/-) {
10636: 	$file=~s-^/adm/wrapper/-/-;
10637: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10638:     }
10639: 
10640:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10641:         $location = $file;
10642:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10643:         my ($udom,$uname,$filename)=
10644:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10645:         my $home=&homeserver($uname,$udom);
10646:         my $is_me=0;
10647:         my @ids=&current_machine_ids();
10648:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10649:         if ($is_me) {
10650:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10651:         } else {
10652:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10653:   	      $udom.'/'.$uname.'/'.$filename;
10654:         }
10655:     } elsif ($file =~ m-^/adm/-) {
10656: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10657:     } else {
10658:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10659:         $file=~s:^/(res|priv)/:/:;
10660:         my $space=$1;
10661:         if ( !( $file =~ m:^/:) ) {
10662:             $location = $dir. '/'.$file;
10663:         } else {
10664:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10665:         }
10666:     }
10667:     $location=~s://+:/:g; # remove duplicate /
10668:     while ($location=~m{/\.\./}) {
10669: 	if ($location =~ m{/[^/]+/\.\./}) {
10670: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10671: 	} else {
10672: 	    $location=~ s{/\.\./}{/}g;
10673: 	}
10674:     } #remove dir/..
10675:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10676:     return $location;
10677: }
10678: 
10679: sub hreflocation {
10680:     my ($dir,$file)=@_;
10681:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10682: 	$file=filelocation($dir,$file);
10683:     } elsif ($file=~m-^/adm/-) {
10684: 	$file=~s-^/adm/wrapper/-/-;
10685: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10686:     }
10687:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10688: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10689:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10690: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10691: 	        {/uploaded/$1/$2/}x;
10692:     }
10693:     if ($file=~ m{^/userfiles/}) {
10694: 	$file =~ s{^/userfiles/}{/uploaded/};
10695:     }
10696:     return $file;
10697: }
10698: 
10699: 
10700: 
10701: 
10702: 
10703: sub current_machine_domains {
10704:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10705: }
10706: 
10707: sub machine_domains {
10708:     my ($hostname) = @_;
10709:     my @domains;
10710:     my %hostname = &all_hostnames();
10711:     while( my($id, $name) = each(%hostname)) {
10712: #	&logthis("-$id-$name-$hostname-");
10713: 	if ($hostname eq $name) {
10714: 	    push(@domains,&host_domain($id));
10715: 	}
10716:     }
10717:     return @domains;
10718: }
10719: 
10720: sub current_machine_ids {
10721:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10722: }
10723: 
10724: sub machine_ids {
10725:     my ($hostname) = @_;
10726:     $hostname ||= &hostname($perlvar{'lonHostID'});
10727:     my @ids;
10728:     my %name_to_host = &all_names();
10729:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10730: 	return @{ $name_to_host{$hostname} };
10731:     }
10732:     return;
10733: }
10734: 
10735: sub additional_machine_domains {
10736:     my @domains;
10737:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10738:     while( my $line = <$fh>) {
10739:         $line =~ s/\s//g;
10740:         push(@domains,$line);
10741:     }
10742:     return @domains;
10743: }
10744: 
10745: sub default_login_domain {
10746:     my $domain = $perlvar{'lonDefDomain'};
10747:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10748:     foreach my $posdom (&current_machine_domains(),
10749:                         &additional_machine_domains()) {
10750:         if (lc($posdom) eq lc($testdomain)) {
10751:             $domain=$posdom;
10752:             last;
10753:         }
10754:     }
10755:     return $domain;
10756: }
10757: 
10758: # ------------------------------------------------------------- Declutters URLs
10759: 
10760: sub declutter {
10761:     my $thisfn=shift;
10762:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10763:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10764:     $thisfn=~s/^\///;
10765:     $thisfn=~s|^adm/wrapper/||;
10766:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10767:     $thisfn=~s/^res\///;
10768:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10769:         $thisfn=~s/\?.+$//;
10770:     }
10771:     return $thisfn;
10772: }
10773: 
10774: # ------------------------------------------------------------- Clutter up URLs
10775: 
10776: sub clutter {
10777:     my $thisfn='/'.&declutter(shift);
10778:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10779: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10780:        $thisfn='/res'.$thisfn; 
10781:     }
10782:     if ($thisfn !~m|^/adm|) {
10783: 	if ($thisfn =~ m|^/ext/|) {
10784: 	    $thisfn='/adm/wrapper'.$thisfn;
10785: 	} else {
10786: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10787: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10788: 	    if ($embstyle eq 'ssi'
10789: 		|| ($embstyle eq 'hdn')
10790: 		|| ($embstyle eq 'rat')
10791: 		|| ($embstyle eq 'prv')
10792: 		|| ($embstyle eq 'ign')) {
10793: 		#do nothing with these
10794: 	    } elsif (($embstyle eq 'img') 
10795: 		|| ($embstyle eq 'emb')
10796: 		|| ($embstyle eq 'wrp')) {
10797: 		$thisfn='/adm/wrapper'.$thisfn;
10798: 	    } elsif ($embstyle eq 'unk'
10799: 		     && $thisfn!~/\.(sequence|page)$/) {
10800: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10801: 	    } else {
10802: #		&logthis("Got a blank emb style");
10803: 	    }
10804: 	}
10805:     }
10806:     return $thisfn;
10807: }
10808: 
10809: sub clutter_with_no_wrapper {
10810:     my $uri = &clutter(shift);
10811:     if ($uri =~ m-^/adm/-) {
10812: 	$uri =~ s-^/adm/wrapper/-/-;
10813: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10814:     }
10815:     return $uri;
10816: }
10817: 
10818: sub freeze_escape {
10819:     my ($value)=@_;
10820:     if (ref($value)) {
10821: 	$value=&nfreeze($value);
10822: 	return '__FROZEN__'.&escape($value);
10823:     }
10824:     return &escape($value);
10825: }
10826: 
10827: 
10828: sub thaw_unescape {
10829:     my ($value)=@_;
10830:     if ($value =~ /^__FROZEN__/) {
10831: 	substr($value,0,10,undef);
10832: 	$value=&unescape($value);
10833: 	return &thaw($value);
10834:     }
10835:     return &unescape($value);
10836: }
10837: 
10838: sub correct_line_ends {
10839:     my ($result)=@_;
10840:     $$result =~s/\r\n/\n/mg;
10841:     $$result =~s/\r/\n/mg;
10842: }
10843: # ================================================================ Main Program
10844: 
10845: sub goodbye {
10846:    &logthis("Starting Shut down");
10847: #not converted to using infrastruture and probably shouldn't be
10848:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10849: #converted
10850: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10851:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10852: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10853: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10854: #1.1 only
10855: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10856: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10857: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10858: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10859:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10860:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10861:    &logthis(sprintf("%-20s is %s",'hits',$hits));
10862:    &flushcourselogs();
10863:    &logthis("Shutting down");
10864: }
10865: 
10866: sub get_dns {
10867:     my ($url,$func,$ignore_cache) = @_;
10868:     if (!$ignore_cache) {
10869: 	my ($content,$cached)=
10870: 	    &Apache::lonnet::is_cached_new('dns',$url);
10871: 	if ($cached) {
10872: 	    &$func($content);
10873: 	    return;
10874: 	}
10875:     }
10876: 
10877:     my %alldns;
10878:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10879:     foreach my $dns (<$config>) {
10880: 	next if ($dns !~ /^\^(\S*)/x);
10881:         my $line = $1;
10882:         my ($host,$protocol) = split(/:/,$line);
10883:         if ($protocol ne 'https') {
10884:             $protocol = 'http';
10885:         }
10886: 	$alldns{$host} = $protocol;
10887:     }
10888:     while (%alldns) {
10889: 	my ($dns) = keys(%alldns);
10890: 	my $ua=new LWP::UserAgent;
10891:         $ua->timeout(30);
10892: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10893: 	my $response=$ua->request($request);
10894:         delete($alldns{$dns});
10895: 	next if ($response->is_error());
10896: 	my @content = split("\n",$response->content);
10897: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10898: 	&$func(\@content);
10899: 	return;
10900:     }
10901:     close($config);
10902:     my $which = (split('/',$url))[3];
10903:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10904:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10905:     my @content = <$config>;
10906:     &$func(\@content);
10907:     return;
10908: }
10909: # ------------------------------------------------------------ Read domain file
10910: {
10911:     my $loaded;
10912:     my %domain;
10913: 
10914:     sub parse_domain_tab {
10915: 	my ($lines) = @_;
10916: 	foreach my $line (@$lines) {
10917: 	    next if ($line =~ /^(\#|\s*$ )/x);
10918: 
10919: 	    chomp($line);
10920: 	    my ($name,@elements) = split(/:/,$line,9);
10921: 	    my %this_domain;
10922: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
10923: 			       'lang_def', 'city', 'longi', 'lati',
10924: 			       'primary') {
10925: 		$this_domain{$field} = shift(@elements);
10926: 	    }
10927: 	    $domain{$name} = \%this_domain;
10928: 	}
10929:     }
10930: 
10931:     sub reset_domain_info {
10932: 	undef($loaded);
10933: 	undef(%domain);
10934:     }
10935: 
10936:     sub load_domain_tab {
10937: 	my ($ignore_cache) = @_;
10938: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10939: 	my $fh;
10940: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10941: 	    my @lines = <$fh>;
10942: 	    &parse_domain_tab(\@lines);
10943: 	}
10944: 	close($fh);
10945: 	$loaded = 1;
10946:     }
10947: 
10948:     sub domain {
10949: 	&load_domain_tab() if (!$loaded);
10950: 
10951: 	my ($name,$what) = @_;
10952: 	return if ( !exists($domain{$name}) );
10953: 
10954: 	if (!$what) {
10955: 	    return $domain{$name}{'description'};
10956: 	}
10957: 	return $domain{$name}{$what};
10958:     }
10959: 
10960:     sub domain_info {
10961:         &load_domain_tab() if (!$loaded);
10962:         return %domain;
10963:     }
10964: 
10965: }
10966: 
10967: 
10968: # ------------------------------------------------------------- Read hosts file
10969: {
10970:     my %hostname;
10971:     my %hostdom;
10972:     my %libserv;
10973:     my $loaded;
10974:     my %name_to_host;
10975:     my %internetdom;
10976:     my %LC_dns_serv;
10977: 
10978:     sub parse_hosts_tab {
10979: 	my ($file) = @_;
10980: 	foreach my $configline (@$file) {
10981: 	    next if ($configline =~ /^(\#|\s*$ )/x);
10982:             chomp($configline);
10983: 	    if ($configline =~ /^\^/) {
10984:                 if ($configline =~ /^\^([\w.\-]+)/) {
10985:                     $LC_dns_serv{$1} = 1;
10986:                 }
10987:                 next;
10988:             }
10989: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10990: 	    $name=~s/\s//g;
10991: 	    if ($id && $domain && $role && $name) {
10992: 		$hostname{$id}=$name;
10993: 		push(@{$name_to_host{$name}}, $id);
10994: 		$hostdom{$id}=$domain;
10995: 		if ($role eq 'library') { $libserv{$id}=$name; }
10996:                 if (defined($protocol)) {
10997:                     if ($protocol eq 'https') {
10998:                         $protocol{$id} = $protocol;
10999:                     } else {
11000:                         $protocol{$id} = 'http'; 
11001:                     }
11002:                 } else {
11003:                     $protocol{$id} = 'http';
11004:                 }
11005:                 if (defined($intdom)) {
11006:                     $internetdom{$id} = $intdom;
11007:                 }
11008: 	    }
11009: 	}
11010:     }
11011:     
11012:     sub reset_hosts_info {
11013: 	&purge_remembered();
11014: 	&reset_domain_info();
11015: 	&reset_hosts_ip_info();
11016: 	undef(%name_to_host);
11017: 	undef(%hostname);
11018: 	undef(%hostdom);
11019: 	undef(%libserv);
11020: 	undef($loaded);
11021:     }
11022: 
11023:     sub load_hosts_tab {
11024: 	my ($ignore_cache) = @_;
11025: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11026: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11027: 	my @config = <$config>;
11028: 	&parse_hosts_tab(\@config);
11029: 	close($config);
11030: 	$loaded=1;
11031:     }
11032: 
11033:     sub hostname {
11034: 	&load_hosts_tab() if (!$loaded);
11035: 
11036: 	my ($lonid) = @_;
11037: 	return $hostname{$lonid};
11038:     }
11039: 
11040:     sub all_hostnames {
11041: 	&load_hosts_tab() if (!$loaded);
11042: 
11043: 	return %hostname;
11044:     }
11045: 
11046:     sub all_names {
11047: 	&load_hosts_tab() if (!$loaded);
11048: 
11049: 	return %name_to_host;
11050:     }
11051: 
11052:     sub all_host_domain {
11053:         &load_hosts_tab() if (!$loaded);
11054:         return %hostdom;
11055:     }
11056: 
11057:     sub is_library {
11058: 	&load_hosts_tab() if (!$loaded);
11059: 
11060: 	return exists($libserv{$_[0]});
11061:     }
11062: 
11063:     sub all_library {
11064: 	&load_hosts_tab() if (!$loaded);
11065: 
11066: 	return %libserv;
11067:     }
11068: 
11069:     sub unique_library {
11070: 	#2x reverse removes all hostnames that appear more than once
11071:         my %unique = reverse &all_library();
11072:         return reverse %unique;
11073:     }
11074: 
11075:     sub get_servers {
11076: 	&load_hosts_tab() if (!$loaded);
11077: 
11078: 	my ($domain,$type) = @_;
11079: 	my %possible_hosts = ($type eq 'library') ? %libserv
11080: 	                                          : %hostname;
11081: 	my %result;
11082: 	if (ref($domain) eq 'ARRAY') {
11083: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11084: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11085: 		    $result{$host} = $hostname;
11086: 		}
11087: 	    }
11088: 	} else {
11089: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11090: 		if ($hostdom{$host} eq $domain) {
11091: 		    $result{$host} = $hostname;
11092: 		}
11093: 	    }
11094: 	}
11095: 	return %result;
11096:     }
11097: 
11098:     sub get_unique_servers {
11099:         my %unique = reverse &get_servers(@_);
11100: 	return reverse %unique;
11101:     }
11102: 
11103:     sub host_domain {
11104: 	&load_hosts_tab() if (!$loaded);
11105: 
11106: 	my ($lonid) = @_;
11107: 	return $hostdom{$lonid};
11108:     }
11109: 
11110:     sub all_domains {
11111: 	&load_hosts_tab() if (!$loaded);
11112: 
11113: 	my %seen;
11114: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11115: 	return @uniq;
11116:     }
11117: 
11118:     sub internet_dom {
11119:         &load_hosts_tab() if (!$loaded);
11120: 
11121:         my ($lonid) = @_;
11122:         return $internetdom{$lonid};
11123:     }
11124: 
11125:     sub is_LC_dns {
11126:         &load_hosts_tab() if (!$loaded);
11127: 
11128:         my ($hostname) = @_;
11129:         return exists($LC_dns_serv{$hostname});
11130:     }
11131: 
11132: }
11133: 
11134: { 
11135:     my %iphost;
11136:     my %name_to_ip;
11137:     my %lonid_to_ip;
11138: 
11139:     sub get_hosts_from_ip {
11140: 	my ($ip) = @_;
11141: 	my %iphosts = &get_iphost();
11142: 	if (ref($iphosts{$ip})) {
11143: 	    return @{$iphosts{$ip}};
11144: 	}
11145: 	return;
11146:     }
11147:     
11148:     sub reset_hosts_ip_info {
11149: 	undef(%iphost);
11150: 	undef(%name_to_ip);
11151: 	undef(%lonid_to_ip);
11152:     }
11153: 
11154:     sub get_host_ip {
11155: 	my ($lonid) = @_;
11156: 	if (exists($lonid_to_ip{$lonid})) {
11157: 	    return $lonid_to_ip{$lonid};
11158: 	}
11159: 	my $name=&hostname($lonid);
11160:    	my $ip = gethostbyname($name);
11161: 	return if (!$ip || length($ip) ne 4);
11162: 	$ip=inet_ntoa($ip);
11163: 	$name_to_ip{$name}   = $ip;
11164: 	$lonid_to_ip{$lonid} = $ip;
11165: 	return $ip;
11166:     }
11167:     
11168:     sub get_iphost {
11169: 	my ($ignore_cache) = @_;
11170: 
11171: 	if (!$ignore_cache) {
11172: 	    if (%iphost) {
11173: 		return %iphost;
11174: 	    }
11175: 	    my ($ip_info,$cached)=
11176: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11177: 	    if ($cached) {
11178: 		%iphost      = %{$ip_info->[0]};
11179: 		%name_to_ip  = %{$ip_info->[1]};
11180: 		%lonid_to_ip = %{$ip_info->[2]};
11181: 		return %iphost;
11182: 	    }
11183: 	}
11184: 
11185: 	# get yesterday's info for fallback
11186: 	my %old_name_to_ip;
11187: 	my ($ip_info,$cached)=
11188: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11189: 	if ($cached) {
11190: 	    %old_name_to_ip = %{$ip_info->[1]};
11191: 	}
11192: 
11193: 	my %name_to_host = &all_names();
11194: 	foreach my $name (keys(%name_to_host)) {
11195: 	    my $ip;
11196: 	    if (!exists($name_to_ip{$name})) {
11197: 		$ip = gethostbyname($name);
11198: 		if (!$ip || length($ip) ne 4) {
11199: 		    if (defined($old_name_to_ip{$name})) {
11200: 			$ip = $old_name_to_ip{$name};
11201: 			&logthis("Can't find $name defaulting to old $ip");
11202: 		    } else {
11203: 			&logthis("Name $name no IP found");
11204: 			next;
11205: 		    }
11206: 		} else {
11207: 		    $ip=inet_ntoa($ip);
11208: 		}
11209: 		$name_to_ip{$name} = $ip;
11210: 	    } else {
11211: 		$ip = $name_to_ip{$name};
11212: 	    }
11213: 	    foreach my $id (@{ $name_to_host{$name} }) {
11214: 		$lonid_to_ip{$id} = $ip;
11215: 	    }
11216: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11217: 	}
11218: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11219: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11220: 				      48*60*60);
11221: 
11222: 	return %iphost;
11223:     }
11224: 
11225:     #
11226:     #  Given a DNS returns the loncapa host name for that DNS 
11227:     # 
11228:     sub host_from_dns {
11229:         my ($dns) = @_;
11230:         my @hosts;
11231:         my $ip;
11232: 
11233:         if (exists($name_to_ip{$dns})) {
11234:             $ip = $name_to_ip{$dns};
11235:         }
11236:         if (!$ip) {
11237:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11238:             if (length($ip) == 4) { 
11239: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11240:             }
11241:         }
11242:         if ($ip) {
11243: 	    @hosts = get_hosts_from_ip($ip);
11244: 	    return $hosts[0];
11245:         }
11246:         return undef;
11247:     }
11248: 
11249:     sub get_internet_names {
11250:         my ($lonid) = @_;
11251:         return if ($lonid eq '');
11252:         my ($idnref,$cached)=
11253:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11254:         if ($cached) {
11255:             return $idnref;
11256:         }
11257:         my $ip = &get_host_ip($lonid);
11258:         my @hosts = &get_hosts_from_ip($ip);
11259:         my %iphost = &get_iphost();
11260:         my (@idns,%seen);
11261:         foreach my $id (@hosts) {
11262:             my $dom = &host_domain($id);
11263:             my $prim_id = &domain($dom,'primary');
11264:             my $prim_ip = &get_host_ip($prim_id);
11265:             next if ($seen{$prim_ip});
11266:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11267:                 foreach my $id (@{$iphost{$prim_ip}}) {
11268:                     my $intdom = &internet_dom($id);
11269:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11270:                         push(@idns,$intdom);
11271:                     }
11272:                 }
11273:             }
11274:             $seen{$prim_ip} = 1;
11275:         }
11276:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11277:     }
11278: 
11279: }
11280: 
11281: sub all_loncaparevs {
11282:     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);
11283: }
11284: 
11285: BEGIN {
11286: 
11287: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11288:     unless ($readit) {
11289: {
11290:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11291:     %perlvar = (%perlvar,%{$configvars});
11292: }
11293: 
11294: 
11295: # ------------------------------------------------------ Read spare server file
11296: {
11297:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11298: 
11299:     while (my $configline=<$config>) {
11300:        chomp($configline);
11301:        if ($configline) {
11302: 	   my ($host,$type) = split(':',$configline,2);
11303: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11304: 	   push(@{ $spareid{$type} }, $host);
11305:        }
11306:     }
11307:     close($config);
11308: }
11309: # ------------------------------------------------------------ Read permissions
11310: {
11311:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11312: 
11313:     while (my $configline=<$config>) {
11314: 	chomp($configline);
11315: 	if ($configline) {
11316: 	    my ($role,$perm)=split(/ /,$configline);
11317: 	    if ($perm ne '') { $pr{$role}=$perm; }
11318: 	}
11319:     }
11320:     close($config);
11321: }
11322: 
11323: # -------------------------------------------- Read plain texts for permissions
11324: {
11325:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11326: 
11327:     while (my $configline=<$config>) {
11328: 	chomp($configline);
11329: 	if ($configline) {
11330: 	    my ($short,@plain)=split(/:/,$configline);
11331:             %{$prp{$short}} = ();
11332: 	    if (@plain > 0) {
11333:                 $prp{$short}{'std'} = $plain[0];
11334:                 for (my $i=1; $i<@plain; $i++) {
11335:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11336:                 }
11337:             }
11338: 	}
11339:     }
11340:     close($config);
11341: }
11342: 
11343: # ---------------------------------------------------------- Read package table
11344: {
11345:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11346: 
11347:     while (my $configline=<$config>) {
11348: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11349: 	chomp($configline);
11350: 	my ($short,$plain)=split(/:/,$configline);
11351: 	my ($pack,$name)=split(/\&/,$short);
11352: 	if ($plain ne '') {
11353: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11354: 	    $packagetab{$short}=$plain; 
11355: 	}
11356:     }
11357:     close($config);
11358: }
11359: 
11360: # ---------------------------------------------------------- Read loncaparev table
11361: {
11362:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11363:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11364:             while (my $configline=<$config>) {
11365:                 chomp($configline);
11366:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11367:                 $loncaparevs{$hostid}=$loncaparev;
11368:             }
11369:             close($config);
11370:         }
11371:     }
11372: }
11373: 
11374: # ---------------------------------------------------------- Read serverhostID table
11375: {
11376:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11377:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11378:             while (my $configline=<$config>) {
11379:                 chomp($configline);
11380:                 my ($name,$id)=split(/:/,$configline);
11381:                 $serverhomeIDs{$name}=$id;
11382:             }
11383:             close($config);
11384:         }
11385:     }
11386: }
11387: 
11388: {
11389:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11390:     if (-e $file) {
11391:         my $parser = HTML::LCParser->new($file);
11392:         while (my $token = $parser->get_token()) {
11393:             if ($token->[0] eq 'S') {
11394:                 my $item = $token->[1];
11395:                 my $name = $token->[2]{'name'};
11396:                 my $value = $token->[2]{'value'};
11397:                 if ($item ne '' && $name ne '' && $value ne '') {
11398:                     my $release = $parser->get_text();
11399:                     $release =~ s/(^\s*|\s*$ )//gx;
11400:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11401:                 }
11402:             }
11403:         }
11404:     }
11405: }
11406: 
11407: # ---------------------------------------------------------- Read managers table
11408: {
11409:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11410:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11411:             while (my $configline=<$config>) {
11412:                 chomp($configline);
11413:                 next if ($configline =~ /^\#/);
11414:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11415:                     $managerstab{$configline} = 1;
11416:                 }
11417:             }
11418:             close($config);
11419:         }
11420:     }
11421: }
11422: 
11423: # ------------- set up temporary directory
11424: {
11425:     $tmpdir = LONCAPA::tempdir();
11426: 
11427: }
11428: 
11429: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11430: 				'compress_threshold'=> 20_000,
11431:  			        });
11432: 
11433: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11434: $dumpcount=0;
11435: $locknum=0;
11436: 
11437: &logtouch();
11438: &logthis('<font color="yellow">INFO: Read configuration</font>');
11439: $readit=1;
11440:     {
11441: 	use integer;
11442: 	my $test=(2**32)+1;
11443: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11444: 	&logthis(" Detected 64bit platform ($_64bit)");
11445:     }
11446: }
11447: }
11448: 
11449: 1;
11450: __END__
11451: 
11452: =pod
11453: 
11454: =head1 NAME
11455: 
11456: Apache::lonnet - Subroutines to ask questions about things in the network.
11457: 
11458: =head1 SYNOPSIS
11459: 
11460: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11461: 
11462:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11463: 
11464: Common parameters:
11465: 
11466: =over 4
11467: 
11468: =item *
11469: 
11470: $uname : an internal username (if $cname expecting a course Id specifically)
11471: 
11472: =item *
11473: 
11474: $udom : a domain (if $cdom expecting a course's domain specifically)
11475: 
11476: =item *
11477: 
11478: $symb : a resource instance identifier
11479: 
11480: =item *
11481: 
11482: $namespace : the name of a .db file that contains the data needed or
11483: being set.
11484: 
11485: =back
11486: 
11487: =head1 OVERVIEW
11488: 
11489: lonnet provides subroutines which interact with the
11490: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11491: about classes, users, and resources.
11492: 
11493: For many of these objects you can also use this to store data about
11494: them or modify them in various ways.
11495: 
11496: =head2 Symbs
11497: 
11498: To identify a specific instance of a resource, LON-CAPA uses symbols
11499: or "symbs"X<symb>. These identifiers are built from the URL of the
11500: map, the resource number of the resource in the map, and the URL of
11501: the resource itself. The latter is somewhat redundant, but might help
11502: if maps change.
11503: 
11504: An example is
11505: 
11506:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11507: 
11508: The respective map entry is
11509: 
11510:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11511:   title="Problem 2">
11512:  </resource>
11513: 
11514: Symbs are used by the random number generator, as well as to store and
11515: restore data specific to a certain instance of for example a problem.
11516: 
11517: =head2 Storing And Retrieving Data
11518: 
11519: X<store()>X<cstore()>X<restore()>Three of the most important functions
11520: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11521: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11522: is is the non-critical message twin of cstore. These functions are for
11523: handlers to store a perl hash to a user's permanent data space in an
11524: easy manner, and to retrieve it again on another call. It is expected
11525: that a handler would use this once at the beginning to retrieve data,
11526: and then again once at the end to send only the new data back.
11527: 
11528: The data is stored in the user's data directory on the user's
11529: homeserver under the ID of the course.
11530: 
11531: The hash that is returned by restore will have all of the previous
11532: value for all of the elements of the hash.
11533: 
11534: Example:
11535: 
11536:  #creating a hash
11537:  my %hash;
11538:  $hash{'foo'}='bar';
11539: 
11540:  #storing it
11541:  &Apache::lonnet::cstore(\%hash);
11542: 
11543:  #changing a value
11544:  $hash{'foo'}='notbar';
11545: 
11546:  #adding a new value
11547:  $hash{'bar'}='foo';
11548:  &Apache::lonnet::cstore(\%hash);
11549: 
11550:  #retrieving the hash
11551:  my %history=&Apache::lonnet::restore();
11552: 
11553:  #print the hash
11554:  foreach my $key (sort(keys(%history))) {
11555:    print("\%history{$key} = $history{$key}");
11556:  }
11557: 
11558: Will print out:
11559: 
11560:  %history{1:foo} = bar
11561:  %history{1:keys} = foo:timestamp
11562:  %history{1:timestamp} = 990455579
11563:  %history{2:bar} = foo
11564:  %history{2:foo} = notbar
11565:  %history{2:keys} = foo:bar:timestamp
11566:  %history{2:timestamp} = 990455580
11567:  %history{bar} = foo
11568:  %history{foo} = notbar
11569:  %history{timestamp} = 990455580
11570:  %history{version} = 2
11571: 
11572: Note that the special hash entries C<keys>, C<version> and
11573: C<timestamp> were added to the hash. C<version> will be equal to the
11574: total number of versions of the data that have been stored. The
11575: C<timestamp> attribute will be the UNIX time the hash was
11576: stored. C<keys> is available in every historical section to list which
11577: keys were added or changed at a specific historical revision of a
11578: hash.
11579: 
11580: B<Warning>: do not store the hash that restore returns directly. This
11581: will cause a mess since it will restore the historical keys as if the
11582: were new keys. I.E. 1:foo will become 1:1:foo etc.
11583: 
11584: Calling convention:
11585: 
11586:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11587:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11588: 
11589: For more detailed information, see lonnet specific documentation.
11590: 
11591: =head1 RETURN MESSAGES
11592: 
11593: =over 4
11594: 
11595: =item * B<con_lost>: unable to contact remote host
11596: 
11597: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11598: when the connection is brought back up
11599: 
11600: =item * B<con_failed>: unable to contact remote host and unable to save message
11601: for later delivery
11602: 
11603: =item * B<error:>: an error a occurred, a description of the error follows the :
11604: 
11605: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11606: that was requested
11607: 
11608: =back
11609: 
11610: =head1 PUBLIC SUBROUTINES
11611: 
11612: =head2 Session Environment Functions
11613: 
11614: =over 4
11615: 
11616: =item * 
11617: X<appenv()>
11618: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11619: the user envirnoment file, and will be restored for each access this
11620: user makes during this session, also modifies the %env for the current
11621: process. Optional rolesarrayref - if defined contains a reference to an array
11622: of roles which are exempt from the restriction on modifying user.role entries 
11623: in the user's environment.db and in %env.    
11624: 
11625: =item *
11626: X<delenv()>
11627: B<delenv($delthis,$regexp)>: removes all items from the session
11628: environment file that begin with $delthis. If the 
11629: optional second arg - $regexp - is true, $delthis is treated as a 
11630: regular expression, otherwise \Q$delthis\E is used. 
11631: The values are also deleted from the current processes %env.
11632: 
11633: =item * get_env_multiple($name) 
11634: 
11635: gets $name from the %env hash, it seemlessly handles the cases where multiple
11636: values may be defined and end up as an array ref.
11637: 
11638: returns an array of values
11639: 
11640: =back
11641: 
11642: =head2 User Information
11643: 
11644: =over 4
11645: 
11646: =item *
11647: X<queryauthenticate()>
11648: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11649: authentication scheme
11650: 
11651: =item *
11652: X<authenticate()>
11653: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11654: authenticate user from domain's lib servers (first use the current
11655: one). C<$upass> should be the users password.
11656: $checkdefauth is optional (value is 1 if a check should be made to
11657:    authenticate user using default authentication method, and allow
11658:    account creation if username does not have account in the domain).
11659: $clientcancheckhost is optional (value is 1 if checking whether the
11660:    server can host will occur on the client side in lonauth.pm).   
11661: 
11662: =item *
11663: X<homeserver()>
11664: B<homeserver($uname,$udom)>: find the server which has
11665: the user's directory and files (there must be only one), this caches
11666: the answer, and also caches if there is a borken connection.
11667: 
11668: =item *
11669: X<idget()>
11670: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11671: (IDs are a unique resource in a domain, there must be only 1 ID per
11672: username, and only 1 username per ID in a specific domain) (returns
11673: hash: id=>name,id=>name)
11674: 
11675: =item *
11676: X<idrget()>
11677: B<idrget($udom,@unames)>: find the IDs behind a list of
11678: usernames (returns hash: name=>id,name=>id)
11679: 
11680: =item *
11681: X<idput()>
11682: B<idput($udom,%ids)>: store away a list of names and associated IDs
11683: 
11684: =item *
11685: X<rolesinit()>
11686: B<rolesinit($udom,$username,$authhost)>: get user privileges
11687: 
11688: =item *
11689: X<getsection()>
11690: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11691: course $cname, return section name/number or '' for "not in course"
11692: and '-1' for "no section"
11693: 
11694: =item *
11695: X<userenvironment()>
11696: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11697: passed in @what from the requested user's environment, returns a hash
11698: 
11699: =item * 
11700: X<userlog_query()>
11701: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11702: activity.log file. %filters defines filters applied when parsing the
11703: log file. These can be start or end timestamps, or the type of action
11704: - log to look for Login or Logout events, check for Checkin or
11705: Checkout, role for role selection. The response is in the form
11706: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11707: escaped strings of the action recorded in the activity.log file.
11708: 
11709: =back
11710: 
11711: =head2 User Roles
11712: 
11713: =over 4
11714: 
11715: =item *
11716: 
11717: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11718:  F: full access
11719:  U,I,K: authentication modes (cxx only)
11720:  '': forbidden
11721:  1: user needs to choose course
11722:  2: browse allowed
11723:  A: passphrase authentication needed
11724: 
11725: =item *
11726: 
11727: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11728: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11729: and course level
11730: 
11731: =item *
11732: 
11733: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11734: (rolesplain.tab); plain text explanation of a user role term.
11735: $type is Course (default) or Community.
11736: If $forcedefault evaluates to true, text returned will be default 
11737: text for $type. Otherwise, if this is a course, the text returned 
11738: will be a custom name for the role (if defined in the course's 
11739: environment).  If no custom name is defined the default is returned.
11740:    
11741: =item *
11742: 
11743: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11744: All arguments are optional. Returns a hash of a roles, either for
11745: co-author/assistant author roles for a user's Construction Space
11746: (default), or if $context is 'userroles', roles for the user himself,
11747: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11748: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11749: For each key, value is set to colon-separated start and end times for
11750: the role.  If no username and domain are specified, will default to
11751: current user/domain. Types, roles, and roledoms are references to arrays
11752: of role statuses (active, future or previous), roles 
11753: (e.g., cc,in, st etc.) and domains of the roles which can be used
11754: to restrict the list of roles reported. If no array ref is 
11755: provided for types, will default to return only active roles.
11756: 
11757: =back
11758: 
11759: =head2 User Modification
11760: 
11761: =over 4
11762: 
11763: =item *
11764: 
11765: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11766: user for the level given by URL.  Optional start and end dates (leave empty
11767: string or zero for "no date")
11768: 
11769: =item *
11770: 
11771: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11772: change a users, password, possible return values are: ok,
11773: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11774: refused
11775: 
11776: =item *
11777: 
11778: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11779: 
11780: =item *
11781: 
11782: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11783:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11784: 
11785: will update user information (firstname,middlename,lastname,generation,
11786: permanentemail), and if forceid is true, student/employee ID also.
11787: A user's institutional affiliation(s) can also be updated.
11788: User information fields will not be overwritten with empty entries 
11789: unless the field is included in the $candelete array reference.
11790: This array is included when a single user is modified via "Manage Users",
11791: or when Autoupdate.pl is run by cron in a domain.
11792: 
11793: =item *
11794: 
11795: modifystudent
11796: 
11797: modify a student's enrollment and identification information.
11798: The course id is resolved based on the current users environment.  
11799: This means the envoking user must be a course coordinator or otherwise
11800: associated with a course.
11801: 
11802: This call is essentially a wrapper for lonnet::modifyuser and
11803: lonnet::modify_student_enrollment
11804: 
11805: Inputs: 
11806: 
11807: =over 4
11808: 
11809: =item B<$udom> Student's loncapa domain
11810: 
11811: =item B<$uname> Student's loncapa login name
11812: 
11813: =item B<$uid> Student/Employee ID
11814: 
11815: =item B<$umode> Student's authentication mode
11816: 
11817: =item B<$upass> Student's password
11818: 
11819: =item B<$first> Student's first name
11820: 
11821: =item B<$middle> Student's middle name
11822: 
11823: =item B<$last> Student's last name
11824: 
11825: =item B<$gene> Student's generation
11826: 
11827: =item B<$usec> Student's section in course
11828: 
11829: =item B<$end> Unix time of the roles expiration
11830: 
11831: =item B<$start> Unix time of the roles start date
11832: 
11833: =item B<$forceid> If defined, allow $uid to be changed
11834: 
11835: =item B<$desiredhome> server to use as home server for student
11836: 
11837: =item B<$email> Student's permanent e-mail address
11838: 
11839: =item B<$type> Type of enrollment (auto or manual)
11840: 
11841: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11842: 
11843: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11844: 
11845: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11846: 
11847: =item B<$context> role change context (shown in User Management Logs display in a course)
11848: 
11849: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11850: 
11851: =back
11852: 
11853: =item *
11854: 
11855: modify_student_enrollment
11856: 
11857: Change a students enrollment status in a class.  The environment variable
11858: 'role.request.course' must be defined for this function to proceed.
11859: 
11860: Inputs:
11861: 
11862: =over 4
11863: 
11864: =item $udom, students domain
11865: 
11866: =item $uname, students name
11867: 
11868: =item $uid, students user id
11869: 
11870: =item $first, students first name
11871: 
11872: =item $middle
11873: 
11874: =item $last
11875: 
11876: =item $gene
11877: 
11878: =item $usec
11879: 
11880: =item $end
11881: 
11882: =item $start
11883: 
11884: =item $type
11885: 
11886: =item $locktype
11887: 
11888: =item $cid
11889: 
11890: =item $selfenroll
11891: 
11892: =item $context
11893: 
11894: =back
11895: 
11896: 
11897: =item *
11898: 
11899: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11900: custom role; give a custom role to a user for the level given by URL.  Specify
11901: name and domain of role author, and role name
11902: 
11903: =item *
11904: 
11905: revokerole($udom,$uname,$url,$role) : revoke a role for url
11906: 
11907: =item *
11908: 
11909: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11910: 
11911: =back
11912: 
11913: =head2 Course Infomation
11914: 
11915: =over 4
11916: 
11917: =item *
11918: 
11919: coursedescription($courseid,$options) : returns a hash of information about the
11920: specified course id, including all environment settings for the
11921: course, the description of the course will be in the hash under the
11922: key 'description'
11923: 
11924: $options is an optional parameter that if supplied is a hash reference that controls
11925: what how this function works.  It has the following key/values:
11926: 
11927: =over 4
11928: 
11929: =item freshen_cache
11930: 
11931: If defined, and the environment cache for the course is valid, it is 
11932: returned in the returned hash.
11933: 
11934: =item one_time
11935: 
11936: If defined, the last cache time is set to _now_
11937: 
11938: =item user
11939: 
11940: If defined, the supplied username is used instead of the current user.
11941: 
11942: 
11943: =back
11944: 
11945: =item *
11946: 
11947: resdata($name,$domain,$type,@which) : request for current parameter
11948: setting for a specific $type, where $type is either 'course' or 'user',
11949: @what should be a list of parameters to ask about. This routine caches
11950: answers for 5 minutes.
11951: 
11952: =item *
11953: 
11954: get_courseresdata($courseid, $domain) : dump the entire course resource
11955: data base, returning a hash that is keyed by the resource name and has
11956: values that are the resource value.  I believe that the timestamps and
11957: versions are also returned.
11958: 
11959: 
11960: =back
11961: 
11962: =head2 Course Modification
11963: 
11964: =over 4
11965: 
11966: =item *
11967: 
11968: writecoursepref($courseid,%prefs) : write preferences (environment
11969: database) for a course
11970: 
11971: =item *
11972: 
11973: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11974: 
11975: =item *
11976: 
11977: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11978: 
11979: =back
11980: 
11981: =head2 Resource Subroutines
11982: 
11983: =over 4
11984: 
11985: =item *
11986: 
11987: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11988: 
11989: =item *
11990: 
11991: repcopy($filename) : subscribes to the requested file, and attempts to
11992: replicate from the owning library server, Might return
11993: 'unavailable', 'not_found', 'forbidden', 'ok', or
11994: 'bad_request', also attempts to grab the metadata for the
11995: resource. Expects the local filesystem pathname
11996: (/home/httpd/html/res/....)
11997: 
11998: =back
11999: 
12000: =head2 Resource Information
12001: 
12002: =over 4
12003: 
12004: =item *
12005: 
12006: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12007: a vairety of different possible values, $varname should be a request
12008: string, and the other parameters can be used to specify who and what
12009: one is asking about.
12010: 
12011: Possible values for $varname are environment.lastname (or other item
12012: from the envirnment hash), user.name (or someother aspect about the
12013: user), resource.0.maxtries (or some other part and parameter of a
12014: resource)
12015: 
12016: =item *
12017: 
12018: directcondval($number) : get current value of a condition; reads from a state
12019: string
12020: 
12021: =item *
12022: 
12023: condval($condidx) : value of condition index based on state
12024: 
12025: =item *
12026: 
12027: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12028: resource's metadata, $what should be either a specific key, or either
12029: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12030: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12031: 
12032: this function automatically caches all requests
12033: 
12034: =item *
12035: 
12036: metadata_query($query,$custom,$customshow) : make a metadata query against the
12037: network of library servers; returns file handle of where SQL and regex results
12038: will be stored for query
12039: 
12040: =item *
12041: 
12042: symbread($filename) : return symbolic list entry (filename argument optional);
12043: returns the data handle
12044: 
12045: =item *
12046: 
12047: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
12048: a possible symb for the URL in $thisfn, and if is an encryypted
12049: resource that the user accessed using /enc/ returns a 1 on success, 0
12050: on failure, user must be in a course, as it assumes the existance of
12051: the course initial hash, and uses $env('request.course.id'}
12052: 
12053: 
12054: =item *
12055: 
12056: symbclean($symb) : removes versions numbers from a symb, returns the
12057: cleaned symb
12058: 
12059: =item *
12060: 
12061: is_on_map($uri) : checks if the $uri is somewhere on the current
12062: course map, user must be in a course for it to work.
12063: 
12064: =item *
12065: 
12066: numval($salt) : return random seed value (addend for rndseed)
12067: 
12068: =item *
12069: 
12070: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12071: a random seed, all arguments are optional, if they aren't sent it uses the
12072: environment to derive them. Note: if symb isn't sent and it can't get one
12073: from &symbread it will use the current time as its return value
12074: 
12075: =item *
12076: 
12077: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12078: unfakeable, receipt
12079: 
12080: =item *
12081: 
12082: receipt() : API to ireceipt working off of env values; given out to users
12083: 
12084: =item *
12085: 
12086: countacc($url) : count the number of accesses to a given URL
12087: 
12088: =item *
12089: 
12090: 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
12091: 
12092: =item *
12093: 
12094: 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)
12095: 
12096: =item *
12097: 
12098: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12099: 
12100: =item *
12101: 
12102: devalidate($symb) : devalidate temporary spreadsheet calculations,
12103: forcing spreadsheet to reevaluate the resource scores next time.
12104: 
12105: =back
12106: 
12107: =head2 Storing/Retreiving Data
12108: 
12109: =over 4
12110: 
12111: =item *
12112: 
12113: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12114: for this url; hashref needs to be given and should be a \%hashname; the
12115: remaining args aren't required and if they aren't passed or are '' they will
12116: be derived from the env
12117: 
12118: =item *
12119: 
12120: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12121: uses critical subroutine
12122: 
12123: =item *
12124: 
12125: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12126: all args are optional
12127: 
12128: =item *
12129: 
12130: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12131: dumps the complete (or key matching regexp) namespace into a hash
12132: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12133: normally &store()ed into
12134: 
12135: $range should be either an integer '100' (give me the first 100
12136:                                            matching records)
12137:               or be  two integers sperated by a - with no spaces
12138:                  '30-50' (give me the 30th through the 50th matching
12139:                           records)
12140: 
12141: 
12142: =item *
12143: 
12144: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12145: replaces a &store() version of data with a replacement set of data
12146: for a particular resource in a namespace passed in the $storehash hash 
12147: reference
12148: 
12149: =item *
12150: 
12151: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12152: works very similar to store/cstore, but all data is stored in a
12153: temporary location and can be reset using tmpreset, $storehash should
12154: be a hash reference, returns nothing on success
12155: 
12156: =item *
12157: 
12158: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12159: similar to restore, but all data is stored in a temporary location and
12160: can be reset using tmpreset. Returns a hash of values on success,
12161: error string otherwise.
12162: 
12163: =item *
12164: 
12165: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12166: deltes all keys for $symb form the temporary storage hash.
12167: 
12168: =item *
12169: 
12170: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12171: reference filled in from namesp ($udom and $uname are optional)
12172: 
12173: =item *
12174: 
12175: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12176: namesp ($udom and $uname are optional)
12177: 
12178: =item *
12179: 
12180: dump($namespace,$udom,$uname,$regexp,$range) : 
12181: dumps the complete (or key matching regexp) namespace into a hash
12182: ($udom, $uname, $regexp, $range are optional)
12183: 
12184: $range should be either an integer '100' (give me the first 100
12185:                                            matching records)
12186:               or be  two integers sperated by a - with no spaces
12187:                  '30-50' (give me the 30th through the 50th matching
12188:                           records)
12189: =item *
12190: 
12191: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12192: $store can be a scalar, an array reference, or if the amount to be 
12193: incremented is > 1, a hash reference.
12194: 
12195: ($udom and $uname are optional)
12196: 
12197: =item *
12198: 
12199: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12200: ($udom and $uname are optional)
12201: 
12202: =item *
12203: 
12204: cput($namespace,$storehash,$udom,$uname) : critical put
12205: ($udom and $uname are optional)
12206: 
12207: =item *
12208: 
12209: newput($namespace,$storehash,$udom,$uname) :
12210: 
12211: Attempts to store the items in the $storehash, but only if they don't
12212: currently exist, if this succeeds you can be certain that you have 
12213: successfully created a new key value pair in the $namespace db.
12214: 
12215: 
12216: Args:
12217:  $namespace: name of database to store values to
12218:  $storehash: hashref to store to the db
12219:  $udom: (optional) domain of user containing the db
12220:  $uname: (optional) name of user caontaining the db
12221: 
12222: Returns:
12223:  'ok' -> succeeded in storing all keys of $storehash
12224:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12225:                         least <key> already existed in the db (other
12226:                         requested keys may also already exist)
12227:  'error: <msg>' -> unable to tie the DB or other error occurred
12228:  'con_lost' -> unable to contact request server
12229:  'refused' -> action was not allowed by remote machine
12230: 
12231: 
12232: =item *
12233: 
12234: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12235: reference filled in from namesp (encrypts the return communication)
12236: ($udom and $uname are optional)
12237: 
12238: =item *
12239: 
12240: log($udom,$name,$home,$message) : write to permanent log for user; use
12241: critical subroutine
12242: 
12243: =item *
12244: 
12245: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12246: array reference filled in from namespace found in domain level on either
12247: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12248: 
12249: =item *
12250: 
12251: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12252: domain level either on specified domain server ($uhome) or primary domain 
12253: server ($udom and $uhome are optional)
12254: 
12255: =item * 
12256: 
12257: get_domain_defaults($target_domain) : returns hash with defaults for
12258: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12259: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12260: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12261: Values are retrieved from cache (if current), or from domain's configuration.db
12262: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12263: or lonTabs/domain.tab. 
12264: 
12265: %domdefaults = &get_auth_defaults($target_domain);
12266: 
12267: =back
12268: 
12269: =head2 Network Status Functions
12270: 
12271: =over 4
12272: 
12273: =item *
12274: 
12275: dirlist() : return directory list based on URI (first arg).
12276: 
12277: Inputs: 1 required, 5 optional.
12278: 
12279: =over
12280: 
12281: =item 
12282: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12283: 
12284: =item
12285: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12286: 
12287: =item
12288: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12289: 
12290: =item
12291: $getpropath - boolean: 1 if prepend path using &propath(). 
12292: 
12293: =item
12294: $getuserdir - boolean: 1 if prepend path for "userfiles".
12295: 
12296: =item 
12297: $alternateRoot - path to prepend in place of path from $uri.
12298: 
12299: =back
12300: 
12301: Returns: Array of up to two items.
12302: 
12303: =over
12304: 
12305: a reference to an array of files/subdirectories
12306: 
12307: =over
12308: 
12309: Each element in the array of files/subdirectories is a & separated list of
12310: item name and the result of running stat on the item.  If dirlist was requested
12311: for a file instead of a directory, the item name will be ''. For a directory 
12312: listing, if the item is a metadata file, the element will end &N&M 
12313: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12314: default copyright set (1).  
12315: 
12316: =back
12317: 
12318: a scalar containing error condition (if encountered).
12319: 
12320: =over
12321: 
12322: =item 
12323: no_host (no homeserver identified for $username:$domain).
12324: 
12325: =item 
12326: no_such_host (server contacted for listing not identified as valid host).
12327: 
12328: =item 
12329: con_lost (connection to remote server failed).
12330: 
12331: =item 
12332: refused (invalid $username:$domain received on lond side).
12333: 
12334: =item 
12335: no_such_dir (directory at specified path on lond side does not exist). 
12336: 
12337: =item 
12338: empty (directory at specified path on lond side is empty).
12339: 
12340: =over
12341: 
12342: This is currently not encountered because the &ls3, &ls2, 
12343: &ls (_handler) routines on the lond side do not filter out
12344: . and .. from a directory listing. 
12345: 
12346: =back
12347: 
12348: =back
12349: 
12350: =back
12351: 
12352: =item *
12353: 
12354: spareserver() : find server with least workload from spare.tab
12355: 
12356: 
12357: =item *
12358: 
12359: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12360: if there is no corresponding loncapa host.
12361: 
12362: =back
12363: 
12364: 
12365: =head2 Apache Request
12366: 
12367: =over 4
12368: 
12369: =item *
12370: 
12371: ssi($url,%hash) : server side include, does a complete request cycle on url to
12372: localhost, posts hash
12373: 
12374: =back
12375: 
12376: =head2 Data to String to Data
12377: 
12378: =over 4
12379: 
12380: =item *
12381: 
12382: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12383: and '&' separators, supports elements that are arrayrefs and hashrefs
12384: 
12385: =item *
12386: 
12387: hashref2str($hashref) : convert a hashref into a string complete with
12388: escaping and '=' and '&' separators, supports elements that are
12389: arrayrefs and hashrefs
12390: 
12391: =item *
12392: 
12393: arrayref2str($arrayref) : convert an arrayref into a string complete
12394: with escaping and '&' separators, supports elements that are arrayrefs
12395: and hashrefs
12396: 
12397: =item *
12398: 
12399: str2hash($string) : convert string to hash using unescaping and
12400: splitting on '=' and '&', supports elements that are arrayrefs and
12401: hashrefs
12402: 
12403: =item *
12404: 
12405: str2array($string) : convert string to hash using unescaping and
12406: splitting on '&', supports elements that are arrayrefs and hashrefs
12407: 
12408: =back
12409: 
12410: =head2 Logging Routines
12411: 
12412: 
12413: These routines allow one to make log messages in the lonnet.log and
12414: lonnet.perm logfiles.
12415: 
12416: =over 4
12417: 
12418: =item *
12419: 
12420: logtouch() : make sure the logfile, lonnet.log, exists
12421: 
12422: =item *
12423: 
12424: logthis() : append message to the normal lonnet.log file, it gets
12425: preiodically rolled over and deleted.
12426: 
12427: =item *
12428: 
12429: logperm() : append a permanent message to lonnet.perm.log, this log
12430: file never gets deleted by any automated portion of the system, only
12431: messages of critical importance should go in here.
12432: 
12433: 
12434: =back
12435: 
12436: =head2 General File Helper Routines
12437: 
12438: =over 4
12439: 
12440: =item *
12441: 
12442: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12443: (a) files in /uploaded
12444:   (i) If a local copy of the file exists - 
12445:       compares modification date of local copy with last-modified date for 
12446:       definitive version stored on home server for course. If local copy is 
12447:       stale, requests a new version from the home server and stores it. 
12448:       If the original has been removed from the home server, then local copy 
12449:       is unlinked.
12450:   (ii) If local copy does not exist -
12451:       requests the file from the home server and stores it. 
12452:   
12453:   If $caller is 'uploadrep':  
12454:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12455:     for request for files originally uploaded via DOCS. 
12456:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12457:   
12458:   Otherwise:
12459:      This indicates a call from the content generation phase of the request.
12460:      -  returns the entire contents of the file or -1.
12461:      
12462: (b) files in /res
12463:    - returns the entire contents of a file or -1; 
12464:    it properly subscribes to and replicates the file if neccessary.
12465: 
12466: 
12467: =item *
12468: 
12469: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12470:                   reference
12471: 
12472: returns either a stat() list of data about the file or an empty list
12473: if the file doesn't exist or couldn't find out about it (connection
12474: problems or user unknown)
12475: 
12476: =item *
12477: 
12478: filelocation($dir,$file) : returns file system location of a file
12479: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12480: directory that relative $file lookups are to looked in ($dir of /a/dir
12481: and a file of ../bob will become /a/bob)
12482: 
12483: =item *
12484: 
12485: hreflocation($dir,$file) : returns file system location or a URL; same as
12486: filelocation except for hrefs
12487: 
12488: =item *
12489: 
12490: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12491: 
12492: =back
12493: 
12494: =head2 Usererfile file routines (/uploaded*)
12495: 
12496: =over 4
12497: 
12498: =item *
12499: 
12500: userfileupload(): main rotine for putting a file in a user or course's
12501:                   filespace, arguments are,
12502: 
12503:  formname - required - this is the name of the element in $env where the
12504:            filename, and the contents of the file to create/modifed exist
12505:            the filename is in $env{'form.'.$formname.'.filename'} and the
12506:            contents of the file is located in $env{'form.'.$formname}
12507:  context - if coursedoc, store the file in the course of the active role
12508:              of the current user; 
12509:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12510:            if 'canceloverwrite': delete file in tmp/overwrites directory
12511:  subdir - required - subdirectory to put the file in under ../userfiles/
12512:          if undefined, it will be placed in "unknown"
12513: 
12514:  (This routine calls clean_filename() to remove any dangerous
12515:  characters from the filename, and then calls finuserfileupload() to
12516:  complete the transaction)
12517: 
12518:  returns either the url of the uploaded file (/uploaded/....) if successful
12519:  and /adm/notfound.html if unsuccessful
12520: 
12521: =item *
12522: 
12523: clean_filename(): routine for cleaing a filename up for storage in
12524:                  userfile space, argument is:
12525: 
12526:  filename - proposed filename
12527: 
12528: returns: the new clean filename
12529: 
12530: =item *
12531: 
12532: finishuserfileupload(): routine that creates and sends the file to
12533: userspace, probably shouldn't be called directly
12534: 
12535:   docuname: username or courseid of destination for the file
12536:   docudom: domain of user/course of destination for the file
12537:   formname: same as for userfileupload()
12538:   fname: filename (including subdirectories) for the file
12539:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12540:   allfiles: reference to hash used to store objects found by parser
12541:   codebase: reference to hash used for codebases of java objects found by parser
12542:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12543:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12544:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12545:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12546:   context: if 'overwrite', will move the uploaded file from its temporary location to
12547:             userfiles to facilitate overwriting a previously uploaded file with same name.
12548:   mimetype: reference to scalar to accommodate mime type determined
12549:             from File::MMagic if $parser = parse.
12550: 
12551:  returns either the url of the uploaded file (/uploaded/....) if successful
12552:  and /adm/notfound.html if unsuccessful (or an error message if context 
12553:  was 'overwrite').
12554:  
12555: 
12556: =item *
12557: 
12558: renameuserfile(): renames an existing userfile to a new name
12559: 
12560:   Args:
12561:    docuname: username or courseid of destination for the file
12562:    docudom: domain of user/course of destination for the file
12563:    old: current file name (including any subdirs under userfiles)
12564:    new: desired file name (including any subdirs under userfiles)
12565: 
12566: =item *
12567: 
12568: mkdiruserfile(): creates a directory is a userfiles dir
12569: 
12570:   Args:
12571:    docuname: username or courseid of destination for the file
12572:    docudom: domain of user/course of destination for the file
12573:    dir: dir to create (including any subdirs under userfiles)
12574: 
12575: =item *
12576: 
12577: removeuserfile(): removes a file that exists in userfiles
12578: 
12579:   Args:
12580:    docuname: username or courseid of destination for the file
12581:    docudom: domain of user/course of destination for the file
12582:    fname: filname to delete (including any subdirs under userfiles)
12583: 
12584: =item *
12585: 
12586: removeuploadedurl(): convience function for removeuserfile()
12587: 
12588:   Args:
12589:    url:  a full /uploaded/... url to delete
12590: 
12591: =item * 
12592: 
12593: get_portfile_permissions():
12594:   Args:
12595:     domain: domain of user or course contain the portfolio files
12596:     user: name of user or num of course contain the portfolio files
12597:   Returns:
12598:     hashref of a dump of the proper file_permissions.db
12599:    
12600: 
12601: =item * 
12602: 
12603: get_access_controls():
12604: 
12605: Args:
12606:   current_permissions: the hash ref returned from get_portfile_permissions()
12607:   group: (optional) the group you want the files associated with
12608:   file: (optional) the file you want access info on
12609: 
12610: Returns:
12611:     a hash (keys are file names) of hashes containing
12612:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12613:         values are XML containing access control settings (see below) 
12614: 
12615: Internal notes:
12616: 
12617:  access controls are stored in file_permissions.db as key=value pairs.
12618:     key -> path to file/file_name\0uniqueID:scope_end_start
12619:         where scope -> public,guest,course,group,domains or users.
12620:               end -> UNIX time for end of access (0 -> no end date)
12621:               start -> UNIX time for start of access
12622: 
12623:     value -> XML description of access control
12624:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12625:             <start></start>
12626:             <end></end>
12627: 
12628:             <password></password>  for scope type = guest
12629: 
12630:             <domain></domain>     for scope type = course or group
12631:             <number></number>
12632:             <roles id="">
12633:              <role></role>
12634:              <access></access>
12635:              <section></section>
12636:              <group></group>
12637:             </roles>
12638: 
12639:             <dom></dom>         for scope type = domains
12640: 
12641:             <users>             for scope type = users
12642:              <user>
12643:               <uname></uname>
12644:               <udom></udom>
12645:              </user>
12646:             </users>
12647:            </scope> 
12648:               
12649:  Access data is also aggregated for each file in an additional key=value pair:
12650:  key -> path to file/file_name\0accesscontrol 
12651:  value -> reference to hash
12652:           hash contains key = value pairs
12653:           where key = uniqueID:scope_end_start
12654:                 value = UNIX time record was last updated
12655: 
12656:           Used to improve speed of look-ups of access controls for each file.  
12657:  
12658:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12659: 
12660: modify_access_controls():
12661: 
12662: Modifies access controls for a portfolio file
12663: Args
12664: 1. file name
12665: 2. reference to hash of required changes,
12666: 3. domain
12667: 4. username
12668:   where domain,username are the domain of the portfolio owner 
12669:   (either a user or a course) 
12670: 
12671: Returns:
12672: 1. result of additions or updates ('ok' or 'error', with error message). 
12673: 2. result of deletions ('ok' or 'error', with error message).
12674: 3. reference to hash of any new or updated access controls.
12675: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12676:    key = integer (inbound ID)
12677:    value = uniqueID  
12678: 
12679: =back
12680: 
12681: =head2 HTTP Helper Routines
12682: 
12683: =over 4
12684: 
12685: =item *
12686: 
12687: escape() : unpack non-word characters into CGI-compatible hex codes
12688: 
12689: =item *
12690: 
12691: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12692: 
12693: =back
12694: 
12695: =head1 PRIVATE SUBROUTINES
12696: 
12697: =head2 Underlying communication routines (Shouldn't call)
12698: 
12699: =over 4
12700: 
12701: =item *
12702: 
12703: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12704: 
12705: =item *
12706: 
12707: reply() : uses subreply to send a message to remote machine, logs all failures
12708: 
12709: =item *
12710: 
12711: critical() : passes a critical message to another server; if cannot
12712: get through then place message in connection buffer directory and
12713: returns con_delayed, if incapable of saving message, returns
12714: con_failed
12715: 
12716: =item *
12717: 
12718: reconlonc() : tries to reconnect lonc client processes.
12719: 
12720: =back
12721: 
12722: =head2 Resource Access Logging
12723: 
12724: =over 4
12725: 
12726: =item *
12727: 
12728: flushcourselogs() : flush (save) buffer logs and access logs
12729: 
12730: =item *
12731: 
12732: courselog($what) : save message for course in hash
12733: 
12734: =item *
12735: 
12736: courseacclog($what) : save message for course using &courselog().  Perform
12737: special processing for specific resource types (problems, exams, quizzes, etc).
12738: 
12739: =item *
12740: 
12741: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12742: as a PerlChildExitHandler
12743: 
12744: =back
12745: 
12746: =head2 Other
12747: 
12748: =over 4
12749: 
12750: =item *
12751: 
12752: symblist($mapname,%newhash) : update symbolic storage links
12753: 
12754: =back
12755: 
12756: =cut
12757: 

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