File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1252: download - view: text, annotated - select for diffs
Sun Mar 9 15:39:04 2014 UTC (10 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Coding style: split()
- thaw_unescape() is a subroutine within lonnet.pm

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1252 2014/03/09 15:39:04 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$cachekeys) = @_;
  360:     my $items;
  361:     return unless (ref($cachekeys) eq 'ARRAY');
  362:     my $cachestr = join('&',@{$cachekeys});
  363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  364:     return $response;
  365: }
  366: 
  367: # -------------------------------------------------- Non-critical communication
  368: sub subreply {
  369:     my ($cmd,$server)=@_;
  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  371:     #
  372:     #  With loncnew process trimming, there's a timing hole between lonc server
  373:     #  process exit and the master server picking up the listen on the AF_UNIX
  374:     #  socket.  In that time interval, a lock file will exist:
  375: 
  376:     my $lockfile=$peerfile.".lock";
  377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  378: 	sleep(1);
  379:     }
  380:     # At this point, either a loncnew parent is listening or an old lonc
  381:     # or loncnew child is listening so we can connect or everything's dead.
  382:     #
  383:     #   We'll give the connection a few tries before abandoning it.  If
  384:     #   connection is not possible, we'll con_lost back to the client.
  385:     #   
  386:     my $client;
  387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  389: 				      Type    => SOCK_STREAM,
  390: 				      Timeout => 10);
  391: 	if ($client) {
  392: 	    last;		# Connected!
  393: 	} else {
  394: 	    &create_connection(&hostname($server),$server);
  395: 	}
  396:         sleep(1);		# Try again later if failed connection.
  397:     }
  398:     my $answer;
  399:     if ($client) {
  400: 	print $client "sethost:$server:$cmd\n";
  401: 	$answer=<$client>;
  402: 	if (!$answer) { $answer="con_lost"; }
  403: 	chomp($answer);
  404:     } else {
  405: 	$answer = 'con_lost';	# Failed connection.
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: sub reply {
  411:     my ($cmd,$server)=@_;
  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  413:     my $answer=subreply($cmd,$server);
  414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  415:        &logthis("<font color=\"blue\">WARNING:".
  416:                 " $cmd to $server returned $answer</font>");
  417:     }
  418:     return $answer;
  419: }
  420: 
  421: # ----------------------------------------------------------- Send USR1 to lonc
  422: 
  423: sub reconlonc {
  424:     my ($lonid) = @_;
  425:     my $hostname = &hostname($lonid);
  426:     if ($lonid) {
  427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  428: 	if ($hostname && -e $peerfile) {
  429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  431: 					     Type    => SOCK_STREAM,
  432: 					     Timeout => 10);
  433: 	    if ($client) {
  434: 		print $client ("reset_retries\n");
  435: 		my $answer=<$client>;
  436: 		#reset just this one.
  437: 	    }
  438: 	}
  439: 	return;
  440:     }
  441: 
  442:     &logthis("Trying to reconnect lonc");
  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  444:     if (open(my $fh,"<$loncfile")) {
  445: 	my $loncpid=<$fh>;
  446:         chomp($loncpid);
  447:         if (kill 0 => $loncpid) {
  448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  449:             kill USR1 => $loncpid;
  450:             sleep 1;
  451:          } else {
  452: 	    &logthis(
  453:                "<font color=\"blue\">WARNING:".
  454:                " lonc at pid $loncpid not responding, giving up</font>");
  455:         }
  456:     } else {
  457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  458:     }
  459: }
  460: 
  461: # ------------------------------------------------------ Critical communication
  462: 
  463: sub critical {
  464:     my ($cmd,$server)=@_;
  465:     unless (&hostname($server)) {
  466:         &logthis("<font color=\"blue\">WARNING:".
  467:                " Critical message to unknown server ($server)</font>");
  468:         return 'no_such_host';
  469:     }
  470:     my $answer=reply($cmd,$server);
  471:     if ($answer eq 'con_lost') {
  472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  473: 	my $answer=reply($cmd,$server);
  474:         if ($answer eq 'con_lost') {
  475:             my $now=time;
  476:             my $middlename=$cmd;
  477:             $middlename=substr($middlename,0,16);
  478:             $middlename=~s/\W//g;
  479:             my $dfilename=
  480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  481:             $dumpcount++;
  482:             {
  483: 		my $dfh;
  484: 		if (open($dfh,">$dfilename")) {
  485: 		    print $dfh "$cmd\n"; 
  486: 		    close($dfh);
  487: 		}
  488:             }
  489:             sleep 2;
  490:             my $wcmd='';
  491:             {
  492: 		my $dfh;
  493: 		if (open($dfh,"<$dfilename")) {
  494: 		    $wcmd=<$dfh>; 
  495: 		    close($dfh);
  496: 		}
  497:             }
  498:             chomp($wcmd);
  499:             if ($wcmd eq $cmd) {
  500: 		&logthis("<font color=\"blue\">WARNING: ".
  501:                          "Connection buffer $dfilename: $cmd</font>");
  502:                 &logperm("D:$server:$cmd");
  503: 	        return 'con_delayed';
  504:             } else {
  505:                 &logthis("<font color=\"red\">CRITICAL:"
  506:                         ." Critical connection failed: $server $cmd</font>");
  507:                 &logperm("F:$server:$cmd");
  508:                 return 'con_failed';
  509:             }
  510:         }
  511:     }
  512:     return $answer;
  513: }
  514: 
  515: # ------------------------------------------- check if return value is an error
  516: 
  517: sub error {
  518:     my ($result) = @_;
  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  520: 	if ($2 == 2) { return undef; }
  521: 	return $1;
  522:     }
  523:     return undef;
  524: }
  525: 
  526: sub convert_and_load_session_env {
  527:     my ($lonidsdir,$handle)=@_;
  528:     my @profile;
  529:     {
  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  531: 	if (!$opened) {
  532: 	    return 0;
  533: 	}
  534: 	flock($idf,LOCK_SH);
  535: 	@profile=<$idf>;
  536: 	close($idf);
  537:     }
  538:     my %temp_env;
  539:     foreach my $line (@profile) {
  540: 	if ($line !~ m/=/) {
  541: 	    return 0;
  542: 	}
  543: 	chomp($line);
  544: 	my ($envname,$envvalue)=split(/=/,$line,2);
  545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  546:     }
  547:     unlink("$lonidsdir/$handle.id");
  548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  549: 	    0640)) {
  550: 	%disk_env = %temp_env;
  551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  552: 	untie(%disk_env);
  553:     }
  554:     return 1;
  555: }
  556: 
  557: # ------------------------------------------- Transfer profile into environment
  558: my $env_loaded;
  559: sub transfer_profile_to_env {
  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
  561:     if (!$force_transfer && $env_loaded) { return; } 
  562: 
  563:     if (!defined($lonidsdir)) {
  564: 	$lonidsdir = $perlvar{'lonIDsDir'};
  565:     }
  566:     if (!defined($handle)) {
  567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  568:     }
  569: 
  570:     my $convert;
  571:     {
  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  573: 	if (!$opened) {
  574: 	    return;
  575: 	}
  576: 	flock($idf,LOCK_SH);
  577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  578: 		&GDBM_READER(),0640)) {
  579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  580: 	    untie(%disk_env);
  581: 	} else {
  582: 	    $convert = 1;
  583: 	}
  584:     }
  585:     if ($convert) {
  586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  587: 	    &logthis("Failed to load session, or convert session.");
  588: 	}
  589:     }
  590: 
  591:     my %remove;
  592:     while ( my $envname = each(%env) ) {
  593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  594:             if ($time < time-300) {
  595:                 $remove{$key}++;
  596:             }
  597:         }
  598:     }
  599: 
  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  601:     $env_loaded=1;
  602:     foreach my $expired_key (keys(%remove)) {
  603:         &delenv($expired_key);
  604:     }
  605: }
  606: 
  607: # ---------------------------------------------------- Check for valid session 
  608: sub check_for_valid_session {
  609:     my ($r,$name,$userhashref) = @_;
  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  611:     if ($name eq '') {
  612:         $name = 'lonID';
  613:     }
  614:     my $lonid=$cookies{$name};
  615:     return undef if (!$lonid);
  616: 
  617:     my $handle=&LONCAPA::clean_handle($lonid->value);
  618:     my $lonidsdir;
  619:     if ($name eq 'lonDAV') {
  620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  621:     } else {
  622:         $lonidsdir=$r->dir_config('lonIDsDir');
  623:     }
  624:     return undef if (!-e "$lonidsdir/$handle.id");
  625: 
  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  627:     return undef if (!$opened);
  628: 
  629:     flock($idf,LOCK_SH);
  630:     my %disk_env;
  631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  632: 	    &GDBM_READER(),0640)) {
  633: 	return undef;	
  634:     }
  635: 
  636:     if (!defined($disk_env{'user.name'})
  637: 	|| !defined($disk_env{'user.domain'})) {
  638: 	return undef;
  639:     }
  640: 
  641:     if (ref($userhashref) eq 'HASH') {
  642:         $userhashref->{'name'} = $disk_env{'user.name'};
  643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  644:     }
  645: 
  646:     return $handle;
  647: }
  648: 
  649: sub timed_flock {
  650:     my ($file,$lock_type) = @_;
  651:     my $failed=0;
  652:     eval {
  653: 	local $SIG{__DIE__}='DEFAULT';
  654: 	local $SIG{ALRM}=sub {
  655: 	    $failed=1;
  656: 	    die("failed lock");
  657: 	};
  658: 	alarm(13);
  659: 	flock($file,$lock_type);
  660: 	alarm(0);
  661:     };
  662:     if ($failed) {
  663: 	return undef;
  664:     } else {
  665: 	return 1;
  666:     }
  667: }
  668: 
  669: # ---------------------------------------------------------- Append Environment
  670: 
  671: sub appenv {
  672:     my ($newenv,$roles) = @_;
  673:     if (ref($newenv) eq 'HASH') {
  674:         foreach my $key (keys(%{$newenv})) {
  675:             my $refused = 0;
  676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  677:                 $refused = 1;
  678:                 if (ref($roles) eq 'ARRAY') {
  679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  681:                         $refused = 0;
  682:                     }
  683:                 }
  684:             }
  685:             if ($refused) {
  686:                 &logthis("<font color=\"blue\">WARNING: ".
  687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  688:                          .'</font>');
  689: 	        delete($newenv->{$key});
  690:             } else {
  691:                 $env{$key}=$newenv->{$key};
  692:             }
  693:         }
  694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  695:         if ($opened
  696: 	    && &timed_flock($env_file,LOCK_EX)
  697: 	    &&
  698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  700: 	    while (my ($key,$value) = each(%{$newenv})) {
  701: 	        $disk_env{$key} = $value;
  702: 	    }
  703: 	    untie(%disk_env);
  704:         }
  705:     }
  706:     return 'ok';
  707: }
  708: # ----------------------------------------------------- Delete from Environment
  709: 
  710: sub delenv {
  711:     my ($delthis,$regexp,$roles) = @_;
  712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  713:         my $refused = 1;
  714:         if (ref($roles) eq 'ARRAY') {
  715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  716:             if (grep(/^\Q$role\E$/,@{$roles})) {
  717:                 $refused = 0;
  718:             }
  719:         }
  720:         if ($refused) {
  721:             &logthis("<font color=\"blue\">WARNING: ".
  722:                      "Attempt to delete from environment ".$delthis);
  723:             return 'error';
  724:         }
  725:     }
  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  727:     if ($opened
  728: 	&& &timed_flock($env_file,LOCK_EX)
  729: 	&&
  730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  732: 	foreach my $key (keys(%disk_env)) {
  733: 	    if ($regexp) {
  734:                 if ($key=~/^$delthis/) {
  735:                     delete($env{$key});
  736:                     delete($disk_env{$key});
  737:                 } 
  738:             } else {
  739:                 if ($key=~/^\Q$delthis\E/) {
  740: 		    delete($env{$key});
  741: 		    delete($disk_env{$key});
  742: 	        }
  743:             }
  744: 	}
  745: 	untie(%disk_env);
  746:     }
  747:     return 'ok';
  748: }
  749: 
  750: sub get_env_multiple {
  751:     my ($name) = @_;
  752:     my @values;
  753:     if (defined($env{$name})) {
  754:         # exists is it an array
  755:         if (ref($env{$name})) {
  756:             @values=@{ $env{$name} };
  757:         } else {
  758:             $values[0]=$env{$name};
  759:         }
  760:     }
  761:     return(@values);
  762: }
  763: 
  764: # ------------------------------------------------------------------- Locking
  765: 
  766: sub set_lock {
  767:     my ($text)=@_;
  768:     $locknum++;
  769:     my $id=$$.'-'.$locknum;
  770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  771:              'session.lock.'.$id => $text});
  772:     return $id;
  773: }
  774: 
  775: sub get_locks {
  776:     my $num=0;
  777:     my %texts=();
  778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  779:        if ($lock=~/\w/) {
  780:           $num++;
  781:           $texts{$lock}=$env{'session.lock.'.$lock};
  782:        }
  783:    }
  784:    return ($num,%texts);
  785: }
  786: 
  787: sub remove_lock {
  788:     my ($id)=@_;
  789:     my $newlocks='';
  790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  791:        if (($lock=~/\w/) && ($lock ne $id)) {
  792:           $newlocks.=','.$lock;
  793:        }
  794:     }
  795:     &appenv({'session.locks' => $newlocks});
  796:     &delenv('session.lock.'.$id);
  797: }
  798: 
  799: sub remove_all_locks {
  800:     my $activelocks=$env{'session.locks'};
  801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  802:        if ($lock=~/\w/) {
  803:           &remove_lock($lock);
  804:        }
  805:     }
  806: }
  807: 
  808: 
  809: # ------------------------------------------ Find out current server userload
  810: sub userload {
  811:     my $numusers=0;
  812:     {
  813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  814: 	my $filename;
  815: 	my $curtime=time;
  816: 	while ($filename=readdir(LONIDS)) {
  817: 	    next if ($filename eq '.' || $filename eq '..');
  818: 	    next if ($filename =~ /publicuser_\d+\.id/);
  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  821: 	}
  822: 	closedir(LONIDS);
  823:     }
  824:     my $userloadpercent=0;
  825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  826:     if ($maxuserload) {
  827: 	$userloadpercent=100*$numusers/$maxuserload;
  828:     }
  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  830:     return $userloadpercent;
  831: }
  832: 
  833: # ------------------------------ Find server with least workload from spare.tab
  834: 
  835: sub spareserver {
  836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  837:     my $spare_server;
  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  840:                                                      :  $userloadpercent;
  841:     my ($uint_dom,$remotesessions);
  842:     if (($udom ne '') && (&domain($udom) ne '')) {
  843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  846:         $remotesessions = $udomdefaults{'remotesessions'};
  847:     }
  848:     my $spareshash = &this_host_spares($udom);
  849:     if (ref($spareshash) eq 'HASH') {
  850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  852:                 if ($uint_dom) {
  853:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  854:                                                  $try_server));
  855:                 }
  856: 	        ($spare_server, $lowest_load) =
  857: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  858:             }
  859:         }
  860: 
  861:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  862: 
  863:         if (!$found_server) {
  864:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  865: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  866:                     if ($uint_dom) {
  867:                         next unless (&spare_can_host($udom,$uint_dom,
  868:                                                      $remotesessions,$try_server));
  869:                     }
  870: 	            ($spare_server, $lowest_load) =
  871: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  872:                 }
  873: 	    }
  874:         }
  875:     }
  876: 
  877:     if (!$want_server_name) {
  878:         my $protocol = 'http';
  879:         if ($protocol{$spare_server} eq 'https') {
  880:             $protocol = $protocol{$spare_server};
  881:         }
  882:         if (defined($spare_server)) {
  883:             my $hostname = &hostname($spare_server);
  884:             if (defined($hostname)) {
  885: 	        $spare_server = $protocol.'://'.$hostname;
  886:             }
  887:         }
  888:     }
  889:     return $spare_server;
  890: }
  891: 
  892: sub compare_server_load {
  893:     my ($try_server, $spare_server, $lowest_load) = @_;
  894: 
  895:     my $loadans     = &reply('load',    $try_server);
  896:     my $userloadans = &reply('userload',$try_server);
  897: 
  898:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  899: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  900:     }
  901: 
  902:     my $load;
  903:     if ($loadans =~ /\d/) {
  904: 	if ($userloadans =~ /\d/) {
  905: 	    #both are numbers, pick the bigger one
  906: 	    $load = ($loadans > $userloadans) ? $loadans 
  907: 		                              : $userloadans;
  908: 	} else {
  909: 	    $load = $loadans;
  910: 	}
  911:     } else {
  912: 	$load = $userloadans;
  913:     }
  914: 
  915:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  916: 	$spare_server = $try_server;
  917: 	$lowest_load  = $load;
  918:     }
  919:     return ($spare_server,$lowest_load);
  920: }
  921: 
  922: # --------------------------- ask offload servers if user already has a session
  923: sub find_existing_session {
  924:     my ($udom,$uname) = @_;
  925:     my $spareshash = &this_host_spares($udom);
  926:     if (ref($spareshash) eq 'HASH') {
  927:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  928:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  929:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  930:             }
  931:         }
  932:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  933:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  934:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  935:             }
  936:         }
  937:     }
  938:     return;
  939: }
  940: 
  941: # -------------------------------- ask if server already has a session for user
  942: sub has_user_session {
  943:     my ($lonid,$udom,$uname) = @_;
  944:     my $result = &reply(join(':','userhassession',
  945: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  946:     return 1 if ($result eq 'ok');
  947: 
  948:     return 0;
  949: }
  950: 
  951: # --------- determine least loaded server in a user's domain which allows login
  952: 
  953: sub choose_server {
  954:     my ($udom,$checkloginvia) = @_;
  955:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  956:     my %servers = &get_servers($udom);
  957:     my $lowest_load = 30000;
  958:     my ($login_host,$hostname,$portal_path,$isredirect);
  959:     foreach my $lonhost (keys(%servers)) {
  960:         my $loginvia;
  961:         if ($checkloginvia) {
  962:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  963:             if ($loginvia) {
  964:                 my ($server,$path) = split(/:/,$loginvia);
  965:                 ($login_host, $lowest_load) =
  966:                     &compare_server_load($server, $login_host, $lowest_load);
  967:                 if ($login_host eq $server) {
  968:                     $portal_path = $path;
  969:                     $isredirect = 1;
  970:                 }
  971:             } else {
  972:                 ($login_host, $lowest_load) =
  973:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  974:                 if ($login_host eq $lonhost) {
  975:                     $portal_path = '';
  976:                     $isredirect = ''; 
  977:                 }
  978:             }
  979:         } else {
  980:             ($login_host, $lowest_load) =
  981:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  982:         }
  983:     }
  984:     if ($login_host ne '') {
  985:         $hostname = &hostname($login_host);
  986:     }
  987:     return ($login_host,$hostname,$portal_path,$isredirect);
  988: }
  989: 
  990: # --------------------------------------------- Try to change a user's password
  991: 
  992: sub changepass {
  993:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  994:     $currentpass = &escape($currentpass);
  995:     $newpass     = &escape($newpass);
  996:     my $lonhost = $perlvar{'lonHostID'};
  997:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  998: 		       $server);
  999:     if (! $answer) {
 1000: 	&logthis("No reply on password change request to $server ".
 1001: 		 "by $uname in domain $udom.");
 1002:     } elsif ($answer =~ "^ok") {
 1003:         &logthis("$uname in $udom successfully changed their password ".
 1004: 		 "on $server.");
 1005:     } elsif ($answer =~ "^pwchange_failure") {
 1006: 	&logthis("$uname in $udom was unable to change their password ".
 1007: 		 "on $server.  The action was blocked by either lcpasswd ".
 1008: 		 "or pwchange");
 1009:     } elsif ($answer =~ "^non_authorized") {
 1010:         &logthis("$uname in $udom did not get their password correct when ".
 1011: 		 "attempting to change it on $server.");
 1012:     } elsif ($answer =~ "^auth_mode_error") {
 1013:         &logthis("$uname in $udom attempted to change their password despite ".
 1014: 		 "not being locally or internally authenticated on $server.");
 1015:     } elsif ($answer =~ "^unknown_user") {
 1016:         &logthis("$uname in $udom attempted to change their password ".
 1017: 		 "on $server but were unable to because $server is not ".
 1018: 		 "their home server.");
 1019:     } elsif ($answer =~ "^refused") {
 1020: 	&logthis("$server refused to change $uname in $udom password because ".
 1021: 		 "it was sent an unencrypted request to change the password.");
 1022:     } elsif ($answer =~ "invalid_client") {
 1023:         &logthis("$server refused to change $uname in $udom password because ".
 1024:                  "it was a reset by e-mail originating from an invalid server.");
 1025:     }
 1026:     return $answer;
 1027: }
 1028: 
 1029: # ----------------------- Try to determine user's current authentication scheme
 1030: 
 1031: sub queryauthenticate {
 1032:     my ($uname,$udom)=@_;
 1033:     my $uhome=&homeserver($uname,$udom);
 1034:     if (!$uhome) {
 1035: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1036: 	return 'no_host';
 1037:     }
 1038:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1039:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1040: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1041:     }
 1042:     return $answer;
 1043: }
 1044: 
 1045: # --------- Try to authenticate user from domain's lib servers (first this one)
 1046: 
 1047: sub authenticate {
 1048:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1049:     $upass=&escape($upass);
 1050:     $uname= &LONCAPA::clean_username($uname);
 1051:     my $uhome=&homeserver($uname,$udom,1);
 1052:     my $newhome;
 1053:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1054: # Maybe the machine was offline and only re-appeared again recently?
 1055:         &reconlonc();
 1056: # One more
 1057: 	$uhome=&homeserver($uname,$udom,1);
 1058:         if (($uhome eq 'no_host') && $checkdefauth) {
 1059:             if (defined(&domain($udom,'primary'))) {
 1060:                 $newhome=&domain($udom,'primary');
 1061:             }
 1062:             if ($newhome ne '') {
 1063:                 $uhome = $newhome;
 1064:             }
 1065:         }
 1066: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1067: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1068: 	    return 'no_host';
 1069:         }
 1070:     }
 1071:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1072:     if ($answer eq 'authorized') {
 1073:         if ($newhome) {
 1074:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1075:             return 'no_account_on_host'; 
 1076:         } else {
 1077:             &logthis("User $uname at $udom authorized by $uhome");
 1078:             return $uhome;
 1079:         }
 1080:     }
 1081:     if ($answer eq 'non_authorized') {
 1082: 	&logthis("User $uname at $udom rejected by $uhome");
 1083: 	return 'no_host'; 
 1084:     }
 1085:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1086:     return 'no_host';
 1087: }
 1088: 
 1089: sub can_host_session {
 1090:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1091:     my $canhost = 1;
 1092:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1093:     if (ref($remotesessions) eq 'HASH') {
 1094:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1095:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1096:                 $canhost = 0;
 1097:             } else {
 1098:                 $canhost = 1;
 1099:             }
 1100:         }
 1101:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1102:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1103:                 $canhost = 1;
 1104:             } else {
 1105:                 $canhost = 0;
 1106:             }
 1107:         }
 1108:         if ($canhost) {
 1109:             if ($remotesessions->{'version'} ne '') {
 1110:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1111:                 if ($reqmajor ne '' && $reqminor ne '') {
 1112:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1113:                         my $major = $1;
 1114:                         my $minor = $2;
 1115:                         if (($major < $reqmajor ) ||
 1116:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1117:                             $canhost = 0;
 1118:                         }
 1119:                     } else {
 1120:                         $canhost = 0;
 1121:                     }
 1122:                 }
 1123:             }
 1124:         }
 1125:     }
 1126:     if ($canhost) {
 1127:         if (ref($hostedsessions) eq 'HASH') {
 1128:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1129:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1130:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1131:                 if (($uint_dom ne '') && 
 1132:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1133:                     $canhost = 0;
 1134:                 } else {
 1135:                     $canhost = 1;
 1136:                 }
 1137:             }
 1138:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1139:                 if (($uint_dom ne '') && 
 1140:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1141:                     $canhost = 1;
 1142:                 } else {
 1143:                     $canhost = 0;
 1144:                 }
 1145:             }
 1146:         }
 1147:     }
 1148:     return $canhost;
 1149: }
 1150: 
 1151: sub spare_can_host {
 1152:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1153:     my $canhost=1;
 1154:     my @intdoms;
 1155:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1156:     if (ref($internet_names) eq 'ARRAY') {
 1157:         @intdoms = @{$internet_names};
 1158:     }
 1159:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1160:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1161:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1162:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1163:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1164:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1165:                                      $remotesessions,
 1166:                                      $defdomdefaults{'hostedsessions'});
 1167:     }
 1168:     return $canhost;
 1169: }
 1170: 
 1171: sub this_host_spares {
 1172:     my ($dom) = @_;
 1173:     my ($dom_in_use,$lonhost_in_use,$result);
 1174:     my @hosts = &current_machine_ids();
 1175:     foreach my $lonhost (@hosts) {
 1176:         if (&host_domain($lonhost) eq $dom) {
 1177:             $dom_in_use = $dom;
 1178:             $lonhost_in_use = $lonhost;
 1179:             last;
 1180:         }
 1181:     }
 1182:     if ($dom_in_use ne '') {
 1183:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1184:     }
 1185:     if (ref($result) ne 'HASH') {
 1186:         $lonhost_in_use = $perlvar{'lonHostID'};
 1187:         $dom_in_use = &host_domain($lonhost_in_use);
 1188:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1189:         if (ref($result) ne 'HASH') {
 1190:             $result = \%spareid;
 1191:         }
 1192:     }
 1193:     return $result;
 1194: }
 1195: 
 1196: sub spares_for_offload  {
 1197:     my ($dom_in_use,$lonhost_in_use) = @_;
 1198:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1199:     if (defined($cached)) {
 1200:         return $result;
 1201:     } else {
 1202:         my $cachetime = 60*60*24;
 1203:         my %domconfig =
 1204:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1205:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1206:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1207:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1208:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1209:                 }
 1210:             }
 1211:         }
 1212:     }
 1213:     return;
 1214: }
 1215: 
 1216: sub get_lonbalancer_config {
 1217:     my ($servers) = @_;
 1218:     my ($currbalancer,$currtargets);
 1219:     if (ref($servers) eq 'HASH') {
 1220:         foreach my $server (keys(%{$servers})) {
 1221:             my %what = (
 1222:                          spareid => 1,
 1223:                          perlvar => 1,
 1224:                        );
 1225:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1226:             if ($result eq 'ok') {
 1227:                 if (ref($returnhash) eq 'HASH') {
 1228:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1229:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1230:                             $currbalancer = $server;
 1231:                             $currtargets = {};
 1232:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1233:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1234:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1235:                                 }
 1236:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1237:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1238:                                 }
 1239:                             }
 1240:                             last;
 1241:                         }
 1242:                     }
 1243:                 }
 1244:             }
 1245:         }
 1246:     }
 1247:     return ($currbalancer,$currtargets);
 1248: }
 1249: 
 1250: sub check_loadbalancing {
 1251:     my ($uname,$udom) = @_;
 1252:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1253:         $rule_in_effect,$offloadto,$otherserver);
 1254:     my $lonhost = $perlvar{'lonHostID'};
 1255:     my @hosts = &current_machine_ids();
 1256:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1257:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1258:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1259:     my $serverhomedom = &host_domain($lonhost);
 1260: 
 1261:     my $cachetime = 60*60*24;
 1262: 
 1263:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1264:         $dom_in_use = $udom;
 1265:         $homeintdom = 1;
 1266:     } else {
 1267:         $dom_in_use = $serverhomedom;
 1268:     }
 1269:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1270:     unless (defined($cached)) {
 1271:         my %domconfig =
 1272:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1273:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1274:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1275:         }
 1276:     }
 1277:     if (ref($result) eq 'HASH') {
 1278:         ($is_balancer,$currtargets,$currrules) = 
 1279:             &check_balancer_result($result,@hosts);
 1280:         if ($is_balancer) {
 1281:             if (ref($currrules) eq 'HASH') {
 1282:                 if ($homeintdom) {
 1283:                     if ($uname ne '') {
 1284:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1285:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1286:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1287:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1288:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1289:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1290:                             }
 1291:                         }
 1292:                         if ($rule_in_effect eq '') {
 1293:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1294:                             if ($userenv{'inststatus'} ne '') {
 1295:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1296:                                 my ($othertitle,$usertypes,$types) =
 1297:                                     &Apache::loncommon::sorted_inst_types($udom);
 1298:                                 if (ref($types) eq 'ARRAY') {
 1299:                                     foreach my $type (@{$types}) {
 1300:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1301:                                             if (exists($currrules->{$type})) {
 1302:                                                 $rule_in_effect = $currrules->{$type};
 1303:                                             }
 1304:                                         }
 1305:                                     }
 1306:                                 }
 1307:                             } else {
 1308:                                 if (exists($currrules->{'default'})) {
 1309:                                     $rule_in_effect = $currrules->{'default'};
 1310:                                 }
 1311:                             }
 1312:                         }
 1313:                     } else {
 1314:                         if (exists($currrules->{'default'})) {
 1315:                             $rule_in_effect = $currrules->{'default'};
 1316:                         }
 1317:                     }
 1318:                 } else {
 1319:                     if ($currrules->{'_LC_external'} ne '') {
 1320:                         $rule_in_effect = $currrules->{'_LC_external'};
 1321:                     }
 1322:                 }
 1323:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1324:                                                        $uname,$udom);
 1325:             }
 1326:         }
 1327:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1328:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1329:         unless (defined($cached)) {
 1330:             my %domconfig =
 1331:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1332:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1333:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1334:             }
 1335:         }
 1336:         if (ref($result) eq 'HASH') {
 1337:             ($is_balancer,$currtargets,$currrules) = 
 1338:                 &check_balancer_result($result,@hosts);
 1339:             if ($is_balancer) {
 1340:                 if (ref($currrules) eq 'HASH') {
 1341:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1342:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1343:                     }
 1344:                 }
 1345:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1346:                                                        $uname,$udom);
 1347:             }
 1348:         } else {
 1349:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1350:                 $is_balancer = 1;
 1351:                 $offloadto = &this_host_spares($dom_in_use);
 1352:             }
 1353:         }
 1354:     } else {
 1355:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1356:             $is_balancer = 1;
 1357:             $offloadto = &this_host_spares($dom_in_use);
 1358:         }
 1359:     }
 1360:     if ($is_balancer) {
 1361:         my $lowest_load = 30000;
 1362:         if (ref($offloadto) eq 'HASH') {
 1363:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1364:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1365:                     ($otherserver,$lowest_load) =
 1366:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1367:                 }
 1368:             }
 1369:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1370: 
 1371:             if (!$found_server) {
 1372:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1373:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1374:                         ($otherserver,$lowest_load) =
 1375:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1376:                     }
 1377:                 }
 1378:             }
 1379:         } elsif (ref($offloadto) eq 'ARRAY') {
 1380:             if (@{$offloadto} == 1) {
 1381:                 $otherserver = $offloadto->[0];
 1382:             } elsif (@{$offloadto} > 1) {
 1383:                 foreach my $try_server (@{$offloadto}) {
 1384:                     ($otherserver,$lowest_load) =
 1385:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1386:                 }
 1387:             }
 1388:         }
 1389:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1390:             $is_balancer = 0;
 1391:             if ($uname ne '' && $udom ne '') {
 1392:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1393:                     
 1394:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1395:                              'user.loadbalcheck.time' => time});
 1396:                 }
 1397:             }
 1398:         }
 1399:     }
 1400:     return ($is_balancer,$otherserver);
 1401: }
 1402: 
 1403: sub check_balancer_result {
 1404:     my ($result,@hosts) = @_;
 1405:     my ($is_balancer,$currtargets,$currrules);
 1406:     if (ref($result) eq 'HASH') {
 1407:         if ($result->{'lonhost'} ne '') {
 1408:             my $currbalancer = $result->{'lonhost'};
 1409:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1410:                 $is_balancer = 1;
 1411:                 $currtargets = $result->{'targets'};
 1412:                 $currrules = $result->{'rules'};
 1413:             }
 1414:         } else {
 1415:             foreach my $key (keys(%{$result})) {
 1416:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1417:                     (ref($result->{$key}) eq 'HASH')) {
 1418:                     $is_balancer = 1;
 1419:                     $currrules = $result->{$key}{'rules'};
 1420:                     $currtargets = $result->{$key}{'targets'};
 1421:                     last;
 1422:                 }
 1423:             }
 1424:         }
 1425:     }
 1426:     return ($is_balancer,$currtargets,$currrules);
 1427: }
 1428: 
 1429: sub get_loadbalancer_targets {
 1430:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1431:     my $offloadto;
 1432:     if ($rule_in_effect eq 'none') {
 1433:         return [$perlvar{'lonHostID'}];
 1434:     } elsif ($rule_in_effect eq '') {
 1435:         $offloadto = $currtargets;
 1436:     } else {
 1437:         if ($rule_in_effect eq 'homeserver') {
 1438:             my $homeserver = &homeserver($uname,$udom);
 1439:             if ($homeserver ne 'no_host') {
 1440:                 $offloadto = [$homeserver];
 1441:             }
 1442:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1443:             my %domconfig =
 1444:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1445:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1446:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1447:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1448:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1449:                     }
 1450:                 }
 1451:             } else {
 1452:                 my %servers = &internet_dom_servers($udom);
 1453:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1454:                 if (&hostname($remotebalancer) ne '') {
 1455:                     $offloadto = [$remotebalancer];
 1456:                 }
 1457:             }
 1458:         } elsif (&hostname($rule_in_effect) ne '') {
 1459:             $offloadto = [$rule_in_effect];
 1460:         }
 1461:     }
 1462:     return $offloadto;
 1463: }
 1464: 
 1465: sub internet_dom_servers {
 1466:     my ($dom) = @_;
 1467:     my (%uniqservers,%servers);
 1468:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1469:     my @machinedoms = &machine_domains($primaryserver);
 1470:     foreach my $mdom (@machinedoms) {
 1471:         my %currservers = %servers;
 1472:         my %server = &get_servers($mdom);
 1473:         %servers = (%currservers,%server);
 1474:     }
 1475:     my %by_hostname;
 1476:     foreach my $id (keys(%servers)) {
 1477:         push(@{$by_hostname{$servers{$id}}},$id);
 1478:     }
 1479:     foreach my $hostname (sort(keys(%by_hostname))) {
 1480:         if (@{$by_hostname{$hostname}} > 1) {
 1481:             my $match = 0;
 1482:             foreach my $id (@{$by_hostname{$hostname}}) {
 1483:                 if (&host_domain($id) eq $dom) {
 1484:                     $uniqservers{$id} = $hostname;
 1485:                     $match = 1;
 1486:                 }
 1487:             }
 1488:             unless ($match) {
 1489:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1490:             }
 1491:         } else {
 1492:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1493:         }
 1494:     }
 1495:     return %uniqservers;
 1496: }
 1497: 
 1498: # ---------------------- Find the homebase for a user from domain's lib servers
 1499: 
 1500: my %homecache;
 1501: sub homeserver {
 1502:     my ($uname,$udom,$ignoreBadCache)=@_;
 1503:     my $index="$uname:$udom";
 1504: 
 1505:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1506: 
 1507:     my %servers = &get_servers($udom,'library');
 1508:     foreach my $tryserver (keys(%servers)) {
 1509:         next if ($ignoreBadCache ne 'true' && 
 1510: 		 exists($badServerCache{$tryserver}));
 1511: 
 1512: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1513: 	if ($answer eq 'found') {
 1514: 	    delete($badServerCache{$tryserver}); 
 1515: 	    return $homecache{$index}=$tryserver;
 1516: 	} elsif ($answer eq 'no_host') {
 1517: 	    $badServerCache{$tryserver}=1;
 1518: 	}
 1519:     }    
 1520:     return 'no_host';
 1521: }
 1522: 
 1523: # ------------------------------------- Find the usernames behind a list of IDs
 1524: 
 1525: sub idget {
 1526:     my ($udom,@ids)=@_;
 1527:     my %returnhash=();
 1528:     
 1529:     my %servers = &get_servers($udom,'library');
 1530:     foreach my $tryserver (keys(%servers)) {
 1531: 	my $idlist=join('&',@ids);
 1532: 	$idlist=~tr/A-Z/a-z/; 
 1533: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1534: 	my @answer=();
 1535: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1536: 	    @answer=split(/\&/,$reply);
 1537: 	}                    ;
 1538: 	my $i;
 1539: 	for ($i=0;$i<=$#ids;$i++) {
 1540: 	    if ($answer[$i]) {
 1541: 		$returnhash{$ids[$i]}=$answer[$i];
 1542: 	    } 
 1543: 	}
 1544:     } 
 1545:     return %returnhash;
 1546: }
 1547: 
 1548: # ------------------------------------- Find the IDs behind a list of usernames
 1549: 
 1550: sub idrget {
 1551:     my ($udom,@unames)=@_;
 1552:     my %returnhash=();
 1553:     foreach my $uname (@unames) {
 1554:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1555:     }
 1556:     return %returnhash;
 1557: }
 1558: 
 1559: # ------------------------------- Store away a list of names and associated IDs
 1560: 
 1561: sub idput {
 1562:     my ($udom,%ids)=@_;
 1563:     my %servers=();
 1564:     foreach my $uname (keys(%ids)) {
 1565: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1566:         my $uhom=&homeserver($uname,$udom);
 1567:         if ($uhom ne 'no_host') {
 1568:             my $id=&escape($ids{$uname});
 1569:             $id=~tr/A-Z/a-z/;
 1570:             my $esc_unam=&escape($uname);
 1571: 	    if ($servers{$uhom}) {
 1572: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1573:             } else {
 1574:                 $servers{$uhom}=$id.'='.$esc_unam;
 1575:             }
 1576:         }
 1577:     }
 1578:     foreach my $server (keys(%servers)) {
 1579:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1580:     }
 1581: }
 1582: 
 1583: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1584: 
 1585: sub iddel {
 1586:     my ($udom,$idshashref,$uhome)=@_;
 1587:     my %result=();
 1588:     unless (ref($idshashref) eq 'HASH') {
 1589:         return %result;
 1590:     }
 1591:     my %servers=();
 1592:     while (my ($id,$uname) = each(%{$idshashref})) {
 1593:         my $uhom;
 1594:         if ($uhome) {
 1595:             $uhom = $uhome;
 1596:         } else {
 1597:             $uhom=&homeserver($uname,$udom);
 1598:         }
 1599:         if ($uhom ne 'no_host') {
 1600:             if ($servers{$uhom}) {
 1601:                 $servers{$uhom}.='&'.&escape($id);
 1602:             } else {
 1603:                 $servers{$uhom}=&escape($id);
 1604:             }
 1605:         }
 1606:     }
 1607:     foreach my $server (keys(%servers)) {
 1608:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1609:     }
 1610:     return %result;
 1611: }
 1612: 
 1613: # ------------------------------dump from db file owned by domainconfig user
 1614: sub dump_dom {
 1615:     my ($namespace, $udom, $regexp) = @_;
 1616: 
 1617:     $udom ||= $env{'user.domain'};
 1618: 
 1619:     return () unless $udom;
 1620: 
 1621:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1622: }
 1623: 
 1624: # ------------------------------------------ get items from domain db files   
 1625: 
 1626: sub get_dom {
 1627:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1628:     my $items='';
 1629:     foreach my $item (@$storearr) {
 1630:         $items.=&escape($item).'&';
 1631:     }
 1632:     $items=~s/\&$//;
 1633:     if (!$udom) {
 1634:         $udom=$env{'user.domain'};
 1635:         if (defined(&domain($udom,'primary'))) {
 1636:             $uhome=&domain($udom,'primary');
 1637:         } else {
 1638:             undef($uhome);
 1639:         }
 1640:     } else {
 1641:         if (!$uhome) {
 1642:             if (defined(&domain($udom,'primary'))) {
 1643:                 $uhome=&domain($udom,'primary');
 1644:             }
 1645:         }
 1646:     }
 1647:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1648:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1649:         my %returnhash;
 1650:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1651:             return %returnhash;
 1652:         }
 1653:         my @pairs=split(/\&/,$rep);
 1654:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1655:             return @pairs;
 1656:         }
 1657:         my $i=0;
 1658:         foreach my $item (@$storearr) {
 1659:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1660:             $i++;
 1661:         }
 1662:         return %returnhash;
 1663:     } else {
 1664:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1665:     }
 1666: }
 1667: 
 1668: # -------------------------------------------- put items in domain db files 
 1669: 
 1670: sub put_dom {
 1671:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1672:     if (!$udom) {
 1673:         $udom=$env{'user.domain'};
 1674:         if (defined(&domain($udom,'primary'))) {
 1675:             $uhome=&domain($udom,'primary');
 1676:         } else {
 1677:             undef($uhome);
 1678:         }
 1679:     } else {
 1680:         if (!$uhome) {
 1681:             if (defined(&domain($udom,'primary'))) {
 1682:                 $uhome=&domain($udom,'primary');
 1683:             }
 1684:         }
 1685:     } 
 1686:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1687:         my $items='';
 1688:         foreach my $item (keys(%$storehash)) {
 1689:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1690:         }
 1691:         $items=~s/\&$//;
 1692:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1693:     } else {
 1694:         &logthis("put_dom failed - no homeserver and/or domain");
 1695:     }
 1696: }
 1697: 
 1698: # --------------------- newput for items in db file owned by domainconfig user
 1699: sub newput_dom {
 1700:     my ($namespace,$storehash,$udom) = @_;
 1701:     my $result;
 1702:     if (!$udom) {
 1703:         $udom=$env{'user.domain'};
 1704:     }
 1705:     if ($udom) {
 1706:         my $uname = &get_domainconfiguser($udom);
 1707:         $result = &newput($namespace,$storehash,$udom,$uname);
 1708:     }
 1709:     return $result;
 1710: }
 1711: 
 1712: # --------------------- delete for items in db file owned by domainconfig user
 1713: sub del_dom {
 1714:     my ($namespace,$storearr,$udom)=@_;
 1715:     if (ref($storearr) eq 'ARRAY') {
 1716:         if (!$udom) {
 1717:             $udom=$env{'user.domain'};
 1718:         }
 1719:         if ($udom) {
 1720:             my $uname = &get_domainconfiguser($udom); 
 1721:             return &del($namespace,$storearr,$udom,$uname);
 1722:         }
 1723:     }
 1724: }
 1725: 
 1726: # ----------------------------------construct domainconfig user for a domain 
 1727: sub get_domainconfiguser {
 1728:     my ($udom) = @_;
 1729:     return $udom.'-domainconfig';
 1730: }
 1731: 
 1732: sub retrieve_inst_usertypes {
 1733:     my ($udom) = @_;
 1734:     my (%returnhash,@order);
 1735:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1736:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1737:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1738:         %returnhash = %{$domdefs{'inststatustypes'}};
 1739:         @order = @{$domdefs{'inststatusorder'}};
 1740:     } else {
 1741:         if (defined(&domain($udom,'primary'))) {
 1742:             my $uhome=&domain($udom,'primary');
 1743:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1744:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1745:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1746:                 return (\%returnhash,\@order);
 1747:             }
 1748:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1749:             my @pairs=split(/\&/,$hashitems);
 1750:             foreach my $item (@pairs) {
 1751:                 my ($key,$value)=split(/=/,$item,2);
 1752:                 $key = &unescape($key);
 1753:                 next if ($key =~ /^error: 2 /);
 1754:                 $returnhash{$key}=&thaw_unescape($value);
 1755:             }
 1756:             my @esc_order = split(/\&/,$orderitems);
 1757:             foreach my $item (@esc_order) {
 1758:                 push(@order,&unescape($item));
 1759:             }
 1760:         } else {
 1761:             &logthis("get_dom failed - no primary domain server for $udom");
 1762:         }
 1763:     }
 1764:     return (\%returnhash,\@order);
 1765: }
 1766: 
 1767: sub is_domainimage {
 1768:     my ($url) = @_;
 1769:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1770:         if (&domain($1) ne '') {
 1771:             return '1';
 1772:         }
 1773:     }
 1774:     return;
 1775: }
 1776: 
 1777: sub inst_directory_query {
 1778:     my ($srch) = @_;
 1779:     my $udom = $srch->{'srchdomain'};
 1780:     my %results;
 1781:     my $homeserver = &domain($udom,'primary');
 1782:     my $outcome;
 1783:     if ($homeserver ne '') {
 1784: 	my $queryid=&reply("querysend:instdirsearch:".
 1785: 			   &escape($srch->{'srchby'}).':'.
 1786: 			   &escape($srch->{'srchterm'}).':'.
 1787: 			   &escape($srch->{'srchtype'}),$homeserver);
 1788: 	my $host=&hostname($homeserver);
 1789: 	if ($queryid !~/^\Q$host\E\_/) {
 1790: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1791: 	    return;
 1792: 	}
 1793: 	my $response = &get_query_reply($queryid);
 1794: 	my $maxtries = 5;
 1795: 	my $tries = 1;
 1796: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1797: 	    $response = &get_query_reply($queryid);
 1798: 	    $tries ++;
 1799: 	}
 1800: 
 1801:         if (!&error($response) && $response ne 'refused') {
 1802:             if ($response eq 'unavailable') {
 1803:                 $outcome = $response;
 1804:             } else {
 1805:                 $outcome = 'ok';
 1806:                 my @matches = split(/\n/,$response);
 1807:                 foreach my $match (@matches) {
 1808:                     my ($key,$value) = split(/=/,$match);
 1809:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1810:                 }
 1811:             }
 1812:         }
 1813:     }
 1814:     return ($outcome,%results);
 1815: }
 1816: 
 1817: sub usersearch {
 1818:     my ($srch) = @_;
 1819:     my $dom = $srch->{'srchdomain'};
 1820:     my %results;
 1821:     my %libserv = &all_library();
 1822:     my $query = 'usersearch';
 1823:     foreach my $tryserver (keys(%libserv)) {
 1824:         if (&host_domain($tryserver) eq $dom) {
 1825:             my $host=&hostname($tryserver);
 1826:             my $queryid=
 1827:                 &reply("querysend:".&escape($query).':'.
 1828:                        &escape($srch->{'srchby'}).':'.
 1829:                        &escape($srch->{'srchtype'}).':'.
 1830:                        &escape($srch->{'srchterm'}),$tryserver);
 1831:             if ($queryid !~/^\Q$host\E\_/) {
 1832:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1833:                 next;
 1834:             }
 1835:             my $reply = &get_query_reply($queryid);
 1836:             my $maxtries = 1;
 1837:             my $tries = 1;
 1838:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1839:                 $reply = &get_query_reply($queryid);
 1840:                 $tries ++;
 1841:             }
 1842:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1843:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1844:             } else {
 1845:                 my @matches;
 1846:                 if ($reply =~ /\n/) {
 1847:                     @matches = split(/\n/,$reply);
 1848:                 } else {
 1849:                     @matches = split(/\&/,$reply);
 1850:                 }
 1851:                 foreach my $match (@matches) {
 1852:                     my ($uname,$udom,%userhash);
 1853:                     foreach my $entry (split(/:/,$match)) {
 1854:                         my ($key,$value) =
 1855:                             map {&unescape($_);} split(/=/,$entry);
 1856:                         $userhash{$key} = $value;
 1857:                         if ($key eq 'username') {
 1858:                             $uname = $value;
 1859:                         } elsif ($key eq 'domain') {
 1860:                             $udom = $value;
 1861:                         }
 1862:                     }
 1863:                     $results{$uname.':'.$udom} = \%userhash;
 1864:                 }
 1865:             }
 1866:         }
 1867:     }
 1868:     return %results;
 1869: }
 1870: 
 1871: sub get_instuser {
 1872:     my ($udom,$uname,$id) = @_;
 1873:     my $homeserver = &domain($udom,'primary');
 1874:     my ($outcome,%results);
 1875:     if ($homeserver ne '') {
 1876:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1877:                            &escape($id).':'.&escape($udom),$homeserver);
 1878:         my $host=&hostname($homeserver);
 1879:         if ($queryid !~/^\Q$host\E\_/) {
 1880:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1881:             return;
 1882:         }
 1883:         my $response = &get_query_reply($queryid);
 1884:         my $maxtries = 5;
 1885:         my $tries = 1;
 1886:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1887:             $response = &get_query_reply($queryid);
 1888:             $tries ++;
 1889:         }
 1890:         if (!&error($response) && $response ne 'refused') {
 1891:             if ($response eq 'unavailable') {
 1892:                 $outcome = $response;
 1893:             } else {
 1894:                 $outcome = 'ok';
 1895:                 my @matches = split(/\n/,$response);
 1896:                 foreach my $match (@matches) {
 1897:                     my ($key,$value) = split(/=/,$match);
 1898:                     $results{&unescape($key)} = &thaw_unescape($value);
 1899:                 }
 1900:             }
 1901:         }
 1902:     }
 1903:     my %userinfo;
 1904:     if (ref($results{$uname}) eq 'HASH') {
 1905:         %userinfo = %{$results{$uname}};
 1906:     } 
 1907:     return ($outcome,%userinfo);
 1908: }
 1909: 
 1910: sub inst_rulecheck {
 1911:     my ($udom,$uname,$id,$item,$rules) = @_;
 1912:     my %returnhash;
 1913:     if ($udom ne '') {
 1914:         if (ref($rules) eq 'ARRAY') {
 1915:             @{$rules} = map {&escape($_);} (@{$rules});
 1916:             my $rulestr = join(':',@{$rules});
 1917:             my $homeserver=&domain($udom,'primary');
 1918:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1919:                 my $response;
 1920:                 if ($item eq 'username') {                
 1921:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1922:                                               ':'.&escape($uname).':'.$rulestr,
 1923:                                               $homeserver));
 1924:                 } elsif ($item eq 'id') {
 1925:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1926:                                               ':'.&escape($id).':'.$rulestr,
 1927:                                               $homeserver));
 1928:                 } elsif ($item eq 'selfcreate') {
 1929:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1930:                                                &escape($udom).':'.&escape($uname).
 1931:                                               ':'.$rulestr,$homeserver));
 1932:                 }
 1933:                 if ($response ne 'refused') {
 1934:                     my @pairs=split(/\&/,$response);
 1935:                     foreach my $item (@pairs) {
 1936:                         my ($key,$value)=split(/=/,$item,2);
 1937:                         $key = &unescape($key);
 1938:                         next if ($key =~ /^error: 2 /);
 1939:                         $returnhash{$key}=&thaw_unescape($value);
 1940:                     }
 1941:                 }
 1942:             }
 1943:         }
 1944:     }
 1945:     return %returnhash;
 1946: }
 1947: 
 1948: sub inst_userrules {
 1949:     my ($udom,$check) = @_;
 1950:     my (%ruleshash,@ruleorder);
 1951:     if ($udom ne '') {
 1952:         my $homeserver=&domain($udom,'primary');
 1953:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1954:             my $response;
 1955:             if ($check eq 'id') {
 1956:                 $response=&reply('instidrules:'.&escape($udom),
 1957:                                  $homeserver);
 1958:             } elsif ($check eq 'email') {
 1959:                 $response=&reply('instemailrules:'.&escape($udom),
 1960:                                  $homeserver);
 1961:             } else {
 1962:                 $response=&reply('instuserrules:'.&escape($udom),
 1963:                                  $homeserver);
 1964:             }
 1965:             if (($response ne 'refused') && ($response ne 'error') && 
 1966:                 ($response ne 'unknown_cmd') && 
 1967:                 ($response ne 'no_such_host')) {
 1968:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1969:                 my @pairs=split(/\&/,$hashitems);
 1970:                 foreach my $item (@pairs) {
 1971:                     my ($key,$value)=split(/=/,$item,2);
 1972:                     $key = &unescape($key);
 1973:                     next if ($key =~ /^error: 2 /);
 1974:                     $ruleshash{$key}=&thaw_unescape($value);
 1975:                 }
 1976:                 my @esc_order = split(/\&/,$orderitems);
 1977:                 foreach my $item (@esc_order) {
 1978:                     push(@ruleorder,&unescape($item));
 1979:                 }
 1980:             }
 1981:         }
 1982:     }
 1983:     return (\%ruleshash,\@ruleorder);
 1984: }
 1985: 
 1986: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1987: 
 1988: sub get_domain_defaults {
 1989:     my ($domain,$ignore_cache) = @_;
 1990:     return if (($domain eq '') || ($domain eq 'public'));
 1991:     my $cachetime = 60*60*24;
 1992:     unless ($ignore_cache) {
 1993:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1994:         if (defined($cached)) {
 1995:             if (ref($result) eq 'HASH') {
 1996:                 return %{$result};
 1997:             }
 1998:         }
 1999:     }
 2000:     my %domdefaults;
 2001:     my %domconfig =
 2002:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2003:                                   'requestcourses','inststatus',
 2004:                                   'coursedefaults','usersessions',
 2005:                                   'requestauthor'],$domain);
 2006:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2007:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2008:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2009:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2010:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2011:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2012:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2013:     } else {
 2014:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2015:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2016:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2017:     }
 2018:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2019:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2020:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2021:         } else {
 2022:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2023:         }
 2024:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2025:         foreach my $item (@usertools) {
 2026:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2027:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2028:             }
 2029:         }
 2030:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2031:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2032:         }
 2033:     }
 2034:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2035:         foreach my $item ('official','unofficial','community','textbook') {
 2036:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2037:         }
 2038:     }
 2039:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2040:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2041:     }
 2042:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2043:         foreach my $item ('inststatustypes','inststatusorder') {
 2044:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2045:         }
 2046:     }
 2047:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2048:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2049:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2050:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
 2051:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
 2052:             $domdefaults{'textbookcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'textbook'};
 2053:         }
 2054:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2055:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
 2056:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
 2057:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};
 2058:             $domdefaults{'textbookquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'textbook'};
 2059:         }
 2060:     }
 2061:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2062:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2063:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2064:         }
 2065:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2066:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2067:         }
 2068:     }
 2069:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2070:     return %domdefaults;
 2071: }
 2072: 
 2073: # --------------------------------------------------- Assign a key to a student
 2074: 
 2075: sub assign_access_key {
 2076: #
 2077: # a valid key looks like uname:udom#comments
 2078: # comments are being appended
 2079: #
 2080:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2081:     $kdom=
 2082:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2083:     $knum=
 2084:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2085:     $cdom=
 2086:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2087:     $cnum=
 2088:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2089:     $udom=$env{'user.name'} unless (defined($udom));
 2090:     $uname=$env{'user.domain'} unless (defined($uname));
 2091:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2092:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2093:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2094:                                                   # assigned to this person
 2095:                                                   # - this should not happen,
 2096:                                                   # unless something went wrong
 2097:                                                   # the first time around
 2098: # ready to assign
 2099:         $logentry=$1.'; '.$logentry;
 2100:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2101:                                                  $kdom,$knum) eq 'ok') {
 2102: # key now belongs to user
 2103: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2104:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2105:                 &appenv({'environment.'.$envkey => $ckey});
 2106:                 return 'ok';
 2107:             } else {
 2108:                 return 
 2109:   'error: Count not permanently assign key, will need to be re-entered later.';
 2110: 	    }
 2111:         } else {
 2112:             return 'error: Could not assign key, try again later.';
 2113:         }
 2114:     } elsif (!$existing{$ckey}) {
 2115: # the key does not exist
 2116: 	return 'error: The key does not exist';
 2117:     } else {
 2118: # the key is somebody else's
 2119: 	return 'error: The key is already in use';
 2120:     }
 2121: }
 2122: 
 2123: # ------------------------------------------ put an additional comment on a key
 2124: 
 2125: sub comment_access_key {
 2126: #
 2127: # a valid key looks like uname:udom#comments
 2128: # comments are being appended
 2129: #
 2130:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2131:     $cdom=
 2132:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2133:     $cnum=
 2134:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2135:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2136:     if ($existing{$ckey}) {
 2137:         $existing{$ckey}.='; '.$logentry;
 2138: # ready to assign
 2139:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2140:                                                  $cdom,$cnum) eq 'ok') {
 2141: 	    return 'ok';
 2142:         } else {
 2143: 	    return 'error: Count not store comment.';
 2144:         }
 2145:     } else {
 2146: # the key does not exist
 2147: 	return 'error: The key does not exist';
 2148:     }
 2149: }
 2150: 
 2151: # ------------------------------------------------------ Generate a set of keys
 2152: 
 2153: sub generate_access_keys {
 2154:     my ($number,$cdom,$cnum,$logentry)=@_;
 2155:     $cdom=
 2156:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2157:     $cnum=
 2158:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2159:     unless (&allowed('mky',$cdom)) { return 0; }
 2160:     unless (($cdom) && ($cnum)) { return 0; }
 2161:     if ($number>10000) { return 0; }
 2162:     sleep(2); # make sure don't get same seed twice
 2163:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2164:     my $total=0;
 2165:     for (my $i=1;$i<=$number;$i++) {
 2166:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2167:                   sprintf("%lx",int(100000*rand)).'-'.
 2168:                   sprintf("%lx",int(100000*rand));
 2169:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2170:        $newkey=~s/0/h/g; # and also 0 and O
 2171:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2172:        if ($existing{$newkey}) {
 2173:            $i--;
 2174:        } else {
 2175: 	  if (&put('accesskeys',
 2176:               { $newkey => '# generated '.localtime().
 2177:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2178:                            '; '.$logentry },
 2179: 		   $cdom,$cnum) eq 'ok') {
 2180:               $total++;
 2181: 	  }
 2182:        }
 2183:     }
 2184:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2185:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2186:     return $total;
 2187: }
 2188: 
 2189: # ------------------------------------------------------- Validate an accesskey
 2190: 
 2191: sub validate_access_key {
 2192:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2193:     $cdom=
 2194:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2195:     $cnum=
 2196:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2197:     $udom=$env{'user.domain'} unless (defined($udom));
 2198:     $uname=$env{'user.name'} unless (defined($uname));
 2199:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2200:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2201: }
 2202: 
 2203: # ------------------------------------- Find the section of student in a course
 2204: sub devalidate_getsection_cache {
 2205:     my ($udom,$unam,$courseid)=@_;
 2206:     my $hashid="$udom:$unam:$courseid";
 2207:     &devalidate_cache_new('getsection',$hashid);
 2208: }
 2209: 
 2210: sub courseid_to_courseurl {
 2211:     my ($courseid) = @_;
 2212:     #already url style courseid
 2213:     return $courseid if ($courseid =~ m{^/});
 2214: 
 2215:     if (exists($env{'course.'.$courseid.'.num'})) {
 2216: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2217: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2218: 	return "/$cdom/$cnum";
 2219:     }
 2220: 
 2221:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2222:     if (exists($courseinfo{'num'})) {
 2223: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2224:     }
 2225: 
 2226:     return undef;
 2227: }
 2228: 
 2229: sub getsection {
 2230:     my ($udom,$unam,$courseid)=@_;
 2231:     my $cachetime=1800;
 2232: 
 2233:     my $hashid="$udom:$unam:$courseid";
 2234:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2235:     if (defined($cached)) { return $result; }
 2236: 
 2237:     my %Pending; 
 2238:     my %Expired;
 2239:     #
 2240:     # Each role can either have not started yet (pending), be active, 
 2241:     #    or have expired.
 2242:     #
 2243:     # If there is an active role, we are done.
 2244:     #
 2245:     # If there is more than one role which has not started yet, 
 2246:     #     choose the one which will start sooner
 2247:     # If there is one role which has not started yet, return it.
 2248:     #
 2249:     # If there is more than one expired role, choose the one which ended last.
 2250:     # If there is a role which has expired, return it.
 2251:     #
 2252:     $courseid = &courseid_to_courseurl($courseid);
 2253:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2254:     foreach my $key (keys(%roleshash)) {
 2255:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2256:         my $section=$1;
 2257:         if ($key eq $courseid.'_st') { $section=''; }
 2258:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2259:         my $now=time;
 2260:         if (defined($end) && $end && ($now > $end)) {
 2261:             $Expired{$end}=$section;
 2262:             next;
 2263:         }
 2264:         if (defined($start) && $start && ($now < $start)) {
 2265:             $Pending{$start}=$section;
 2266:             next;
 2267:         }
 2268:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2269:     }
 2270:     #
 2271:     # Presumedly there will be few matching roles from the above
 2272:     # loop and the sorting time will be negligible.
 2273:     if (scalar(keys(%Pending))) {
 2274:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2275:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2276:     } 
 2277:     if (scalar(keys(%Expired))) {
 2278:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2279:         my $time = pop(@sorted);
 2280:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2281:     }
 2282:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2283: }
 2284: 
 2285: sub save_cache {
 2286:     &purge_remembered();
 2287:     #&Apache::loncommon::validate_page();
 2288:     undef(%env);
 2289:     undef($env_loaded);
 2290: }
 2291: 
 2292: my $to_remember=-1;
 2293: my %remembered;
 2294: my %accessed;
 2295: my $kicks=0;
 2296: my $hits=0;
 2297: sub make_key {
 2298:     my ($name,$id) = @_;
 2299:     if (length($id) > 65 
 2300: 	&& length(&escape($id)) > 200) {
 2301: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2302:     }
 2303:     return &escape($name.':'.$id);
 2304: }
 2305: 
 2306: sub devalidate_cache_new {
 2307:     my ($name,$id,$debug) = @_;
 2308:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2309:     $id=&make_key($name,$id);
 2310:     $memcache->delete($id);
 2311:     delete($remembered{$id});
 2312:     delete($accessed{$id});
 2313: }
 2314: 
 2315: sub is_cached_new {
 2316:     my ($name,$id,$debug) = @_;
 2317:     $id=&make_key($name,$id);
 2318:     if (exists($remembered{$id})) {
 2319: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2320: 	$accessed{$id}=[&gettimeofday()];
 2321: 	$hits++;
 2322: 	return ($remembered{$id},1);
 2323:     }
 2324:     my $value = $memcache->get($id);
 2325:     if (!(defined($value))) {
 2326: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2327: 	return (undef,undef);
 2328:     }
 2329:     if ($value eq '__undef__') {
 2330: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2331: 	$value=undef;
 2332:     }
 2333:     &make_room($id,$value,$debug);
 2334:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2335:     return ($value,1);
 2336: }
 2337: 
 2338: sub do_cache_new {
 2339:     my ($name,$id,$value,$time,$debug) = @_;
 2340:     $id=&make_key($name,$id);
 2341:     my $setvalue=$value;
 2342:     if (!defined($setvalue)) {
 2343: 	$setvalue='__undef__';
 2344:     }
 2345:     if (!defined($time) ) {
 2346: 	$time=600;
 2347:     }
 2348:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2349:     my $result = $memcache->set($id,$setvalue,$time);
 2350:     if (! $result) {
 2351: 	&logthis("caching of id -> $id  failed");
 2352: 	$memcache->disconnect_all();
 2353:     }
 2354:     # need to make a copy of $value
 2355:     &make_room($id,$value,$debug);
 2356:     return $value;
 2357: }
 2358: 
 2359: sub make_room {
 2360:     my ($id,$value,$debug)=@_;
 2361: 
 2362:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2363:                                     : $value;
 2364:     if ($to_remember<0) { return; }
 2365:     $accessed{$id}=[&gettimeofday()];
 2366:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2367:     my $to_kick;
 2368:     my $max_time=0;
 2369:     foreach my $other (keys(%accessed)) {
 2370: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2371: 	    $to_kick=$other;
 2372: 	    $max_time=&tv_interval($accessed{$other});
 2373: 	}
 2374:     }
 2375:     delete($remembered{$to_kick});
 2376:     delete($accessed{$to_kick});
 2377:     $kicks++;
 2378:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2379:     return;
 2380: }
 2381: 
 2382: sub purge_remembered {
 2383:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2384:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2385:     undef(%remembered);
 2386:     undef(%accessed);
 2387: }
 2388: # ------------------------------------- Read an entry from a user's environment
 2389: 
 2390: sub userenvironment {
 2391:     my ($udom,$unam,@what)=@_;
 2392:     my $items;
 2393:     foreach my $item (@what) {
 2394:         $items.=&escape($item).'&';
 2395:     }
 2396:     $items=~s/\&$//;
 2397:     my %returnhash=();
 2398:     my $uhome = &homeserver($unam,$udom);
 2399:     unless ($uhome eq 'no_host') {
 2400:         my @answer=split(/\&/, 
 2401:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2402:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2403:             return %returnhash;
 2404:         }
 2405:         my $i;
 2406:         for ($i=0;$i<=$#what;$i++) {
 2407: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2408:         }
 2409:     }
 2410:     return %returnhash;
 2411: }
 2412: 
 2413: # ---------------------------------------------------------- Get a studentphoto
 2414: sub studentphoto {
 2415:     my ($udom,$unam,$ext) = @_;
 2416:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2417:     if (defined($env{'request.course.id'})) {
 2418:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2419:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2420:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2421:             } else {
 2422:                 my ($result,$perm_reqd)=
 2423: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2424:                 if ($result eq 'ok') {
 2425:                     if (!($perm_reqd eq 'yes')) {
 2426:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2427:                     }
 2428:                 }
 2429:             }
 2430:         }
 2431:     } else {
 2432:         my ($result,$perm_reqd) = 
 2433: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2434:         if ($result eq 'ok') {
 2435:             if (!($perm_reqd eq 'yes')) {
 2436:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2437:             }
 2438:         }
 2439:     }
 2440:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2441: }
 2442: 
 2443: sub retrievestudentphoto {
 2444:     my ($udom,$unam,$ext,$type) = @_;
 2445:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2446:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2447:     if ($ret eq 'ok') {
 2448:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2449:         if ($type eq 'thumbnail') {
 2450:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2451:         }
 2452:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2453:         return $tokenurl;
 2454:     } else {
 2455:         if ($type eq 'thumbnail') {
 2456:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2457:         } else { 
 2458:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2459:         }
 2460:     }
 2461: }
 2462: 
 2463: # -------------------------------------------------------------------- New chat
 2464: 
 2465: sub chatsend {
 2466:     my ($newentry,$anon,$group)=@_;
 2467:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2468:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2469:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2470:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2471: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2472: 		   &escape($newentry)).':'.$group,$chome);
 2473: }
 2474: 
 2475: # ------------------------------------------ Find current version of a resource
 2476: 
 2477: sub getversion {
 2478:     my $fname=&clutter(shift);
 2479:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2480:     return &currentversion(&filelocation('',$fname));
 2481: }
 2482: 
 2483: sub currentversion {
 2484:     my $fname=shift;
 2485:     my $author=$fname;
 2486:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2487:     my ($udom,$uname)=split(/\//,$author);
 2488:     my $home=&homeserver($uname,$udom);
 2489:     if ($home eq 'no_host') { 
 2490:         return -1; 
 2491:     }
 2492:     my $answer=&reply("currentversion:$fname",$home);
 2493:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2494: 	return -1;
 2495:     }
 2496:     return $answer;
 2497: }
 2498: 
 2499: #
 2500: # Return special version number of resource if set by override, empty otherwise
 2501: #
 2502: sub usedversion {
 2503:     my $fname=shift;
 2504:     unless ($fname) { $fname=$env{'request.uri'}; }
 2505:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2506:     if ($urlversion) { return $urlversion; }
 2507:     return '';
 2508: }
 2509: 
 2510: # ----------------------------- Subscribe to a resource, return URL if possible
 2511: 
 2512: sub subscribe {
 2513:     my $fname=shift;
 2514:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2515:     $fname=~s/[\n\r]//g;
 2516:     my $author=$fname;
 2517:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2518:     my ($udom,$uname)=split(/\//,$author);
 2519:     my $home=homeserver($uname,$udom);
 2520:     if ($home eq 'no_host') {
 2521:         return 'not_found';
 2522:     }
 2523:     my $answer=reply("sub:$fname",$home);
 2524:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2525: 	$answer.=' by '.$home;
 2526:     }
 2527:     return $answer;
 2528: }
 2529:     
 2530: # -------------------------------------------------------------- Replicate file
 2531: 
 2532: sub repcopy {
 2533:     my $filename=shift;
 2534:     $filename=~s/\/+/\//g;
 2535:     my $londocroot = $perlvar{'lonDocRoot'};
 2536:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2537:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2538:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2539: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2540: 	return &repcopy_userfile($filename);
 2541:     }
 2542:     $filename=~s/[\n\r]//g;
 2543:     my $transname="$filename.in.transfer";
 2544: # FIXME: this should flock
 2545:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2546:     my $remoteurl=subscribe($filename);
 2547:     if ($remoteurl =~ /^con_lost by/) {
 2548: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2549:            return 'unavailable';
 2550:     } elsif ($remoteurl eq 'not_found') {
 2551: 	   #&logthis("Subscribe returned not_found: $filename");
 2552: 	   return 'not_found';
 2553:     } elsif ($remoteurl =~ /^rejected by/) {
 2554: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2555:            return 'forbidden';
 2556:     } elsif ($remoteurl eq 'directory') {
 2557:            return 'ok';
 2558:     } else {
 2559:         my $author=$filename;
 2560:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2561:         my ($udom,$uname)=split(/\//,$author);
 2562:         my $home=homeserver($uname,$udom);
 2563:         unless ($home eq $perlvar{'lonHostID'}) {
 2564:            my @parts=split(/\//,$filename);
 2565:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2566:            if ($path ne "$londocroot/res") {
 2567:                &logthis("Malconfiguration for replication: $filename");
 2568: 	       return 'bad_request';
 2569:            }
 2570:            my $count;
 2571:            for ($count=5;$count<$#parts;$count++) {
 2572:                $path.="/$parts[$count]";
 2573:                if ((-e $path)!=1) {
 2574: 		   mkdir($path,0777);
 2575:                }
 2576:            }
 2577:            my $ua=new LWP::UserAgent;
 2578:            my $request=new HTTP::Request('GET',"$remoteurl");
 2579:            my $response=$ua->request($request,$transname);
 2580:            if ($response->is_error()) {
 2581: 	       unlink($transname);
 2582:                my $message=$response->status_line;
 2583:                &logthis("<font color=\"blue\">WARNING:"
 2584:                        ." LWP get: $message: $filename</font>");
 2585:                return 'unavailable';
 2586:            } else {
 2587: 	       if ($remoteurl!~/\.meta$/) {
 2588:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2589:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2590:                   if ($mresponse->is_error()) {
 2591: 		      unlink($filename.'.meta');
 2592:                       &logthis(
 2593:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2594:                   }
 2595: 	       }
 2596:                rename($transname,$filename);
 2597:                return 'ok';
 2598:            }
 2599:        }
 2600:     }
 2601: }
 2602: 
 2603: # ------------------------------------------------ Get server side include body
 2604: sub ssi_body {
 2605:     my ($filelink,%form)=@_;
 2606:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2607:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2608:     }
 2609:     my $output='';
 2610:     my $response;
 2611:     if ($filelink=~/^https?\:/) {
 2612:        ($output,$response)=&externalssi($filelink);
 2613:     } else {
 2614:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2615:        $filelink .= 'inhibitmenu=yes';
 2616:        ($output,$response)=&ssi($filelink,%form);
 2617:     }
 2618:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2619:     $output=~s/^.*?\<body[^\>]*\>//si;
 2620:     $output=~s/\<\/body\s*\>.*?$//si;
 2621:     if (wantarray) {
 2622:         return ($output, $response);
 2623:     } else {
 2624:         return $output;
 2625:     }
 2626: }
 2627: 
 2628: # --------------------------------------------------------- Server Side Include
 2629: 
 2630: sub absolute_url {
 2631:     my ($host_name) = @_;
 2632:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2633:     if ($host_name eq '') {
 2634: 	$host_name = $ENV{'SERVER_NAME'};
 2635:     }
 2636:     return $protocol.$host_name;
 2637: }
 2638: 
 2639: #
 2640: #   Server side include.
 2641: # Parameters:
 2642: #  fn     Possibly encrypted resource name/id.
 2643: #  form   Hash that describes how the rendering should be done
 2644: #         and other things.
 2645: # Returns:
 2646: #   Scalar context: The content of the response.
 2647: #   Array context:  2 element list of the content and the full response object.
 2648: #     
 2649: sub ssi {
 2650: 
 2651:     my ($fn,%form)=@_;
 2652:     my $ua=new LWP::UserAgent;
 2653:     my $request;
 2654: 
 2655:     $form{'no_update_last_known'}=1;
 2656:     &Apache::lonenc::check_encrypt(\$fn);
 2657:     if (%form) {
 2658:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2659:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2660:     } else {
 2661:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2662:     }
 2663: 
 2664:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2665:     my $response= $ua->request($request);
 2666:     my $content = $response->content;
 2667: 
 2668: 
 2669:     if (wantarray) {
 2670: 	return ($content, $response);
 2671:     } else {
 2672: 	return $content;
 2673:     }
 2674: }
 2675: 
 2676: sub externalssi {
 2677:     my ($url)=@_;
 2678:     my $ua=new LWP::UserAgent;
 2679:     my $request=new HTTP::Request('GET',$url);
 2680:     my $response=$ua->request($request);
 2681:     if (wantarray) {
 2682:         return ($response->content, $response);
 2683:     } else {
 2684:         return $response->content;
 2685:     }
 2686: }
 2687: 
 2688: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2689: 
 2690: sub allowuploaded {
 2691:     my ($srcurl,$url)=@_;
 2692:     $url=&clutter(&declutter($url));
 2693:     my $dir=$url;
 2694:     $dir=~s/\/[^\/]+$//;
 2695:     my %httpref=();
 2696:     my $httpurl=&hreflocation('',$url);
 2697:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2698:     &Apache::lonnet::appenv(\%httpref);
 2699: }
 2700: 
 2701: #
 2702: # Determine if the current user should be able to edit a particular resource,
 2703: # when viewing in course context.
 2704: # (a) When viewing resource used to determine if "Edit" item is included in 
 2705: #     Functions.
 2706: # (b) When displaying folder contents in course editor, used to determine if
 2707: #     "Edit" link will be displayed alongside resource.
 2708: #
 2709: #  input: six args -- filename (decluttered), course number, course domain,
 2710: #                   url, symb (if registered) and group (if this is a group
 2711: #                   item -- e.g., bulletin board, group page etc.).
 2712: #  output: array of five scalars -- 
 2713: #          $cfile -- url for file editing if editable on current server
 2714: #          $home -- homeserver of resource (i.e., for author if published,
 2715: #                                           or course if uploaded.).
 2716: #          $switchserver --  1 if server switch will be needed.
 2717: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2718: #          $forceview -- 1 if icon/link should be to go to view mode
 2719: #
 2720: 
 2721: sub can_edit_resource {
 2722:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2723:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2724: #
 2725: # For aboutme pages user can only edit his/her own.
 2726: #
 2727:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2728:         my ($sdom,$sname) = ($1,$2);
 2729:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2730:             $home = $env{'user.home'};
 2731:             $cfile = $resurl;
 2732:             if ($env{'form.forceedit'}) {
 2733:                 $forceview = 1;
 2734:             } else {
 2735:                 $forceedit = 1;
 2736:             }
 2737:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2738:         } else {
 2739:             return;
 2740:         }
 2741:     }
 2742: 
 2743:     if ($env{'request.course.id'}) {
 2744:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2745:         if ($group ne '') {
 2746: # if this is a group homepage or group bulletin board, check group privs
 2747:             my $allowed = 0;
 2748:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2749:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2750:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2751:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2752:                     $allowed = 1;
 2753:                 }
 2754:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2755:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2756:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2757:                     $allowed = 1;
 2758:                 }
 2759:             }
 2760:             if ($allowed) {
 2761:                 $home=&homeserver($cnum,$cdom);
 2762:                 if ($env{'form.forceedit'}) {
 2763:                     $forceview = 1;
 2764:                 } else {
 2765:                     $forceedit = 1;
 2766:                 }
 2767:                 $cfile = $resurl;
 2768:             } else {
 2769:                 return;
 2770:             }
 2771:         } else {
 2772:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2773:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2774:                     return;
 2775:                 }
 2776:             } elsif (!$crsedit) {
 2777: #
 2778: # No edit allowed where CC has switched to student role.
 2779: #
 2780:                 return;
 2781:             }
 2782:         }
 2783:     }
 2784: 
 2785:     if ($file ne '') {
 2786:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2787:             if (&is_course_upload($file,$cnum,$cdom)) {
 2788:                 $uploaded = 1;
 2789:                 $incourse = 1;
 2790:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2791:                     $cfile = &hreflocation('',$file);
 2792:                     if ($env{'form.forceedit'}) {
 2793:                         $forceview = 1;
 2794:                     } else {
 2795:                         $forceedit = 1;
 2796:                     }
 2797:                 }
 2798:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2799:                 $incourse = 1;
 2800:                 if ($env{'form.forceedit'}) {
 2801:                     $forceview = 1;
 2802:                 } else {
 2803:                     $forceedit = 1;
 2804:                 }
 2805:                 $cfile = $resurl;
 2806:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2807:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2808:                     $incourse = 1;
 2809:                     if ($env{'form.forceedit'}) {
 2810:                         $forceview = 1;
 2811:                     } else {
 2812:                         $forceedit = 1;
 2813:                     }
 2814:                     $cfile = $resurl;
 2815:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2816:                     $incourse = 1;
 2817:                     $cfile = $resurl.'/smpedit';
 2818:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2819:                     $incourse = 1;
 2820:                     if ($env{'form.forceedit'}) {
 2821:                         $forceview = 1;
 2822:                     } else {
 2823:                         $forceedit = 1;
 2824:                     }
 2825:                     $cfile = $resurl;
 2826:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2827:                     $incourse = 1;
 2828:                     if ($env{'form.forceedit'}) {
 2829:                         $forceview = 1;
 2830:                     } else {
 2831:                         $forceedit = 1;
 2832:                     }
 2833:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2834:                 }
 2835:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2836:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2837:                 if (&is_on_map($template)) { 
 2838:                     $incourse = 1;
 2839:                     $forceview = 1;
 2840:                     $cfile = $template;
 2841:                 }
 2842:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2843:                     $incourse = 1;
 2844:                     if ($env{'form.forceedit'}) {
 2845:                         $forceview = 1;
 2846:                     } else {
 2847:                         $forceedit = 1;
 2848:                     }
 2849:                     $cfile = $resurl;
 2850:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2851:                 $incourse = 1;
 2852:                 $forceview = 1;
 2853:                 if ($symb) {
 2854:                     my ($map,$id,$res)=&decode_symb($symb);
 2855:                     $env{'request.symb'} = $symb;
 2856:                     $cfile = &clutter($res);
 2857:                 } else {
 2858:                     $cfile = $env{'form.suppurl'};
 2859:                     $cfile =~ s{^http://}{};
 2860:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2861:                 }
 2862:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2863:                 if ($env{'form.forceedit'}) {
 2864:                     $forceview = 1;
 2865:                 } else {
 2866:                     $forceedit = 1;
 2867:                 }
 2868:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2869:             }
 2870:         }
 2871:         if ($uploaded || $incourse) {
 2872:             $home=&homeserver($cnum,$cdom);
 2873:         } elsif ($file !~ m{/$}) {
 2874:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2875:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2876:             # Check that the user has permission to edit this resource
 2877:             my $setpriv = 1;
 2878:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2879:             if (defined($cfudom)) {
 2880:                 $home=&homeserver($cfuname,$cfudom);
 2881:                 $cfile=$file;
 2882:             }
 2883:         }
 2884:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2885:             (($home ne '') && ($home ne 'no_host'))) {
 2886:             my @ids=&current_machine_ids();
 2887:             unless (grep(/^\Q$home\E$/,@ids)) {
 2888:                 $switchserver=1;
 2889:             }
 2890:         }
 2891:     }
 2892:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2893: }
 2894: 
 2895: sub is_course_upload {
 2896:     my ($file,$cnum,$cdom) = @_;
 2897:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2898:     $uploadpath =~ s{^\/}{};
 2899:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2900:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2901:         return 1;
 2902:     }
 2903:     return;
 2904: }
 2905: 
 2906: sub in_course {
 2907:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2908:     if ($hideprivileged) {
 2909:         my $skipuser;
 2910:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2911:         my @possdoms = ($cdom);  
 2912:         if ($coursehash{'checkforpriv'}) { 
 2913:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2914:         }
 2915:         if (&privileged($uname,$udom,\@possdoms)) {
 2916:             $skipuser = 1;
 2917:             if ($coursehash{'nothideprivileged'}) {
 2918:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2919:                     my $user;
 2920:                     if ($item =~ /:/) {
 2921:                         $user = $item;
 2922:                     } else {
 2923:                         $user = join(':',split(/[\@]/,$item));
 2924:                     }
 2925:                     if ($user eq $uname.':'.$udom) {
 2926:                         undef($skipuser);
 2927:                         last;
 2928:                     }
 2929:                 }
 2930:             }
 2931:             if ($skipuser) {
 2932:                 return 0;
 2933:             }
 2934:         }
 2935:     }
 2936:     $type ||= 'any';
 2937:     if (!defined($cdom) || !defined($cnum)) {
 2938:         my $cid  = $env{'request.course.id'};
 2939:         $cdom = $env{'course.'.$cid.'.domain'};
 2940:         $cnum = $env{'course.'.$cid.'.num'};
 2941:     }
 2942:     my $typesref;
 2943:     if (($type eq 'any') || ($type eq 'all')) {
 2944:         $typesref = ['active','previous','future'];
 2945:     } elsif ($type eq 'previous' || $type eq 'future') {
 2946:         $typesref = [$type];
 2947:     }
 2948:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2949:                               $typesref,undef,[$cdom]);
 2950:     my ($tmp) = keys(%roles);
 2951:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2952:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2953:     if (@course_roles > 0) {
 2954:         return 1;
 2955:     }
 2956:     return 0;
 2957: }
 2958: 
 2959: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2960: # input: action, courseID, current domain, intended
 2961: #        path to file, source of file, instruction to parse file for objects,
 2962: #        ref to hash for embedded objects,
 2963: #        ref to hash for codebase of java objects.
 2964: #        reference to scalar to accommodate mime type determined
 2965: #          from File::MMagic if $parser = parse.
 2966: #
 2967: # output: url to file (if action was uploaddoc), 
 2968: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2969: #
 2970: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2971: # course.
 2972: #
 2973: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2974: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2975: #          course's home server.
 2976: #
 2977: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2978: #          be copied from $source (current location) to 
 2979: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2980: #         and will then be copied to
 2981: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2982: #         course's home server.
 2983: #
 2984: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2985: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2986: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2987: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2988: #         in course's home server.
 2989: #
 2990: 
 2991: sub process_coursefile {
 2992:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2993:         $mimetype)=@_;
 2994:     my $fetchresult;
 2995:     my $home=&homeserver($docuname,$docudom);
 2996:     if ($action eq 'propagate') {
 2997:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2998: 			     $home);
 2999:     } else {
 3000:         my $fpath = '';
 3001:         my $fname = $file;
 3002:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3003:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3004:         my $filepath = &build_filepath($fpath);
 3005:         if ($action eq 'copy') {
 3006:             if ($source eq '') {
 3007:                 $fetchresult = 'no source file';
 3008:                 return $fetchresult;
 3009:             } else {
 3010:                 my $destination = $filepath.'/'.$fname;
 3011:                 rename($source,$destination);
 3012:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3013:                                  $home);
 3014:             }
 3015:         } elsif ($action eq 'uploaddoc') {
 3016:             open(my $fh,'>'.$filepath.'/'.$fname);
 3017:             print $fh $env{'form.'.$source};
 3018:             close($fh);
 3019:             if ($parser eq 'parse') {
 3020:                 my $mm = new File::MMagic;
 3021:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3022:                 if ($type eq 'text/html') {
 3023:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3024:                     unless ($parse_result eq 'ok') {
 3025:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3026:                     }
 3027:                 }
 3028:                 if (ref($mimetype)) {
 3029:                     $$mimetype = $type;
 3030:                 } 
 3031:             }
 3032:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3033:                                  $home);
 3034:             if ($fetchresult eq 'ok') {
 3035:                 return '/uploaded/'.$fpath.'/'.$fname;
 3036:             } else {
 3037:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3038:                         ' to host '.$home.': '.$fetchresult);
 3039:                 return '/adm/notfound.html';
 3040:             }
 3041:         }
 3042:     }
 3043:     unless ( $fetchresult eq 'ok') {
 3044:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3045:              ' to host '.$home.': '.$fetchresult);
 3046:     }
 3047:     return $fetchresult;
 3048: }
 3049: 
 3050: sub build_filepath {
 3051:     my ($fpath) = @_;
 3052:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3053:     unless ($fpath eq '') {
 3054:         my @parts=split('/',$fpath);
 3055:         foreach my $part (@parts) {
 3056:             $filepath.= '/'.$part;
 3057:             if ((-e $filepath)!=1) {
 3058:                 mkdir($filepath,0777);
 3059:             }
 3060:         }
 3061:     }
 3062:     return $filepath;
 3063: }
 3064: 
 3065: sub store_edited_file {
 3066:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3067:     my $file = $primary_url;
 3068:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3069:     my $fpath = '';
 3070:     my $fname = $file;
 3071:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3072:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3073:     my $filepath = &build_filepath($fpath);
 3074:     open(my $fh,'>'.$filepath.'/'.$fname);
 3075:     print $fh $content;
 3076:     close($fh);
 3077:     my $home=&homeserver($docuname,$docudom);
 3078:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3079: 			  $home);
 3080:     if ($$fetchresult eq 'ok') {
 3081:         return '/uploaded/'.$fpath.'/'.$fname;
 3082:     } else {
 3083:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3084: 		 ' to host '.$home.': '.$$fetchresult);
 3085:         return '/adm/notfound.html';
 3086:     }
 3087: }
 3088: 
 3089: sub clean_filename {
 3090:     my ($fname,$args)=@_;
 3091: # Replace Windows backslashes by forward slashes
 3092:     $fname=~s/\\/\//g;
 3093:     if (!$args->{'keep_path'}) {
 3094:         # Get rid of everything but the actual filename
 3095: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3096:     }
 3097: # Replace spaces by underscores
 3098:     $fname=~s/\s+/\_/g;
 3099: # Replace all other weird characters by nothing
 3100:     $fname=~s{[^/\w\.\-]}{}g;
 3101: # Replace all .\d. sequences with _\d. so they no longer look like version
 3102: # numbers
 3103:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3104:     return $fname;
 3105: }
 3106: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3107: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3108: # image with the same aspect ratio as the original, but with dimensions which do 
 3109: # not exceed $resizewidth and $resizeheight.
 3110:  
 3111: sub resizeImage {
 3112:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3113:     my $ima = Image::Magick->new;
 3114:     my $resized;
 3115:     if (-e $img_path) {
 3116:         $ima->Read($img_path);
 3117:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3118:             my $width = $ima->Get('width');
 3119:             my $height = $ima->Get('height');
 3120:             if ($width > $resizewidth) {
 3121: 	        my $factor = $width/$resizewidth;
 3122:                 my $newheight = $height/$factor;
 3123:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3124:                 $resized = 1;
 3125:             }
 3126:         }
 3127:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3128:             my $width = $ima->Get('width');
 3129:             my $height = $ima->Get('height');
 3130:             if ($height > $resizeheight) {
 3131:                 my $factor = $height/$resizeheight;
 3132:                 my $newwidth = $width/$factor;
 3133:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3134:                 $resized = 1;
 3135:             }
 3136:         }
 3137:         if ($resized) {
 3138:             $ima->Write($img_path);
 3139:         }
 3140:     }
 3141:     return;
 3142: }
 3143: 
 3144: # --------------- Take an uploaded file and put it into the userfiles directory
 3145: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3146: #                    the desired filename is in $env{"form.$formname.filename"}
 3147: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3148: #                                    canceloverwrite, or ''. 
 3149: #                   if 'coursedoc': upload to the current course
 3150: #                   if 'existingfile': write file to tmp/overwrites directory 
 3151: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3152: #                   $context is passed as argument to &finishuserfileupload
 3153: #        $subdir - directory in userfile to store the file into
 3154: #        $parser - instruction to parse file for objects ($parser = parse)    
 3155: #        $allfiles - reference to hash for embedded objects
 3156: #        $codebase - reference to hash for codebase of java objects
 3157: #        $desuname - username for permanent storage of uploaded file
 3158: #        $dsetudom - domain for permanaent storage of uploaded file
 3159: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3160: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3161: #        $resizewidth - width (pixels) to which to resize uploaded image
 3162: #        $resizeheight - height (pixels) to which to resize uploaded image
 3163: #        $mimetype - reference to scalar to accommodate mime type determined
 3164: #                    from File::MMagic.
 3165: # 
 3166: # output: url of file in userspace, or error: <message> 
 3167: #             or /adm/notfound.html if failure to upload occurse
 3168: 
 3169: sub userfileupload {
 3170:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3171:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3172:     if (!defined($subdir)) { $subdir='unknown'; }
 3173:     my $fname=$env{'form.'.$formname.'.filename'};
 3174:     $fname=&clean_filename($fname);
 3175:     # See if there is anything left
 3176:     unless ($fname) { return 'error: no uploaded file'; }
 3177:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3178:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3179:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3180:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3181:         my $now = time;
 3182:         my $filepath;
 3183:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3184:              $filepath = 'tmp/helprequests/'.$now;
 3185:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3186:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3187:                          '_'.$env{'user.domain'}.'/pending';
 3188:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3189:             my ($docuname,$docudom);
 3190:             if ($destudom) {
 3191:                 $docudom = $destudom;
 3192:             } else {
 3193:                 $docudom = $env{'user.domain'};
 3194:             }
 3195:             if ($destuname) {
 3196:                 $docuname = $destuname;
 3197:             } else {
 3198:                 $docuname = $env{'user.name'};
 3199:             }
 3200:             if (exists($env{'form.group'})) {
 3201:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3202:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3203:             }
 3204:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3205:             if ($context eq 'canceloverwrite') {
 3206:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3207:                 if (-e  $tempfile) {
 3208:                     my @info = stat($tempfile);
 3209:                     if ($info[9] eq $env{'form.timestamp'}) {
 3210:                         unlink($tempfile);
 3211:                     }
 3212:                 }
 3213:                 return;
 3214:             }
 3215:         }
 3216:         # Create the directory if not present
 3217:         my @parts=split(/\//,$filepath);
 3218:         my $fullpath = $perlvar{'lonDaemons'};
 3219:         for (my $i=0;$i<@parts;$i++) {
 3220:             $fullpath .= '/'.$parts[$i];
 3221:             if ((-e $fullpath)!=1) {
 3222:                 mkdir($fullpath,0777);
 3223:             }
 3224:         }
 3225:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3226:         print $fh $env{'form.'.$formname};
 3227:         close($fh);
 3228:         if ($context eq 'existingfile') {
 3229:             my @info = stat($fullpath.'/'.$fname);
 3230:             return ($fullpath.'/'.$fname,$info[9]);
 3231:         } else {
 3232:             return $fullpath.'/'.$fname;
 3233:         }
 3234:     }
 3235:     if ($subdir eq 'scantron') {
 3236:         $fname = 'scantron_orig_'.$fname;
 3237:     } else {
 3238:         $fname="$subdir/$fname";
 3239:     }
 3240:     if ($context eq 'coursedoc') {
 3241: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3242: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3243:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3244:             return &finishuserfileupload($docuname,$docudom,
 3245: 					 $formname,$fname,$parser,$allfiles,
 3246: 					 $codebase,$thumbwidth,$thumbheight,
 3247:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3248:         } else {
 3249:             if ($env{'form.folder'}) {
 3250:                 $fname=$env{'form.folder'}.'/'.$fname;
 3251:             }
 3252:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3253: 				       $fname,$formname,$parser,
 3254: 				       $allfiles,$codebase,$mimetype);
 3255:         }
 3256:     } elsif (defined($destuname)) {
 3257:         my $docuname=$destuname;
 3258:         my $docudom=$destudom;
 3259: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3260: 				     $parser,$allfiles,$codebase,
 3261:                                      $thumbwidth,$thumbheight,
 3262:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3263:     } else {
 3264:         my $docuname=$env{'user.name'};
 3265:         my $docudom=$env{'user.domain'};
 3266:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3267:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3268:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3269:         }
 3270: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3271: 				     $parser,$allfiles,$codebase,
 3272:                                      $thumbwidth,$thumbheight,
 3273:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3274:     }
 3275: }
 3276: 
 3277: sub finishuserfileupload {
 3278:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3279:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3280:     my $path=$docudom.'/'.$docuname.'/';
 3281:     my $filepath=$perlvar{'lonDocRoot'};
 3282:   
 3283:     my ($fnamepath,$file,$fetchthumb);
 3284:     $file=$fname;
 3285:     if ($fname=~m|/|) {
 3286:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3287: 	$path.=$fnamepath.'/';
 3288:     }
 3289:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3290:     my $count;
 3291:     for ($count=4;$count<=$#parts;$count++) {
 3292:         $filepath.="/$parts[$count]";
 3293:         if ((-e $filepath)!=1) {
 3294: 	    mkdir($filepath,0777);
 3295:         }
 3296:     }
 3297: 
 3298: # Save the file
 3299:     {
 3300: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3301: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3302: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3303: 	    return '/adm/notfound.html';
 3304: 	}
 3305:         if ($context eq 'overwrite') {
 3306:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3307:             my $target = $filepath.'/'.$file;
 3308:             if (-e $source) {
 3309:                 my @info = stat($source);
 3310:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3311:                     unless (&File::Copy::move($source,$target)) {
 3312:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3313:                         return "Moving from $source failed";
 3314:                     }
 3315:                 } else {
 3316:                     return "Temporary file: $source had unexpected date/time for last modification";
 3317:                 }
 3318:             } else {
 3319:                 return "Temporary file: $source missing";
 3320:             }
 3321:         } elsif (!print FH ($env{'form.'.$formname})) {
 3322: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3323: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3324: 	    return '/adm/notfound.html';
 3325: 	}
 3326: 	close(FH);
 3327:         if ($resizewidth && $resizeheight) {
 3328:             my $mm = new File::MMagic;
 3329:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3330:             if ($mime_type =~ m{^image/}) {
 3331: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3332:             }  
 3333: 	}
 3334:     }
 3335:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3336:         if (ref($mimetype)) {
 3337:             if ($$mimetype eq '') {
 3338:                 my $mm = new File::MMagic;
 3339:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3340:                 $$mimetype = $type;
 3341:             }
 3342:         }
 3343:     }
 3344:     if ($parser eq 'parse') {
 3345:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3346:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3347:                                                        $allfiles,$codebase);
 3348:             unless ($parse_result eq 'ok') {
 3349:                 &logthis('Failed to parse '.$filepath.$file.
 3350: 	   	         ' for embedded media: '.$parse_result); 
 3351:             }
 3352:         }
 3353:     }
 3354:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3355:         my $input = $filepath.'/'.$file;
 3356:         my $output = $filepath.'/'.'tn-'.$file;
 3357:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3358:         system("convert -sample $thumbsize $input $output");
 3359:         if (-e $filepath.'/'.'tn-'.$file) {
 3360:             $fetchthumb  = 1; 
 3361:         }
 3362:     }
 3363:  
 3364: # Notify homeserver to grep it
 3365: #
 3366:     my $docuhome=&homeserver($docuname,$docudom);	
 3367:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3368:     if ($fetchresult eq 'ok') {
 3369:         if ($fetchthumb) {
 3370:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3371:             if ($thumbresult ne 'ok') {
 3372:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3373:                          $docuhome.': '.$thumbresult);
 3374:             }
 3375:         }
 3376: #
 3377: # Return the URL to it
 3378:         return '/uploaded/'.$path.$file;
 3379:     } else {
 3380:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3381: 		 ': '.$fetchresult);
 3382:         return '/adm/notfound.html';
 3383:     }
 3384: }
 3385: 
 3386: sub extract_embedded_items {
 3387:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3388:     my @state = ();
 3389:     my (%lastids,%related,%shockwave,%flashvars);
 3390:     my %javafiles = (
 3391:                       codebase => '',
 3392:                       code => '',
 3393:                       archive => ''
 3394:                     );
 3395:     my %mediafiles = (
 3396:                       src => '',
 3397:                       movie => '',
 3398:                      );
 3399:     my $p;
 3400:     if ($content) {
 3401:         $p = HTML::LCParser->new($content);
 3402:     } else {
 3403:         $p = HTML::LCParser->new($fullpath);
 3404:     }
 3405:     while (my $t=$p->get_token()) {
 3406: 	if ($t->[0] eq 'S') {
 3407: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3408: 	    push(@state, $tagname);
 3409:             if (lc($tagname) eq 'allow') {
 3410:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3411:             }
 3412: 	    if (lc($tagname) eq 'img') {
 3413: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3414: 	    }
 3415: 	    if (lc($tagname) eq 'a') {
 3416:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3417:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3418:                 }
 3419: 	    }
 3420:             if (lc($tagname) eq 'script') {
 3421:                 my $src;
 3422:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3423:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3424:                 } else {
 3425:                     if ($attr->{'src'} ne '') {
 3426:                         $src = $attr->{'src'};
 3427:                         &add_filetype($allfiles,$src,'src');
 3428:                     }
 3429:                 }
 3430:                 my $text = $p->get_trimmed_text();
 3431:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3432:                     my @swfargs = split(/,/,$1);
 3433:                     foreach my $item (@swfargs) {
 3434:                         $item =~ s/["']//g;
 3435:                         $item =~ s/^\s+//;
 3436:                         $item =~ s/\s+$//;
 3437:                     }
 3438:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3439:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3440:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3441:                         } else {
 3442:                             $related{$swfargs[0]} = [$swfargs[2]];
 3443:                         }
 3444:                     }
 3445:                 }
 3446:             }
 3447:             if (lc($tagname) eq 'link') {
 3448:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3449:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3450:                 }
 3451:             }
 3452: 	    if (lc($tagname) eq 'object' ||
 3453: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3454: 		foreach my $item (keys(%javafiles)) {
 3455: 		    $javafiles{$item} = '';
 3456: 		}
 3457:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3458:                     $lastids{lc($tagname)} = $attr->{'id'};
 3459:                 }
 3460: 	    }
 3461: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3462: 		my $name = lc($attr->{'name'});
 3463: 		foreach my $item (keys(%javafiles)) {
 3464: 		    if ($name eq $item) {
 3465: 			$javafiles{$item} = $attr->{'value'};
 3466: 			last;
 3467: 		    }
 3468: 		}
 3469:                 my $pathfrom;
 3470: 		foreach my $item (keys(%mediafiles)) {
 3471: 		    if ($name eq $item) {
 3472:                         $pathfrom = $attr->{'value'};
 3473:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3474: 			&add_filetype($allfiles,$pathfrom,$name);
 3475: 			last;
 3476: 		    }
 3477: 		}
 3478:                 if ($name eq 'flashvars') {
 3479:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3480:                 }
 3481:                 if ($pathfrom ne '') {
 3482:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3483:                                          $pathfrom);
 3484:                 }
 3485: 	    }
 3486: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3487: 		foreach my $item (keys(%javafiles)) {
 3488: 		    if ($attr->{$item}) {
 3489: 			$javafiles{$item} = $attr->{$item};
 3490: 			last;
 3491: 		    }
 3492: 		}
 3493: 		foreach my $item (keys(%mediafiles)) {
 3494: 		    if ($attr->{$item}) {
 3495: 			&add_filetype($allfiles,$attr->{$item},$item);
 3496: 			last;
 3497: 		    }
 3498: 		}
 3499:                 if (lc($tagname) eq 'embed') {
 3500:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3501:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3502:                                              $attr->{'src'});
 3503:                     }
 3504:                 }
 3505: 	    }
 3506:             if (lc($tagname) eq 'iframe') {
 3507:                 my $src = $attr->{'src'} ;
 3508:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3509:                     &add_filetype($allfiles,$src,'src');
 3510:                 } elsif ($src =~ m{^/}) {
 3511:                     if ($env{'request.course.id'}) {
 3512:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3513:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3514:                         my $url = &hreflocation('',$fullpath);
 3515:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3516:                             my $relpath = $1;
 3517:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3518:                                 &add_filetype($allfiles,$1,'src');
 3519:                             }
 3520:                         }
 3521:                     }
 3522:                 }
 3523:             }
 3524:             if ($t->[4] =~ m{/>$}) {
 3525:                 pop(@state);
 3526:             }
 3527: 	} elsif ($t->[0] eq 'E') {
 3528: 	    my ($tagname) = ($t->[1]);
 3529: 	    if ($javafiles{'codebase'} ne '') {
 3530: 		$javafiles{'codebase'} .= '/';
 3531: 	    }  
 3532: 	    if (lc($tagname) eq 'applet' ||
 3533: 		lc($tagname) eq 'object' ||
 3534: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3535: 		) {
 3536: 		foreach my $item (keys(%javafiles)) {
 3537: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3538: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3539: 			&add_filetype($allfiles,$file,$item);
 3540: 		    }
 3541: 		}
 3542: 	    } 
 3543: 	    pop @state;
 3544: 	}
 3545:     }
 3546:     foreach my $id (sort(keys(%flashvars))) {
 3547:         if ($shockwave{$id} ne '') {
 3548:             my @pairs = split(/\&/,$flashvars{$id});
 3549:             foreach my $pair (@pairs) {
 3550:                 my ($key,$value) = split(/\=/,$pair);
 3551:                 if ($key eq 'thumb') {
 3552:                     &add_filetype($allfiles,$value,$key);
 3553:                 } elsif ($key eq 'content') {
 3554:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3555:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3556:                     if ($ext ne '') {
 3557:                         &add_filetype($allfiles,$path.$value,$ext);
 3558:                     }
 3559:                 }
 3560:             }
 3561:         }
 3562:     }
 3563:     return 'ok';
 3564: }
 3565: 
 3566: sub add_filetype {
 3567:     my ($allfiles,$file,$type)=@_;
 3568:     if (exists($allfiles->{$file})) {
 3569: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3570: 	    push(@{$allfiles->{$file}}, &escape($type));
 3571: 	}
 3572:     } else {
 3573: 	@{$allfiles->{$file}} = (&escape($type));
 3574:     }
 3575: }
 3576: 
 3577: sub embedded_dependency {
 3578:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3579:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3580:         if (($identifier ne '') &&
 3581:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3582:             ($pathfrom ne '')) {
 3583:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3584:             foreach my $dep (@{$related->{$identifier}}) {
 3585:                 &add_filetype($allfiles,$path.$dep,'object');
 3586:             }
 3587:         }
 3588:     }
 3589:     return;
 3590: }
 3591: 
 3592: sub removeuploadedurl {
 3593:     my ($url)=@_;	
 3594:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3595:     return &removeuserfile($uname,$udom,$fname);
 3596: }
 3597: 
 3598: sub removeuserfile {
 3599:     my ($docuname,$docudom,$fname)=@_;
 3600:     my $home=&homeserver($docuname,$docudom);    
 3601:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3602:     if ($result eq 'ok') {	
 3603:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3604:             my $metafile = $fname.'.meta';
 3605:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3606: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3607:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3608:             my $sqlresult = 
 3609:                 &update_portfolio_table($docuname,$docudom,$file,
 3610:                                         'portfolio_metadata',$group,
 3611:                                         'delete');
 3612:         }
 3613:     }
 3614:     return $result;
 3615: }
 3616: 
 3617: sub mkdiruserfile {
 3618:     my ($docuname,$docudom,$dir)=@_;
 3619:     my $home=&homeserver($docuname,$docudom);
 3620:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3621: }
 3622: 
 3623: sub renameuserfile {
 3624:     my ($docuname,$docudom,$old,$new)=@_;
 3625:     my $home=&homeserver($docuname,$docudom);
 3626:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3627:                         &escape("$old").':'.&escape("$new"),$home);
 3628:     if ($result eq 'ok') {
 3629:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3630:             my $oldmeta = $old.'.meta';
 3631:             my $newmeta = $new.'.meta';
 3632:             my $metaresult = 
 3633:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3634: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3635:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3636:             my $sqlresult = 
 3637:                 &update_portfolio_table($docuname,$docudom,$file,
 3638:                                         'portfolio_metadata',$group,
 3639:                                         'delete');
 3640:         }
 3641:     }
 3642:     return $result;
 3643: }
 3644: 
 3645: # ------------------------------------------------------------------------- Log
 3646: 
 3647: sub log {
 3648:     my ($dom,$nam,$hom,$what)=@_;
 3649:     return critical("log:$dom:$nam:$what",$hom);
 3650: }
 3651: 
 3652: # ------------------------------------------------------------------ Course Log
 3653: #
 3654: # This routine flushes several buffers of non-mission-critical nature
 3655: #
 3656: 
 3657: sub flushcourselogs {
 3658:     &logthis('Flushing log buffers');
 3659: #
 3660: # course logs
 3661: # This is a log of all transactions in a course, which can be used
 3662: # for data mining purposes
 3663: #
 3664: # It also collects the courseid database, which lists last transaction
 3665: # times and course titles for all courseids
 3666: #
 3667:     my %courseidbuffer=();
 3668:     foreach my $crsid (keys(%courselogs)) {
 3669:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3670: 		          &escape($courselogs{$crsid}),
 3671: 		          $coursehombuf{$crsid}) eq 'ok') {
 3672: 	    delete $courselogs{$crsid};
 3673:         } else {
 3674:             &logthis('Failed to flush log buffer for '.$crsid);
 3675:             if (length($courselogs{$crsid})>40000) {
 3676:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3677:                         " exceeded maximum size, deleting.</font>");
 3678:                delete $courselogs{$crsid};
 3679:             }
 3680:         }
 3681:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3682:             'description' => $coursedescrbuf{$crsid},
 3683:             'inst_code'    => $courseinstcodebuf{$crsid},
 3684:             'type'        => $coursetypebuf{$crsid},
 3685:             'owner'       => $courseownerbuf{$crsid},
 3686:         };
 3687:     }
 3688: #
 3689: # Write course id database (reverse lookup) to homeserver of courses 
 3690: # Is used in pickcourse
 3691: #
 3692:     foreach my $crs_home (keys(%courseidbuffer)) {
 3693:         my $response = &courseidput(&host_domain($crs_home),
 3694:                                     $courseidbuffer{$crs_home},
 3695:                                     $crs_home,'timeonly');
 3696:     }
 3697: #
 3698: # File accesses
 3699: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3700: #
 3701:     foreach my $entry (keys(%accesshash)) {
 3702:         if ($entry =~ /___count$/) {
 3703:             my ($dom,$name);
 3704:             ($dom,$name,undef)=
 3705: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3706:             if (! defined($dom) || $dom eq '' || 
 3707:                 ! defined($name) || $name eq '') {
 3708:                 my $cid = $env{'request.course.id'};
 3709:                 $dom  = $env{'request.'.$cid.'.domain'};
 3710:                 $name = $env{'request.'.$cid.'.num'};
 3711:             }
 3712:             my $value = $accesshash{$entry};
 3713:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3714:             my %temphash=($url => $value);
 3715:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3716:             if ($result eq 'ok') {
 3717:                 delete $accesshash{$entry};
 3718:             }
 3719:         } else {
 3720:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3721:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3722:             my %temphash=($entry => $accesshash{$entry});
 3723:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3724:                 delete $accesshash{$entry};
 3725:             }
 3726:         }
 3727:     }
 3728: #
 3729: # Roles
 3730: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3731: #
 3732:     foreach my $entry (keys(%userrolehash)) {
 3733:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3734: 	    split(/\:/,$entry);
 3735:         if (&Apache::lonnet::put('nohist_userroles',
 3736:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3737:                 $rudom,$runame) eq 'ok') {
 3738: 	    delete $userrolehash{$entry};
 3739:         }
 3740:     }
 3741: #
 3742: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3743: #
 3744:     my %domrolebuffer = ();
 3745:     foreach my $entry (keys(%domainrolehash)) {
 3746:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3747:         if ($domrolebuffer{$rudom}) {
 3748:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3749:                       '='.&escape($domainrolehash{$entry});
 3750:         } else {
 3751:             $domrolebuffer{$rudom}.=&escape($entry).
 3752:                       '='.&escape($domainrolehash{$entry});
 3753:         }
 3754:         delete $domainrolehash{$entry};
 3755:     }
 3756:     foreach my $dom (keys(%domrolebuffer)) {
 3757: 	my %servers = &get_servers($dom,'library');
 3758: 	foreach my $tryserver (keys(%servers)) {
 3759: 	    unless (&reply('domroleput:'.$dom.':'.
 3760: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3761: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3762: 	    }
 3763:         }
 3764:     }
 3765:     $dumpcount++;
 3766: }
 3767: 
 3768: sub courselog {
 3769:     my $what=shift;
 3770:     $what=time.':'.$what;
 3771:     unless ($env{'request.course.id'}) { return ''; }
 3772:     $coursedombuf{$env{'request.course.id'}}=
 3773:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3774:     $coursenumbuf{$env{'request.course.id'}}=
 3775:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3776:     $coursehombuf{$env{'request.course.id'}}=
 3777:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3778:     $coursedescrbuf{$env{'request.course.id'}}=
 3779:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3780:     $courseinstcodebuf{$env{'request.course.id'}}=
 3781:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3782:     $courseownerbuf{$env{'request.course.id'}}=
 3783:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3784:     $coursetypebuf{$env{'request.course.id'}}=
 3785:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3786:     if (defined $courselogs{$env{'request.course.id'}}) {
 3787: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3788:     } else {
 3789: 	$courselogs{$env{'request.course.id'}}.=$what;
 3790:     }
 3791:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3792: 	&flushcourselogs();
 3793:     }
 3794: }
 3795: 
 3796: sub courseacclog {
 3797:     my $fnsymb=shift;
 3798:     unless ($env{'request.course.id'}) { return ''; }
 3799:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3800:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3801:         $what.=':POST';
 3802:         # FIXME: Probably ought to escape things....
 3803: 	foreach my $key (keys(%env)) {
 3804:             if ($key=~/^form\.(.*)/) {
 3805:                 my $formitem = $1;
 3806:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3807:                     $what.=':'.$formitem.'='.$env{$key};
 3808:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3809:                     $what.=':'.$formitem.'='.$env{$key};
 3810:                 }
 3811:             }
 3812:         }
 3813:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3814:         # FIXME: We should not be depending on a form parameter that someone
 3815:         # editing lonsearchcat.pm might change in the future.
 3816:         if ($env{'form.phase'} eq 'course_search') {
 3817:             $what.= ':POST';
 3818:             # FIXME: Probably ought to escape things....
 3819:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3820:                                  'crsdiscuss') {
 3821:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3822:             }
 3823:         }
 3824:     }
 3825:     &courselog($what);
 3826: }
 3827: 
 3828: sub countacc {
 3829:     my $url=&declutter(shift);
 3830:     return if (! defined($url) || $url eq '');
 3831:     unless ($env{'request.course.id'}) { return ''; }
 3832: #
 3833: # Mark that this url was used in this course
 3834: #
 3835:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3836: #
 3837: # Increase the access count for this resource in this child process
 3838: #
 3839:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3840:     $accesshash{$key}++;
 3841: }
 3842: 
 3843: sub linklog {
 3844:     my ($from,$to)=@_;
 3845:     $from=&declutter($from);
 3846:     $to=&declutter($to);
 3847:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3848:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3849: }
 3850: 
 3851: sub statslog {
 3852:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3853:     if ($users<2) { return; }
 3854:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3855:             'course'       => $env{'request.course.id'},
 3856:             'sections'     => '"all"',
 3857:             'num_students' => $users,
 3858:             'part'         => $part,
 3859:             'symb'         => $symb,
 3860:             'mean_tries'   => $av_attempts,
 3861:             'deg_of_diff'  => $degdiff});
 3862:     foreach my $key (keys(%dynstore)) {
 3863:         $accesshash{$key}=$dynstore{$key};
 3864:     }
 3865: }
 3866:   
 3867: sub userrolelog {
 3868:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3869:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3870:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3871:        $userrolehash
 3872:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3873:                     =$tend.':'.$tstart;
 3874:     }
 3875:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3876:        $userrolehash
 3877:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3878:                     =$tend.':'.$tstart;
 3879:     }
 3880:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3881:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3882:        $domainrolehash
 3883:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3884:                     = $tend.':'.$tstart;
 3885:     }
 3886: }
 3887: 
 3888: sub courserolelog {
 3889:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3890:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3891:         my $cdom = $1;
 3892:         my $cnum = $2;
 3893:         my $sec = $3;
 3894:         my $namespace = 'rolelog';
 3895:         my %storehash = (
 3896:                            role    => $trole,
 3897:                            start   => $tstart,
 3898:                            end     => $tend,
 3899:                            selfenroll => $selfenroll,
 3900:                            context    => $context,
 3901:                         );
 3902:         if ($trole eq 'gr') {
 3903:             $namespace = 'groupslog';
 3904:             $storehash{'group'} = $sec;
 3905:         } else {
 3906:             $storehash{'section'} = $sec;
 3907:         }
 3908:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3909:                    $domain,$cnum,$cdom);
 3910:         if (($trole ne 'st') || ($sec ne '')) {
 3911:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3912:         }
 3913:     }
 3914:     return;
 3915: }
 3916: 
 3917: sub domainrolelog {
 3918:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3919:     if ($area =~ m{^/($match_domain)/$}) {
 3920:         my $cdom = $1;
 3921:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3922:         my $namespace = 'rolelog';
 3923:         my %storehash = (
 3924:                            role    => $trole,
 3925:                            start   => $tstart,
 3926:                            end     => $tend,
 3927:                            context => $context,
 3928:                         );
 3929:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3930:                    $domain,$domconfiguser,$cdom);
 3931:     }
 3932:     return;
 3933: 
 3934: }
 3935: 
 3936: sub coauthorrolelog {
 3937:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3938:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3939:         my $audom = $1;
 3940:         my $auname = $2;
 3941:         my $namespace = 'rolelog';
 3942:         my %storehash = (
 3943:                            role    => $trole,
 3944:                            start   => $tstart,
 3945:                            end     => $tend,
 3946:                            context => $context,
 3947:                         );
 3948:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3949:                    $domain,$auname,$audom);
 3950:     }
 3951:     return;
 3952: }
 3953: 
 3954: sub get_course_adv_roles {
 3955:     my ($cid,$codes) = @_;
 3956:     $cid=$env{'request.course.id'} unless (defined($cid));
 3957:     my %coursehash=&coursedescription($cid);
 3958:     my $crstype = &Apache::loncommon::course_type($cid);
 3959:     my %nothide=();
 3960:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3961:         if ($user !~ /:/) {
 3962: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3963:         } else {
 3964:             $nothide{$user}=1;
 3965:         }
 3966:     }
 3967:     my @possdoms = ($coursehash{'domain'});
 3968:     if ($coursehash{'checkforpriv'}) {
 3969:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3970:     }
 3971:     my %returnhash=();
 3972:     my %dumphash=
 3973:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3974:     my $now=time;
 3975:     my %privileged;
 3976:     foreach my $entry (keys(%dumphash)) {
 3977: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3978:         if (($tstart) && ($tstart<0)) { next; }
 3979:         if (($tend) && ($tend<$now)) { next; }
 3980:         if (($tstart) && ($now<$tstart)) { next; }
 3981:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3982: 	if ($username eq '' || $domain eq '') { next; }
 3983:         if ((&privileged($username,$domain,\@possdoms)) &&
 3984:             (!$nothide{$username.':'.$domain})) { next; }
 3985: 	if ($role eq 'cr') { next; }
 3986:         if ($codes) {
 3987:             if ($section) { $role .= ':'.$section; }
 3988:             if ($returnhash{$role}) {
 3989:                 $returnhash{$role}.=','.$username.':'.$domain;
 3990:             } else {
 3991:                 $returnhash{$role}=$username.':'.$domain;
 3992:             }
 3993:         } else {
 3994:             my $key=&plaintext($role,$crstype);
 3995:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3996:             if ($returnhash{$key}) {
 3997: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3998:             } else {
 3999:                 $returnhash{$key}=$username.':'.$domain;
 4000:             }
 4001:         }
 4002:     }
 4003:     return %returnhash;
 4004: }
 4005: 
 4006: sub get_my_roles {
 4007:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4008:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4009:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4010:     my (%dumphash,%nothide);
 4011:     if ($context eq 'userroles') {
 4012:         %dumphash = &dump('roles',$udom,$uname);
 4013:     } else {
 4014:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4015:         if ($hidepriv) {
 4016:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4017:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4018:                 if ($user !~ /:/) {
 4019:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4020:                 } else {
 4021:                     $nothide{$user} = 1;
 4022:                 }
 4023:             }
 4024:         }
 4025:     }
 4026:     my %returnhash=();
 4027:     my $now=time;
 4028:     my %privileged;
 4029:     foreach my $entry (keys(%dumphash)) {
 4030:         my ($role,$tend,$tstart);
 4031:         if ($context eq 'userroles') {
 4032:             next if ($entry =~ /^rolesdef/);
 4033: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4034:         } else {
 4035:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4036:         }
 4037:         if (($tstart) && ($tstart<0)) { next; }
 4038:         my $status = 'active';
 4039:         if (($tend) && ($tend<=$now)) {
 4040:             $status = 'previous';
 4041:         } 
 4042:         if (($tstart) && ($now<$tstart)) {
 4043:             $status = 'future';
 4044:         }
 4045:         if (ref($types) eq 'ARRAY') {
 4046:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4047:                 next;
 4048:             } 
 4049:         } else {
 4050:             if ($status ne 'active') {
 4051:                 next;
 4052:             }
 4053:         }
 4054:         my ($rolecode,$username,$domain,$section,$area);
 4055:         if ($context eq 'userroles') {
 4056:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4057:             (undef,$domain,$username,$section) = split(/\//,$area);
 4058:         } else {
 4059:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4060:         }
 4061:         if (ref($roledoms) eq 'ARRAY') {
 4062:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4063:                 next;
 4064:             }
 4065:         }
 4066:         if (ref($roles) eq 'ARRAY') {
 4067:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4068:                 if ($role =~ /^cr\//) {
 4069:                     if (!grep(/^cr$/,@{$roles})) {
 4070:                         next;
 4071:                     }
 4072:                 } elsif ($role =~ /^gr\//) {
 4073:                     if (!grep(/^gr$/,@{$roles})) {
 4074:                         next;
 4075:                     }
 4076:                 } else {
 4077:                     next;
 4078:                 }
 4079:             }
 4080:         }
 4081:         if ($hidepriv) {
 4082:             my @privroles = ('dc','su');
 4083:             if ($context eq 'userroles') {
 4084:                 next if (grep(/^\Q$role\E$/,@privroles));
 4085:             } else {
 4086:                 my $possdoms = [$domain];
 4087:                 if (ref($roledoms) eq 'ARRAY') {
 4088:                    push(@{$possdoms},@{$roledoms}); 
 4089:                 }
 4090:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4091:                     if (!$nothide{$username.':'.$domain}) {
 4092:                         next;
 4093:                     }
 4094:                 }
 4095:             }
 4096:         }
 4097:         if ($withsec) {
 4098:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4099:                 $tstart.':'.$tend;
 4100:         } else {
 4101:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4102:         }
 4103:     }
 4104:     return %returnhash;
 4105: }
 4106: 
 4107: # ----------------------------------------------------- Frontpage Announcements
 4108: #
 4109: #
 4110: 
 4111: sub postannounce {
 4112:     my ($server,$text)=@_;
 4113:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4114:     unless ($text=~/\w/) { $text=''; }
 4115:     return &reply('setannounce:'.&escape($text),$server);
 4116: }
 4117: 
 4118: sub getannounce {
 4119: 
 4120:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4121: 	my $announcement='';
 4122: 	while (my $line = <$fh>) { $announcement .= $line; }
 4123: 	close($fh);
 4124: 	if ($announcement=~/\w/) { 
 4125: 	    return 
 4126:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4127:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4128: 	} else {
 4129: 	    return '';
 4130: 	}
 4131:     } else {
 4132: 	return '';
 4133:     }
 4134: }
 4135: 
 4136: # ---------------------------------------------------------- Course ID routines
 4137: # Deal with domain's nohist_courseid.db files
 4138: #
 4139: 
 4140: sub courseidput {
 4141:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4142:     return unless (ref($storehash) eq 'HASH');
 4143:     my $outcome;
 4144:     if ($caller eq 'timeonly') {
 4145:         my $cids = '';
 4146:         foreach my $item (keys(%$storehash)) {
 4147:             $cids.=&escape($item).'&';
 4148:         }
 4149:         $cids=~s/\&$//;
 4150:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4151:                           $coursehome);       
 4152:     } else {
 4153:         my $items = '';
 4154:         foreach my $item (keys(%$storehash)) {
 4155:             $items.= &escape($item).'='.
 4156:                      &freeze_escape($$storehash{$item}).'&';
 4157:         }
 4158:         $items=~s/\&$//;
 4159:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4160:                           $coursehome);
 4161:     }
 4162:     if ($outcome eq 'unknown_cmd') {
 4163:         my $what;
 4164:         foreach my $cid (keys(%$storehash)) {
 4165:             $what .= &escape($cid).'=';
 4166:             foreach my $item ('description','inst_code','owner','type') {
 4167:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4168:             }
 4169:             $what =~ s/\:$/&/;
 4170:         }
 4171:         $what =~ s/\&$//;  
 4172:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4173:     } else {
 4174:         return $outcome;
 4175:     }
 4176: }
 4177: 
 4178: sub courseiddump {
 4179:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4180:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4181:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4182:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4183:         $hasuniquecode)=@_;
 4184:     my $as_hash = 1;
 4185:     my %returnhash;
 4186:     if (!$domfilter) { $domfilter=''; }
 4187:     my %libserv = &all_library();
 4188:     foreach my $tryserver (keys(%libserv)) {
 4189:         if ( (  $hostidflag == 1 
 4190: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4191: 	     || (!defined($hostidflag)) ) {
 4192: 
 4193: 	    if (($domfilter eq '') ||
 4194: 		(&host_domain($tryserver) eq $domfilter)) {
 4195:                 my $rep;
 4196:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4197:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4198:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4199:                                 &escape($descfilter), &escape($instcodefilter), 
 4200:                                 &escape($ownerfilter), &escape($coursefilter),
 4201:                                 &escape($typefilter), &escape($regexp_ok), 
 4202:                                 $as_hash, &escape($selfenrollonly), 
 4203:                                 &escape($catfilter), $showhidden, $caller, 
 4204:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4205:                                 &escape($createdbefore), &escape($createdafter), 
 4206:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
 4207:                 } else {
 4208:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4209:                              $sincefilter.':'.&escape($descfilter).':'.
 4210:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4211:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4212:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4213:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4214:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4215:                              &escape($cc_clone).':'.$cloneonly.':'.
 4216:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4217:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
 4218:                              $tryserver);
 4219:                 }
 4220:                      
 4221:                 my @pairs=split(/\&/,$rep);
 4222:                 foreach my $item (@pairs) {
 4223:                     my ($key,$value)=split(/\=/,$item,2);
 4224:                     $key = &unescape($key);
 4225:                     next if ($key =~ /^error: 2 /);
 4226:                     my $result = &thaw_unescape($value);
 4227:                     if (ref($result) eq 'HASH') {
 4228:                         $returnhash{$key}=$result;
 4229:                     } else {
 4230:                         my @responses = split(/:/,$value);
 4231:                         my @items = ('description','inst_code','owner','type');
 4232:                         for (my $i=0; $i<@responses; $i++) {
 4233:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4234:                         }
 4235:                     }
 4236:                 }
 4237:             }
 4238:         }
 4239:     }
 4240:     return %returnhash;
 4241: }
 4242: 
 4243: sub courselastaccess {
 4244:     my ($cdom,$cnum,$hostidref) = @_;
 4245:     my %returnhash;
 4246:     if ($cdom && $cnum) {
 4247:         my $chome = &homeserver($cnum,$cdom);
 4248:         if ($chome ne 'no_host') {
 4249:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4250:             &extract_lastaccess(\%returnhash,$rep);
 4251:         }
 4252:     } else {
 4253:         if (!$cdom) { $cdom=''; }
 4254:         my %libserv = &all_library();
 4255:         foreach my $tryserver (keys(%libserv)) {
 4256:             if (ref($hostidref) eq 'ARRAY') {
 4257:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4258:             } 
 4259:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4260:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4261:                 &extract_lastaccess(\%returnhash,$rep);
 4262:             }
 4263:         }
 4264:     }
 4265:     return %returnhash;
 4266: }
 4267: 
 4268: sub extract_lastaccess {
 4269:     my ($returnhash,$rep) = @_;
 4270:     if (ref($returnhash) eq 'HASH') {
 4271:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4272:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4273:                  $rep eq '') {
 4274:             my @pairs=split(/\&/,$rep);
 4275:             foreach my $item (@pairs) {
 4276:                 my ($key,$value)=split(/\=/,$item,2);
 4277:                 $key = &unescape($key);
 4278:                 next if ($key =~ /^error: 2 /);
 4279:                 $returnhash->{$key} = &thaw_unescape($value);
 4280:             }
 4281:         }
 4282:     }
 4283:     return;
 4284: }
 4285: 
 4286: # ---------------------------------------------------------- DC e-mail
 4287: 
 4288: sub dcmailput {
 4289:     my ($domain,$msgid,$message,$server)=@_;
 4290:     my $status = &Apache::lonnet::critical(
 4291:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4292:        &escape($message),$server);
 4293:     return $status;
 4294: }
 4295: 
 4296: sub dcmaildump {
 4297:     my ($dom,$startdate,$enddate,$senders) = @_;
 4298:     my %returnhash=();
 4299: 
 4300:     if (defined(&domain($dom,'primary'))) {
 4301:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4302:                                                          &escape($enddate).':';
 4303: 	my @esc_senders=map { &escape($_)} @$senders;
 4304: 	$cmd.=&escape(join('&',@esc_senders));
 4305: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4306:             my ($key,$value) = split(/\=/,$line,2);
 4307:             if (($key) && ($value)) {
 4308:                 $returnhash{&unescape($key)} = &unescape($value);
 4309:             }
 4310:         }
 4311:     }
 4312:     return %returnhash;
 4313: }
 4314: # ---------------------------------------------------------- Domain roles
 4315: 
 4316: sub get_domain_roles {
 4317:     my ($dom,$roles,$startdate,$enddate)=@_;
 4318:     if ((!defined($startdate)) || ($startdate eq '')) {
 4319:         $startdate = '.';
 4320:     }
 4321:     if ((!defined($enddate)) || ($enddate eq '')) {
 4322:         $enddate = '.';
 4323:     }
 4324:     my $rolelist;
 4325:     if (ref($roles) eq 'ARRAY') {
 4326:         $rolelist = join('&',@{$roles});
 4327:     }
 4328:     my %personnel = ();
 4329: 
 4330:     my %servers = &get_servers($dom,'library');
 4331:     foreach my $tryserver (keys(%servers)) {
 4332: 	%{$personnel{$tryserver}}=();
 4333: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4334: 					    &escape($startdate).':'.
 4335: 					    &escape($enddate).':'.
 4336: 					    &escape($rolelist), $tryserver))) {
 4337: 	    my ($key,$value) = split(/\=/,$line,2);
 4338: 	    if (($key) && ($value)) {
 4339: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4340: 	    }
 4341: 	}
 4342:     }
 4343:     return %personnel;
 4344: }
 4345: 
 4346: # ----------------------------------------------------------- Interval timing 
 4347: 
 4348: {
 4349: # Caches needed for speedup of navmaps
 4350: # We don't want to cache this for very long at all (5 seconds at most)
 4351: # 
 4352: # The user for whom we cache
 4353: my $cachedkey='';
 4354: # The cached times for this user
 4355: my %cachedtimes=();
 4356: # When this was last done
 4357: my $cachedtime=();
 4358: 
 4359: sub load_all_first_access {
 4360:     my ($uname,$udom)=@_;
 4361:     if (($cachedkey eq $uname.':'.$udom) &&
 4362:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4363:         return;
 4364:     }
 4365:     $cachedtime=time;
 4366:     $cachedkey=$uname.':'.$udom;
 4367:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4368: }
 4369: 
 4370: sub get_first_access {
 4371:     my ($type,$argsymb,$argmap)=@_;
 4372:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4373:     if ($argsymb) { $symb=$argsymb; }
 4374:     my ($map,$id,$res)=&decode_symb($symb);
 4375:     if ($argmap) { $map = $argmap; }
 4376:     if ($type eq 'course') {
 4377: 	$res='course';
 4378:     } elsif ($type eq 'map') {
 4379: 	$res=&symbread($map);
 4380:     } else {
 4381: 	$res=$symb;
 4382:     }
 4383:     &load_all_first_access($uname,$udom);
 4384:     return $cachedtimes{"$courseid\0$res"};
 4385: }
 4386: 
 4387: sub set_first_access {
 4388:     my ($type,$interval)=@_;
 4389:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4390:     my ($map,$id,$res)=&decode_symb($symb);
 4391:     if ($type eq 'course') {
 4392: 	$res='course';
 4393:     } elsif ($type eq 'map') {
 4394: 	$res=&symbread($map);
 4395:     } else {
 4396: 	$res=$symb;
 4397:     }
 4398:     $cachedkey='';
 4399:     my $firstaccess=&get_first_access($type,$symb,$map);
 4400:     if (!$firstaccess) {
 4401:         my $start = time;
 4402: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4403:                           $udom,$uname);
 4404:         if ($putres eq 'ok') {
 4405:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4406:                  $udom,$uname); 
 4407:             &appenv(
 4408:                      {
 4409:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4410:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4411:                      }
 4412:                   );
 4413:         }
 4414:         return $putres;
 4415:     }
 4416:     return 'already_set';
 4417: }
 4418: }
 4419: # --------------------------------------------- Set Expire Date for Spreadsheet
 4420: 
 4421: sub expirespread {
 4422:     my ($uname,$udom,$stype,$usymb)=@_;
 4423:     my $cid=$env{'request.course.id'}; 
 4424:     if ($cid) {
 4425:        my $now=time;
 4426:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4427:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4428:                             $env{'course.'.$cid.'.num'}.
 4429: 	        	    ':nohist_expirationdates:'.
 4430:                             &escape($key).'='.$now,
 4431:                             $env{'course.'.$cid.'.home'})
 4432:     }
 4433:     return 'ok';
 4434: }
 4435: 
 4436: # ----------------------------------------------------- Devalidate Spreadsheets
 4437: 
 4438: sub devalidate {
 4439:     my ($symb,$uname,$udom)=@_;
 4440:     my $cid=$env{'request.course.id'}; 
 4441:     if ($cid) {
 4442:         # delete the stored spreadsheets for
 4443:         # - the student level sheet of this user in course's homespace
 4444:         # - the assessment level sheet for this resource 
 4445:         #   for this user in user's homespace
 4446: 	# - current conditional state info
 4447: 	my $key=$uname.':'.$udom.':';
 4448:         my $status=
 4449: 	    &del('nohist_calculatedsheets',
 4450: 		 [$key.'studentcalc:'],
 4451: 		 $env{'course.'.$cid.'.domain'},
 4452: 		 $env{'course.'.$cid.'.num'})
 4453: 		.' '.
 4454: 	    &del('nohist_calculatedsheets_'.$cid,
 4455: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4456:         unless ($status eq 'ok ok') {
 4457:            &logthis('Could not devalidate spreadsheet '.
 4458:                     $uname.' at '.$udom.' for '.
 4459: 		    $symb.': '.$status);
 4460:         }
 4461: 	&delenv('user.state.'.$cid);
 4462:     }
 4463: }
 4464: 
 4465: sub get_scalar {
 4466:     my ($string,$end) = @_;
 4467:     my $value;
 4468:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4469: 	$value = $1;
 4470:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4471: 	$value = $1;
 4472:     }
 4473:     return &unescape($value);
 4474: }
 4475: 
 4476: sub array2str {
 4477:   my (@array) = @_;
 4478:   my $result=&arrayref2str(\@array);
 4479:   $result=~s/^__ARRAY_REF__//;
 4480:   $result=~s/__END_ARRAY_REF__$//;
 4481:   return $result;
 4482: }
 4483: 
 4484: sub arrayref2str {
 4485:   my ($arrayref) = @_;
 4486:   my $result='__ARRAY_REF__';
 4487:   foreach my $elem (@$arrayref) {
 4488:     if(ref($elem) eq 'ARRAY') {
 4489:       $result.=&arrayref2str($elem).'&';
 4490:     } elsif(ref($elem) eq 'HASH') {
 4491:       $result.=&hashref2str($elem).'&';
 4492:     } elsif(ref($elem)) {
 4493:       #print("Got a ref of ".(ref($elem))." skipping.");
 4494:     } else {
 4495:       $result.=&escape($elem).'&';
 4496:     }
 4497:   }
 4498:   $result=~s/\&$//;
 4499:   $result .= '__END_ARRAY_REF__';
 4500:   return $result;
 4501: }
 4502: 
 4503: sub hash2str {
 4504:   my (%hash) = @_;
 4505:   my $result=&hashref2str(\%hash);
 4506:   $result=~s/^__HASH_REF__//;
 4507:   $result=~s/__END_HASH_REF__$//;
 4508:   return $result;
 4509: }
 4510: 
 4511: sub hashref2str {
 4512:   my ($hashref)=@_;
 4513:   my $result='__HASH_REF__';
 4514:   foreach my $key (sort(keys(%$hashref))) {
 4515:     if (ref($key) eq 'ARRAY') {
 4516:       $result.=&arrayref2str($key).'=';
 4517:     } elsif (ref($key) eq 'HASH') {
 4518:       $result.=&hashref2str($key).'=';
 4519:     } elsif (ref($key)) {
 4520:       $result.='=';
 4521:       #print("Got a ref of ".(ref($key))." skipping.");
 4522:     } else {
 4523: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4524:     }
 4525: 
 4526:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4527:       $result.=&arrayref2str($hashref->{$key}).'&';
 4528:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4529:       $result.=&hashref2str($hashref->{$key}).'&';
 4530:     } elsif(ref($hashref->{$key})) {
 4531:        $result.='&';
 4532:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4533:     } else {
 4534:       $result.=&escape($hashref->{$key}).'&';
 4535:     }
 4536:   }
 4537:   $result=~s/\&$//;
 4538:   $result .= '__END_HASH_REF__';
 4539:   return $result;
 4540: }
 4541: 
 4542: sub str2hash {
 4543:     my ($string)=@_;
 4544:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4545:     return %$hash;
 4546: }
 4547: 
 4548: sub str2hashref {
 4549:   my ($string) = @_;
 4550: 
 4551:   my %hash;
 4552: 
 4553:   if($string !~ /^__HASH_REF__/) {
 4554:       if (! ($string eq '' || !defined($string))) {
 4555: 	  $hash{'error'}='Not hash reference';
 4556:       }
 4557:       return (\%hash, $string);
 4558:   }
 4559: 
 4560:   $string =~ s/^__HASH_REF__//;
 4561: 
 4562:   while($string !~ /^__END_HASH_REF__/) {
 4563:       #key
 4564:       my $key='';
 4565:       if($string =~ /^__HASH_REF__/) {
 4566:           ($key, $string)=&str2hashref($string);
 4567:           if(defined($key->{'error'})) {
 4568:               $hash{'error'}='Bad data';
 4569:               return (\%hash, $string);
 4570:           }
 4571:       } elsif($string =~ /^__ARRAY_REF__/) {
 4572:           ($key, $string)=&str2arrayref($string);
 4573:           if($key->[0] eq 'Array reference error') {
 4574:               $hash{'error'}='Bad data';
 4575:               return (\%hash, $string);
 4576:           }
 4577:       } else {
 4578:           $string =~ s/^(.*?)=//;
 4579: 	  $key=&unescape($1);
 4580:       }
 4581:       $string =~ s/^=//;
 4582: 
 4583:       #value
 4584:       my $value='';
 4585:       if($string =~ /^__HASH_REF__/) {
 4586:           ($value, $string)=&str2hashref($string);
 4587:           if(defined($value->{'error'})) {
 4588:               $hash{'error'}='Bad data';
 4589:               return (\%hash, $string);
 4590:           }
 4591:       } elsif($string =~ /^__ARRAY_REF__/) {
 4592:           ($value, $string)=&str2arrayref($string);
 4593:           if($value->[0] eq 'Array reference error') {
 4594:               $hash{'error'}='Bad data';
 4595:               return (\%hash, $string);
 4596:           }
 4597:       } else {
 4598: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4599:       }
 4600:       $string =~ s/^&//;
 4601: 
 4602:       $hash{$key}=$value;
 4603:   }
 4604: 
 4605:   $string =~ s/^__END_HASH_REF__//;
 4606: 
 4607:   return (\%hash, $string);
 4608: }
 4609: 
 4610: sub str2array {
 4611:     my ($string)=@_;
 4612:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4613:     return @$array;
 4614: }
 4615: 
 4616: sub str2arrayref {
 4617:   my ($string) = @_;
 4618:   my @array;
 4619: 
 4620:   if($string !~ /^__ARRAY_REF__/) {
 4621:       if (! ($string eq '' || !defined($string))) {
 4622: 	  $array[0]='Array reference error';
 4623:       }
 4624:       return (\@array, $string);
 4625:   }
 4626: 
 4627:   $string =~ s/^__ARRAY_REF__//;
 4628: 
 4629:   while($string !~ /^__END_ARRAY_REF__/) {
 4630:       my $value='';
 4631:       if($string =~ /^__HASH_REF__/) {
 4632:           ($value, $string)=&str2hashref($string);
 4633:           if(defined($value->{'error'})) {
 4634:               $array[0] ='Array reference error';
 4635:               return (\@array, $string);
 4636:           }
 4637:       } elsif($string =~ /^__ARRAY_REF__/) {
 4638:           ($value, $string)=&str2arrayref($string);
 4639:           if($value->[0] eq 'Array reference error') {
 4640:               $array[0] ='Array reference error';
 4641:               return (\@array, $string);
 4642:           }
 4643:       } else {
 4644: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4645:       }
 4646:       $string =~ s/^&//;
 4647: 
 4648:       push(@array, $value);
 4649:   }
 4650: 
 4651:   $string =~ s/^__END_ARRAY_REF__//;
 4652: 
 4653:   return (\@array, $string);
 4654: }
 4655: 
 4656: # -------------------------------------------------------------------Temp Store
 4657: 
 4658: sub tmpreset {
 4659:   my ($symb,$namespace,$domain,$stuname) = @_;
 4660:   if (!$symb) {
 4661:     $symb=&symbread();
 4662:     if (!$symb) { $symb= $env{'request.url'}; }
 4663:   }
 4664:   $symb=escape($symb);
 4665: 
 4666:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4667:   $namespace=~s/\//\_/g;
 4668:   $namespace=~s/\W//g;
 4669: 
 4670:   if (!$domain) { $domain=$env{'user.domain'}; }
 4671:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4672:   if ($domain eq 'public' && $stuname eq 'public') {
 4673:       $stuname=$ENV{'REMOTE_ADDR'};
 4674:   }
 4675:   my $path=LONCAPA::tempdir();
 4676:   my %hash;
 4677:   if (tie(%hash,'GDBM_File',
 4678: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4679: 	  &GDBM_WRCREAT(),0640)) {
 4680:     foreach my $key (keys(%hash)) {
 4681:       if ($key=~ /:$symb/) {
 4682: 	delete($hash{$key});
 4683:       }
 4684:     }
 4685:   }
 4686: }
 4687: 
 4688: sub tmpstore {
 4689:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4690: 
 4691:   if (!$symb) {
 4692:     $symb=&symbread();
 4693:     if (!$symb) { $symb= $env{'request.url'}; }
 4694:   }
 4695:   $symb=escape($symb);
 4696: 
 4697:   if (!$namespace) {
 4698:     # I don't think we would ever want to store this for a course.
 4699:     # it seems this will only be used if we don't have a course.
 4700:     #$namespace=$env{'request.course.id'};
 4701:     #if (!$namespace) {
 4702:       $namespace=$env{'request.state'};
 4703:     #}
 4704:   }
 4705:   $namespace=~s/\//\_/g;
 4706:   $namespace=~s/\W//g;
 4707:   if (!$domain) { $domain=$env{'user.domain'}; }
 4708:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4709:   if ($domain eq 'public' && $stuname eq 'public') {
 4710:       $stuname=$ENV{'REMOTE_ADDR'};
 4711:   }
 4712:   my $now=time;
 4713:   my %hash;
 4714:   my $path=LONCAPA::tempdir();
 4715:   if (tie(%hash,'GDBM_File',
 4716: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4717: 	  &GDBM_WRCREAT(),0640)) {
 4718:     $hash{"version:$symb"}++;
 4719:     my $version=$hash{"version:$symb"};
 4720:     my $allkeys=''; 
 4721:     foreach my $key (keys(%$storehash)) {
 4722:       $allkeys.=$key.':';
 4723:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4724:     }
 4725:     $hash{"$version:$symb:timestamp"}=$now;
 4726:     $allkeys.='timestamp';
 4727:     $hash{"$version:keys:$symb"}=$allkeys;
 4728:     if (untie(%hash)) {
 4729:       return 'ok';
 4730:     } else {
 4731:       return "error:$!";
 4732:     }
 4733:   } else {
 4734:     return "error:$!";
 4735:   }
 4736: }
 4737: 
 4738: # -----------------------------------------------------------------Temp Restore
 4739: 
 4740: sub tmprestore {
 4741:   my ($symb,$namespace,$domain,$stuname) = @_;
 4742: 
 4743:   if (!$symb) {
 4744:     $symb=&symbread();
 4745:     if (!$symb) { $symb= $env{'request.url'}; }
 4746:   }
 4747:   $symb=escape($symb);
 4748: 
 4749:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4750: 
 4751:   if (!$domain) { $domain=$env{'user.domain'}; }
 4752:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4753:   if ($domain eq 'public' && $stuname eq 'public') {
 4754:       $stuname=$ENV{'REMOTE_ADDR'};
 4755:   }
 4756:   my %returnhash;
 4757:   $namespace=~s/\//\_/g;
 4758:   $namespace=~s/\W//g;
 4759:   my %hash;
 4760:   my $path=LONCAPA::tempdir();
 4761:   if (tie(%hash,'GDBM_File',
 4762: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4763: 	  &GDBM_READER(),0640)) {
 4764:     my $version=$hash{"version:$symb"};
 4765:     $returnhash{'version'}=$version;
 4766:     my $scope;
 4767:     for ($scope=1;$scope<=$version;$scope++) {
 4768:       my $vkeys=$hash{"$scope:keys:$symb"};
 4769:       my @keys=split(/:/,$vkeys);
 4770:       my $key;
 4771:       $returnhash{"$scope:keys"}=$vkeys;
 4772:       foreach $key (@keys) {
 4773: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4774: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4775:       }
 4776:     }
 4777:     if (!(untie(%hash))) {
 4778:       return "error:$!";
 4779:     }
 4780:   } else {
 4781:     return "error:$!";
 4782:   }
 4783:   return %returnhash;
 4784: }
 4785: 
 4786: # ----------------------------------------------------------------------- Store
 4787: 
 4788: sub store {
 4789:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4790:     my $home='';
 4791: 
 4792:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4793: 
 4794:     $symb=&symbclean($symb);
 4795:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4796: 
 4797:     if (!$domain) { $domain=$env{'user.domain'}; }
 4798:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4799: 
 4800:     &devalidate($symb,$stuname,$domain);
 4801: 
 4802:     $symb=escape($symb);
 4803:     if (!$namespace) { 
 4804:        unless ($namespace=$env{'request.course.id'}) { 
 4805:           return ''; 
 4806:        } 
 4807:     }
 4808:     if (!$home) { $home=$env{'user.home'}; }
 4809: 
 4810:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4811:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4812: 
 4813:     my $namevalue='';
 4814:     foreach my $key (keys(%$storehash)) {
 4815:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4816:     }
 4817:     $namevalue=~s/\&$//;
 4818:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4819:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4820: }
 4821: 
 4822: # -------------------------------------------------------------- Critical Store
 4823: 
 4824: sub cstore {
 4825:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4826:     my $home='';
 4827: 
 4828:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4829: 
 4830:     $symb=&symbclean($symb);
 4831:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4832: 
 4833:     if (!$domain) { $domain=$env{'user.domain'}; }
 4834:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4835: 
 4836:     &devalidate($symb,$stuname,$domain);
 4837: 
 4838:     $symb=escape($symb);
 4839:     if (!$namespace) { 
 4840:        unless ($namespace=$env{'request.course.id'}) { 
 4841:           return ''; 
 4842:        } 
 4843:     }
 4844:     if (!$home) { $home=$env{'user.home'}; }
 4845: 
 4846:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4847:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4848: 
 4849:     my $namevalue='';
 4850:     foreach my $key (keys(%$storehash)) {
 4851:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4852:     }
 4853:     $namevalue=~s/\&$//;
 4854:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4855:     return critical
 4856:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4857: }
 4858: 
 4859: # --------------------------------------------------------------------- Restore
 4860: 
 4861: sub restore {
 4862:     my ($symb,$namespace,$domain,$stuname) = @_;
 4863:     my $home='';
 4864: 
 4865:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4866: 
 4867:     if (!$symb) {
 4868:         return if ($namespace eq 'courserequests');
 4869:         unless ($symb=escape(&symbread())) { return ''; }
 4870:     } else {
 4871:         unless ($namespace eq 'courserequests') {
 4872:             $symb=&escape(&symbclean($symb));
 4873:         }
 4874:     }
 4875:     if (!$namespace) { 
 4876:        unless ($namespace=$env{'request.course.id'}) { 
 4877:           return ''; 
 4878:        } 
 4879:     }
 4880:     if (!$domain) { $domain=$env{'user.domain'}; }
 4881:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4882:     if (!$home) { $home=$env{'user.home'}; }
 4883:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4884: 
 4885:     my %returnhash=();
 4886:     foreach my $line (split(/\&/,$answer)) {
 4887: 	my ($name,$value)=split(/\=/,$line);
 4888:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4889:     }
 4890:     my $version;
 4891:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4892:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4893:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4894:        }
 4895:     }
 4896:     return %returnhash;
 4897: }
 4898: 
 4899: # ---------------------------------------------------------- Course Description
 4900: #
 4901: #  
 4902: 
 4903: sub coursedescription {
 4904:     my ($courseid,$args)=@_;
 4905:     $courseid=~s/^\///;
 4906:     $courseid=~s/\_/\//g;
 4907:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4908:     my $chome=&homeserver($cnum,$cdomain);
 4909:     my $normalid=$cdomain.'_'.$cnum;
 4910:     # need to always cache even if we get errors otherwise we keep 
 4911:     # trying and trying and trying to get the course description.
 4912:     my %envhash=();
 4913:     my %returnhash=();
 4914:     
 4915:     my $expiretime=600;
 4916:     if ($env{'request.course.id'} eq $normalid) {
 4917: 	$expiretime=120;
 4918:     }
 4919: 
 4920:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4921:     if (!$args->{'freshen_cache'}
 4922: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4923: 	foreach my $key (keys(%env)) {
 4924: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4925: 	    my ($setting) = $1;
 4926: 	    $returnhash{$setting} = $env{$key};
 4927: 	}
 4928: 	return %returnhash;
 4929:     }
 4930: 
 4931:     # get the data again
 4932: 
 4933:     if (!$args->{'one_time'}) {
 4934: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4935:     }
 4936: 
 4937:     if ($chome ne 'no_host') {
 4938:        %returnhash=&dump('environment',$cdomain,$cnum);
 4939:        if (!exists($returnhash{'con_lost'})) {
 4940: 	   my $username = $env{'user.name'}; # Defult username
 4941: 	   if(defined $args->{'user'}) {
 4942: 	       $username = $args->{'user'};
 4943: 	   }
 4944:            $returnhash{'home'}= $chome;
 4945: 	   $returnhash{'domain'} = $cdomain;
 4946: 	   $returnhash{'num'} = $cnum;
 4947:            if (!defined($returnhash{'type'})) {
 4948:                $returnhash{'type'} = 'Course';
 4949:            }
 4950:            while (my ($name,$value) = each %returnhash) {
 4951:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4952:            }
 4953:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4954:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4955: 	       $username.'_'.$cdomain.'_'.$cnum;
 4956:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4957:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4958:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4959:        }
 4960:     }
 4961:     if (!$args->{'one_time'}) {
 4962: 	&appenv(\%envhash);
 4963:     }
 4964:     return %returnhash;
 4965: }
 4966: 
 4967: sub update_released_required {
 4968:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4969:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4970:         $cid = $env{'request.course.id'};
 4971:         $cdom = $env{'course.'.$cid.'.domain'};
 4972:         $cnum = $env{'course.'.$cid.'.num'};
 4973:         $chome = $env{'course.'.$cid.'.home'};
 4974:     }
 4975:     if ($needsrelease) {
 4976:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4977:         my $needsupdate;
 4978:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4979:             $needsupdate = 1;
 4980:         } else {
 4981:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4982:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4983:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4984:                 $needsupdate = 1;
 4985:             }
 4986:         }
 4987:         if ($needsupdate) {
 4988:             my %needshash = (
 4989:                              'internal.releaserequired' => $needsrelease,
 4990:                             );
 4991:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4992:             if ($putresult eq 'ok') {
 4993:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4994:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4995:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4996:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4997:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4998:                 }
 4999:             }
 5000:         }
 5001:     }
 5002:     return;
 5003: }
 5004: 
 5005: # -------------------------------------------------See if a user is privileged
 5006: 
 5007: sub privileged {
 5008:     my ($username,$domain,$possdomains,$possroles)=@_;
 5009:     my $now = time;
 5010:     my $roles;
 5011:     if (ref($possroles) eq 'ARRAY') {
 5012:         $roles = $possroles; 
 5013:     } else {
 5014:         $roles = ['dc','su'];
 5015:     }
 5016:     if (ref($possdomains) eq 'ARRAY') {
 5017:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5018:         foreach my $dom (@{$possdomains}) {
 5019:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5020:                 (ref($privileged{$dom}) eq 'HASH')) {
 5021:                 foreach my $role (@{$roles}) {
 5022:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5023:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5024:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5025:                             return 1 unless (($end && $end < $now) ||
 5026:                                              ($start && $start > $now));
 5027:                         }
 5028:                     }
 5029:                 }
 5030:             }
 5031:         }
 5032:     } else {
 5033:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5034:         my $now = time;
 5035: 
 5036:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5037:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5038:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5039:                 return 1 unless ($tend && $tend < $now) 
 5040:                         or ($tstart && $tstart > $now);
 5041:             }
 5042:         }
 5043:     }
 5044:     return 0;
 5045: }
 5046: 
 5047: sub privileged_by_domain {
 5048:     my ($domains,$roles) = @_;
 5049:     my %privileged = ();
 5050:     my $cachetime = 60*60*24;
 5051:     my $now = time;
 5052:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5053:         return %privileged;
 5054:     }
 5055:     foreach my $dom (@{$domains}) {
 5056:         next if (ref($privileged{$dom}) eq 'HASH');
 5057:         my $needroles;
 5058:         foreach my $role (@{$roles}) {
 5059:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5060:             if (defined($cached)) {
 5061:                 if (ref($result) eq 'HASH') {
 5062:                     $privileged{$dom}{$role} = $result;
 5063:                 }
 5064:             } else {
 5065:                 $needroles = 1;
 5066:             }
 5067:         }
 5068:         if ($needroles) {
 5069:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5070:             $privileged{$dom} = {};
 5071:             foreach my $server (keys(%dompersonnel)) {
 5072:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5073:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5074:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5075:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5076:                         next if ($end && $end < $now);
 5077:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5078:                             $dompersonnel{$server}{$item};
 5079:                     }
 5080:                 }
 5081:             }
 5082:             if (ref($privileged{$dom}) eq 'HASH') {
 5083:                 foreach my $role (@{$roles}) {
 5084:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5085:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5086:                     } else {
 5087:                         my %hash = ();
 5088:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5089:                     }
 5090:                 }
 5091:             }
 5092:         }
 5093:     }
 5094:     return %privileged;
 5095: }
 5096: 
 5097: # -------------------------------------------------------- Get user privileges
 5098: 
 5099: sub rolesinit {
 5100:     my ($domain, $username) = @_;
 5101:     my %userroles = ('user.login.time' => time);
 5102:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5103: 
 5104:     # firstaccess and timerinterval are related to timed maps/resources. 
 5105:     # also, blocking can be triggered by an activating timer
 5106:     # it's saved in the user's %env.
 5107:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5108:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5109:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5110:         %timerintchk, %timerintenv);
 5111: 
 5112:     foreach my $key (keys(%firstaccess)) {
 5113:         my ($cid, $rest) = split(/\0/, $key);
 5114:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5115:     }
 5116: 
 5117:     foreach my $key (keys(%timerinterval)) {
 5118:         my ($cid,$rest) = split(/\0/,$key);
 5119:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5120:     }
 5121: 
 5122:     my %allroles=();
 5123:     my %allgroups=();
 5124: 
 5125:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5126:         my $role = $rolesdump{$area};
 5127:         $area =~ s/\_\w\w$//;
 5128: 
 5129:         my ($trole, $tend, $tstart, $group_privs);
 5130: 
 5131:         if ($role =~ /^cr/) {
 5132:         # Custom role, defined by a user 
 5133:         # e.g., user.role.cr/msu/smith/mynewrole
 5134:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5135:                 $trole = $1;
 5136:                 ($tend, $tstart) = split('_', $2);
 5137:             } else {
 5138:                 $trole = $role;
 5139:             }
 5140:         } elsif ($role =~ m|^gr/|) {
 5141:         # Role of member in a group, defined within a course/community
 5142:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5143:             ($trole, $tend, $tstart) = split(/_/, $role);
 5144:             next if $tstart eq '-1';
 5145:             ($trole, $group_privs) = split(/\//, $trole);
 5146:             $group_privs = &unescape($group_privs);
 5147:         } else {
 5148:         # Just a normal role, defined in roles.tab
 5149:             ($trole, $tend, $tstart) = split(/_/,$role);
 5150:         }
 5151: 
 5152:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5153:                  $username);
 5154:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5155: 
 5156:         # role expired or not available yet?
 5157:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5158:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5159: 
 5160:         next if $area eq '' or $trole eq '';
 5161: 
 5162:         my $spec = "$trole.$area";
 5163:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5164: 
 5165:         if ($trole =~ /^cr\//) {
 5166:         # Custom role, defined by a user
 5167:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5168:         } elsif ($trole eq 'gr') {
 5169:         # Role of a member in a group, defined within a course/community
 5170:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5171:             next;
 5172:         } else {
 5173:         # Normal role, defined in roles.tab
 5174:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5175:         }
 5176: 
 5177:         my $cid = $tdomain.'_'.$trest;
 5178:         unless ($firstaccchk{$cid}) {
 5179:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5180:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5181:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5182:                         $coursetimerstarts{$cid}{$item}; 
 5183:                 }
 5184:             }
 5185:             $firstaccchk{$cid} = 1;
 5186:         }
 5187:         unless ($timerintchk{$cid}) {
 5188:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5189:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5190:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5191:                        $coursetimerintervals{$cid}{$item};
 5192:                 }
 5193:             }
 5194:             $timerintchk{$cid} = 1;
 5195:         }
 5196:     }
 5197: 
 5198:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5199:         \%allroles, \%allgroups);
 5200:     $env{'user.adv'} = $userroles{'user.adv'};
 5201: 
 5202:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5203: }
 5204: 
 5205: sub set_arearole {
 5206:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5207:     unless ($nolog) {
 5208: # log the associated role with the area
 5209:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5210:     }
 5211:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5212: }
 5213: 
 5214: sub custom_roleprivs {
 5215:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5216:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5217:     my $homsvr = &homeserver($rauthor,$rdomain);
 5218:     if (&hostname($homsvr) ne '') {
 5219:         my ($rdummy,$roledef)=
 5220:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5221:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5222:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5223:             if (defined($syspriv)) {
 5224:                 if ($trest =~ /^$match_community$/) {
 5225:                     $syspriv =~ s/bre\&S//; 
 5226:                 }
 5227:                 $$allroles{'cm./'}.=':'.$syspriv;
 5228:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5229:             }
 5230:             if ($tdomain ne '') {
 5231:                 if (defined($dompriv)) {
 5232:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5233:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5234:                 }
 5235:                 if (($trest ne '') && (defined($coursepriv))) {
 5236:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5237:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5238:                 }
 5239:             }
 5240:         }
 5241:     }
 5242: }
 5243: 
 5244: sub group_roleprivs {
 5245:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5246:     my $access = 1;
 5247:     my $now = time;
 5248:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5249:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5250:     if ($access) {
 5251:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5252:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5253:     }
 5254: }
 5255: 
 5256: sub standard_roleprivs {
 5257:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5258:     if (defined($pr{$trole.':s'})) {
 5259:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5260:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5261:     }
 5262:     if ($tdomain ne '') {
 5263:         if (defined($pr{$trole.':d'})) {
 5264:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5265:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5266:         }
 5267:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5268:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5269:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5270:         }
 5271:     }
 5272: }
 5273: 
 5274: sub set_userprivs {
 5275:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5276:     my $author=0;
 5277:     my $adv=0;
 5278:     my %grouproles = ();
 5279:     if (keys(%{$allgroups}) > 0) {
 5280:         my @groupkeys; 
 5281:         foreach my $role (keys(%{$allroles})) {
 5282:             push(@groupkeys,$role);
 5283:         }
 5284:         if (ref($groups_roles) eq 'HASH') {
 5285:             foreach my $key (keys(%{$groups_roles})) {
 5286:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5287:                     push(@groupkeys,$key);
 5288:                 }
 5289:             }
 5290:         }
 5291:         if (@groupkeys > 0) {
 5292:             foreach my $role (@groupkeys) {
 5293:                 my ($trole,$area,$sec,$extendedarea);
 5294:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5295:                     $trole = $1;
 5296:                     $area = $2;
 5297:                     $sec = $3;
 5298:                     $extendedarea = $area.$sec;
 5299:                     if (exists($$allgroups{$area})) {
 5300:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5301:                             my $spec = $trole.'.'.$extendedarea;
 5302:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5303:                                                 $$allgroups{$area}{$group};
 5304:                         }
 5305:                     }
 5306:                 }
 5307:             }
 5308:         }
 5309:     }
 5310:     foreach my $group (keys(%grouproles)) {
 5311:         $$allroles{$group} = $grouproles{$group};
 5312:     }
 5313:     foreach my $role (keys(%{$allroles})) {
 5314:         my %thesepriv;
 5315:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5316:         foreach my $item (split(/:/,$$allroles{$role})) {
 5317:             if ($item ne '') {
 5318:                 my ($privilege,$restrictions)=split(/&/,$item);
 5319:                 if ($restrictions eq '') {
 5320:                     $thesepriv{$privilege}='F';
 5321:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5322:                     $thesepriv{$privilege}.=$restrictions;
 5323:                 }
 5324:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5325:             }
 5326:         }
 5327:         my $thesestr='';
 5328:         foreach my $priv (sort(keys(%thesepriv))) {
 5329: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5330: 	}
 5331:         $userroles->{'user.priv.'.$role} = $thesestr;
 5332:     }
 5333:     return ($author,$adv);
 5334: }
 5335: 
 5336: sub role_status {
 5337:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5338:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5339:         my ($one,$two) = split(m{\./},$rolekey,2);
 5340:         (undef,undef,$$role) = split(/\./,$one,3);
 5341:         unless (!defined($$role) || $$role eq '') {
 5342:             $$where = '/'.$two;
 5343:             $$trolecode=$$role.'.'.$$where;
 5344:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5345:             $$tstatus='is';
 5346:             if ($$tstart && $$tstart>$update) {
 5347:                 $$tstatus='future';
 5348:                 if ($$tstart<$now) {
 5349:                     if ($$tstart && $$tstart>$refresh) {
 5350:                         if (($$where ne '') && ($$role ne '')) {
 5351:                             my (%allroles,%allgroups,$group_privs,
 5352:                                 %groups_roles,@rolecodes);
 5353:                             my %userroles = (
 5354:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5355:                             );
 5356:                             @rolecodes = ('cm'); 
 5357:                             my $spec=$$role.'.'.$$where;
 5358:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5359:                             if ($$role =~ /^cr\//) {
 5360:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5361:                                 push(@rolecodes,'cr');
 5362:                             } elsif ($$role eq 'gr') {
 5363:                                 push(@rolecodes,$$role);
 5364:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5365:                                                     $env{'user.name'});
 5366:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5367:                                 (undef,my $group_privs) = split(/\//,$trole);
 5368:                                 $group_privs = &unescape($group_privs);
 5369:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5370:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5371:                                 &get_groups_roles($tdomain,$trest,
 5372:                                                   \%course_roles,\@rolecodes,
 5373:                                                   \%groups_roles);
 5374:                             } else {
 5375:                                 push(@rolecodes,$$role);
 5376:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5377:                             }
 5378:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5379:                             &appenv(\%userroles,\@rolecodes);
 5380:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5381:                         }
 5382:                     }
 5383:                     $$tstatus = 'is';
 5384:                 }
 5385:             }
 5386:             if ($$tend) {
 5387:                 if ($$tend<$update) {
 5388:                     $$tstatus='expired';
 5389:                 } elsif ($$tend<$now) {
 5390:                     $$tstatus='will_not';
 5391:                 }
 5392:             }
 5393:         }
 5394:     }
 5395: }
 5396: 
 5397: sub get_groups_roles {
 5398:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5399:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5400:                   (ref($rolecodes) eq 'ARRAY') && 
 5401:                   (ref($groups_roles) eq 'HASH')); 
 5402:     if (keys(%{$cdom_courseroles}) > 0) {
 5403:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5404:         if ($cdom ne '' && $cnum ne '') {
 5405:             foreach my $key (keys(%{$cdom_courseroles})) {
 5406:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5407:                     my $crsrole = $1;
 5408:                     my $crssec = $2;
 5409:                     if ($crsrole =~ /^cr/) {
 5410:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5411:                             push(@{$rolecodes},'cr');
 5412:                         }
 5413:                     } else {
 5414:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5415:                             push(@{$rolecodes},$crsrole);
 5416:                         }
 5417:                     }
 5418:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5419:                     if ($crssec ne '') {
 5420:                         $rolekey .= "/$crssec";
 5421:                     }
 5422:                     $rolekey .= './';
 5423:                     $groups_roles->{$rolekey} = $rolecodes;
 5424:                 }
 5425:             }
 5426:         }
 5427:     }
 5428:     return;
 5429: }
 5430: 
 5431: sub delete_env_groupprivs {
 5432:     my ($where,$courseroles,$possroles) = @_;
 5433:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5434:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5435:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5436:         %{$courseroles->{$udom}} =
 5437:             &get_my_roles('','','userroles',['active'],
 5438:                           $possroles,[$udom],1);
 5439:     }
 5440:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5441:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5442:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5443:             my $area = '/'.$cdom.'/'.$cnum;
 5444:             my $privkey = "user.priv.$crsrole.$area";
 5445:             if ($crssec ne '') {
 5446:                 $privkey .= '/'.$crssec;
 5447:             }
 5448:             $privkey .= ".$area/$group";
 5449:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5450:         }
 5451:     }
 5452:     return;
 5453: }
 5454: 
 5455: sub check_adhoc_privs {
 5456:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5457:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5458:     my $setprivs;
 5459:     if ($env{$cckey}) {
 5460:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5461:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5462:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5463:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5464:             $setprivs = 1;
 5465:         }
 5466:     } else {
 5467:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5468:         $setprivs = 1;
 5469:     }
 5470:     return $setprivs;
 5471: }
 5472: 
 5473: sub set_adhoc_privileges {
 5474: # role can be cc or ca
 5475:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5476:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5477:     my $spec = $role.'.'.$area;
 5478:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5479:                                   $env{'user.name'},1);
 5480:     my %ccrole = ();
 5481:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5482:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5483:     &appenv(\%userroles,[$role,'cm']);
 5484:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5485:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5486:         &appenv( {'request.role'        => $spec,
 5487:                   'request.role.domain' => $dcdom,
 5488:                   'request.course.sec'  => ''
 5489:                  }
 5490:                );
 5491:         my $tadv=0;
 5492:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5493:         &appenv({'request.role.adv'    => $tadv});
 5494:     }
 5495: }
 5496: 
 5497: # --------------------------------------------------------------- get interface
 5498: 
 5499: sub get {
 5500:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5501:    my $items='';
 5502:    foreach my $item (@$storearr) {
 5503:        $items.=&escape($item).'&';
 5504:    }
 5505:    $items=~s/\&$//;
 5506:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5507:    if (!$uname) { $uname=$env{'user.name'}; }
 5508:    my $uhome=&homeserver($uname,$udomain);
 5509: 
 5510:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5511:    my @pairs=split(/\&/,$rep);
 5512:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5513:      return @pairs;
 5514:    }
 5515:    my %returnhash=();
 5516:    my $i=0;
 5517:    foreach my $item (@$storearr) {
 5518:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5519:       $i++;
 5520:    }
 5521:    return %returnhash;
 5522: }
 5523: 
 5524: # --------------------------------------------------------------- del interface
 5525: 
 5526: sub del {
 5527:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5528:    my $items='';
 5529:    foreach my $item (@$storearr) {
 5530:        $items.=&escape($item).'&';
 5531:    }
 5532: 
 5533:    $items=~s/\&$//;
 5534:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5535:    if (!$uname) { $uname=$env{'user.name'}; }
 5536:    my $uhome=&homeserver($uname,$udomain);
 5537:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5538: }
 5539: 
 5540: # -------------------------------------------------------------- dump interface
 5541: 
 5542: sub unserialize {
 5543:     my ($rep, $escapedkeys) = @_;
 5544: 
 5545:     return {} if $rep =~ /^error/;
 5546: 
 5547:     my %returnhash=();
 5548: 	foreach my $item (split(/\&/,$rep)) {
 5549: 	    my ($key, $value) = split(/=/, $item, 2);
 5550: 	    $key = unescape($key) unless $escapedkeys;
 5551: 	    next if $key =~ /^error: 2 /;
 5552: 	    $returnhash{$key} = &thaw_unescape($value);
 5553: 	}
 5554:     #return %returnhash;
 5555:     return \%returnhash;
 5556: }        
 5557: 
 5558: # see Lond::dump_with_regexp
 5559: # if $escapedkeys hash keys won't get unescaped.
 5560: sub dump {
 5561:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5562:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5563:     if (!$uname) { $uname=$env{'user.name'}; }
 5564:     my $uhome=&homeserver($uname,$udomain);
 5565: 
 5566:     my $reply;
 5567:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5568:         # user is hosted on this machine
 5569:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5570:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5571:         return %{unserialize($reply, $escapedkeys)};
 5572:     }
 5573:     if ($regexp) {
 5574: 	$regexp=&escape($regexp);
 5575:     } else {
 5576: 	$regexp='.';
 5577:     }
 5578:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5579:     my @pairs=split(/\&/,$rep);
 5580:     my %returnhash=();
 5581:     if (!($rep =~ /^error/ )) {
 5582: 	foreach my $item (@pairs) {
 5583: 	    my ($key,$value)=split(/=/,$item,2);
 5584:         $key = unescape($key) unless $escapedkeys;
 5585:         #$key = &unescape($key);
 5586: 	    next if ($key =~ /^error: 2 /);
 5587: 	    $returnhash{$key}=&thaw_unescape($value);
 5588: 	}
 5589:     }
 5590:     return %returnhash;
 5591: }
 5592: 
 5593: 
 5594: # --------------------------------------------------------- dumpstore interface
 5595: 
 5596: sub dumpstore {
 5597:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5598:    # same as dump but keys must be escaped. They may contain colon separated
 5599:    # lists of values that may themself contain colons (e.g. symbs).
 5600:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5601: }
 5602: 
 5603: # -------------------------------------------------------------- keys interface
 5604: 
 5605: sub getkeys {
 5606:    my ($namespace,$udomain,$uname)=@_;
 5607:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5608:    if (!$uname) { $uname=$env{'user.name'}; }
 5609:    my $uhome=&homeserver($uname,$udomain);
 5610:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5611:    my @keyarray=();
 5612:    foreach my $key (split(/\&/,$rep)) {
 5613:       next if ($key =~ /^error: 2 /);
 5614:       push(@keyarray,&unescape($key));
 5615:    }
 5616:    return @keyarray;
 5617: }
 5618: 
 5619: # --------------------------------------------------------------- currentdump
 5620: sub currentdump {
 5621:    my ($courseid,$sdom,$sname)=@_;
 5622:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5623:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5624:    $sname    = $env{'user.name'}         if (! defined($sname));
 5625:    my $uhome = &homeserver($sname,$sdom);
 5626:    my $rep;
 5627: 
 5628:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5629:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5630:                    $courseid)));
 5631:    } else {
 5632:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5633:    }
 5634: 
 5635:    return if ($rep =~ /^(error:|no_such_host)/);
 5636:    #
 5637:    my %returnhash=();
 5638:    #
 5639:    if ($rep eq "unknown_cmd") { 
 5640:        # an old lond will not know currentdump
 5641:        # Do a dump and make it look like a currentdump
 5642:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5643:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5644:        my %hash = @tmp;
 5645:        @tmp=();
 5646:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5647:    } else {
 5648:        my @pairs=split(/\&/,$rep);
 5649:        foreach my $pair (@pairs) {
 5650:            my ($key,$value)=split(/=/,$pair,2);
 5651:            my ($symb,$param) = split(/:/,$key);
 5652:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5653:                                                         &thaw_unescape($value);
 5654:        }
 5655:    }
 5656:    return %returnhash;
 5657: }
 5658: 
 5659: sub convert_dump_to_currentdump{
 5660:     my %hash = %{shift()};
 5661:     my %returnhash;
 5662:     # Code ripped from lond, essentially.  The only difference
 5663:     # here is the unescaping done by lonnet::dump().  Conceivably
 5664:     # we might run in to problems with parameter names =~ /^v\./
 5665:     while (my ($key,$value) = each(%hash)) {
 5666:         my ($v,$symb,$param) = split(/:/,$key);
 5667: 	$symb  = &unescape($symb);
 5668: 	$param = &unescape($param);
 5669:         next if ($v eq 'version' || $symb eq 'keys');
 5670:         next if (exists($returnhash{$symb}) &&
 5671:                  exists($returnhash{$symb}->{$param}) &&
 5672:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5673:         $returnhash{$symb}->{$param}=$value;
 5674:         $returnhash{$symb}->{'v.'.$param}=$v;
 5675:     }
 5676:     #
 5677:     # Remove all of the keys in the hashes which keep track of
 5678:     # the version of the parameter.
 5679:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5680:         # use a foreach because we are going to delete from the hash.
 5681:         foreach my $key (keys(%$param_hash)) {
 5682:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5683:         }
 5684:     }
 5685:     return \%returnhash;
 5686: }
 5687: 
 5688: # ------------------------------------------------------ critical inc interface
 5689: 
 5690: sub cinc {
 5691:     return &inc(@_,'critical');
 5692: }
 5693: 
 5694: # --------------------------------------------------------------- inc interface
 5695: 
 5696: sub inc {
 5697:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5698:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5699:     if (!$uname) { $uname=$env{'user.name'}; }
 5700:     my $uhome=&homeserver($uname,$udomain);
 5701:     my $items='';
 5702:     if (! ref($store)) {
 5703:         # got a single value, so use that instead
 5704:         $items = &escape($store).'=&';
 5705:     } elsif (ref($store) eq 'SCALAR') {
 5706:         $items = &escape($$store).'=&';        
 5707:     } elsif (ref($store) eq 'ARRAY') {
 5708:         $items = join('=&',map {&escape($_);} @{$store});
 5709:     } elsif (ref($store) eq 'HASH') {
 5710:         while (my($key,$value) = each(%{$store})) {
 5711:             $items.= &escape($key).'='.&escape($value).'&';
 5712:         }
 5713:     }
 5714:     $items=~s/\&$//;
 5715:     if ($critical) {
 5716: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5717:     } else {
 5718: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5719:     }
 5720: }
 5721: 
 5722: # --------------------------------------------------------------- put interface
 5723: 
 5724: sub put {
 5725:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5726:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5727:    if (!$uname) { $uname=$env{'user.name'}; }
 5728:    my $uhome=&homeserver($uname,$udomain);
 5729:    my $items='';
 5730:    foreach my $item (keys(%$storehash)) {
 5731:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5732:    }
 5733:    $items=~s/\&$//;
 5734:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5735: }
 5736: 
 5737: # ------------------------------------------------------------ newput interface
 5738: 
 5739: sub newput {
 5740:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5741:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5742:    if (!$uname) { $uname=$env{'user.name'}; }
 5743:    my $uhome=&homeserver($uname,$udomain);
 5744:    my $items='';
 5745:    foreach my $key (keys(%$storehash)) {
 5746:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5747:    }
 5748:    $items=~s/\&$//;
 5749:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5750: }
 5751: 
 5752: # ---------------------------------------------------------  putstore interface
 5753: 
 5754: sub putstore {
 5755:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5756:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5757:    if (!$uname) { $uname=$env{'user.name'}; }
 5758:    my $uhome=&homeserver($uname,$udomain);
 5759:    my $items='';
 5760:    foreach my $key (keys(%$storehash)) {
 5761:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5762:    }
 5763:    $items=~s/\&$//;
 5764:    my $esc_symb=&escape($symb);
 5765:    my $esc_v=&escape($version);
 5766:    my $reply =
 5767:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5768: 	      $uhome);
 5769:    if ($reply eq 'unknown_cmd') {
 5770:        # gfall back to way things use to be done
 5771:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5772: 			    $uname);
 5773:    }
 5774:    return $reply;
 5775: }
 5776: 
 5777: sub old_putstore {
 5778:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5779:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5780:     if (!$uname) { $uname=$env{'user.name'}; }
 5781:     my $uhome=&homeserver($uname,$udomain);
 5782:     my %newstorehash;
 5783:     foreach my $item (keys(%$storehash)) {
 5784: 	my $key = $version.':'.&escape($symb).':'.$item;
 5785: 	$newstorehash{$key} = $storehash->{$item};
 5786:     }
 5787:     my $items='';
 5788:     my %allitems = ();
 5789:     foreach my $item (keys(%newstorehash)) {
 5790: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5791: 	    my $key = $1.':keys:'.$2;
 5792: 	    $allitems{$key} .= $3.':';
 5793: 	}
 5794: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5795:     }
 5796:     foreach my $item (keys(%allitems)) {
 5797: 	$allitems{$item} =~ s/\:$//;
 5798: 	$items.= $item.'='.$allitems{$item}.'&';
 5799:     }
 5800:     $items=~s/\&$//;
 5801:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5802: }
 5803: 
 5804: # ------------------------------------------------------ critical put interface
 5805: 
 5806: sub cput {
 5807:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5808:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5809:    if (!$uname) { $uname=$env{'user.name'}; }
 5810:    my $uhome=&homeserver($uname,$udomain);
 5811:    my $items='';
 5812:    foreach my $item (keys(%$storehash)) {
 5813:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5814:    }
 5815:    $items=~s/\&$//;
 5816:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5817: }
 5818: 
 5819: # -------------------------------------------------------------- eget interface
 5820: 
 5821: sub eget {
 5822:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5823:    my $items='';
 5824:    foreach my $item (@$storearr) {
 5825:        $items.=&escape($item).'&';
 5826:    }
 5827:    $items=~s/\&$//;
 5828:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5829:    if (!$uname) { $uname=$env{'user.name'}; }
 5830:    my $uhome=&homeserver($uname,$udomain);
 5831:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5832:    my @pairs=split(/\&/,$rep);
 5833:    my %returnhash=();
 5834:    my $i=0;
 5835:    foreach my $item (@$storearr) {
 5836:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5837:       $i++;
 5838:    }
 5839:    return %returnhash;
 5840: }
 5841: 
 5842: # ------------------------------------------------------------ tmpput interface
 5843: sub tmpput {
 5844:     my ($storehash,$server,$context)=@_;
 5845:     my $items='';
 5846:     foreach my $item (keys(%$storehash)) {
 5847: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5848:     }
 5849:     $items=~s/\&$//;
 5850:     if (defined($context)) {
 5851:         $items .= ':'.&escape($context);
 5852:     }
 5853:     return &reply("tmpput:$items",$server);
 5854: }
 5855: 
 5856: # ------------------------------------------------------------ tmpget interface
 5857: sub tmpget {
 5858:     my ($token,$server)=@_;
 5859:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5860:     my $rep=&reply("tmpget:$token",$server);
 5861:     my %returnhash;
 5862:     foreach my $item (split(/\&/,$rep)) {
 5863: 	my ($key,$value)=split(/=/,$item);
 5864:         next if ($key =~ /^error: 2 /);
 5865: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5866:     }
 5867:     return %returnhash;
 5868: }
 5869: 
 5870: # ------------------------------------------------------------ tmpdel interface
 5871: sub tmpdel {
 5872:     my ($token,$server)=@_;
 5873:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5874:     return &reply("tmpdel:$token",$server);
 5875: }
 5876: 
 5877: # ------------------------------------------------------------ get_timebased_id 
 5878: 
 5879: sub get_timebased_id {
 5880:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5881:         $maxtries) = @_;
 5882:     my ($newid,$error,$dellock);
 5883:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5884:         return ('','ok','invalid call to get suffix');
 5885:     }
 5886: 
 5887: # set defaults for any optional args for which values were not supplied
 5888:     if ($who eq '') {
 5889:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5890:     }
 5891:     if (!$locktries) {
 5892:         $locktries = 3;
 5893:     }
 5894:     if (!$maxtries) {
 5895:         $maxtries = 10;
 5896:     }
 5897:     
 5898:     if (($cdom eq '') || ($cnum eq '')) {
 5899:         if ($env{'request.course.id'}) {
 5900:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5901:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5902:         }
 5903:         if (($cdom eq '') || ($cnum eq '')) {
 5904:             return ('','ok','call to get suffix not in course context');
 5905:         }
 5906:     }
 5907: 
 5908: # construct locking item
 5909:     my $lockhash = {
 5910:                       $prefix."\0".'locked_'.$keyid => $who,
 5911:                    };
 5912:     my $tries = 0;
 5913: 
 5914: # attempt to get lock on nohist_$namespace file
 5915:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5916:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5917:         $tries ++;
 5918:         sleep 1;
 5919:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5920:     }
 5921: 
 5922: # attempt to get unique identifier, based on current timestamp
 5923:     if ($gotlock eq 'ok') {
 5924:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5925:         my $id = time;
 5926:         $newid = $id;
 5927:         my $idtries = 0;
 5928:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5929:             if ($idtype eq 'concat') {
 5930:                 $newid = $id.$idtries;
 5931:             } else {
 5932:                 $newid ++;
 5933:             }
 5934:             $idtries ++;
 5935:         }
 5936:         if (!exists($inuse{$prefix."\0".$newid})) {
 5937:             my %new_item =  (
 5938:                               $prefix."\0".$newid => $who,
 5939:                             );
 5940:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5941:                                                  $cdom,$cnum);
 5942:             if ($putresult ne 'ok') {
 5943:                 undef($newid);
 5944:                 $error = 'error saving new item: '.$putresult;
 5945:             }
 5946:         } else {
 5947:              $error = ('error: no unique suffix available for the new item ');
 5948:         }
 5949: #  remove lock
 5950:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5951:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5952:     } else {
 5953:         $error = "error: could not obtain lockfile\n";
 5954:         $dellock = 'ok';
 5955:     }
 5956:     return ($newid,$dellock,$error);
 5957: }
 5958: 
 5959: # -------------------------------------------------- portfolio access checking
 5960: 
 5961: sub portfolio_access {
 5962:     my ($requrl) = @_;
 5963:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5964:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5965:     if ($result) {
 5966:         my %setters;
 5967:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5968:             my ($startblock,$endblock) =
 5969:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5970:             if ($startblock && $endblock) {
 5971:                 return 'B';
 5972:             }
 5973:         } else {
 5974:             my ($startblock,$endblock) =
 5975:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5976:             if ($startblock && $endblock) {
 5977:                 return 'B';
 5978:             }
 5979:         }
 5980:     }
 5981:     if ($result eq 'ok') {
 5982:        return 'F';
 5983:     } elsif ($result =~ /^[^:]+:guest_/) {
 5984:        return 'A';
 5985:     }
 5986:     return '';
 5987: }
 5988: 
 5989: sub get_portfolio_access {
 5990:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5991: 
 5992:     if (!ref($access_hash)) {
 5993: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5994: 	my %access_controls = &get_access_controls($current_perms,$group,
 5995: 						   $file_name);
 5996: 	$access_hash = $access_controls{$file_name};
 5997:     }
 5998: 
 5999:     my ($public,$guest,@domains,@users,@courses,@groups);
 6000:     my $now = time;
 6001:     if (ref($access_hash) eq 'HASH') {
 6002:         foreach my $key (keys(%{$access_hash})) {
 6003:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6004:             if ($start > $now) {
 6005:                 next;
 6006:             }
 6007:             if ($end && $end<$now) {
 6008:                 next;
 6009:             }
 6010:             if ($scope eq 'public') {
 6011:                 $public = $key;
 6012:                 last;
 6013:             } elsif ($scope eq 'guest') {
 6014:                 $guest = $key;
 6015:             } elsif ($scope eq 'domains') {
 6016:                 push(@domains,$key);
 6017:             } elsif ($scope eq 'users') {
 6018:                 push(@users,$key);
 6019:             } elsif ($scope eq 'course') {
 6020:                 push(@courses,$key);
 6021:             } elsif ($scope eq 'group') {
 6022:                 push(@groups,$key);
 6023:             }
 6024:         }
 6025:         if ($public) {
 6026:             return 'ok';
 6027:         }
 6028:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6029:             if ($guest) {
 6030:                 return $guest;
 6031:             }
 6032:         } else {
 6033:             if (@domains > 0) {
 6034:                 foreach my $domkey (@domains) {
 6035:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6036:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6037:                             return 'ok';
 6038:                         }
 6039:                     }
 6040:                 }
 6041:             }
 6042:             if (@users > 0) {
 6043:                 foreach my $userkey (@users) {
 6044:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6045:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6046:                             if (ref($item) eq 'HASH') {
 6047:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6048:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6049:                                     return 'ok';
 6050:                                 }
 6051:                             }
 6052:                         }
 6053:                     } 
 6054:                 }
 6055:             }
 6056:             my %roleshash;
 6057:             my @courses_and_groups = @courses;
 6058:             push(@courses_and_groups,@groups); 
 6059:             if (@courses_and_groups > 0) {
 6060:                 my (%allgroups,%allroles); 
 6061:                 my ($start,$end,$role,$sec,$group);
 6062:                 foreach my $envkey (%env) {
 6063:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6064:                         my $cid = $2.'_'.$3; 
 6065:                         if ($1 eq 'gr') {
 6066:                             $group = $4;
 6067:                             $allgroups{$cid}{$group} = $env{$envkey};
 6068:                         } else {
 6069:                             if ($4 eq '') {
 6070:                                 $sec = 'none';
 6071:                             } else {
 6072:                                 $sec = $4;
 6073:                             }
 6074:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6075:                         }
 6076:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6077:                         my $cid = $2.'_'.$3;
 6078:                         if ($4 eq '') {
 6079:                             $sec = 'none';
 6080:                         } else {
 6081:                             $sec = $4;
 6082:                         }
 6083:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6084:                     }
 6085:                 }
 6086:                 if (keys(%allroles) == 0) {
 6087:                     return;
 6088:                 }
 6089:                 foreach my $key (@courses_and_groups) {
 6090:                     my %content = %{$$access_hash{$key}};
 6091:                     my $cnum = $content{'number'};
 6092:                     my $cdom = $content{'domain'};
 6093:                     my $cid = $cdom.'_'.$cnum;
 6094:                     if (!exists($allroles{$cid})) {
 6095:                         next;
 6096:                     }    
 6097:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6098:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6099:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6100:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6101:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6102:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6103:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6104:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6105:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6106:                                         if (grep/^all$/,@sections) {
 6107:                                             return 'ok';
 6108:                                         } else {
 6109:                                             if (grep/^$sec$/,@sections) {
 6110:                                                 return 'ok';
 6111:                                             }
 6112:                                         }
 6113:                                     }
 6114:                                 }
 6115:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6116:                                     if (grep/^none$/,@groups) {
 6117:                                         return 'ok';
 6118:                                     }
 6119:                                 } else {
 6120:                                     if (grep/^all$/,@groups) {
 6121:                                         return 'ok';
 6122:                                     } 
 6123:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6124:                                         if (grep/^$group$/,@groups) {
 6125:                                             return 'ok';
 6126:                                         }
 6127:                                     }
 6128:                                 } 
 6129:                             }
 6130:                         }
 6131:                     }
 6132:                 }
 6133:             }
 6134:             if ($guest) {
 6135:                 return $guest;
 6136:             }
 6137:         }
 6138:     }
 6139:     return;
 6140: }
 6141: 
 6142: sub course_group_datechecker {
 6143:     my ($dates,$now,$status) = @_;
 6144:     my ($start,$end) = split(/\./,$dates);
 6145:     if (!$start && !$end) {
 6146:         return 'ok';
 6147:     }
 6148:     if (grep/^active$/,@{$status}) {
 6149:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6150:             return 'ok';
 6151:         }
 6152:     }
 6153:     if (grep/^previous$/,@{$status}) {
 6154:         if ($end > $now ) {
 6155:             return 'ok';
 6156:         }
 6157:     }
 6158:     if (grep/^future$/,@{$status}) {
 6159:         if ($start > $now) {
 6160:             return 'ok';
 6161:         }
 6162:     }
 6163:     return; 
 6164: }
 6165: 
 6166: sub parse_portfolio_url {
 6167:     my ($url) = @_;
 6168: 
 6169:     my ($type,$udom,$unum,$group,$file_name);
 6170:     
 6171:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6172: 	$type = 1;
 6173:         $udom = $1;
 6174:         $unum = $2;
 6175:         $file_name = $3;
 6176:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6177: 	$type = 2;
 6178:         $udom = $1;
 6179:         $unum = $2;
 6180:         $group = $3;
 6181:         $file_name = $3.'/'.$4;
 6182:     }
 6183:     if (wantarray) {
 6184: 	return ($type,$udom,$unum,$file_name,$group);
 6185:     }
 6186:     return $type;
 6187: }
 6188: 
 6189: sub is_portfolio_url {
 6190:     my ($url) = @_;
 6191:     return scalar(&parse_portfolio_url($url));
 6192: }
 6193: 
 6194: sub is_portfolio_file {
 6195:     my ($file) = @_;
 6196:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6197:         return 1;
 6198:     }
 6199:     return;
 6200: }
 6201: 
 6202: sub usertools_access {
 6203:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6204:     my ($access,%tools);
 6205:     if ($context eq '') {
 6206:         $context = 'tools';
 6207:     }
 6208:     if ($context eq 'requestcourses') {
 6209:         %tools = (
 6210:                       official   => 1,
 6211:                       unofficial => 1,
 6212:                       community  => 1,
 6213:                       textbook   => 1,
 6214:                  );
 6215:     } elsif ($context eq 'requestauthor') {
 6216:         %tools = (
 6217:                       requestauthor => 1,
 6218:                  );
 6219:     } else {
 6220:         %tools = (
 6221:                       aboutme   => 1,
 6222:                       blog      => 1,
 6223:                       webdav    => 1,
 6224:                       portfolio => 1,
 6225:                  );
 6226:     }
 6227:     return if (!defined($tools{$tool}));
 6228: 
 6229:     if (($udom eq '') || ($uname eq '')) {
 6230:         $udom = $env{'user.domain'};
 6231:         $uname = $env{'user.name'};
 6232:     }
 6233: 
 6234:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6235:         if ($action ne 'reload') {
 6236:             if ($context eq 'requestcourses') {
 6237:                 return $env{'environment.canrequest.'.$tool};
 6238:             } elsif ($context eq 'requestauthor') {
 6239:                 return $env{'environment.canrequest.author'};
 6240:             } else {
 6241:                 return $env{'environment.availabletools.'.$tool};
 6242:             }
 6243:         }
 6244:     }
 6245: 
 6246:     my ($toolstatus,$inststatus,$envkey);
 6247:     if ($context eq 'requestauthor') {
 6248:         $envkey = $context; 
 6249:     } else {
 6250:         $envkey = $context.'.'.$tool;
 6251:     }
 6252: 
 6253:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6254:          ($action ne 'reload')) {
 6255:         $toolstatus = $env{'environment.'.$envkey};
 6256:         $inststatus = $env{'environment.inststatus'};
 6257:     } else {
 6258:         if (ref($userenvref) eq 'HASH') {
 6259:             $toolstatus = $userenvref->{$envkey};
 6260:             $inststatus = $userenvref->{'inststatus'};
 6261:         } else {
 6262:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6263:             $toolstatus = $userenv{$envkey};
 6264:             $inststatus = $userenv{'inststatus'};
 6265:         }
 6266:     }
 6267: 
 6268:     if ($toolstatus ne '') {
 6269:         if ($toolstatus) {
 6270:             $access = 1;
 6271:         } else {
 6272:             $access = 0;
 6273:         }
 6274:         return $access;
 6275:     }
 6276: 
 6277:     my ($is_adv,%domdef);
 6278:     if (ref($is_advref) eq 'HASH') {
 6279:         $is_adv = $is_advref->{'is_adv'};
 6280:     } else {
 6281:         $is_adv = &is_advanced_user($udom,$uname);
 6282:     }
 6283:     if (ref($domdefref) eq 'HASH') {
 6284:         %domdef = %{$domdefref};
 6285:     } else {
 6286:         %domdef = &get_domain_defaults($udom);
 6287:     }
 6288:     if (ref($domdef{$tool}) eq 'HASH') {
 6289:         if ($is_adv) {
 6290:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6291:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6292:                     $access = 1;
 6293:                 } else {
 6294:                     $access = 0;
 6295:                 }
 6296:                 return $access;
 6297:             }
 6298:         }
 6299:         if ($inststatus ne '') {
 6300:             my ($hasaccess,$hasnoaccess);
 6301:             foreach my $affiliation (split(/:/,$inststatus)) {
 6302:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6303:                     if ($domdef{$tool}{$affiliation}) {
 6304:                         $hasaccess = 1;
 6305:                     } else {
 6306:                         $hasnoaccess = 1;
 6307:                     }
 6308:                 }
 6309:             }
 6310:             if ($hasaccess || $hasnoaccess) {
 6311:                 if ($hasaccess) {
 6312:                     $access = 1;
 6313:                 } elsif ($hasnoaccess) {
 6314:                     $access = 0; 
 6315:                 }
 6316:                 return $access;
 6317:             }
 6318:         } else {
 6319:             if ($domdef{$tool}{'default'} ne '') {
 6320:                 if ($domdef{$tool}{'default'}) {
 6321:                     $access = 1;
 6322:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6323:                     $access = 0;
 6324:                 }
 6325:                 return $access;
 6326:             }
 6327:         }
 6328:     } else {
 6329:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6330:             $access = 1;
 6331:         } else {
 6332:             $access = 0;
 6333:         }
 6334:         return $access;
 6335:     }
 6336: }
 6337: 
 6338: sub is_course_owner {
 6339:     my ($cdom,$cnum,$udom,$uname) = @_;
 6340:     if (($udom eq '') || ($uname eq '')) {
 6341:         $udom = $env{'user.domain'};
 6342:         $uname = $env{'user.name'};
 6343:     }
 6344:     unless (($udom eq '') || ($uname eq '')) {
 6345:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6346:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6347:                 return 1;
 6348:             } else {
 6349:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6350:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6351:                     return 1;
 6352:                 }
 6353:             }
 6354:         }
 6355:     }
 6356:     return;
 6357: }
 6358: 
 6359: sub is_advanced_user {
 6360:     my ($udom,$uname) = @_;
 6361:     if ($udom ne '' && $uname ne '') {
 6362:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6363:             if (wantarray) {
 6364:                 return ($env{'user.adv'},$env{'user.author'});
 6365:             } else {
 6366:                 return $env{'user.adv'};
 6367:             }
 6368:         }
 6369:     }
 6370:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6371:     my %allroles;
 6372:     my ($is_adv,$is_author);
 6373:     foreach my $role (keys(%roleshash)) {
 6374:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6375:         my $area = '/'.$tdomain.'/'.$trest;
 6376:         if ($sec ne '') {
 6377:             $area .= '/'.$sec;
 6378:         }
 6379:         if (($area ne '') && ($trole ne '')) {
 6380:             my $spec=$trole.'.'.$area;
 6381:             if ($trole =~ /^cr\//) {
 6382:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6383:             } elsif ($trole ne 'gr') {
 6384:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6385:             }
 6386:             if ($trole eq 'au') {
 6387:                 $is_author = 1;
 6388:             }
 6389:         }
 6390:     }
 6391:     foreach my $role (keys(%allroles)) {
 6392:         last if ($is_adv);
 6393:         foreach my $item (split(/:/,$allroles{$role})) {
 6394:             if ($item ne '') {
 6395:                 my ($privilege,$restrictions)=split(/&/,$item);
 6396:                 if ($privilege eq 'adv') {
 6397:                     $is_adv = 1;
 6398:                     last;
 6399:                 }
 6400:             }
 6401:         }
 6402:     }
 6403:     if (wantarray) {
 6404:         return ($is_adv,$is_author);
 6405:     }
 6406:     return $is_adv;
 6407: }
 6408: 
 6409: sub check_can_request {
 6410:     my ($dom,$can_request,$request_domains) = @_;
 6411:     my $canreq = 0;
 6412:     my ($types,$typename) = &Apache::loncommon::course_types();
 6413:     my @options = ('approval','validate','autolimit');
 6414:     my $optregex = join('|',@options);
 6415:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6416:         foreach my $type (@{$types}) {
 6417:             if (&usertools_access($env{'user.name'},
 6418:                                   $env{'user.domain'},
 6419:                                   $type,undef,'requestcourses')) {
 6420:                 $canreq ++;
 6421:                 if (ref($request_domains) eq 'HASH') {
 6422:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6423:                 }
 6424:                 if ($dom eq $env{'user.domain'}) {
 6425:                     $can_request->{$type} = 1;
 6426:                 }
 6427:             }
 6428:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6429:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6430:                 if (@curr > 0) {
 6431:                     foreach my $item (@curr) {
 6432:                         if (ref($request_domains) eq 'HASH') {
 6433:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6434:                             if ($otherdom ne '') {
 6435:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6436:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6437:                                         push(@{$request_domains->{$type}},$otherdom);
 6438:                                     }
 6439:                                 } else {
 6440:                                     push(@{$request_domains->{$type}},$otherdom);
 6441:                                 }
 6442:                             }
 6443:                         }
 6444:                     }
 6445:                     unless($dom eq $env{'user.domain'}) {
 6446:                         $canreq ++;
 6447:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6448:                             $can_request->{$type} = 1;
 6449:                         }
 6450:                     }
 6451:                 }
 6452:             }
 6453:         }
 6454:     }
 6455:     return $canreq;
 6456: }
 6457: 
 6458: # ---------------------------------------------- Custom access rule evaluation
 6459: 
 6460: sub customaccess {
 6461:     my ($priv,$uri)=@_;
 6462:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6463:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6464:     $udom = &LONCAPA::clean_domain($udom);
 6465:     $ucrs = &LONCAPA::clean_username($ucrs);
 6466:     my $access=0;
 6467:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6468: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6469: 	if ($type eq 'user') {
 6470: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6471: 		my ($tdom,$tuname)=split(m{/},$scope);
 6472: 		if ($tdom) {
 6473: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6474: 		}
 6475: 		if ($tuname) {
 6476: 		    if ($tuname ne $env{'user.name'}) { next; }
 6477: 		}
 6478: 		$access=($effect eq 'allow');
 6479: 		last;
 6480: 	    }
 6481: 	} else {
 6482: 	    if ($role) {
 6483: 		if ($role ne $urole) { next; }
 6484: 	    }
 6485: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6486: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6487: 		if ($tdom) {
 6488: 		    if ($tdom ne $udom) { next; }
 6489: 		}
 6490: 		if ($tcrs) {
 6491: 		    if ($tcrs ne $ucrs) { next; }
 6492: 		}
 6493: 		if ($tsec) {
 6494: 		    if ($tsec ne $usec) { next; }
 6495: 		}
 6496: 		$access=($effect eq 'allow');
 6497: 		last;
 6498: 	    }
 6499: 	    if ($realm eq '' && $role eq '') {
 6500: 		$access=($effect eq 'allow');
 6501: 	    }
 6502: 	}
 6503:     }
 6504:     return $access;
 6505: }
 6506: 
 6507: # ------------------------------------------------- Check for a user privilege
 6508: 
 6509: sub allowed {
 6510:     my ($priv,$uri,$symb,$role)=@_;
 6511:     my $ver_orguri=$uri;
 6512:     $uri=&deversion($uri);
 6513:     my $orguri=$uri;
 6514:     $uri=&declutter($uri);
 6515: 
 6516:     if ($priv eq 'evb') {
 6517: # Evade communication block restrictions for specified role in a course
 6518:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6519:             return $1;
 6520:         } else {
 6521:             return;
 6522:         }
 6523:     }
 6524: 
 6525:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6526: # Free bre access to adm and meta resources
 6527:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6528: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6529: 	&& ($priv eq 'bre')) {
 6530: 	return 'F';
 6531:     }
 6532: 
 6533: # Free bre access to user's own portfolio contents
 6534:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6535:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6536: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6537:         my %setters;
 6538:         my ($startblock,$endblock) = 
 6539:             &Apache::loncommon::blockcheck(\%setters,'port');
 6540:         if ($startblock && $endblock) {
 6541:             return 'B';
 6542:         } else {
 6543:             return 'F';
 6544:         }
 6545:     }
 6546: 
 6547: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6548:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6549:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6550:         if (exists($env{'request.course.id'})) {
 6551:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6552:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6553:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6554:                 my $courseprivid=$env{'request.course.id'};
 6555:                 $courseprivid=~s/\_/\//;
 6556:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6557:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6558:                     return $1; 
 6559:                 } else {
 6560:                     if ($env{'request.course.sec'}) {
 6561:                         $courseprivid.='/'.$env{'request.course.sec'};
 6562:                     }
 6563:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6564:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6565:                         return $2;
 6566:                     }
 6567:                 }
 6568:             }
 6569:         }
 6570:     }
 6571: 
 6572: # Free bre to public access
 6573: 
 6574:     if ($priv eq 'bre') {
 6575:         my $copyright=&metadata($uri,'copyright');
 6576: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6577:            return 'F'; 
 6578:         }
 6579:         if ($copyright eq 'priv') {
 6580:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6581: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6582: 		return '';
 6583:             }
 6584:         }
 6585:         if ($copyright eq 'domain') {
 6586:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6587: 	    unless (($env{'user.domain'} eq $1) ||
 6588:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6589: 		return '';
 6590:             }
 6591:         }
 6592:         if ($env{'request.role'}=~ /li\.\//) {
 6593:             # Library role, so allow browsing of resources in this domain.
 6594:             return 'F';
 6595:         }
 6596:         if ($copyright eq 'custom') {
 6597: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6598:         }
 6599:     }
 6600:     # Domain coordinator is trying to create a course
 6601:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6602:         # uri is the requested domain in this case.
 6603:         # comparison to 'request.role.domain' shows if the user has selected
 6604:         # a role of dc for the domain in question.
 6605:         return 'F' if ($uri eq $env{'request.role.domain'});
 6606:     }
 6607: 
 6608:     my $thisallowed='';
 6609:     my $statecond=0;
 6610:     my $courseprivid='';
 6611: 
 6612:     my $ownaccess;
 6613:     # Community Coordinator or Assistant Co-author browsing resource space.
 6614:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6615:         if ($uri eq '') {
 6616:             $ownaccess = 1;
 6617:         } else {
 6618:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6619:                 my $udom = $env{'user.domain'};
 6620:                 my $uname = $env{'user.name'};
 6621:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6622:                     $ownaccess = 1;
 6623:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6624:                     unless ($uri =~ m{\.\./}) {
 6625:                         $ownaccess = 1;
 6626:                     }
 6627:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6628:                     my $now = time;
 6629:                     if ($uri =~ m{^([^/]+)/?$}) {
 6630:                         my $adom = $1;
 6631:                         foreach my $key (keys(%env)) {
 6632:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6633:                                 my ($start,$end) = split('.',$env{$key});
 6634:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6635:                                     $ownaccess = 1;
 6636:                                     last;
 6637:                                 }
 6638:                             }
 6639:                         }
 6640:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6641:                         my $adom = $1;
 6642:                         my $aname = $2;
 6643:                         foreach my $role ('ca','aa') { 
 6644:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6645:                                 my ($start,$end) =
 6646:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6647:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6648:                                     $ownaccess = 1;
 6649:                                     last;
 6650:                                 }
 6651:                             }
 6652:                         }
 6653:                     }
 6654:                 }
 6655:             }
 6656:         }
 6657:     }
 6658: 
 6659: # Course
 6660: 
 6661:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6662:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6663:             $thisallowed.=$1;
 6664:         }
 6665:     }
 6666: 
 6667: # Domain
 6668: 
 6669:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6670:        =~/\Q$priv\E\&([^\:]*)/) {
 6671:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6672:             $thisallowed.=$1;
 6673:         }
 6674:     }
 6675: 
 6676: # User who is not author or co-author might still be able to edit
 6677: # resource of an author in the domain (e.g., if Domain Coordinator).
 6678:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6679:         (&allowed('mdc',$env{'request.course.id'}))) {
 6680:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6681:             $thisallowed.=$1;
 6682:         }
 6683:     }
 6684: 
 6685: # Course: uri itself is a course
 6686:     my $courseuri=$uri;
 6687:     $courseuri=~s/\_(\d)/\/$1/;
 6688:     $courseuri=~s/^([^\/])/\/$1/;
 6689: 
 6690:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6691:        =~/\Q$priv\E\&([^\:]*)/) {
 6692:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6693:             $thisallowed.=$1;
 6694:         }
 6695:     }
 6696: 
 6697: # URI is an uploaded document for this course, default permissions don't matter
 6698: # not allowing 'edit' access (editupload) to uploaded course docs
 6699:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6700: 	$thisallowed='';
 6701:         my ($match)=&is_on_map($uri);
 6702:         if ($match) {
 6703:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6704:                   =~/\Q$priv\E\&([^\:]*)/) {
 6705:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6706:                 if (@blockers > 0) {
 6707:                     $thisallowed = 'B';
 6708:                 } else {
 6709:                     $thisallowed.=$1;
 6710:                 }
 6711:             }
 6712:         } else {
 6713:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6714:             if ($refuri) {
 6715:                 if ($refuri =~ m|^/adm/|) {
 6716:                     $thisallowed='F';
 6717:                 } else {
 6718:                     $refuri=&declutter($refuri);
 6719:                     my ($match) = &is_on_map($refuri);
 6720:                     if ($match) {
 6721:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6722:                         if (@blockers > 0) {
 6723:                             $thisallowed = 'B';
 6724:                         } else {
 6725:                             $thisallowed='F';
 6726:                         }
 6727:                     }
 6728:                 }
 6729:             }
 6730:         }
 6731:     }
 6732: 
 6733:     if ($priv eq 'bre'
 6734: 	&& $thisallowed ne 'F' 
 6735: 	&& $thisallowed ne '2'
 6736: 	&& &is_portfolio_url($uri)) {
 6737: 	$thisallowed = &portfolio_access($uri);
 6738:     }
 6739: 
 6740: # Full access at system, domain or course-wide level? Exit.
 6741:     if ($thisallowed=~/F/) {
 6742: 	return 'F';
 6743:     }
 6744: 
 6745: # If this is generating or modifying users, exit with special codes
 6746: 
 6747:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6748: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6749: 	    my ($audom,$auname)=split('/',$uri);
 6750: # no author name given, so this just checks on the general right to make a co-author in this domain
 6751: 	    unless ($auname) { return $thisallowed; }
 6752: # an author name is given, so we are about to actually make a co-author for a certain account
 6753: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6754: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6755: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6756: 	}
 6757: 	return $thisallowed;
 6758:     }
 6759: #
 6760: # Gathered so far: system, domain and course wide privileges
 6761: #
 6762: # Course: See if uri or referer is an individual resource that is part of 
 6763: # the course
 6764: 
 6765:     if ($env{'request.course.id'}) {
 6766: 
 6767:        $courseprivid=$env{'request.course.id'};
 6768:        if ($env{'request.course.sec'}) {
 6769:           $courseprivid.='/'.$env{'request.course.sec'};
 6770:        }
 6771:        $courseprivid=~s/\_/\//;
 6772:        my $checkreferer=1;
 6773:        my ($match,$cond)=&is_on_map($uri);
 6774:        if ($match) {
 6775:            $statecond=$cond;
 6776:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6777:                =~/\Q$priv\E\&([^\:]*)/) {
 6778:                my $value = $1;
 6779:                if ($priv eq 'bre') {
 6780:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6781:                    if (@blockers > 0) {
 6782:                        $thisallowed = 'B';
 6783:                    } else {
 6784:                        $thisallowed.=$value;
 6785:                    }
 6786:                } else {
 6787:                    $thisallowed.=$value;
 6788:                }
 6789:                $checkreferer=0;
 6790:            }
 6791:        }
 6792:        
 6793:        if ($checkreferer) {
 6794: 	  my $refuri=$env{'httpref.'.$orguri};
 6795:             unless ($refuri) {
 6796:                 foreach my $key (keys(%env)) {
 6797: 		    if ($key=~/^httpref\..*\*/) {
 6798: 			my $pattern=$key;
 6799:                         $pattern=~s/^httpref\.\/res\///;
 6800:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6801:                         $pattern=~s/\//\\\//g;
 6802:                         if ($orguri=~/$pattern/) {
 6803: 			    $refuri=$env{$key};
 6804:                         }
 6805:                     }
 6806:                 }
 6807:             }
 6808: 
 6809:          if ($refuri) { 
 6810: 	  $refuri=&declutter($refuri);
 6811:           my ($match,$cond)=&is_on_map($refuri);
 6812:             if ($match) {
 6813:               my $refstatecond=$cond;
 6814:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6815:                   =~/\Q$priv\E\&([^\:]*)/) {
 6816:                   my $value = $1;
 6817:                   if ($priv eq 'bre') {
 6818:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6819:                       if (@blockers > 0) {
 6820:                           $thisallowed = 'B';
 6821:                       } else {
 6822:                           $thisallowed.=$value;
 6823:                       }
 6824:                   } else {
 6825:                       $thisallowed.=$value;
 6826:                   }
 6827:                   $uri=$refuri;
 6828:                   $statecond=$refstatecond;
 6829:               }
 6830:           }
 6831:         }
 6832:        }
 6833:    }
 6834: 
 6835: #
 6836: # Gathered now: all privileges that could apply, and condition number
 6837: # 
 6838: #
 6839: # Full or no access?
 6840: #
 6841: 
 6842:     if ($thisallowed=~/F/) {
 6843: 	return 'F';
 6844:     }
 6845: 
 6846:     unless ($thisallowed) {
 6847:         return '';
 6848:     }
 6849: 
 6850: # Restrictions exist, deal with them
 6851: #
 6852: #   C:according to course preferences
 6853: #   R:according to resource settings
 6854: #   L:unless locked
 6855: #   X:according to user session state
 6856: #
 6857: 
 6858: # Possibly locked functionality, check all courses
 6859: # Locks might take effect only after 10 minutes cache expiration for other
 6860: # courses, and 2 minutes for current course
 6861: 
 6862:     my $envkey;
 6863:     if ($thisallowed=~/L/) {
 6864:         foreach $envkey (keys(%env)) {
 6865:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6866:                my $courseid=$2;
 6867:                my $roleid=$1.'.'.$2;
 6868:                $courseid=~s/^\///;
 6869:                my $expiretime=600;
 6870:                if ($env{'request.role'} eq $roleid) {
 6871: 		  $expiretime=120;
 6872:                }
 6873: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6874:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6875:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6876: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6877:                }
 6878:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6879:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6880: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6881:                        &log($env{'user.domain'},$env{'user.name'},
 6882:                             $env{'user.home'},
 6883:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6884:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6885:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6886: 		       return '';
 6887:                    }
 6888:                }
 6889:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6890:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6891: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6892:                        &log($env{'user.domain'},$env{'user.name'},
 6893:                             $env{'user.home'},
 6894:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6895:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6896:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6897: 		       return '';
 6898:                    }
 6899:                }
 6900: 	   }
 6901:        }
 6902:     }
 6903:    
 6904: #
 6905: # Rest of the restrictions depend on selected course
 6906: #
 6907: 
 6908:     unless ($env{'request.course.id'}) {
 6909: 	if ($thisallowed eq 'A') {
 6910: 	    return 'A';
 6911:         } elsif ($thisallowed eq 'B') {
 6912:             return 'B';
 6913: 	} else {
 6914: 	    return '1';
 6915: 	}
 6916:     }
 6917: 
 6918: #
 6919: # Now user is definitely in a course
 6920: #
 6921: 
 6922: 
 6923: # Course preferences
 6924: 
 6925:    if ($thisallowed=~/C/) {
 6926:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6927:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6928:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6929: 	   =~/\Q$rolecode\E/) {
 6930: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6931: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6932: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6933: 			$env{'request.course.id'});
 6934: 	   }
 6935:            return '';
 6936:        }
 6937: 
 6938:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6939: 	   =~/\Q$unamedom\E/) {
 6940: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6941: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6942: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6943: 			$env{'request.course.id'});
 6944: 	   }
 6945:            return '';
 6946:        }
 6947:    }
 6948: 
 6949: # Resource preferences
 6950: 
 6951:    if ($thisallowed=~/R/) {
 6952:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6953:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6954: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6955: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6956: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6957: 	   }
 6958: 	   return '';
 6959:        }
 6960:    }
 6961: 
 6962: # Restricted by state or randomout?
 6963: 
 6964:    if ($thisallowed=~/X/) {
 6965:       if ($env{'acc.randomout'}) {
 6966: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6967:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6968:             return ''; 
 6969:          }
 6970:       }
 6971:       if (&condval($statecond)) {
 6972: 	 return '2';
 6973:       } else {
 6974:          return '';
 6975:       }
 6976:    }
 6977: 
 6978:     if ($thisallowed eq 'A') {
 6979: 	return 'A';
 6980:     } elsif ($thisallowed eq 'B') {
 6981:         return 'B';
 6982:     }
 6983:    return 'F';
 6984: }
 6985: 
 6986: # ------------------------------------------- Check construction space access
 6987: 
 6988: sub constructaccess {
 6989:     my ($url,$setpriv)=@_;
 6990: 
 6991: # We do not allow editing of previous versions of files
 6992:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6993: 
 6994: # Get username and domain from URL
 6995:     my ($ownername,$ownerdomain,$ownerhome);
 6996: 
 6997:     ($ownerdomain,$ownername) =
 6998:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6999: 
 7000: # The URL does not really point to any authorspace, forget it
 7001:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7002: 
 7003: # Now we need to see if the user has access to the authorspace of
 7004: # $ownername at $ownerdomain
 7005: 
 7006:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7007: # Real author for this?
 7008:        $ownerhome = $env{'user.home'};
 7009:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7010:           return ($ownername,$ownerdomain,$ownerhome);
 7011:        }
 7012:     } else {
 7013: # Co-author for this?
 7014:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7015:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7016:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7017:             return ($ownername,$ownerdomain,$ownerhome);
 7018:         }
 7019:     }
 7020: 
 7021: # We don't have any access right now. If we are not possibly going to do anything about this,
 7022: # we might as well leave
 7023:    unless ($setpriv) { return ''; }
 7024: 
 7025: # Backdoor access?
 7026:     my $allowed=&allowed('eco',$ownerdomain);
 7027: # Nope
 7028:     unless ($allowed) { return ''; }
 7029: # Looks like we may have access, but could be locked by the owner of the construction space
 7030:     if ($allowed eq 'U') {
 7031:         my %blocked=&get('environment',['domcoord.author'],
 7032:                          $ownerdomain,$ownername);
 7033: # Is blocked by owner
 7034:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7035:     }
 7036:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7037: # Grant temporary access
 7038:         my $then=$env{'user.login.time'};
 7039:         my $update=$env{'user.update.time'};
 7040:         if (!$update) { $update = $then; }
 7041:         my $refresh=$env{'user.refresh.time'};
 7042:         if (!$refresh) { $refresh = $update; }
 7043:         my $now = time;
 7044:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7045:                            $now,'ca','constructaccess');
 7046:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7047:         return($ownername,$ownerdomain,$ownerhome);
 7048:     }
 7049: # No business here
 7050:     return '';
 7051: }
 7052: 
 7053: sub get_comm_blocks {
 7054:     my ($cdom,$cnum) = @_;
 7055:     if ($cdom eq '' || $cnum eq '') {
 7056:         return unless ($env{'request.course.id'});
 7057:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7058:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7059:     }
 7060:     my %commblocks;
 7061:     my $hashid=$cdom.'_'.$cnum;
 7062:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7063:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7064:         %commblocks = %{$blocksref};
 7065:     } else {
 7066:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7067:         my $cachetime = 600;
 7068:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7069:     }
 7070:     return %commblocks;
 7071: }
 7072: 
 7073: sub has_comm_blocking {
 7074:     my ($priv,$symb,$uri,$blocks) = @_;
 7075:     return unless ($env{'request.course.id'});
 7076:     return unless ($priv eq 'bre');
 7077:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7078:     my %commblocks;
 7079:     if (ref($blocks) eq 'HASH') {
 7080:         %commblocks = %{$blocks};
 7081:     } else {
 7082:         %commblocks = &get_comm_blocks();
 7083:     }
 7084:     return unless (keys(%commblocks) > 0);
 7085:     if (!$symb) { $symb=&symbread($uri,1); }
 7086:     my ($map,$resid,undef)=&decode_symb($symb);
 7087:     my %tocheck = (
 7088:                     maps      => $map,
 7089:                     resources => $symb,
 7090:                   );
 7091:     my @blockers;
 7092:     my $now = time;
 7093:     my $navmap = Apache::lonnavmaps::navmap->new();
 7094:     foreach my $block (keys(%commblocks)) {
 7095:         if ($block =~ /^(\d+)____(\d+)$/) {
 7096:             my ($start,$end) = ($1,$2);
 7097:             if ($start <= $now && $end >= $now) {
 7098:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7099:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7100:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7101:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7102:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7103:                                     push(@blockers,$block);
 7104:                                 }
 7105:                             }
 7106:                         }
 7107:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7108:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7109:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7110:                                     push(@blockers,$block);
 7111:                                 }
 7112:                             }
 7113:                         }
 7114:                     }
 7115:                 }
 7116:             }
 7117:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7118:             my $item = $1;
 7119:             my @to_test;
 7120:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7121:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7122:                     my $check_interval;
 7123:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7124:                         my @interval;
 7125:                         my $type = 'map';
 7126:                         if ($item eq 'course') {
 7127:                             $type = 'course';
 7128:                             @interval=&EXT("resource.0.interval");
 7129:                         } else {
 7130:                             if ($item =~ /___\d+___/) {
 7131:                                 $type = 'resource';
 7132:                                 @interval=&EXT("resource.0.interval",$item);
 7133:                                 if (ref($navmap)) {                        
 7134:                                     my $res = $navmap->getBySymb($item); 
 7135:                                     push(@to_test,$res);
 7136:                                 }
 7137:                             } else {
 7138:                                 my $mapsymb = &symbread($item,1);
 7139:                                 if ($mapsymb) {
 7140:                                     if (ref($navmap)) {
 7141:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7142:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7143:                                         foreach my $res (@to_test) {
 7144:                                             my $symb = $res->symb();
 7145:                                             next if ($symb eq $mapsymb);
 7146:                                             if ($symb ne '') {
 7147:                                                 @interval=&EXT("resource.0.interval",$symb);
 7148:                                                 last;
 7149:                                             }
 7150:                                         }
 7151:                                     }
 7152:                                 }
 7153:                             }
 7154:                         }
 7155:                         if ($interval[0] =~ /\d+/) {
 7156:                             my $first_access;
 7157:                             if ($type eq 'resource') {
 7158:                                 $first_access=&get_first_access($interval[1],$item);
 7159:                             } elsif ($type eq 'map') {
 7160:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7161:                             } else {
 7162:                                 $first_access=&get_first_access($interval[1]);
 7163:                             }
 7164:                             if ($first_access) {
 7165:                                 my $timesup = $first_access+$interval[0];
 7166:                                 if ($timesup > $now) {
 7167:                                     foreach my $res (@to_test) {
 7168:                                         if ($res->is_problem()) {
 7169:                                             if ($res->completable()) {
 7170:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7171:                                                     push(@blockers,$block);
 7172:                                                 }
 7173:                                                 last;
 7174:                                             }
 7175:                                         }
 7176:                                     }
 7177:                                 }
 7178:                             }
 7179:                         }
 7180:                     }
 7181:                 }
 7182:             }
 7183:         }
 7184:     }
 7185:     return @blockers;
 7186: }
 7187: 
 7188: sub check_docs_block {
 7189:     my ($docsblock,$tocheck) =@_;
 7190:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7191:         return;
 7192:     }
 7193:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7194:         if ($tocheck->{'maps'}) {
 7195:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7196:                 return 1;
 7197:             }
 7198:         }
 7199:     }
 7200:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7201:         if ($tocheck->{'resources'}) {
 7202:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7203:                 return 1;
 7204:             }
 7205:         }
 7206:     }
 7207:     return;
 7208: }
 7209: 
 7210: #
 7211: #   Removes the versino from a URI and
 7212: #   splits it in to its filename and path to the filename.
 7213: #   Seems like File::Basename could have done this more clearly.
 7214: #   Parameters:
 7215: #      $uri   - input URI
 7216: #   Returns:
 7217: #     Two element list consisting of 
 7218: #     $pathname  - the URI up to and excluding the trailing /
 7219: #     $filename  - The part of the URI following the last /
 7220: #  NOTE:
 7221: #    Another realization of this is simply:
 7222: #    use File::Basename;
 7223: #    ...
 7224: #    $uri = shift;
 7225: #    $filename = basename($uri);
 7226: #    $path     = dirname($uri);
 7227: #    return ($filename, $path);
 7228: #
 7229: #     The implementation below is probably faster however.
 7230: #
 7231: sub split_uri_for_cond {
 7232:     my $uri=&deversion(&declutter(shift));
 7233:     my @uriparts=split(/\//,$uri);
 7234:     my $filename=pop(@uriparts);
 7235:     my $pathname=join('/',@uriparts);
 7236:     return ($pathname,$filename);
 7237: }
 7238: # --------------------------------------------------- Is a resource on the map?
 7239: 
 7240: sub is_on_map {
 7241:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7242:     #Trying to find the conditional for the file
 7243:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7244: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7245:     if ($match) {
 7246: 	return (1,$1);
 7247:     } else {
 7248: 	return (0,0);
 7249:     }
 7250: }
 7251: 
 7252: # --------------------------------------------------------- Get symb from alias
 7253: 
 7254: sub get_symb_from_alias {
 7255:     my $symb=shift;
 7256:     my ($map,$resid,$url)=&decode_symb($symb);
 7257: # Already is a symb
 7258:     if ($url) { return $symb; }
 7259: # Must be an alias
 7260:     my $aliassymb='';
 7261:     my %bighash;
 7262:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7263:                             &GDBM_READER(),0640)) {
 7264:         my $rid=$bighash{'mapalias_'.$symb};
 7265: 	if ($rid) {
 7266: 	    my ($mapid,$resid)=split(/\./,$rid);
 7267: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7268: 				    $resid,$bighash{'src_'.$rid});
 7269: 	}
 7270:         untie %bighash;
 7271:     }
 7272:     return $aliassymb;
 7273: }
 7274: 
 7275: # ----------------------------------------------------------------- Define Role
 7276: 
 7277: sub definerole {
 7278:   if (allowed('mcr','/')) {
 7279:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7280:     foreach my $role (split(':',$sysrole)) {
 7281: 	my ($crole,$cqual)=split(/\&/,$role);
 7282:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7283:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7284: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7285:                return "refused:s:$crole&$cqual"; 
 7286:             }
 7287:         }
 7288:     }
 7289:     foreach my $role (split(':',$domrole)) {
 7290: 	my ($crole,$cqual)=split(/\&/,$role);
 7291:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7292:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7293: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7294:                return "refused:d:$crole&$cqual"; 
 7295:             }
 7296:         }
 7297:     }
 7298:     foreach my $role (split(':',$courole)) {
 7299: 	my ($crole,$cqual)=split(/\&/,$role);
 7300:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7301:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7302: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7303:                return "refused:c:$crole&$cqual"; 
 7304:             }
 7305:         }
 7306:     }
 7307:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7308:                 "$env{'user.domain'}:$env{'user.name'}:".
 7309: 	        "rolesdef_$rolename=".
 7310:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7311:     return reply($command,$env{'user.home'});
 7312:   } else {
 7313:     return 'refused';
 7314:   }
 7315: }
 7316: 
 7317: # ---------------- Make a metadata query against the network of library servers
 7318: 
 7319: sub metadata_query {
 7320:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7321:     my %rhash;
 7322:     my %libserv = &all_library();
 7323:     my @server_list = (defined($server_array) ? @$server_array
 7324:                                               : keys(%libserv) );
 7325:     for my $server (@server_list) {
 7326:         my $domains = ''; 
 7327:         if (ref($domains_hash) eq 'HASH') {
 7328:             $domains = $domains_hash->{$server}; 
 7329:         }
 7330: 	unless ($custom or $customshow) {
 7331: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7332: 	    $rhash{$server}=$reply;
 7333: 	}
 7334: 	else {
 7335: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7336: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7337: 			     $server);
 7338: 	    $rhash{$server}=$reply;
 7339: 	}
 7340:     }
 7341:     return \%rhash;
 7342: }
 7343: 
 7344: # ----------------------------------------- Send log queries and wait for reply
 7345: 
 7346: sub log_query {
 7347:     my ($uname,$udom,$query,%filters)=@_;
 7348:     my $uhome=&homeserver($uname,$udom);
 7349:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7350:     my $uhost=&hostname($uhome);
 7351:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7352:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7353:                        $uhome);
 7354:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7355:     return get_query_reply($queryid);
 7356: }
 7357: 
 7358: # -------------------------- Update MySQL table for portfolio file
 7359: 
 7360: sub update_portfolio_table {
 7361:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7362:     if ($group ne '') {
 7363:         $file_name =~s /^\Q$group\E//;
 7364:     }
 7365:     my $homeserver = &homeserver($uname,$udom);
 7366:     my $queryid=
 7367:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7368:                ':'.&escape($file_name).':'.$action,$homeserver);
 7369:     my $reply = &get_query_reply($queryid);
 7370:     return $reply;
 7371: }
 7372: 
 7373: # -------------------------- Update MySQL allusers table
 7374: 
 7375: sub update_allusers_table {
 7376:     my ($uname,$udom,$names) = @_;
 7377:     my $homeserver = &homeserver($uname,$udom);
 7378:     my $queryid=
 7379:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7380:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7381:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7382:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7383:                'generation='.&escape($names->{'generation'}).'%%'.
 7384:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7385:                'id='.&escape($names->{'id'}),$homeserver);
 7386:     return;
 7387: }
 7388: 
 7389: # ------- Request retrieval of institutional classlists for course(s)
 7390: 
 7391: sub fetch_enrollment_query {
 7392:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7393:     my $homeserver;
 7394:     my $maxtries = 1;
 7395:     if ($context eq 'automated') {
 7396:         $homeserver = $perlvar{'lonHostID'};
 7397:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7398:     } else {
 7399:         $homeserver = &homeserver($cnum,$dom);
 7400:     }
 7401:     my $host=&hostname($homeserver);
 7402:     my $cmd = '';
 7403:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7404:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7405:     }
 7406:     $cmd =~ s/%%$//;
 7407:     $cmd = &escape($cmd);
 7408:     my $query = 'fetchenrollment';
 7409:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7410:     unless ($queryid=~/^\Q$host\E\_/) { 
 7411:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7412:         return 'error: '.$queryid;
 7413:     }
 7414:     my $reply = &get_query_reply($queryid);
 7415:     my $tries = 1;
 7416:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7417:         $reply = &get_query_reply($queryid);
 7418:         $tries ++;
 7419:     }
 7420:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7421:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7422:     } else {
 7423:         my @responses = split(/:/,$reply);
 7424:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7425:             foreach my $line (@responses) {
 7426:                 my ($key,$value) = split(/=/,$line,2);
 7427:                 $$replyref{$key} = $value;
 7428:             }
 7429:         } else {
 7430:             my $pathname = LONCAPA::tempdir();
 7431:             foreach my $line (@responses) {
 7432:                 my ($key,$value) = split(/=/,$line);
 7433:                 $$replyref{$key} = $value;
 7434:                 if ($value > 0) {
 7435:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7436:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7437:                         my $destname = $pathname.'/'.$filename;
 7438:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7439:                         if ($xml_classlist =~ /^error/) {
 7440:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7441:                         } else {
 7442:                             if ( open(FILE,">$destname") ) {
 7443:                                 print FILE &unescape($xml_classlist);
 7444:                                 close(FILE);
 7445:                             } else {
 7446:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7447:                             }
 7448:                         }
 7449:                     }
 7450:                 }
 7451:             }
 7452:         }
 7453:         return 'ok';
 7454:     }
 7455:     return 'error';
 7456: }
 7457: 
 7458: sub get_query_reply {
 7459:     my $queryid=shift;
 7460:     my $replyfile=LONCAPA::tempdir().$queryid;
 7461:     my $reply='';
 7462:     for (1..100) {
 7463: 	sleep 2;
 7464:         if (-e $replyfile.'.end') {
 7465: 	    if (open(my $fh,$replyfile)) {
 7466: 		$reply = join('',<$fh>);
 7467: 		close($fh);
 7468: 	   } else { return 'error: reply_file_error'; }
 7469:            return &unescape($reply);
 7470: 	}
 7471:     }
 7472:     return 'timeout:'.$queryid;
 7473: }
 7474: 
 7475: sub courselog_query {
 7476: #
 7477: # possible filters:
 7478: # url: url or symb
 7479: # username
 7480: # domain
 7481: # action: view, submit, grade
 7482: # start: timestamp
 7483: # end: timestamp
 7484: #
 7485:     my (%filters)=@_;
 7486:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7487:     if ($filters{'url'}) {
 7488: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7489:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7490:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7491:     }
 7492:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7493:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7494:     return &log_query($cname,$cdom,'courselog',%filters);
 7495: }
 7496: 
 7497: sub userlog_query {
 7498: #
 7499: # possible filters:
 7500: # action: log check role
 7501: # start: timestamp
 7502: # end: timestamp
 7503: #
 7504:     my ($uname,$udom,%filters)=@_;
 7505:     return &log_query($uname,$udom,'userlog',%filters);
 7506: }
 7507: 
 7508: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7509: 
 7510: sub auto_run {
 7511:     my ($cnum,$cdom) = @_;
 7512:     my $response = 0;
 7513:     my $settings;
 7514:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7515:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7516:         $settings = $domconfig{'autoenroll'};
 7517:         if ($settings->{'run'} eq '1') {
 7518:             $response = 1;
 7519:         }
 7520:     } else {
 7521:         my $homeserver;
 7522:         if (&is_course($cdom,$cnum)) {
 7523:             $homeserver = &homeserver($cnum,$cdom);
 7524:         } else {
 7525:             $homeserver = &domain($cdom,'primary');
 7526:         }
 7527:         if ($homeserver ne 'no_host') {
 7528:             $response = &reply('autorun:'.$cdom,$homeserver);
 7529:         }
 7530:     }
 7531:     return $response;
 7532: }
 7533: 
 7534: sub auto_get_sections {
 7535:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7536:     my $homeserver;
 7537:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7538:         $homeserver = &homeserver($cnum,$cdom);
 7539:     }
 7540:     if (!defined($homeserver)) { 
 7541:         if ($cdom =~ /^$match_domain$/) {
 7542:             $homeserver = &domain($cdom,'primary');
 7543:         }
 7544:     }
 7545:     my @secs;
 7546:     if (defined($homeserver)) {
 7547:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7548:         unless ($response eq 'refused') {
 7549:             @secs = split(/:/,$response);
 7550:         }
 7551:     }
 7552:     return @secs;
 7553: }
 7554: 
 7555: sub auto_new_course {
 7556:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7557:     my $homeserver = &homeserver($cnum,$cdom);
 7558:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7559:     return $response;
 7560: }
 7561: 
 7562: sub auto_validate_courseID {
 7563:     my ($cnum,$cdom,$inst_course_id) = @_;
 7564:     my $homeserver = &homeserver($cnum,$cdom);
 7565:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7566:     return $response;
 7567: }
 7568: 
 7569: sub auto_validate_instcode {
 7570:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7571:     my ($homeserver,$response);
 7572:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7573:         $homeserver = &homeserver($cnum,$cdom);
 7574:     }
 7575:     if (!defined($homeserver)) {
 7576:         if ($cdom =~ /^$match_domain$/) {
 7577:             $homeserver = &domain($cdom,'primary');
 7578:         }
 7579:     }
 7580:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7581:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7582:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7583:     return ($outcome,$description,$defaultcredits);
 7584: }
 7585: 
 7586: sub auto_create_password {
 7587:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7588:     my ($homeserver,$response);
 7589:     my $create_passwd = 0;
 7590:     my $authchk = '';
 7591:     if ($udom =~ /^$match_domain$/) {
 7592:         $homeserver = &domain($udom,'primary');
 7593:     }
 7594:     if ($homeserver eq '') {
 7595:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7596:             $homeserver = &homeserver($cnum,$cdom);
 7597:         }
 7598:     }
 7599:     if ($homeserver eq '') {
 7600:         $authchk = 'nodomain';
 7601:     } else {
 7602:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7603:         if ($response eq 'refused') {
 7604:             $authchk = 'refused';
 7605:         } else {
 7606:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7607:         }
 7608:     }
 7609:     return ($authparam,$create_passwd,$authchk);
 7610: }
 7611: 
 7612: sub auto_photo_permission {
 7613:     my ($cnum,$cdom,$students) = @_;
 7614:     my $homeserver = &homeserver($cnum,$cdom);
 7615:     my ($outcome,$perm_reqd,$conditions) = 
 7616: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7617:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7618: 	return (undef,undef);
 7619:     }
 7620:     return ($outcome,$perm_reqd,$conditions);
 7621: }
 7622: 
 7623: sub auto_checkphotos {
 7624:     my ($uname,$udom,$pid) = @_;
 7625:     my $homeserver = &homeserver($uname,$udom);
 7626:     my ($result,$resulttype);
 7627:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7628: 				   &escape($uname).':'.&escape($pid),
 7629: 				   $homeserver));
 7630:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7631: 	return (undef,undef);
 7632:     }
 7633:     if ($outcome) {
 7634:         ($result,$resulttype) = split(/:/,$outcome);
 7635:     } 
 7636:     return ($result,$resulttype);
 7637: }
 7638: 
 7639: sub auto_photochoice {
 7640:     my ($cnum,$cdom) = @_;
 7641:     my $homeserver = &homeserver($cnum,$cdom);
 7642:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7643: 						       &escape($cdom),
 7644: 						       $homeserver)));
 7645:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7646: 	return (undef,undef);
 7647:     }
 7648:     return ($update,$comment);
 7649: }
 7650: 
 7651: sub auto_photoupdate {
 7652:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7653:     my $homeserver = &homeserver($cnum,$dom);
 7654:     my $host=&hostname($homeserver);
 7655:     my $cmd = '';
 7656:     my $maxtries = 1;
 7657:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7658:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7659:     }
 7660:     $cmd =~ s/%%$//;
 7661:     $cmd = &escape($cmd);
 7662:     my $query = 'institutionalphotos';
 7663:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7664:     unless ($queryid=~/^\Q$host\E\_/) {
 7665:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7666:         return 'error: '.$queryid;
 7667:     }
 7668:     my $reply = &get_query_reply($queryid);
 7669:     my $tries = 1;
 7670:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7671:         $reply = &get_query_reply($queryid);
 7672:         $tries ++;
 7673:     }
 7674:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7675:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7676:     } else {
 7677:         my @responses = split(/:/,$reply);
 7678:         my $outcome = shift(@responses); 
 7679:         foreach my $item (@responses) {
 7680:             my ($key,$value) = split(/=/,$item);
 7681:             $$photo{$key} = $value;
 7682:         }
 7683:         return $outcome;
 7684:     }
 7685:     return 'error';
 7686: }
 7687: 
 7688: sub auto_instcode_format {
 7689:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7690: 	$cat_order) = @_;
 7691:     my $courses = '';
 7692:     my @homeservers;
 7693:     if ($caller eq 'global') {
 7694: 	my %servers = &get_servers($codedom,'library');
 7695: 	foreach my $tryserver (keys(%servers)) {
 7696: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7697: 		push(@homeservers,$tryserver);
 7698: 	    }
 7699:         }
 7700:     } elsif ($caller eq 'requests') {
 7701:         if ($codedom =~ /^$match_domain$/) {
 7702:             my $chome = &domain($codedom,'primary');
 7703:             unless ($chome eq 'no_host') {
 7704:                 push(@homeservers,$chome);
 7705:             }
 7706:         }
 7707:     } else {
 7708:         push(@homeservers,&homeserver($caller,$codedom));
 7709:     }
 7710:     foreach my $code (keys(%{$instcodes})) {
 7711:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7712:     }
 7713:     chop($courses);
 7714:     my $ok_response = 0;
 7715:     my $response;
 7716:     while (@homeservers > 0 && $ok_response == 0) {
 7717:         my $server = shift(@homeservers); 
 7718:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7719:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7720:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7721: 		split(/:/,$response);
 7722:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7723:             push(@{$codetitles},&str2array($codetitles_str));
 7724:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7725:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7726:             $ok_response = 1;
 7727:         }
 7728:     }
 7729:     if ($ok_response) {
 7730:         return 'ok';
 7731:     } else {
 7732:         return $response;
 7733:     }
 7734: }
 7735: 
 7736: sub auto_instcode_defaults {
 7737:     my ($domain,$returnhash,$code_order) = @_;
 7738:     my @homeservers;
 7739: 
 7740:     my %servers = &get_servers($domain,'library');
 7741:     foreach my $tryserver (keys(%servers)) {
 7742: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7743: 	    push(@homeservers,$tryserver);
 7744: 	}
 7745:     }
 7746: 
 7747:     my $response;
 7748:     foreach my $server (@homeservers) {
 7749:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7750:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7751: 	
 7752: 	foreach my $pair (split(/\&/,$response)) {
 7753: 	    my ($name,$value)=split(/\=/,$pair);
 7754: 	    if ($name eq 'code_order') {
 7755: 		@{$code_order} = split(/\&/,&unescape($value));
 7756: 	    } else {
 7757: 		$returnhash->{&unescape($name)}=&unescape($value);
 7758: 	    }
 7759: 	}
 7760: 	return 'ok';
 7761:     }
 7762: 
 7763:     return $response;
 7764: }
 7765: 
 7766: sub auto_possible_instcodes {
 7767:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7768:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7769:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7770:         return;
 7771:     }
 7772:     my (@homeservers,$uhome);
 7773:     if (defined(&domain($domain,'primary'))) {
 7774:         $uhome=&domain($domain,'primary');
 7775:         push(@homeservers,&domain($domain,'primary'));
 7776:     } else {
 7777:         my %servers = &get_servers($domain,'library');
 7778:         foreach my $tryserver (keys(%servers)) {
 7779:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7780:                 push(@homeservers,$tryserver);
 7781:             }
 7782:         }
 7783:     }
 7784:     my $response;
 7785:     foreach my $server (@homeservers) {
 7786:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7787:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7788:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7789:             split(':',$response);
 7790:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7791:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7792:         foreach my $item (split('&',$cat_title)) {   
 7793:             my ($name,$value)=split('=',$item);
 7794:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7795:         }
 7796:         foreach my $item (split('&',$cat_order)) {
 7797:             my ($name,$value)=split('=',$item);
 7798:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7799:         }
 7800:         return 'ok';
 7801:     }
 7802:     return $response;
 7803: }
 7804: 
 7805: sub auto_courserequest_checks {
 7806:     my ($dom) = @_;
 7807:     my ($homeserver,%validations);
 7808:     if ($dom =~ /^$match_domain$/) {
 7809:         $homeserver = &domain($dom,'primary');
 7810:     }
 7811:     unless ($homeserver eq 'no_host') {
 7812:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7813:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7814:             my @items = split(/&/,$response);
 7815:             foreach my $item (@items) {
 7816:                 my ($key,$value) = split('=',$item);
 7817:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7818:             }
 7819:         }
 7820:     }
 7821:     return %validations; 
 7822: }
 7823: 
 7824: sub auto_courserequest_validation {
 7825:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7826:     my ($homeserver,$response);
 7827:     if ($dom =~ /^$match_domain$/) {
 7828:         $homeserver = &domain($dom,'primary');
 7829:     }
 7830:     unless ($homeserver eq 'no_host') {  
 7831:           
 7832:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7833:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7834:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7835:                                     $homeserver));
 7836:     }
 7837:     return $response;
 7838: }
 7839: 
 7840: sub auto_validate_class_sec {
 7841:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7842:     my $homeserver = &homeserver($cnum,$cdom);
 7843:     my $ownerlist;
 7844:     if (ref($owners) eq 'ARRAY') {
 7845:         $ownerlist = join(',',@{$owners});
 7846:     } else {
 7847:         $ownerlist = $owners;
 7848:     }
 7849:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7850:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7851:     return $response;
 7852: }
 7853: 
 7854: sub auto_crsreq_update {
 7855:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 7856:         $code,$inbound) = @_;
 7857:     my ($homeserver,%crsreqresponse);
 7858:     if ($cdom =~ /^$match_domain$/) {
 7859:         $homeserver = &domain($cdom,'primary');
 7860:     }
 7861:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 7862:         my $info;
 7863:         if (ref($inbound) eq 'HASH') {
 7864:             $info = &freeze_escape($inbound);
 7865:         }
 7866:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 7867:                             ':'.&escape($action).':'.&escape($ownername).':'.
 7868:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 7869:                             &escape($title).':'.&escape($code).':'.$info,$homeserver);
 7870:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7871:             my @items = split(/&/,$response);
 7872:             foreach my $item (@items) {
 7873:                 my ($key,$value) = split('=',$item);
 7874:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 7875:             }
 7876:         }
 7877:     }
 7878:     return \%crsreqresponse;
 7879: }
 7880: 
 7881: # ------------------------------------------------------- Course Group routines
 7882: 
 7883: sub get_coursegroups {
 7884:     my ($cdom,$cnum,$group,$namespace) = @_;
 7885:     return(&dump($namespace,$cdom,$cnum,$group));
 7886: }
 7887: 
 7888: sub modify_coursegroup {
 7889:     my ($cdom,$cnum,$groupsettings) = @_;
 7890:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7891: }
 7892: 
 7893: sub toggle_coursegroup_status {
 7894:     my ($cdom,$cnum,$group,$action) = @_;
 7895:     my ($from_namespace,$to_namespace);
 7896:     if ($action eq 'delete') {
 7897:         $from_namespace = 'coursegroups';
 7898:         $to_namespace = 'deleted_groups';
 7899:     } else {
 7900:         $from_namespace = 'deleted_groups';
 7901:         $to_namespace = 'coursegroups';
 7902:     }
 7903:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7904:     if (my $tmp = &error(%curr_group)) {
 7905:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7906:         return ('read error',$tmp);
 7907:     } else {
 7908:         my %savedsettings = %curr_group; 
 7909:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7910:         my $deloutcome;
 7911:         if ($result eq 'ok') {
 7912:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7913:         } else {
 7914:             return ('write error',$result);
 7915:         }
 7916:         if ($deloutcome eq 'ok') {
 7917:             return 'ok';
 7918:         } else {
 7919:             return ('delete error',$deloutcome);
 7920:         }
 7921:     }
 7922: }
 7923: 
 7924: sub modify_group_roles {
 7925:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7926:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7927:     my $role = 'gr/'.&escape($userprivs);
 7928:     my ($uname,$udom) = split(/:/,$user);
 7929:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7930:     if ($result eq 'ok') {
 7931:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7932:     }
 7933:     return $result;
 7934: }
 7935: 
 7936: sub modify_coursegroup_membership {
 7937:     my ($cdom,$cnum,$membership) = @_;
 7938:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7939:     return $result;
 7940: }
 7941: 
 7942: sub get_active_groups {
 7943:     my ($udom,$uname,$cdom,$cnum) = @_;
 7944:     my $now = time;
 7945:     my %groups = ();
 7946:     foreach my $key (keys(%env)) {
 7947:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7948:             my ($start,$end) = split(/\./,$env{$key});
 7949:             if (($end!=0) && ($end<$now)) { next; }
 7950:             if (($start!=0) && ($start>$now)) { next; }
 7951:             if ($1 eq $cdom && $2 eq $cnum) {
 7952:                 $groups{$3} = $env{$key} ;
 7953:             }
 7954:         }
 7955:     }
 7956:     return %groups;
 7957: }
 7958: 
 7959: sub get_group_membership {
 7960:     my ($cdom,$cnum,$group) = @_;
 7961:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7962: }
 7963: 
 7964: sub get_users_groups {
 7965:     my ($udom,$uname,$courseid) = @_;
 7966:     my @usersgroups;
 7967:     my $cachetime=1800;
 7968: 
 7969:     my $hashid="$udom:$uname:$courseid";
 7970:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7971:     if (defined($cached)) {
 7972:         @usersgroups = split(/:/,$grouplist);
 7973:     } else {  
 7974:         $grouplist = '';
 7975:         my $courseurl = &courseid_to_courseurl($courseid);
 7976:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7977:         my $access_end = $env{'course.'.$courseid.
 7978:                               '.default_enrollment_end_date'};
 7979:         my $now = time;
 7980:         foreach my $key (keys(%roleshash)) {
 7981:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7982:                 my $group = $1;
 7983:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7984:                     my $start = $2;
 7985:                     my $end = $1;
 7986:                     if ($start == -1) { next; } # deleted from group
 7987:                     if (($start!=0) && ($start>$now)) { next; }
 7988:                     if (($end!=0) && ($end<$now)) {
 7989:                         if ($access_end && $access_end < $now) {
 7990:                             if ($access_end - $end < 86400) {
 7991:                                 push(@usersgroups,$group);
 7992:                             }
 7993:                         }
 7994:                         next;
 7995:                     }
 7996:                     push(@usersgroups,$group);
 7997:                 }
 7998:             }
 7999:         }
 8000:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8001:         $grouplist = join(':',@usersgroups);
 8002:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8003:     }
 8004:     return @usersgroups;
 8005: }
 8006: 
 8007: sub devalidate_getgroups_cache {
 8008:     my ($udom,$uname,$cdom,$cnum)=@_;
 8009:     my $courseid = $cdom.'_'.$cnum;
 8010: 
 8011:     my $hashid="$udom:$uname:$courseid";
 8012:     &devalidate_cache_new('getgroups',$hashid);
 8013: }
 8014: 
 8015: # ------------------------------------------------------------------ Plain Text
 8016: 
 8017: sub plaintext {
 8018:     my ($short,$type,$cid,$forcedefault) = @_;
 8019:     if ($short =~ m{^cr/}) {
 8020: 	return (split('/',$short))[-1];
 8021:     }
 8022:     if (!defined($cid)) {
 8023:         $cid = $env{'request.course.id'};
 8024:     }
 8025:     my %rolenames = (
 8026:                       Course    => 'std',
 8027:                       Community => 'alt1',
 8028:                     );
 8029:     if ($cid ne '') {
 8030:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8031:             unless ($forcedefault) {
 8032:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8033:                 &Apache::lonlocal::mt_escape(\$roletext);
 8034:                 return &Apache::lonlocal::mt($roletext);
 8035:             }
 8036:         }
 8037:     }
 8038:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8039:         (defined($rolenames{$type})) && 
 8040:         (defined($prp{$short}{$rolenames{$type}}))) {
 8041:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8042:     } elsif ($cid ne '') {
 8043:         my $crstype = $env{'course.'.$cid.'.type'};
 8044:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8045:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8046:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8047:         }
 8048:     }
 8049:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8050: }
 8051: 
 8052: # ----------------------------------------------------------------- Assign Role
 8053: 
 8054: sub assignrole {
 8055:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8056:         $context)=@_;
 8057:     my $mrole;
 8058:     if ($role =~ /^cr\//) {
 8059:         my $cwosec=$url;
 8060:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8061: 	unless (&allowed('ccr',$cwosec)) {
 8062:            my $refused = 1;
 8063:            if ($context eq 'requestcourses') {
 8064:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8065:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8066:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8067:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8068:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8069:                            if ($crsenv{'internal.courseowner'} eq
 8070:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8071:                                $refused = '';
 8072:                            }
 8073:                        }
 8074:                    }
 8075:                }
 8076:            }
 8077:            if ($refused) {
 8078:                &logthis('Refused custom assignrole: '.
 8079:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8080:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8081:                return 'refused';
 8082:            }
 8083:         }
 8084:         $mrole='cr';
 8085:     } elsif ($role =~ /^gr\//) {
 8086:         my $cwogrp=$url;
 8087:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8088:         unless (&allowed('mdg',$cwogrp)) {
 8089:             &logthis('Refused group assignrole: '.
 8090:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8091:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8092:             return 'refused';
 8093:         }
 8094:         $mrole='gr';
 8095:     } else {
 8096:         my $cwosec=$url;
 8097:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8098:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8099:             my $refused;
 8100:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8101:                 if (!(&allowed('c'.$role,$url))) {
 8102:                     $refused = 1;
 8103:                 }
 8104:             } else {
 8105:                 $refused = 1;
 8106:             }
 8107:             if ($refused) {
 8108:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8109:                 if (!$selfenroll && $context eq 'course') {
 8110:                     my %crsenv;
 8111:                     if ($role eq 'cc' || $role eq 'co') {
 8112:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8113:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8114:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8115:                                 if ($crsenv{'internal.courseowner'} eq 
 8116:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8117:                                     $refused = '';
 8118:                                 }
 8119:                             }
 8120:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8121:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8122:                                 if ($crsenv{'internal.courseowner'} eq 
 8123:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8124:                                     $refused = '';
 8125:                                 }
 8126:                             }
 8127:                         }
 8128:                     }
 8129:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8130:                     $refused = '';
 8131:                 } elsif ($context eq 'requestcourses') {
 8132:                     my @possroles = ('st','ta','ep','in','cc','co');
 8133:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8134:                         my $wrongcc;
 8135:                         if ($cnum =~ /^$match_community$/) {
 8136:                             $wrongcc = 1 if ($role eq 'cc');
 8137:                         } else {
 8138:                             $wrongcc = 1 if ($role eq 'co');
 8139:                         }
 8140:                         unless ($wrongcc) {
 8141:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8142:                             if ($crsenv{'internal.courseowner'} eq 
 8143:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8144:                                 $refused = '';
 8145:                             }
 8146:                         }
 8147:                     }
 8148:                 } elsif ($context eq 'requestauthor') {
 8149:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8150:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8151:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8152:                             $refused = '';
 8153:                         } else {
 8154:                             my %domdefaults = &get_domain_defaults($udom);
 8155:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8156:                                 my $checkbystatus;
 8157:                                 if ($env{'user.adv'}) { 
 8158:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8159:                                     if ($disposition eq 'automatic') {
 8160:                                         $refused = '';
 8161:                                     } elsif ($disposition eq '') {
 8162:                                         $checkbystatus = 1;
 8163:                                     } 
 8164:                                 } else {
 8165:                                     $checkbystatus = 1;
 8166:                                 }
 8167:                                 if ($checkbystatus) {
 8168:                                     if ($env{'environment.inststatus'}) {
 8169:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8170:                                         foreach my $type (@inststatuses) {
 8171:                                             if (($type ne '') &&
 8172:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8173:                                                 $refused = '';
 8174:                                             }
 8175:                                         }
 8176:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8177:                                         $refused = '';
 8178:                                     }
 8179:                                 }
 8180:                             }
 8181:                         }
 8182:                     }
 8183:                 }
 8184:                 if ($refused) {
 8185:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8186:                              ' '.$role.' '.$end.' '.$start.' by '.
 8187: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8188:                     return 'refused';
 8189:                 }
 8190:             }
 8191:         } elsif ($role eq 'au') {
 8192:             if ($url ne '/'.$udom.'/') {
 8193:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8194:                          ' to assign author role for '.$uname.':'.$udom.
 8195:                          ' in domain: '.$url.' refused (wrong domain).');
 8196:                 return 'refused';
 8197:             }
 8198:         }
 8199:         $mrole=$role;
 8200:     }
 8201:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8202:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8203:     if ($end) { $command.='_'.$end; }
 8204:     if ($start) {
 8205: 	if ($end) { 
 8206:            $command.='_'.$start; 
 8207:         } else {
 8208:            $command.='_0_'.$start;
 8209:         }
 8210:     }
 8211:     my $origstart = $start;
 8212:     my $origend = $end;
 8213:     my $delflag;
 8214: # actually delete
 8215:     if ($deleteflag) {
 8216: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8217: # modify command to delete the role
 8218:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8219:                 "$udom:$uname:$url".'_'."$mrole";
 8220: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8221: # set start and finish to negative values for userrolelog
 8222:            $start=-1;
 8223:            $end=-1;
 8224:            $delflag = 1;
 8225:         }
 8226:     }
 8227: # send command
 8228:     my $answer=&reply($command,&homeserver($uname,$udom));
 8229: # log new user role if status is ok
 8230:     if ($answer eq 'ok') {
 8231: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8232:         if (($role eq 'cc') || ($role eq 'in') ||
 8233:             ($role eq 'ep') || ($role eq 'ad') ||
 8234:             ($role eq 'ta') || ($role eq 'st') ||
 8235:             ($role=~/^cr/) || ($role eq 'gr') ||
 8236:             ($role eq 'co')) {
 8237: # for course roles, perform group memberships changes triggered by role change.
 8238:             unless ($role =~ /^gr/) {
 8239:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8240:                                                  $origstart,$selfenroll,$context);
 8241:             }
 8242:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8243:                            $selfenroll,$context);
 8244:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8245:                  ($role eq 'au') || ($role eq 'dc')) {
 8246:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8247:                            $context);
 8248:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8249:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8250:                              $context); 
 8251:         }
 8252:         if ($role eq 'cc') {
 8253:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8254:         }
 8255:     }
 8256:     return $answer;
 8257: }
 8258: 
 8259: sub autoupdate_coowners {
 8260:     my ($url,$end,$start,$uname,$udom) = @_;
 8261:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8262:     if (($cdom ne '') && ($cnum ne '')) {
 8263:         my $now = time;
 8264:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8265:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8266:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8267:             my $instcode = $coursehash{'internal.coursecode'};
 8268:             if ($instcode ne '') {
 8269:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8270:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8271:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8272:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8273:                         if ($result eq 'valid') {
 8274:                             if ($coursehash{'internal.co-owners'}) {
 8275:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8276:                                     push(@newcoowners,$coowner);
 8277:                                 }
 8278:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8279:                                     push(@newcoowners,$uname.':'.$udom);
 8280:                                 }
 8281:                                 @newcoowners = sort(@newcoowners);
 8282:                             } else {
 8283:                                 push(@newcoowners,$uname.':'.$udom);
 8284:                             }
 8285:                         } else {
 8286:                             if ($coursehash{'internal.co-owners'}) {
 8287:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8288:                                     unless ($coowner eq $uname.':'.$udom) {
 8289:                                         push(@newcoowners,$coowner);
 8290:                                     }
 8291:                                 }
 8292:                                 unless (@newcoowners > 0) {
 8293:                                     $delcoowners = 1;
 8294:                                     $coowners = '';
 8295:                                 }
 8296:                             }
 8297:                         }
 8298:                         if (@newcoowners || $delcoowners) {
 8299:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8300:                                             $delcoowners,@newcoowners);
 8301:                         }
 8302:                     }
 8303:                 }
 8304:             }
 8305:         }
 8306:     }
 8307: }
 8308: 
 8309: sub store_coowners {
 8310:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8311:     my $cid = $cdom.'_'.$cnum;
 8312:     my ($coowners,$delresult,$putresult);
 8313:     if (@newcoowners) {
 8314:         $coowners = join(',',@newcoowners);
 8315:         my %coownershash = (
 8316:                             'internal.co-owners' => $coowners,
 8317:                            );
 8318:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8319:         if ($putresult eq 'ok') {
 8320:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8321:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8322:             }
 8323:         }
 8324:     }
 8325:     if ($delcoowners) {
 8326:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8327:         if ($delresult eq 'ok') {
 8328:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8329:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8330:             }
 8331:         }
 8332:     }
 8333:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8334:         my %crsinfo =
 8335:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8336:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8337:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8338:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8339:         }
 8340:     }
 8341: }
 8342: 
 8343: # -------------------------------------------------- Modify user authentication
 8344: # Overrides without validation
 8345: 
 8346: sub modifyuserauth {
 8347:     my ($udom,$uname,$umode,$upass)=@_;
 8348:     my $uhome=&homeserver($uname,$udom);
 8349:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8350:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8351:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8352:              ' in domain '.$env{'request.role.domain'});  
 8353:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8354: 		     &escape($upass),$uhome);
 8355:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8356:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8357:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8358:     &log($udom,,$uname,$uhome,
 8359:         'Authentication changed by '.$env{'user.domain'}.', '.
 8360:                                      $env{'user.name'}.', '.$umode.
 8361:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8362:     unless ($reply eq 'ok') {
 8363:         &logthis('Authentication mode error: '.$reply);
 8364: 	return 'error: '.$reply;
 8365:     }   
 8366:     return 'ok';
 8367: }
 8368: 
 8369: # --------------------------------------------------------------- Modify a user
 8370: 
 8371: sub modifyuser {
 8372:     my ($udom,    $uname, $uid,
 8373:         $umode,   $upass, $first,
 8374:         $middle,  $last,  $gene,
 8375:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8376:     $udom= &LONCAPA::clean_domain($udom);
 8377:     $uname=&LONCAPA::clean_username($uname);
 8378:     my $showcandelete = 'none';
 8379:     if (ref($candelete) eq 'ARRAY') {
 8380:         if (@{$candelete} > 0) {
 8381:             $showcandelete = join(', ',@{$candelete});
 8382:         }
 8383:     }
 8384:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8385:              $umode.', '.$first.', '.$middle.', '.
 8386: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8387:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8388:                                      ' desiredhome not specified'). 
 8389:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8390:              ' in domain '.$env{'request.role.domain'});
 8391:     my $uhome=&homeserver($uname,$udom,'true');
 8392:     my $newuser;
 8393:     if ($uhome eq 'no_host') {
 8394:         $newuser = 1;
 8395:     }
 8396: # ----------------------------------------------------------------- Create User
 8397:     if (($uhome eq 'no_host') && 
 8398: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8399:         my $unhome='';
 8400:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8401:             $unhome = $desiredhome;
 8402: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8403: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8404:         } else { # load balancing routine for determining $unhome
 8405:             my $loadm=10000000;
 8406: 	    my %servers = &get_servers($udom,'library');
 8407: 	    foreach my $tryserver (keys(%servers)) {
 8408: 		my $answer=reply('load',$tryserver);
 8409: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8410: 		    $loadm=$answer;
 8411: 		    $unhome=$tryserver;
 8412: 		}
 8413: 	    }
 8414:         }
 8415:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8416: 	    return 'error: unable to find a home server for '.$uname.
 8417:                    ' in domain '.$udom;
 8418:         }
 8419:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8420:                          &escape($upass),$unhome);
 8421: 	unless ($reply eq 'ok') {
 8422:             return 'error: '.$reply;
 8423:         }   
 8424:         $uhome=&homeserver($uname,$udom,'true');
 8425:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8426: 	    return 'error: unable verify users home machine.';
 8427:         }
 8428:     }   # End of creation of new user
 8429: # ---------------------------------------------------------------------- Add ID
 8430:     if ($uid) {
 8431:        $uid=~tr/A-Z/a-z/;
 8432:        my %uidhash=&idrget($udom,$uname);
 8433:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8434:          && (!$forceid)) {
 8435: 	  unless ($uid eq $uidhash{$uname}) {
 8436: 	      return 'error: user id "'.$uid.'" does not match '.
 8437:                   'current user id "'.$uidhash{$uname}.'".';
 8438:           }
 8439:        } else {
 8440: 	  &idput($udom,($uname => $uid));
 8441:        }
 8442:     }
 8443: # -------------------------------------------------------------- Add names, etc
 8444:     my @tmp=&get('environment',
 8445: 		   ['firstname','middlename','lastname','generation','id',
 8446:                     'permanentemail','inststatus'],
 8447: 		   $udom,$uname);
 8448:     my (%names,%oldnames);
 8449:     if ($tmp[0] =~ m/^error:.*/) { 
 8450:         %names=(); 
 8451:     } else {
 8452:         %names = @tmp;
 8453:         %oldnames = %names;
 8454:     }
 8455: #
 8456: # If name, email and/or uid are blank (e.g., because an uploaded file
 8457: # of users did not contain them), do not overwrite existing values
 8458: # unless field is in $candelete array ref.  
 8459: #
 8460: 
 8461:     my @fields = ('firstname','middlename','lastname','generation',
 8462:                   'permanentemail','id');
 8463:     my %newvalues;
 8464:     if (ref($candelete) eq 'ARRAY') {
 8465:         foreach my $field (@fields) {
 8466:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8467:                 if ($field eq 'firstname') {
 8468:                     $names{$field} = $first;
 8469:                 } elsif ($field eq 'middlename') {
 8470:                     $names{$field} = $middle;
 8471:                 } elsif ($field eq 'lastname') {
 8472:                     $names{$field} = $last;
 8473:                 } elsif ($field eq 'generation') { 
 8474:                     $names{$field} = $gene;
 8475:                 } elsif ($field eq 'permanentemail') {
 8476:                     $names{$field} = $email;
 8477:                 } elsif ($field eq 'id') {
 8478:                     $names{$field}  = $uid;
 8479:                 }
 8480:             }
 8481:         }
 8482:     }
 8483:     if ($first)  { $names{'firstname'}  = $first; }
 8484:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8485:     if ($last)   { $names{'lastname'}   = $last; }
 8486:     if (defined($gene))   { $names{'generation'} = $gene; }
 8487:     if ($email) {
 8488:        $email=~s/[^\w\@\.\-\,]//gs;
 8489:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8490:     }
 8491:     if ($uid) { $names{'id'}  = $uid; }
 8492:     if (defined($inststatus)) {
 8493:         $names{'inststatus'} = '';
 8494:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8495:         if (ref($usertypes) eq 'HASH') {
 8496:             my @okstatuses; 
 8497:             foreach my $item (split(/:/,$inststatus)) {
 8498:                 if (defined($usertypes->{$item})) {
 8499:                     push(@okstatuses,$item);  
 8500:                 }
 8501:             }
 8502:             if (@okstatuses) {
 8503:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8504:             }
 8505:         }
 8506:     }
 8507:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8508:                  $umode.', '.$first.', '.$middle.', '.
 8509:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8510:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8511:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8512:     } else {
 8513:         $logmsg .= ' during self creation';
 8514:     }
 8515:     my $changed;
 8516:     if ($newuser) {
 8517:         $changed = 1;
 8518:     } else {
 8519:         foreach my $field (@fields) {
 8520:             if ($names{$field} ne $oldnames{$field}) {
 8521:                 $changed = 1;
 8522:                 last;
 8523:             }
 8524:         }
 8525:     }
 8526:     unless ($changed) {
 8527:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8528:         &logthis($logmsg);
 8529:         return 'ok';
 8530:     }
 8531:     my $reply = &put('environment', \%names, $udom,$uname);
 8532:     if ($reply ne 'ok') { 
 8533:         return 'error: '.$reply;
 8534:     }
 8535:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8536:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8537:     }
 8538:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8539:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8540:     $logmsg = 'Success modifying user '.$logmsg;
 8541:     &logthis($logmsg);
 8542:     return 'ok';
 8543: }
 8544: 
 8545: # -------------------------------------------------------------- Modify student
 8546: 
 8547: sub modifystudent {
 8548:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8549:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8550:         $selfenroll,$context,$inststatus,$credits)=@_;
 8551:     if (!$cid) {
 8552: 	unless ($cid=$env{'request.course.id'}) {
 8553: 	    return 'not_in_class';
 8554: 	}
 8555:     }
 8556: # --------------------------------------------------------------- Make the user
 8557:     my $reply=&modifyuser
 8558: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8559:          $desiredhome,$email,$inststatus);
 8560:     unless ($reply eq 'ok') { return $reply; }
 8561:     # This will cause &modify_student_enrollment to get the uid from the
 8562:     # student's environment
 8563:     $uid = undef if (!$forceid);
 8564:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8565:                                         $gene,$usec,$end,$start,$type,$locktype,
 8566:                                         $cid,$selfenroll,$context,$credits);
 8567:     return $reply;
 8568: }
 8569: 
 8570: sub modify_student_enrollment {
 8571:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8572:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8573:     my ($cdom,$cnum,$chome);
 8574:     if (!$cid) {
 8575: 	unless ($cid=$env{'request.course.id'}) {
 8576: 	    return 'not_in_class';
 8577: 	}
 8578: 	$cdom=$env{'course.'.$cid.'.domain'};
 8579: 	$cnum=$env{'course.'.$cid.'.num'};
 8580:     } else {
 8581: 	($cdom,$cnum)=split(/_/,$cid);
 8582:     }
 8583:     $chome=$env{'course.'.$cid.'.home'};
 8584:     if (!$chome) {
 8585: 	$chome=&homeserver($cnum,$cdom);
 8586:     }
 8587:     if (!$chome) { return 'unknown_course'; }
 8588:     # Make sure the user exists
 8589:     my $uhome=&homeserver($uname,$udom);
 8590:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8591: 	return 'error: no such user';
 8592:     }
 8593:     # Get student data if we were not given enough information
 8594:     if (!defined($first)  || $first  eq '' || 
 8595:         !defined($last)   || $last   eq '' || 
 8596:         !defined($uid)    || $uid    eq '' || 
 8597:         !defined($middle) || $middle eq '' || 
 8598:         !defined($gene)   || $gene   eq '') {
 8599:         # They did not supply us with enough data to enroll the student, so
 8600:         # we need to pick up more information.
 8601:         my %tmp = &get('environment',
 8602:                        ['firstname','middlename','lastname', 'generation','id']
 8603:                        ,$udom,$uname);
 8604: 
 8605:         #foreach my $key (keys(%tmp)) {
 8606:         #    &logthis("key $key = ".$tmp{$key});
 8607:         #}
 8608:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8609:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8610:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8611:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8612:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8613:     }
 8614:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8615:     my $user = "$uname:$udom";
 8616:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8617:     my $reply=cput('classlist',
 8618: 		   {$user => 
 8619: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8620: 		   $cdom,$cnum);
 8621:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8622:         &devalidate_getsection_cache($udom,$uname,$cid);
 8623:     } else { 
 8624: 	return 'error: '.$reply;
 8625:     }
 8626:     # Add student role to user
 8627:     my $uurl='/'.$cid;
 8628:     $uurl=~s/\_/\//g;
 8629:     if ($usec) {
 8630: 	$uurl.='/'.$usec;
 8631:     }
 8632:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8633:                              $selfenroll,$context);
 8634:     if ($result ne 'ok') {
 8635:         if ($old_entry{$user} ne '') {
 8636:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8637:         } else {
 8638:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8639:         }
 8640:     }
 8641:     return $result; 
 8642: }
 8643: 
 8644: sub format_name {
 8645:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8646:     my $name;
 8647:     if ($first ne 'lastname') {
 8648: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8649:     } else {
 8650: 	if ($lastname=~/\S/) {
 8651: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8652: 	    $name=~s/\s+,/,/;
 8653: 	} else {
 8654: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8655: 	}
 8656:     }
 8657:     $name=~s/^\s+//;
 8658:     $name=~s/\s+$//;
 8659:     $name=~s/\s+/ /g;
 8660:     return $name;
 8661: }
 8662: 
 8663: # ------------------------------------------------- Write to course preferences
 8664: 
 8665: sub writecoursepref {
 8666:     my ($courseid,%prefs)=@_;
 8667:     $courseid=~s/^\///;
 8668:     $courseid=~s/\_/\//g;
 8669:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8670:     my $chome=homeserver($cnum,$cdomain);
 8671:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8672: 	return 'error: no such course';
 8673:     }
 8674:     my $cstring='';
 8675:     foreach my $pref (keys(%prefs)) {
 8676: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8677:     }
 8678:     $cstring=~s/\&$//;
 8679:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8680: }
 8681: 
 8682: # ---------------------------------------------------------- Make/modify course
 8683: 
 8684: sub createcourse {
 8685:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8686:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8687:     $url=&declutter($url);
 8688:     my $cid='';
 8689:     if ($context eq 'requestcourses') {
 8690:         my $can_create = 0;
 8691:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8692:         if ($udom eq $ownerdom) {
 8693:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8694:                                   $context)) {
 8695:                 $can_create = 1;
 8696:             }
 8697:         } else {
 8698:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8699:                                            $category);
 8700:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8701:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8702:                 if (@curr > 0) {
 8703:                     my @options = qw(approval validate autolimit);
 8704:                     my $optregex = join('|',@options);
 8705:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8706:                         $can_create = 1;
 8707:                     }
 8708:                 }
 8709:             }
 8710:         }
 8711:         if ($can_create) {
 8712:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8713:                 unless (&allowed('ccc',$udom)) {
 8714:                     return 'refused'; 
 8715:                 }
 8716:             }
 8717:         } else {
 8718:             return 'refused';
 8719:         }
 8720:     } elsif (!&allowed('ccc',$udom)) {
 8721:         return 'refused';
 8722:     }
 8723: # --------------------------------------------------------------- Get Unique ID
 8724:     my $uname;
 8725:     if ($cnum =~ /^$match_courseid$/) {
 8726:         my $chome=&homeserver($cnum,$udom,'true');
 8727:         if (($chome eq '') || ($chome eq 'no_host')) {
 8728:             $uname = $cnum;
 8729:         } else {
 8730:             $uname = &generate_coursenum($udom,$crstype);
 8731:         }
 8732:     } else {
 8733:         $uname = &generate_coursenum($udom,$crstype);
 8734:     }
 8735:     return $uname if ($uname =~ /^error/);
 8736: # -------------------------------------------------- Check supplied server name
 8737:     if (!defined($course_server)) {
 8738:         if (defined(&domain($udom,'primary'))) {
 8739:             $course_server = &domain($udom,'primary');
 8740:         } else {
 8741:             $course_server = $env{'user.home'}; 
 8742:         }
 8743:     }
 8744:     my %host_servers =
 8745:         &Apache::lonnet::get_servers($udom,'library');
 8746:     unless ($host_servers{$course_server}) {
 8747:         return 'error: invalid home server for course: '.$course_server;
 8748:     }
 8749: # ------------------------------------------------------------- Make the course
 8750:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8751:                       $course_server);
 8752:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8753:     my $uhome=&homeserver($uname,$udom,'true');
 8754:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8755: 	return 'error: no such course';
 8756:     }
 8757: # ----------------------------------------------------------------- Course made
 8758: # log existence
 8759:     my $now = time;
 8760:     my $newcourse = {
 8761:                     $udom.'_'.$uname => {
 8762:                                      description => $description,
 8763:                                      inst_code   => $inst_code,
 8764:                                      owner       => $course_owner,
 8765:                                      type        => $crstype,
 8766:                                      creator     => $env{'user.name'}.':'.
 8767:                                                     $env{'user.domain'},
 8768:                                      created     => $now,
 8769:                                      context     => $context,
 8770:                                                 },
 8771:                     };
 8772:     &courseidput($udom,$newcourse,$uhome,'notime');
 8773: # set toplevel url
 8774:     my $topurl=$url;
 8775:     unless ($nonstandard) {
 8776: # ------------------------------------------ For standard courses, make top url
 8777:         my $mapurl=&clutter($url);
 8778:         if ($mapurl eq '/res/') { $mapurl=''; }
 8779:         $env{'form.initmap'}=(<<ENDINITMAP);
 8780: <map>
 8781: <resource id="1" type="start"></resource>
 8782: <resource id="2" src="$mapurl"></resource>
 8783: <resource id="3" type="finish"></resource>
 8784: <link index="1" from="1" to="2"></link>
 8785: <link index="2" from="2" to="3"></link>
 8786: </map>
 8787: ENDINITMAP
 8788:         $topurl=&declutter(
 8789:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8790:                           );
 8791:     }
 8792: # ----------------------------------------------------------- Write preferences
 8793:     &writecoursepref($udom.'_'.$uname,
 8794:                      ('description'              => $description,
 8795:                       'url'                      => $topurl,
 8796:                       'internal.creator'         => $env{'user.name'}.':'.
 8797:                                                     $env{'user.domain'},
 8798:                       'internal.created'         => $now,
 8799:                       'internal.creationcontext' => $context)
 8800:                     );
 8801:     return '/'.$udom.'/'.$uname;
 8802: }
 8803: 
 8804: # ------------------------------------------------------------------- Create ID
 8805: sub generate_coursenum {
 8806:     my ($udom,$crstype) = @_;
 8807:     my $domdesc = &domain($udom);
 8808:     return 'error: invalid domain' if ($domdesc eq '');
 8809:     my $first;
 8810:     if ($crstype eq 'Community') {
 8811:         $first = '0';
 8812:     } else {
 8813:         $first = int(1+rand(9)); 
 8814:     } 
 8815:     my $uname=$first.
 8816:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8817:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8818:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8819: # ----------------------------------------------- Make sure that does not exist
 8820:     my $uhome=&homeserver($uname,$udom,'true');
 8821:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8822:         if ($crstype eq 'Community') {
 8823:             $first = '0';
 8824:         } else {
 8825:             $first = int(1+rand(9));
 8826:         }
 8827:         $uname=$first.
 8828:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8829:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8830:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8831:         $uhome=&homeserver($uname,$udom,'true');
 8832:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8833:             return 'error: unable to generate unique course-ID';
 8834:         }
 8835:     }
 8836:     return $uname;
 8837: }
 8838: 
 8839: sub is_course {
 8840:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8841:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8842: 
 8843:     return unless $cdom and $cnum;
 8844: 
 8845:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8846:         '.');
 8847: 
 8848:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8849:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8850: }
 8851: 
 8852: sub store_userdata {
 8853:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8854:     my $result;
 8855:     if ($datakey ne '') {
 8856:         if (ref($storehash) eq 'HASH') {
 8857:             if ($udom eq '' || $uname eq '') {
 8858:                 $udom = $env{'user.domain'};
 8859:                 $uname = $env{'user.name'};
 8860:             }
 8861:             my $uhome=&homeserver($uname,$udom);
 8862:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8863:                 $result = 'error: no_host';
 8864:             } else {
 8865:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8866:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8867: 
 8868:                 my $namevalue='';
 8869:                 foreach my $key (keys(%{$storehash})) {
 8870:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8871:                 }
 8872:                 $namevalue=~s/\&$//;
 8873:                 unless ($namespace eq 'courserequests') {
 8874:                     $datakey = &escape($datakey);
 8875:                 }
 8876:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8877:                                   $namevalue,$uhome);
 8878:             }
 8879:         } else {
 8880:             $result = 'error: data to store was not a hash reference'; 
 8881:         }
 8882:     } else {
 8883:         $result= 'error: invalid requestkey'; 
 8884:     }
 8885:     return $result;
 8886: }
 8887: 
 8888: # ---------------------------------------------------------- Assign Custom Role
 8889: 
 8890: sub assigncustomrole {
 8891:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8892:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8893:                        $end,$start,$deleteflag,$selfenroll,$context);
 8894: }
 8895: 
 8896: # ----------------------------------------------------------------- Revoke Role
 8897: 
 8898: sub revokerole {
 8899:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8900:     my $now=time;
 8901:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8902: }
 8903: 
 8904: # ---------------------------------------------------------- Revoke Custom Role
 8905: 
 8906: sub revokecustomrole {
 8907:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8908:     my $now=time;
 8909:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8910:            $deleteflag,$selfenroll,$context);
 8911: }
 8912: 
 8913: # ------------------------------------------------------------ Disk usage
 8914: sub diskusage {
 8915:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8916:     $directorypath =~ s/\/$//;
 8917:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8918:                        .&escape($getpropath).':'.&escape($uname).':'
 8919:                        .&escape($udom),homeserver($uname,$udom));
 8920:     if ($listing eq 'unknown_cmd') {
 8921:         if ($getpropath) {
 8922:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8923:         }
 8924:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8925:     }
 8926:     return $listing;
 8927: }
 8928: 
 8929: sub is_locked {
 8930:     my ($file_name, $domain, $user, $which) = @_;
 8931:     my @check;
 8932:     my $is_locked;
 8933:     push (@check,$file_name);
 8934:     my %locked = &get('file_permissions',\@check,
 8935: 		      $env{'user.domain'},$env{'user.name'});
 8936:     my ($tmp)=keys(%locked);
 8937:     if ($tmp=~/^error:/) { undef(%locked); }
 8938:     
 8939:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8940:         $is_locked = 'false';
 8941:         foreach my $entry (@{$locked{$file_name}}) {
 8942:            if (ref($entry) eq 'ARRAY') {
 8943:                $is_locked = 'true';
 8944:                if (ref($which) eq 'ARRAY') {
 8945:                    push(@{$which},$entry);
 8946:                } else {
 8947:                    last;
 8948:                }
 8949:            }
 8950:        }
 8951:     } else {
 8952:         $is_locked = 'false';
 8953:     }
 8954:     return $is_locked;
 8955: }
 8956: 
 8957: sub declutter_portfile {
 8958:     my ($file) = @_;
 8959:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8960:     return $file;
 8961: }
 8962: 
 8963: # ------------------------------------------------------------- Mark as Read Only
 8964: 
 8965: sub mark_as_readonly {
 8966:     my ($domain,$user,$files,$what) = @_;
 8967:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8968:     my ($tmp)=keys(%current_permissions);
 8969:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8970:     foreach my $file (@{$files}) {
 8971: 	$file = &declutter_portfile($file);
 8972:         push(@{$current_permissions{$file}},$what);
 8973:     }
 8974:     &put('file_permissions',\%current_permissions,$domain,$user);
 8975:     return;
 8976: }
 8977: 
 8978: # ------------------------------------------------------------Save Selected Files
 8979: 
 8980: sub save_selected_files {
 8981:     my ($user, $path, @files) = @_;
 8982:     my $filename = $user."savedfiles";
 8983:     my @other_files = &files_not_in_path($user, $path);
 8984:     open (OUT, '>'.$tmpdir.$filename);
 8985:     foreach my $file (@files) {
 8986:         print (OUT $env{'form.currentpath'}.$file."\n");
 8987:     }
 8988:     foreach my $file (@other_files) {
 8989:         print (OUT $file."\n");
 8990:     }
 8991:     close (OUT);
 8992:     return 'ok';
 8993: }
 8994: 
 8995: sub clear_selected_files {
 8996:     my ($user) = @_;
 8997:     my $filename = $user."savedfiles";
 8998:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8999:     print (OUT undef);
 9000:     close (OUT);
 9001:     return ("ok");    
 9002: }
 9003: 
 9004: sub files_in_path {
 9005:     my ($user, $path) = @_;
 9006:     my $filename = $user."savedfiles";
 9007:     my %return_files;
 9008:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9009:     while (my $line_in = <IN>) {
 9010:         chomp ($line_in);
 9011:         my @paths_and_file = split (m!/!, $line_in);
 9012:         my $file_part = pop (@paths_and_file);
 9013:         my $path_part = join ('/', @paths_and_file);
 9014:         $path_part.='/';
 9015:         my $path_and_file = $path_part.$file_part;
 9016:         if ($path_part eq $path) {
 9017:             $return_files{$file_part}= 'selected';
 9018:         }
 9019:     }
 9020:     close (IN);
 9021:     return (\%return_files);
 9022: }
 9023: 
 9024: # called in portfolio select mode, to show files selected NOT in current directory
 9025: sub files_not_in_path {
 9026:     my ($user, $path) = @_;
 9027:     my $filename = $user."savedfiles";
 9028:     my @return_files;
 9029:     my $path_part;
 9030:     open(IN, '<'.LONCAPA::.$filename);
 9031:     while (my $line = <IN>) {
 9032:         #ok, I know it's clunky, but I want it to work
 9033:         my @paths_and_file = split(m|/|, $line);
 9034:         my $file_part = pop(@paths_and_file);
 9035:         chomp($file_part);
 9036:         my $path_part = join('/', @paths_and_file);
 9037:         $path_part .= '/';
 9038:         my $path_and_file = $path_part.$file_part;
 9039:         if ($path_part ne $path) {
 9040:             push(@return_files, ($path_and_file));
 9041:         }
 9042:     }
 9043:     close(OUT);
 9044:     return (@return_files);
 9045: }
 9046: 
 9047: #----------------------------------------------Get portfolio file permissions
 9048: 
 9049: sub get_portfile_permissions {
 9050:     my ($domain,$user) = @_;
 9051:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9052:     my ($tmp)=keys(%current_permissions);
 9053:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9054:     return \%current_permissions;
 9055: }
 9056: 
 9057: #---------------------------------------------Get portfolio file access controls
 9058: 
 9059: sub get_access_controls {
 9060:     my ($current_permissions,$group,$file) = @_;
 9061:     my %access;
 9062:     my $real_file = $file;
 9063:     $file =~ s/\.meta$//;
 9064:     if (defined($file)) {
 9065:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9066:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9067:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9068:             }
 9069:         }
 9070:     } else {
 9071:         foreach my $key (keys(%{$current_permissions})) {
 9072:             if ($key =~ /\0accesscontrol$/) {
 9073:                 if (defined($group)) {
 9074:                     if ($key !~ m-^\Q$group\E/-) {
 9075:                         next;
 9076:                     }
 9077:                 }
 9078:                 my ($fullpath) = split(/\0/,$key);
 9079:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9080:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9081:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9082:                     }
 9083:                 }
 9084:             }
 9085:         }
 9086:     }
 9087:     return %access;
 9088: }
 9089: 
 9090: sub modify_access_controls {
 9091:     my ($file_name,$changes,$domain,$user)=@_;
 9092:     my ($outcome,$deloutcome);
 9093:     my %store_permissions;
 9094:     my %new_values;
 9095:     my %new_control;
 9096:     my %translation;
 9097:     my @deletions = ();
 9098:     my $now = time;
 9099:     if (exists($$changes{'activate'})) {
 9100:         if (ref($$changes{'activate'}) eq 'HASH') {
 9101:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9102:             my $numnew = scalar(@newitems);
 9103:             for (my $i=0; $i<$numnew; $i++) {
 9104:                 my $newkey = $newitems[$i];
 9105:                 my $newid = &Apache::loncommon::get_cgi_id();
 9106:                 if ($newkey =~ /^\d+:/) { 
 9107:                     $newkey =~ s/^(\d+)/$newid/;
 9108:                     $translation{$1} = $newid;
 9109:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9110:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9111:                     $translation{$1} = $newid;
 9112:                 }
 9113:                 $new_values{$file_name."\0".$newkey} = 
 9114:                                           $$changes{'activate'}{$newitems[$i]};
 9115:                 $new_control{$newkey} = $now;
 9116:             }
 9117:         }
 9118:     }
 9119:     my %todelete;
 9120:     my %changed_items;
 9121:     foreach my $action ('delete','update') {
 9122:         if (exists($$changes{$action})) {
 9123:             if (ref($$changes{$action}) eq 'HASH') {
 9124:                 foreach my $key (keys(%{$$changes{$action}})) {
 9125:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9126:                     if ($action eq 'delete') { 
 9127:                         $todelete{$itemnum} = 1;
 9128:                     } else {
 9129:                         $changed_items{$itemnum} = $key;
 9130:                     }
 9131:                 }
 9132:             }
 9133:         }
 9134:     }
 9135:     # get lock on access controls for file.
 9136:     my $lockhash = {
 9137:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9138:                                                        ':'.$env{'user.domain'},
 9139:                    }; 
 9140:     my $tries = 0;
 9141:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9142:    
 9143:     while (($gotlock ne 'ok') && $tries <3) {
 9144:         $tries ++;
 9145:         sleep 1;
 9146:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9147:     }
 9148:     if ($gotlock eq 'ok') {
 9149:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9150:         my ($tmp)=keys(%curr_permissions);
 9151:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9152:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9153:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9154:             if (ref($curr_controls) eq 'HASH') {
 9155:                 foreach my $control_item (keys(%{$curr_controls})) {
 9156:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9157:                     if (defined($todelete{$itemnum})) {
 9158:                         push(@deletions,$file_name."\0".$control_item);
 9159:                     } else {
 9160:                         if (defined($changed_items{$itemnum})) {
 9161:                             $new_control{$changed_items{$itemnum}} = $now;
 9162:                             push(@deletions,$file_name."\0".$control_item);
 9163:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9164:                         } else {
 9165:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9166:                         }
 9167:                     }
 9168:                 }
 9169:             }
 9170:         }
 9171:         my ($group);
 9172:         if (&is_course($domain,$user)) {
 9173:             ($group,my $file) = split(/\//,$file_name,2);
 9174:         }
 9175:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9176:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9177:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9178:         #  remove lock
 9179:         my @del_lock = ($file_name."\0".'locked_access_records');
 9180:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9181:         my $sqlresult =
 9182:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9183:                                     $group);
 9184:     } else {
 9185:         $outcome = "error: could not obtain lockfile\n";  
 9186:     }
 9187:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9188: }
 9189: 
 9190: sub make_public_indefinitely {
 9191:     my ($requrl) = @_;
 9192:     my $now = time;
 9193:     my $action = 'activate';
 9194:     my $aclnum = 0;
 9195:     if (&is_portfolio_url($requrl)) {
 9196:         my (undef,$udom,$unum,$file_name,$group) =
 9197:             &parse_portfolio_url($requrl);
 9198:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9199:         my %access_controls = &get_access_controls($current_perms,
 9200:                                                    $group,$file_name);
 9201:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9202:             my ($num,$scope,$end,$start) = 
 9203:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9204:             if ($scope eq 'public') {
 9205:                 if ($start <= $now && $end == 0) {
 9206:                     $action = 'none';
 9207:                 } else {
 9208:                     $action = 'update';
 9209:                     $aclnum = $num;
 9210:                 }
 9211:                 last;
 9212:             }
 9213:         }
 9214:         if ($action eq 'none') {
 9215:              return 'ok';
 9216:         } else {
 9217:             my %changes;
 9218:             my $newend = 0;
 9219:             my $newstart = $now;
 9220:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9221:             $changes{$action}{$newkey} = {
 9222:                 type => 'public',
 9223:                 time => {
 9224:                     start => $newstart,
 9225:                     end   => $newend,
 9226:                 },
 9227:             };
 9228:             my ($outcome,$deloutcome,$new_values,$translation) =
 9229:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9230:             return $outcome;
 9231:         }
 9232:     } else {
 9233:         return 'invalid';
 9234:     }
 9235: }
 9236: 
 9237: #------------------------------------------------------Get Marked as Read Only
 9238: 
 9239: sub get_marked_as_readonly {
 9240:     my ($domain,$user,$what,$group) = @_;
 9241:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9242:     my @readonly_files;
 9243:     my $cmp1=$what;
 9244:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9245:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9246:         if (defined($group)) {
 9247:             if ($file_name !~ m-^\Q$group\E/-) {
 9248:                 next;
 9249:             }
 9250:         }
 9251:         if (ref($value) eq "ARRAY"){
 9252:             foreach my $stored_what (@{$value}) {
 9253:                 my $cmp2=$stored_what;
 9254:                 if (ref($stored_what) eq 'ARRAY') {
 9255:                     $cmp2=join('',@{$stored_what});
 9256:                 }
 9257:                 if ($cmp1 eq $cmp2) {
 9258:                     push(@readonly_files, $file_name);
 9259:                     last;
 9260:                 } elsif (!defined($what)) {
 9261:                     push(@readonly_files, $file_name);
 9262:                     last;
 9263:                 }
 9264:             }
 9265:         }
 9266:     }
 9267:     return @readonly_files;
 9268: }
 9269: #-----------------------------------------------------------Get Marked as Read Only Hash
 9270: 
 9271: sub get_marked_as_readonly_hash {
 9272:     my ($current_permissions,$group,$what) = @_;
 9273:     my %readonly_files;
 9274:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9275:         if (defined($group)) {
 9276:             if ($file_name !~ m-^\Q$group\E/-) {
 9277:                 next;
 9278:             }
 9279:         }
 9280:         if (ref($value) eq "ARRAY"){
 9281:             foreach my $stored_what (@{$value}) {
 9282:                 if (ref($stored_what) eq 'ARRAY') {
 9283:                     foreach my $lock_descriptor(@{$stored_what}) {
 9284:                         if ($lock_descriptor eq 'graded') {
 9285:                             $readonly_files{$file_name} = 'graded';
 9286:                         } elsif ($lock_descriptor eq 'handback') {
 9287:                             $readonly_files{$file_name} = 'handback';
 9288:                         } else {
 9289:                             if (!exists($readonly_files{$file_name})) {
 9290:                                 $readonly_files{$file_name} = 'locked';
 9291:                             }
 9292:                         }
 9293:                     }
 9294:                 } 
 9295:             }
 9296:         } 
 9297:     }
 9298:     return %readonly_files;
 9299: }
 9300: # ------------------------------------------------------------ Unmark as Read Only
 9301: 
 9302: sub unmark_as_readonly {
 9303:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9304:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9305:     my ($domain,$user,$what,$file_name,$group) = @_;
 9306:     $file_name = &declutter_portfile($file_name);
 9307:     my $symb_crs = $what;
 9308:     if (ref($what)) { $symb_crs=join('',@$what); }
 9309:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9310:     my ($tmp)=keys(%current_permissions);
 9311:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9312:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9313:     foreach my $file (@readonly_files) {
 9314: 	my $clean_file = &declutter_portfile($file);
 9315: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9316: 	my $current_locks = $current_permissions{$file};
 9317:         my @new_locks;
 9318:         my @del_keys;
 9319:         if (ref($current_locks) eq "ARRAY"){
 9320:             foreach my $locker (@{$current_locks}) {
 9321:                 my $compare=$locker;
 9322:                 if (ref($locker) eq 'ARRAY') {
 9323:                     $compare=join('',@{$locker});
 9324:                     if ($compare ne $symb_crs) {
 9325:                         push(@new_locks, $locker);
 9326:                     }
 9327:                 }
 9328:             }
 9329:             if (scalar(@new_locks) > 0) {
 9330:                 $current_permissions{$file} = \@new_locks;
 9331:             } else {
 9332:                 push(@del_keys, $file);
 9333:                 &del('file_permissions',\@del_keys, $domain, $user);
 9334:                 delete($current_permissions{$file});
 9335:             }
 9336:         }
 9337:     }
 9338:     &put('file_permissions',\%current_permissions,$domain,$user);
 9339:     return;
 9340: }
 9341: 
 9342: # ------------------------------------------------------------ Directory lister
 9343: 
 9344: sub dirlist {
 9345:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9346:     $uri=~s/^\///;
 9347:     $uri=~s/\/$//;
 9348:     my ($udom, $uname);
 9349:     if ($getuserdir) {
 9350:         $udom = $userdomain;
 9351:         $uname = $username;
 9352:     } else {
 9353:         (undef,$udom,$uname)=split(/\//,$uri);
 9354:         if(defined($userdomain)) {
 9355:             $udom = $userdomain;
 9356:         }
 9357:         if(defined($username)) {
 9358:             $uname = $username;
 9359:         }
 9360:     }
 9361:     my ($dirRoot,$listing,@listing_results);
 9362: 
 9363:     $dirRoot = $perlvar{'lonDocRoot'};
 9364:     if (defined($getpropath)) {
 9365:         $dirRoot = &propath($udom,$uname);
 9366:         $dirRoot =~ s/\/$//;
 9367:     } elsif (defined($getuserdir)) {
 9368:         my $subdir=$uname.'__';
 9369:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9370:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9371:                    ."/$udom/$subdir/$uname";
 9372:     } elsif (defined($alternateRoot)) {
 9373:         $dirRoot = $alternateRoot;
 9374:     }
 9375: 
 9376:     if($udom) {
 9377:         if($uname) {
 9378:             my $uhome = &homeserver($uname,$udom);
 9379:             if ($uhome eq 'no_host') {
 9380:                 return ([],'no_host');
 9381:             }
 9382:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9383:                               .$getuserdir.':'.&escape($dirRoot)
 9384:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9385:             if ($listing eq 'unknown_cmd') {
 9386:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9387:             } else {
 9388:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9389:             }
 9390:             if ($listing eq 'unknown_cmd') {
 9391:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9392:                 @listing_results = split(/:/,$listing);
 9393:             } else {
 9394:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9395:             }
 9396:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9397:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9398:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9399:                 return ([],$listing);
 9400:             } else {
 9401:                 return (\@listing_results);
 9402:             }
 9403:         } elsif(!$alternateRoot) {
 9404:             my (%allusers,%listerror);
 9405: 	    my %servers = &get_servers($udom,'library');
 9406:  	    foreach my $tryserver (keys(%servers)) {
 9407:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9408:                                   &escape($udom),$tryserver);
 9409:                 if ($listing eq 'unknown_cmd') {
 9410: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9411: 				      $udom, $tryserver);
 9412:                 } else {
 9413:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9414:                 }
 9415: 		if ($listing eq 'unknown_cmd') {
 9416: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9417: 				      $udom, $tryserver);
 9418: 		    @listing_results = split(/:/,$listing);
 9419: 		} else {
 9420: 		    @listing_results =
 9421: 			map { &unescape($_); } split(/:/,$listing);
 9422: 		}
 9423:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9424:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9425:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9426:                     $listerror{$tryserver} = $listing;
 9427:                 } else {
 9428: 		    foreach my $line (@listing_results) {
 9429: 			my ($entry) = split(/&/,$line,2);
 9430: 			$allusers{$entry} = 1;
 9431: 		    }
 9432: 		}
 9433:             }
 9434:             my @alluserslist=();
 9435:             foreach my $user (sort(keys(%allusers))) {
 9436:                 push(@alluserslist,$user.'&user');
 9437:             }
 9438:             return (\@alluserslist);
 9439:         } else {
 9440:             return ([],'missing username');
 9441:         }
 9442:     } elsif(!defined($getpropath)) {
 9443:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9444:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9445:         return (\@all_domains);
 9446:     } else {
 9447:         return ([],'missing domain');
 9448:     }
 9449: }
 9450: 
 9451: # --------------------------------------------- GetFileTimestamp
 9452: # This function utilizes dirlist and returns the date stamp for
 9453: # when it was last modified.  It will also return an error of -1
 9454: # if an error occurs
 9455: 
 9456: sub GetFileTimestamp {
 9457:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9458:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9459:     $studentName   = &LONCAPA::clean_username($studentName);
 9460:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9461:                                     undef,$getuserdir);
 9462:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9463:         return -1;
 9464:     }
 9465:     if (ref($fileref) eq 'ARRAY') {
 9466:         my @stats = split('&',$fileref->[0]);
 9467:         # @stats contains first the filename, then the stat output
 9468:         return $stats[10]; # so this is 10 instead of 9.
 9469:     } else {
 9470:         return -1;
 9471:     }
 9472: }
 9473: 
 9474: sub stat_file {
 9475:     my ($uri) = @_;
 9476:     $uri = &clutter_with_no_wrapper($uri);
 9477: 
 9478:     my ($udom,$uname,$file);
 9479:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9480: 	($udom,$uname,$file) =
 9481: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9482: 	$file = 'userfiles/'.$file;
 9483:     }
 9484:     if ($uri =~ m-^/res/-) {
 9485: 	($udom,$uname) = 
 9486: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9487: 	$file = $uri;
 9488:     }
 9489: 
 9490:     if (!$udom || !$uname || !$file) {
 9491: 	# unable to handle the uri
 9492: 	return ();
 9493:     }
 9494:     my $getpropath;
 9495:     if ($file =~ /^userfiles\//) {
 9496:         $getpropath = 1;
 9497:     }
 9498:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9499:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9500:         return ();
 9501:     } else {
 9502:         if (ref($listref) eq 'ARRAY') {
 9503:             my @stats = split('&',$listref->[0]);
 9504: 	    shift(@stats); #filename is first
 9505: 	    return @stats;
 9506:         }
 9507:     }
 9508:     return ();
 9509: }
 9510: 
 9511: # -------------------------------------------------------- Value of a Condition
 9512: 
 9513: # gets the value of a specific preevaluated condition
 9514: #    stored in the string  $env{user.state.<cid>}
 9515: # or looks up a condition reference in the bighash and if if hasn't
 9516: # already been evaluated recurses into docondval to get the value of
 9517: # the condition, then memoizing it to 
 9518: #   $env{user.state.<cid>.<condition>}
 9519: sub directcondval {
 9520:     my $number=shift;
 9521:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9522: 	&Apache::lonuserstate::evalstate();
 9523:     }
 9524:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9525: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9526:     } elsif ($number =~ /^_/) {
 9527: 	my $sub_condition;
 9528: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9529: 		&GDBM_READER(),0640)) {
 9530: 	    $sub_condition=$bighash{'conditions'.$number};
 9531: 	    untie(%bighash);
 9532: 	}
 9533: 	my $value = &docondval($sub_condition);
 9534: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9535: 	return $value;
 9536:     }
 9537:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9538:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9539:     } else {
 9540:        return 2;
 9541:     }
 9542: }
 9543: 
 9544: # get the collection of conditions for this resource
 9545: sub condval {
 9546:     my $condidx=shift;
 9547:     my $allpathcond='';
 9548:     foreach my $cond (split(/\|/,$condidx)) {
 9549: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9550: 	    $allpathcond.=
 9551: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9552: 	}
 9553:     }
 9554:     $allpathcond=~s/\|$//;
 9555:     return &docondval($allpathcond);
 9556: }
 9557: 
 9558: #evaluates an expression of conditions
 9559: sub docondval {
 9560:     my ($allpathcond) = @_;
 9561:     my $result=0;
 9562:     if ($env{'request.course.id'}
 9563: 	&& defined($allpathcond)) {
 9564: 	my $operand='|';
 9565: 	my @stack;
 9566: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9567: 	    if ($chunk eq '(') {
 9568: 		push @stack,($operand,$result);
 9569: 	    } elsif ($chunk eq ')') {
 9570: 		my $before=pop @stack;
 9571: 		if (pop @stack eq '&') {
 9572: 		    $result=$result>$before?$before:$result;
 9573: 		} else {
 9574: 		    $result=$result>$before?$result:$before;
 9575: 		}
 9576: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9577: 		$operand=$chunk;
 9578: 	    } else {
 9579: 		my $new=directcondval($chunk);
 9580: 		if ($operand eq '&') {
 9581: 		    $result=$result>$new?$new:$result;
 9582: 		} else {
 9583: 		    $result=$result>$new?$result:$new;
 9584: 		}
 9585: 	    }
 9586: 	}
 9587:     }
 9588:     return $result;
 9589: }
 9590: 
 9591: # ---------------------------------------------------- Devalidate courseresdata
 9592: 
 9593: sub devalidatecourseresdata {
 9594:     my ($coursenum,$coursedomain)=@_;
 9595:     my $hashid=$coursenum.':'.$coursedomain;
 9596:     &devalidate_cache_new('courseres',$hashid);
 9597: }
 9598: 
 9599: 
 9600: # --------------------------------------------------- Course Resourcedata Query
 9601: #
 9602: #  Parameters:
 9603: #      $coursenum    - Number of the course.
 9604: #      $coursedomain - Domain at which the course was created.
 9605: #  Returns:
 9606: #     A hash of the course parameters along (I think) with timestamps
 9607: #     and version info.
 9608: 
 9609: sub get_courseresdata {
 9610:     my ($coursenum,$coursedomain)=@_;
 9611:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9612:     my $hashid=$coursenum.':'.$coursedomain;
 9613:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9614:     my %dumpreply;
 9615:     unless (defined($cached)) {
 9616: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9617: 	$result=\%dumpreply;
 9618: 	my ($tmp) = keys(%dumpreply);
 9619: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9620: 	    &do_cache_new('courseres',$hashid,$result,600);
 9621: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9622: 	    return $tmp;
 9623: 	} elsif ($tmp =~ /^(error)/) {
 9624: 	    $result=undef;
 9625: 	    &do_cache_new('courseres',$hashid,$result,600);
 9626: 	}
 9627:     }
 9628:     return $result;
 9629: }
 9630: 
 9631: sub devalidateuserresdata {
 9632:     my ($uname,$udom)=@_;
 9633:     my $hashid="$udom:$uname";
 9634:     &devalidate_cache_new('userres',$hashid);
 9635: }
 9636: 
 9637: sub get_userresdata {
 9638:     my ($uname,$udom)=@_;
 9639:     #most student don\'t have any data set, check if there is some data
 9640:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9641: 
 9642:     my $hashid="$udom:$uname";
 9643:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9644:     if (!defined($cached)) {
 9645: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9646: 	$result=\%resourcedata;
 9647: 	&do_cache_new('userres',$hashid,$result,600);
 9648:     }
 9649:     my ($tmp)=keys(%$result);
 9650:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9651: 	return $result;
 9652:     }
 9653:     #error 2 occurs when the .db doesn't exist
 9654:     if ($tmp!~/error: 2 /) {
 9655: 	&logthis("<font color=\"blue\">WARNING:".
 9656: 		 " Trying to get resource data for ".
 9657: 		 $uname." at ".$udom.": ".
 9658: 		 $tmp."</font>");
 9659:     } elsif ($tmp=~/error: 2 /) {
 9660: 	#&EXT_cache_set($udom,$uname);
 9661: 	&do_cache_new('userres',$hashid,undef,600);
 9662: 	undef($tmp); # not really an error so don't send it back
 9663:     }
 9664:     return $tmp;
 9665: }
 9666: #----------------------------------------------- resdata - return resource data
 9667: #  Purpose:
 9668: #    Return resource data for either users or for a course.
 9669: #  Parameters:
 9670: #     $name      - Course/user name.
 9671: #     $domain    - Name of the domain the user/course is registered on.
 9672: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9673: #     @which     - Array of names of resources desired.
 9674: #  Returns:
 9675: #     The value of the first reasource in @which that is found in the
 9676: #     resource hash.
 9677: #  Exceptional Conditions:
 9678: #     If the $type passed in is not valid (not the string 'course' or 
 9679: #     'user', an undefined  reference is returned.
 9680: #     If none of the resources are found, an undef is returned
 9681: sub resdata {
 9682:     my ($name,$domain,$type,@which)=@_;
 9683:     my $result;
 9684:     if ($type eq 'course') {
 9685: 	$result=&get_courseresdata($name,$domain);
 9686:     } elsif ($type eq 'user') {
 9687: 	$result=&get_userresdata($name,$domain);
 9688:     }
 9689:     if (!ref($result)) { return $result; }    
 9690:     foreach my $item (@which) {
 9691: 	if (defined($result->{$item->[0]})) {
 9692: 	    return [$result->{$item->[0]},$item->[1]];
 9693: 	}
 9694:     }
 9695:     return undef;
 9696: }
 9697: 
 9698: sub get_numsuppfiles {
 9699:     my ($cnum,$cdom,$ignorecache)=@_;
 9700:     my $hashid=$cnum.':'.$cdom;
 9701:     my ($suppcount,$cached);
 9702:     unless ($ignorecache) {
 9703:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9704:     }
 9705:     unless (defined($cached)) {
 9706:         my $chome=&homeserver($cnum,$cdom);
 9707:         unless ($chome eq 'no_host') {
 9708:             ($suppcount,my $errors) = (0,0);
 9709:             my $suppmap = 'supplemental.sequence';
 9710:             ($suppcount,$errors) = 
 9711:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9712:         }
 9713:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9714:     }
 9715:     return $suppcount;
 9716: }
 9717: 
 9718: #
 9719: # EXT resource caching routines
 9720: #
 9721: 
 9722: sub clear_EXT_cache_status {
 9723:     &delenv('cache.EXT.');
 9724: }
 9725: 
 9726: sub EXT_cache_status {
 9727:     my ($target_domain,$target_user) = @_;
 9728:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9729:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9730:         # We know already the user has no data
 9731:         return 1;
 9732:     } else {
 9733:         return 0;
 9734:     }
 9735: }
 9736: 
 9737: sub EXT_cache_set {
 9738:     my ($target_domain,$target_user) = @_;
 9739:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9740:     #&appenv({$cachename => time});
 9741: }
 9742: 
 9743: # --------------------------------------------------------- Value of a Variable
 9744: sub EXT {
 9745: 
 9746:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9747:     unless ($varname) { return ''; }
 9748:     #get real user name/domain, courseid and symb
 9749:     my $courseid;
 9750:     my $publicuser;
 9751:     if ($symbparm) {
 9752: 	$symbparm=&get_symb_from_alias($symbparm);
 9753:     }
 9754:     if (!($uname && $udom)) {
 9755:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9756:       if (!$symbparm) {	$symbparm=$cursymb; }
 9757:     } else {
 9758: 	$courseid=$env{'request.course.id'};
 9759:     }
 9760:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9761:     my $rest;
 9762:     if (defined($therest[0])) {
 9763:        $rest=join('.',@therest);
 9764:     } else {
 9765:        $rest='';
 9766:     }
 9767: 
 9768:     my $qualifierrest=$qualifier;
 9769:     if ($rest) { $qualifierrest.='.'.$rest; }
 9770:     my $spacequalifierrest=$space;
 9771:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9772:     if ($realm eq 'user') {
 9773: # --------------------------------------------------------------- user.resource
 9774: 	if ($space eq 'resource') {
 9775: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9776: 		  || defined($Apache::lonhomework::parsing_a_task))
 9777: 		 &&
 9778: 		 ($symbparm eq &symbread()) ) {	
 9779: 		# if we are in the middle of processing the resource the
 9780: 		# get the value we are planning on committing
 9781:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9782:                     return $Apache::lonhomework::results{$qualifierrest};
 9783:                 } else {
 9784:                     return $Apache::lonhomework::history{$qualifierrest};
 9785:                 }
 9786: 	    } else {
 9787: 		my %restored;
 9788: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9789: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9790: 		} else {
 9791: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9792: 		}
 9793: 		return $restored{$qualifierrest};
 9794: 	    }
 9795: # ----------------------------------------------------------------- user.access
 9796:         } elsif ($space eq 'access') {
 9797: 	    # FIXME - not supporting calls for a specific user
 9798:             return &allowed($qualifier,$rest);
 9799: # ------------------------------------------ user.preferences, user.environment
 9800:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9801: 	    if (($uname eq $env{'user.name'}) &&
 9802: 		($udom eq $env{'user.domain'})) {
 9803: 		return $env{join('.',('environment',$qualifierrest))};
 9804: 	    } else {
 9805: 		my %returnhash;
 9806: 		if (!$publicuser) {
 9807: 		    %returnhash=&userenvironment($udom,$uname,
 9808: 						 $qualifierrest);
 9809: 		}
 9810: 		return $returnhash{$qualifierrest};
 9811: 	    }
 9812: # ----------------------------------------------------------------- user.course
 9813:         } elsif ($space eq 'course') {
 9814: 	    # FIXME - not supporting calls for a specific user
 9815:             return $env{join('.',('request.course',$qualifier))};
 9816: # ------------------------------------------------------------------- user.role
 9817:         } elsif ($space eq 'role') {
 9818: 	    # FIXME - not supporting calls for a specific user
 9819:             my ($role,$where)=split(/\./,$env{'request.role'});
 9820:             if ($qualifier eq 'value') {
 9821: 		return $role;
 9822:             } elsif ($qualifier eq 'extent') {
 9823:                 return $where;
 9824:             }
 9825: # ----------------------------------------------------------------- user.domain
 9826:         } elsif ($space eq 'domain') {
 9827:             return $udom;
 9828: # ------------------------------------------------------------------- user.name
 9829:         } elsif ($space eq 'name') {
 9830:             return $uname;
 9831: # ---------------------------------------------------- Any other user namespace
 9832:         } else {
 9833: 	    my %reply;
 9834: 	    if (!$publicuser) {
 9835: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9836: 	    }
 9837: 	    return $reply{$qualifierrest};
 9838:         }
 9839:     } elsif ($realm eq 'query') {
 9840: # ---------------------------------------------- pull stuff out of query string
 9841:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9842: 						[$spacequalifierrest]);
 9843: 	return $env{'form.'.$spacequalifierrest}; 
 9844:    } elsif ($realm eq 'request') {
 9845: # ------------------------------------------------------------- request.browser
 9846:         if ($space eq 'browser') {
 9847:             return $env{'browser.'.$qualifier};
 9848: # ------------------------------------------------------------ request.filename
 9849:         } else {
 9850:             return $env{'request.'.$spacequalifierrest};
 9851:         }
 9852:     } elsif ($realm eq 'course') {
 9853: # ---------------------------------------------------------- course.description
 9854:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9855:     } elsif ($realm eq 'resource') {
 9856: 
 9857: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9858: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9859: 	}
 9860: 
 9861:         if ($qualifier eq '') {
 9862: 	    if ($space eq 'title') {
 9863: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9864: 	        return &gettitle($symbparm);
 9865: 	    }
 9866: 	
 9867: 	    if ($space eq 'map') {
 9868: 	        my ($map) = &decode_symb($symbparm);
 9869: 	        return &symbread($map);
 9870: 	    }
 9871:             if ($space eq 'maptitle') {
 9872:                 my ($map) = &decode_symb($symbparm);
 9873:                 return &gettitle($map);
 9874:             }
 9875: 	    if ($space eq 'filename') {
 9876: 	        if ($symbparm) {
 9877: 		    return &clutter((&decode_symb($symbparm))[2]);
 9878: 	        }
 9879: 	        return &hreflocation('',$env{'request.filename'});
 9880: 	    }
 9881: 
 9882:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9883:                 if ($space eq 'visibleparts') {
 9884:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9885:                     my $item;
 9886:                     if (ref($navmap)) {
 9887:                         my $res = $navmap->getBySymb($symbparm);
 9888:                         my $parts = $res->parts();
 9889:                         if (ref($parts) eq 'ARRAY') {
 9890:                             $item = join(',',@{$parts});
 9891:                         }
 9892:                         undef($navmap);
 9893:                     }
 9894:                     return $item;
 9895:                 }
 9896:             }
 9897:         }
 9898: 
 9899: 	my ($section, $group, @groups);
 9900: 	my ($courselevelm,$courselevel);
 9901:         if (($courseid eq '') && ($cid)) {
 9902:             $courseid = $cid;
 9903:         }
 9904: 	if (($symbparm && $courseid) && 
 9905: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
 9906: 
 9907: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9908: 
 9909: # ----------------------------------------------------- Cascading lookup scheme
 9910: 	    my $symbp=$symbparm;
 9911: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9912: 
 9913: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9914: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9915: 
 9916: 	    if (($env{'user.name'} eq $uname) &&
 9917: 		($env{'user.domain'} eq $udom)) {
 9918: 		$section=$env{'request.course.sec'};
 9919:                 @groups = split(/:/,$env{'request.course.groups'});  
 9920:                 @groups=&sort_course_groups($courseid,@groups); 
 9921: 	    } else {
 9922: 		if (! defined($usection)) {
 9923: 		    $section=&getsection($udom,$uname,$courseid);
 9924: 		} else {
 9925: 		    $section = $usection;
 9926: 		}
 9927:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9928: 	    }
 9929: 
 9930: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9931: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9932: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9933: 
 9934: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9935: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9936: 	    $courselevelm=$courseid.'.'.$mapparm;
 9937: 
 9938: # ----------------------------------------------------------- first, check user
 9939: 
 9940: 	    my $userreply=&resdata($uname,$udom,'user',
 9941: 				       ([$courselevelr,'resource'],
 9942: 					[$courselevelm,'map'     ],
 9943: 					[$courselevel, 'course'  ]));
 9944: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9945: 
 9946: # ------------------------------------------------ second, check some of course
 9947:             my $coursereply;
 9948:             if (@groups > 0) {
 9949:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9950:                                        $mapparm,$spacequalifierrest);
 9951:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9952:             }
 9953: 
 9954: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9955: 				  $env{'course.'.$courseid.'.domain'},
 9956: 				  'course',
 9957: 				  ([$seclevelr,   'resource'],
 9958: 				   [$seclevelm,   'map'     ],
 9959: 				   [$seclevel,    'course'  ],
 9960: 				   [$courselevelr,'resource']));
 9961: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9962: 
 9963: # ------------------------------------------------------ third, check map parms
 9964: 	    my %parmhash=();
 9965: 	    my $thisparm='';
 9966: 	    if (tie(%parmhash,'GDBM_File',
 9967: 		    $env{'request.course.fn'}.'_parms.db',
 9968: 		    &GDBM_READER(),0640)) {
 9969: 		$thisparm=$parmhash{$symbparm};
 9970: 		untie(%parmhash);
 9971: 	    }
 9972: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9973: 	}
 9974: # ------------------------------------------ fourth, look in resource metadata
 9975: 
 9976: 	$spacequalifierrest=~s/\./\_/;
 9977: 	my $filename;
 9978: 	if (!$symbparm) { $symbparm=&symbread(); }
 9979: 	if ($symbparm) {
 9980: 	    $filename=(&decode_symb($symbparm))[2];
 9981: 	} else {
 9982: 	    $filename=$env{'request.filename'};
 9983: 	}
 9984: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9985: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9986: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9987: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9988: 
 9989: # ---------------------------------------------- fourth, look in rest of course
 9990: 	if ($symbparm && defined($courseid) && 
 9991: 	    $courseid eq $env{'request.course.id'}) {
 9992: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9993: 				     $env{'course.'.$courseid.'.domain'},
 9994: 				     'course',
 9995: 				     ([$courselevelm,'map'   ],
 9996: 				      [$courselevel, 'course']));
 9997: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9998: 	}
 9999: # ------------------------------------------------------------------ Cascade up
10000: 	unless ($space eq '0') {
10001: 	    my @parts=split(/_/,$space);
10002: 	    my $id=pop(@parts);
10003: 	    my $part=join('_',@parts);
10004: 	    if ($part eq '') { $part='0'; }
10005: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10006: 				 $symbparm,$udom,$uname,$section,1);
10007: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10008: 	}
10009: 	if ($recurse) { return undef; }
10010: 	my $pack_def=&packages_tab_default($filename,$varname);
10011: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10012: # ---------------------------------------------------- Any other user namespace
10013:     } elsif ($realm eq 'environment') {
10014: # ----------------------------------------------------------------- environment
10015: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10016: 	    return $env{'environment.'.$spacequalifierrest};
10017: 	} else {
10018: 	    if ($uname eq 'anonymous' && $udom eq '') {
10019: 		return '';
10020: 	    }
10021: 	    my %returnhash=&userenvironment($udom,$uname,
10022: 					    $spacequalifierrest);
10023: 	    return $returnhash{$spacequalifierrest};
10024: 	}
10025:     } elsif ($realm eq 'system') {
10026: # ----------------------------------------------------------------- system.time
10027: 	if ($space eq 'time') {
10028: 	    return time;
10029:         }
10030:     } elsif ($realm eq 'server') {
10031: # ----------------------------------------------------------------- system.time
10032: 	if ($space eq 'name') {
10033: 	    return $ENV{'SERVER_NAME'};
10034:         }
10035:     }
10036:     return '';
10037: }
10038: 
10039: sub get_reply {
10040:     my ($reply_value) = @_;
10041:     if (ref($reply_value) eq 'ARRAY') {
10042:         if (wantarray) {
10043: 	    return @$reply_value;
10044:         }
10045:         return $reply_value->[0];
10046:     } else {
10047:         return $reply_value;
10048:     }
10049: }
10050: 
10051: sub check_group_parms {
10052:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10053:     my @groupitems = ();
10054:     my $resultitem;
10055:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10056:     foreach my $group (@{$groups}) {
10057:         foreach my $level (@levels) {
10058:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10059:              push(@groupitems,[$item,$level->[1]]);
10060:         }
10061:     }
10062:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10063:                             $env{'course.'.$courseid.'.domain'},
10064:                                      'course',@groupitems);
10065:     return $coursereply;
10066: }
10067: 
10068: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10069:     my ($courseid,@groups) = @_;
10070:     @groups = sort(@groups);
10071:     return @groups;
10072: }
10073: 
10074: sub packages_tab_default {
10075:     my ($uri,$varname)=@_;
10076:     my (undef,$part,$name)=split(/\./,$varname);
10077: 
10078:     my (@extension,@specifics,$do_default);
10079:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10080: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10081: 	if ($pack_type eq 'default') {
10082: 	    $do_default=1;
10083: 	} elsif ($pack_type eq 'extension') {
10084: 	    push(@extension,[$package,$pack_type,$pack_part]);
10085: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10086: 	    # only look at packages defaults for packages that this id is
10087: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10088: 	}
10089:     }
10090:     # first look for a package that matches the requested part id
10091:     foreach my $package (@specifics) {
10092: 	my (undef,$pack_type,$pack_part)=@{$package};
10093: 	next if ($pack_part ne $part);
10094: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10095: 	    return $packagetab{"$pack_type&$name&default"};
10096: 	}
10097:     }
10098:     # look for any possible matching non extension_ package
10099:     foreach my $package (@specifics) {
10100: 	my (undef,$pack_type,$pack_part)=@{$package};
10101: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10102: 	    return $packagetab{"$pack_type&$name&default"};
10103: 	}
10104: 	if ($pack_type eq 'part') { $pack_part='0'; }
10105: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10106: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10107: 	}
10108:     }
10109:     # look for any posible extension_ match
10110:     foreach my $package (@extension) {
10111: 	my ($package,$pack_type)=@{$package};
10112: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10113: 	    return $packagetab{"$pack_type&$name&default"};
10114: 	}
10115: 	if (defined($packagetab{$package."&$name&default"})) {
10116: 	    return $packagetab{$package."&$name&default"};
10117: 	}
10118:     }
10119:     # look for a global default setting
10120:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10121: 	return $packagetab{"default&$name&default"};
10122:     }
10123:     return undef;
10124: }
10125: 
10126: sub add_prefix_and_part {
10127:     my ($prefix,$part)=@_;
10128:     my $keyroot;
10129:     if (defined($prefix) && $prefix !~ /^__/) {
10130: 	# prefix that has a part already
10131: 	$keyroot=$prefix;
10132:     } elsif (defined($prefix)) {
10133: 	# prefix that is missing a part
10134: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10135:     } else {
10136: 	# no prefix at all
10137: 	if (defined($part)) { $keyroot='_'.$part; }
10138:     }
10139:     return $keyroot;
10140: }
10141: 
10142: # ---------------------------------------------------------------- Get metadata
10143: 
10144: my %metaentry;
10145: my %importedpartids;
10146: sub metadata {
10147:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10148:     $uri=&declutter($uri);
10149:     # if it is a non metadata possible uri return quickly
10150:     if (($uri eq '') || 
10151: 	(($uri =~ m|^/*adm/|) && 
10152: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10153:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10154: 	return undef;
10155:     }
10156:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10157: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10158: 	return undef;
10159:     }
10160:     my $filename=$uri;
10161:     $uri=~s/\.meta$//;
10162: #
10163: # Is the metadata already cached?
10164: # Look at timestamp of caching
10165: # Everything is cached by the main uri, libraries are never directly cached
10166: #
10167:     if (!defined($liburi)) {
10168: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10169: 	if (defined($cached)) { return $result->{':'.$what}; }
10170:     }
10171:     {
10172: # Imported parts would go here
10173:         my %importedids=();
10174:         my @origfileimportpartids=();
10175:         my $importedparts=0;
10176: #
10177: # Is this a recursive call for a library?
10178: #
10179: #	if (! exists($metacache{$uri})) {
10180: #	    $metacache{$uri}={};
10181: #	}
10182: 	my $cachetime = 60*60;
10183:         if ($liburi) {
10184: 	    $liburi=&declutter($liburi);
10185:             $filename=$liburi;
10186:         } else {
10187: 	    &devalidate_cache_new('meta',$uri);
10188: 	    undef(%metaentry);
10189: 	}
10190:         my %metathesekeys=();
10191:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10192: 	my $metastring;
10193: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10194: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10195: 	    $metastring = 
10196: 		&Apache::lonnet::ssi_body($which,
10197: 					  ('grade_target' => 'meta'));
10198: 	    $cachetime = 1; # only want this cached in the child not long term
10199: 	} elsif (($uri !~ m -^(editupload)/-) && 
10200:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10201: 	    my $file=&filelocation('',&clutter($filename));
10202: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10203: 	    $metastring=&getfile($file);
10204: 	}
10205:         my $parser=HTML::LCParser->new(\$metastring);
10206:         my $token;
10207:         undef %metathesekeys;
10208:         while ($token=$parser->get_token) {
10209: 	    if ($token->[0] eq 'S') {
10210: 		if (defined($token->[2]->{'package'})) {
10211: #
10212: # This is a package - get package info
10213: #
10214: 		    my $package=$token->[2]->{'package'};
10215: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10216: 		    if (defined($token->[2]->{'id'})) { 
10217: 			$keyroot.='_'.$token->[2]->{'id'}; 
10218: 		    }
10219: 		    if ($metaentry{':packages'}) {
10220: 			$metaentry{':packages'}.=','.$package.$keyroot;
10221: 		    } else {
10222: 			$metaentry{':packages'}=$package.$keyroot;
10223: 		    }
10224: 		    foreach my $pack_entry (keys(%packagetab)) {
10225: 			my $part=$keyroot;
10226: 			$part=~s/^\_//;
10227: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10228: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10229: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10230: 			    # ignore package.tab specified default values
10231:                             # here &package_tab_default() will fetch those
10232: 			    if ($subp eq 'default') { next; }
10233: 			    my $value=$packagetab{$pack_entry};
10234: 			    my $unikey;
10235: 			    if ($pack =~ /_0$/) {
10236: 				$unikey='parameter_0_'.$name;
10237: 				$part=0;
10238: 			    } else {
10239: 				$unikey='parameter'.$keyroot.'_'.$name;
10240: 			    }
10241: 			    if ($subp eq 'display') {
10242: 				$value.=' [Part: '.$part.']';
10243: 			    }
10244: 			    $metaentry{':'.$unikey.'.part'}=$part;
10245: 			    $metathesekeys{$unikey}=1;
10246: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10247: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10248: 			    }
10249: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10250: 				$metaentry{':'.$unikey}=
10251: 				    $metaentry{':'.$unikey.'.default'};
10252: 			    }
10253: 			}
10254: 		    }
10255: 		} else {
10256: #
10257: # This is not a package - some other kind of start tag
10258: #
10259: 		    my $entry=$token->[1];
10260: 		    my $unikey='';
10261: 
10262: 		    if ($entry eq 'import') {
10263: #
10264: # Importing a library here
10265: #
10266:                         my $location=$parser->get_text('/import');
10267:                         my $dir=$filename;
10268:                         $dir=~s|[^/]*$||;
10269:                         $location=&filelocation($dir,$location);
10270:                        
10271:                         my $importmode=$token->[2]->{'importmode'};
10272:                         if ($importmode eq 'problem') {
10273: # Import as problem/response
10274:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10275:                         } elsif ($importmode eq 'part') {
10276: # Import as part(s)
10277:                            $importedparts=1;
10278: # We need to get the original file and the imported file to get the part order correct
10279: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10280: # Load and inspect original file
10281:                            if ($#origfileimportpartids<0) {
10282:                               undef(%importedpartids);
10283:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10284:                               my $origfile=&getfile($origfilelocation);
10285:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10286:                            }
10287: 
10288: # Load and inspect imported file
10289:                            my $impfile=&getfile($location);
10290:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10291:                            if ($#impfilepartids>=0) {
10292: # This problem had parts
10293:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10294:                            } else {
10295: # Importing by turning a single problem into a problem part
10296: # It gets the import-tags ID as part-ID
10297:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10298:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10299:                            }
10300:                         } else {
10301: # Normal import
10302:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10303:                            if (defined($token->[2]->{'id'})) {
10304:                               $unikey.='_'.$token->[2]->{'id'};
10305:                            }
10306:                         }
10307: 
10308: 			if ($depthcount<20) {
10309: 			    my $metadata = 
10310: 				&metadata($uri,'keys', $location,$unikey,
10311: 					  $depthcount+1);
10312: 			    foreach my $meta (split(',',$metadata)) {
10313: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10314: 				$metathesekeys{$meta}=1;
10315: 			    }
10316: 			
10317:                         }
10318: 		    } else {
10319: #
10320: # Not importing, some other kind of non-package, non-library start tag
10321: # 
10322:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10323:                         if (defined($token->[2]->{'id'})) {
10324:                             $unikey.='_'.$token->[2]->{'id'};
10325:                         }
10326: 			if (defined($token->[2]->{'name'})) { 
10327: 			    $unikey.='_'.$token->[2]->{'name'}; 
10328: 			}
10329: 			$metathesekeys{$unikey}=1;
10330: 			foreach my $param (@{$token->[3]}) {
10331: 			    $metaentry{':'.$unikey.'.'.$param} =
10332: 				$token->[2]->{$param};
10333: 			}
10334: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10335: 			my $default=$metaentry{':'.$unikey.'.default'};
10336: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10337: 		 # only ws inside the tag, and not in default, so use default
10338: 		 # as value
10339: 			    $metaentry{':'.$unikey}=$default;
10340: 			} elsif ( $internaltext =~ /\S/ ) {
10341: 		  # something interesting inside the tag
10342: 			    $metaentry{':'.$unikey}=$internaltext;
10343: 			} else {
10344: 		  # no interesting values, don't set a default
10345: 			}
10346: # end of not-a-package not-a-library import
10347: 		    }
10348: # end of not-a-package start tag
10349: 		}
10350: # the next is the end of "start tag"
10351: 	    }
10352: 	}
10353: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10354: 	$extension = lc($extension);
10355: 	if ($extension eq 'htm') { $extension='html'; }
10356: 
10357: 	foreach my $key (keys(%packagetab)) {
10358: 	    #no specific packages #how's our extension
10359: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10360: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10361: 					 \%metathesekeys);
10362: 	}
10363: 
10364: 	if (!exists($metaentry{':packages'})
10365: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10366: 	    foreach my $key (keys(%packagetab)) {
10367: 		#no specific packages well let's get default then
10368: 		if ($key!~/^default&/) { next; }
10369: 		&metadata_create_package_def($uri,$key,'default',
10370: 					     \%metathesekeys);
10371: 	    }
10372: 	}
10373: # are there custom rights to evaluate
10374: 	if ($metaentry{':copyright'} eq 'custom') {
10375: 
10376:     #
10377:     # Importing a rights file here
10378:     #
10379: 	    unless ($depthcount) {
10380: 		my $location=$metaentry{':customdistributionfile'};
10381: 		my $dir=$filename;
10382: 		$dir=~s|[^/]*$||;
10383: 		$location=&filelocation($dir,$location);
10384: 		my $rights_metadata =
10385: 		    &metadata($uri,'keys',$location,'_rights',
10386: 			      $depthcount+1);
10387: 		foreach my $rights (split(',',$rights_metadata)) {
10388: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10389: 		    $metathesekeys{$rights}=1;
10390: 		}
10391: 	    }
10392: 	}
10393: 	# uniqifiy package listing
10394: 	my %seen;
10395: 	my @uniq_packages =
10396: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10397: 	$metaentry{':packages'} = join(',',@uniq_packages);
10398: 
10399:         if ($importedparts) {
10400: # We had imported parts and need to rebuild partorder
10401:            $metaentry{':partorder'}='';
10402:            $metathesekeys{'partorder'}=1;
10403:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10404:                if ($origfileimportpartids[$index] eq 'part') {
10405: # original part, part of the problem
10406:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10407:                } else {
10408: # we have imported parts at this position
10409:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10410:                }
10411:            }
10412:            $metaentry{':partorder'}=~s/^\,//;
10413:         }
10414: 
10415: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10416: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10417: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10418: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10419: # this is the end of "was not already recently cached
10420:     }
10421:     return $metaentry{':'.$what};
10422: }
10423: 
10424: sub metadata_create_package_def {
10425:     my ($uri,$key,$package,$metathesekeys)=@_;
10426:     my ($pack,$name,$subp)=split(/\&/,$key);
10427:     if ($subp eq 'default') { next; }
10428:     
10429:     if (defined($metaentry{':packages'})) {
10430: 	$metaentry{':packages'}.=','.$package;
10431:     } else {
10432: 	$metaentry{':packages'}=$package;
10433:     }
10434:     my $value=$packagetab{$key};
10435:     my $unikey;
10436:     $unikey='parameter_0_'.$name;
10437:     $metaentry{':'.$unikey.'.part'}=0;
10438:     $$metathesekeys{$unikey}=1;
10439:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10440: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10441:     }
10442:     if (defined($metaentry{':'.$unikey.'.default'})) {
10443: 	$metaentry{':'.$unikey}=
10444: 	    $metaentry{':'.$unikey.'.default'};
10445:     }
10446: }
10447: 
10448: sub metadata_generate_part0 {
10449:     my ($metadata,$metacache,$uri) = @_;
10450:     my %allnames;
10451:     foreach my $metakey (keys(%$metadata)) {
10452: 	if ($metakey=~/^parameter\_(.*)/) {
10453: 	  my $part=$$metacache{':'.$metakey.'.part'};
10454: 	  my $name=$$metacache{':'.$metakey.'.name'};
10455: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10456: 	    $allnames{$name}=$part;
10457: 	  }
10458: 	}
10459:     }
10460:     foreach my $name (keys(%allnames)) {
10461:       $$metadata{"parameter_0_$name"}=1;
10462:       my $key=":parameter_0_$name";
10463:       $$metacache{"$key.part"}='0';
10464:       $$metacache{"$key.name"}=$name;
10465:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10466: 					   $allnames{$name}.'_'.$name.
10467: 					   '.type'};
10468:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10469: 			     '.display'};
10470:       my $expr='[Part: '.$allnames{$name}.']';
10471:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10472:       $$metacache{"$key.display"}=$olddis;
10473:     }
10474: }
10475: 
10476: # ------------------------------------------------------ Devalidate title cache
10477: 
10478: sub devalidate_title_cache {
10479:     my ($url)=@_;
10480:     if (!$env{'request.course.id'}) { return; }
10481:     my $symb=&symbread($url);
10482:     if (!$symb) { return; }
10483:     my $key=$env{'request.course.id'}."\0".$symb;
10484:     &devalidate_cache_new('title',$key);
10485: }
10486: 
10487: # ------------------------------------------------- Get the title of a course
10488: 
10489: sub current_course_title {
10490:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10491: }
10492: # ------------------------------------------------- Get the title of a resource
10493: 
10494: sub gettitle {
10495:     my $urlsymb=shift;
10496:     my $symb=&symbread($urlsymb);
10497:     if ($symb) {
10498: 	my $key=$env{'request.course.id'}."\0".$symb;
10499: 	my ($result,$cached)=&is_cached_new('title',$key);
10500: 	if (defined($cached)) { 
10501: 	    return $result;
10502: 	}
10503: 	my ($map,$resid,$url)=&decode_symb($symb);
10504: 	my $title='';
10505: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10506: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10507: 	} else {
10508: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10509: 		    &GDBM_READER(),0640)) {
10510: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10511: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10512: 		untie(%bighash);
10513: 	    }
10514: 	}
10515: 	$title=~s/\&colon\;/\:/gs;
10516: 	if ($title) {
10517: # Remember both $symb and $title for dynamic metadata
10518:             $accesshash{$symb.'___crstitle'}=$title;
10519:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10520: # Cache this title and then return it
10521: 	    return &do_cache_new('title',$key,$title,600);
10522: 	}
10523: 	$urlsymb=$url;
10524:     }
10525:     my $title=&metadata($urlsymb,'title');
10526:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10527:     return $title;
10528: }
10529: 
10530: sub get_slot {
10531:     my ($which,$cnum,$cdom)=@_;
10532:     if (!$cnum || !$cdom) {
10533: 	(undef,my $courseid)=&whichuser();
10534: 	$cdom=$env{'course.'.$courseid.'.domain'};
10535: 	$cnum=$env{'course.'.$courseid.'.num'};
10536:     }
10537:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10538:     my %slotinfo;
10539:     if (exists($remembered{$key})) {
10540: 	$slotinfo{$which} = $remembered{$key};
10541:     } else {
10542: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10543: 	&Apache::lonhomework::showhash(%slotinfo);
10544: 	my ($tmp)=keys(%slotinfo);
10545: 	if ($tmp=~/^error:/) { return (); }
10546: 	$remembered{$key} = $slotinfo{$which};
10547:     }
10548:     if (ref($slotinfo{$which}) eq 'HASH') {
10549: 	return %{$slotinfo{$which}};
10550:     }
10551:     return $slotinfo{$which};
10552: }
10553: 
10554: sub get_reservable_slots {
10555:     my ($cnum,$cdom,$uname,$udom) = @_;
10556:     my $now = time;
10557:     my $reservable_info;
10558:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10559:     if (exists($remembered{$key})) {
10560:         $reservable_info = $remembered{$key};
10561:     } else {
10562:         my %resv;
10563:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10564:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10565:         $reservable_info = \%resv;
10566:         $remembered{$key} = $reservable_info;
10567:     }
10568:     return $reservable_info;
10569: }
10570: 
10571: sub get_course_slots {
10572:     my ($cnum,$cdom) = @_;
10573:     my $hashid=$cnum.':'.$cdom;
10574:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10575:     if (defined($cached)) {
10576:         if (ref($result) eq 'HASH') {
10577:             return %{$result};
10578:         }
10579:     } else {
10580:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10581:         my ($tmp) = keys(%slots);
10582:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10583:             &do_cache_new('allslots',$hashid,\%slots,600);
10584:             return %slots;
10585:         }
10586:     }
10587:     return;
10588: }
10589: 
10590: sub devalidate_slots_cache {
10591:     my ($cnum,$cdom)=@_;
10592:     my $hashid=$cnum.':'.$cdom;
10593:     &devalidate_cache_new('allslots',$hashid);
10594: }
10595: 
10596: sub get_coursechange {
10597:     my ($cdom,$cnum) = @_;
10598:     if ($cdom eq '' || $cnum eq '') {
10599:         return unless ($env{'request.course.id'});
10600:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10601:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10602:     }
10603:     my $hashid=$cdom.'_'.$cnum;
10604:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10605:     if ((defined($cached)) && ($change ne '')) {
10606:         return $change;
10607:     } else {
10608:         my %crshash;
10609:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10610:         if ($crshash{'internal.contentchange'} eq '') {
10611:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10612:             if ($change eq '') {
10613:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10614:                 $change = $crshash{'internal.created'};
10615:             }
10616:         } else {
10617:             $change = $crshash{'internal.contentchange'};
10618:         }
10619:         my $cachetime = 600;
10620:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10621:     }
10622:     return $change;
10623: }
10624: 
10625: sub devalidate_coursechange_cache {
10626:     my ($cnum,$cdom)=@_;
10627:     my $hashid=$cnum.':'.$cdom;
10628:     &devalidate_cache_new('crschange',$hashid);
10629: }
10630: 
10631: # ------------------------------------------------- Update symbolic store links
10632: 
10633: sub symblist {
10634:     my ($mapname,%newhash)=@_;
10635:     $mapname=&deversion(&declutter($mapname));
10636:     my %hash;
10637:     if (($env{'request.course.fn'}) && (%newhash)) {
10638:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10639:                       &GDBM_WRCREAT(),0640)) {
10640: 	    foreach my $url (keys(%newhash)) {
10641: 		next if ($url eq 'last_known'
10642: 			 && $env{'form.no_update_last_known'});
10643: 		$hash{declutter($url)}=&encode_symb($mapname,
10644: 						    $newhash{$url}->[1],
10645: 						    $newhash{$url}->[0]);
10646:             }
10647:             if (untie(%hash)) {
10648: 		return 'ok';
10649:             }
10650:         }
10651:     }
10652:     return 'error';
10653: }
10654: 
10655: # --------------------------------------------------------------- Verify a symb
10656: 
10657: sub symbverify {
10658:     my ($symb,$thisurl,$encstate)=@_;
10659:     my $thisfn=$thisurl;
10660:     $thisfn=&declutter($thisfn);
10661: # direct jump to resource in page or to a sequence - will construct own symbs
10662:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10663: # check URL part
10664:     my ($map,$resid,$url)=&decode_symb($symb);
10665: 
10666:     unless ($url eq $thisfn) { return 0; }
10667: 
10668:     $symb=&symbclean($symb);
10669:     $thisurl=&deversion($thisurl);
10670:     $thisfn=&deversion($thisfn);
10671: 
10672:     my %bighash;
10673:     my $okay=0;
10674: 
10675:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10676:                             &GDBM_READER(),0640)) {
10677:         my $noclutter;
10678:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10679:             $thisurl =~ s/\?.+$//;
10680:             if ($map =~ m{^uploaded/.+\.page$}) {
10681:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10682:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10683:                 $noclutter = 1;
10684:             }
10685:         }
10686:         my $ids;
10687:         if ($noclutter) {
10688:             $ids=$bighash{'ids_'.$thisurl};
10689:         } else {
10690:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10691:         }
10692:         unless ($ids) {
10693:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10694:             $ids=$bighash{$idkey};
10695:         }
10696:         if ($ids) {
10697: # ------------------------------------------------------------------- Has ID(s)
10698:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10699:                 $symb =~ s/\?.+$//;
10700:             }
10701: 	    foreach my $id (split(/\,/,$ids)) {
10702: 	       my ($mapid,$resid)=split(/\./,$id);
10703:                if (
10704:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10705:    eq $symb) {
10706:                    if (ref($encstate)) {
10707:                        $$encstate = $bighash{'encrypted_'.$id};
10708:                    }
10709: 		   if (($env{'request.role.adv'}) ||
10710: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10711:                        ($thisurl eq '/adm/navmaps')) {
10712: 		       $okay=1;
10713:                        last;
10714: 		   }
10715: 	       }
10716: 	   }
10717:         }
10718: 	untie(%bighash);
10719:     }
10720:     return $okay;
10721: }
10722: 
10723: # --------------------------------------------------------------- Clean-up symb
10724: 
10725: sub symbclean {
10726:     my $symb=shift;
10727:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10728: # remove version from map
10729:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10730: 
10731: # remove version from URL
10732:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10733: 
10734: # remove wrapper
10735: 
10736:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10737:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10738:     return $symb;
10739: }
10740: 
10741: # ---------------------------------------------- Split symb to find map and url
10742: 
10743: sub encode_symb {
10744:     my ($map,$resid,$url)=@_;
10745:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10746: }
10747: 
10748: sub decode_symb {
10749:     my $symb=shift;
10750:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10751:     my ($map,$resid,$url)=split(/___/,$symb);
10752:     return (&fixversion($map),$resid,&fixversion($url));
10753: }
10754: 
10755: sub fixversion {
10756:     my $fn=shift;
10757:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10758:     my %bighash;
10759:     my $uri=&clutter($fn);
10760:     my $key=$env{'request.course.id'}.'_'.$uri;
10761: # is this cached?
10762:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10763:     if (defined($cached)) { return $result; }
10764: # unfortunately not cached, or expired
10765:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10766: 	    &GDBM_READER(),0640)) {
10767:  	if ($bighash{'version_'.$uri}) {
10768:  	    my $version=$bighash{'version_'.$uri};
10769:  	    unless (($version eq 'mostrecent') || 
10770: 		    ($version==&getversion($uri))) {
10771:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10772:  	    }
10773:  	}
10774:  	untie %bighash;
10775:     }
10776:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10777: }
10778: 
10779: sub deversion {
10780:     my $url=shift;
10781:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10782:     return $url;
10783: }
10784: 
10785: # ------------------------------------------------------ Return symb list entry
10786: 
10787: sub symbread {
10788:     my ($thisfn,$donotrecurse)=@_;
10789:     my $cache_str;
10790:     if ($thisfn ne '') {
10791:         $cache_str='request.symbread.cached.'.$thisfn;
10792:         if ($env{$cache_str} ne '') {
10793:             return $env{$cache_str};
10794:         }
10795:     } else {
10796: # no filename provided? try from environment
10797:         if ($env{'request.symb'}) {
10798: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10799: 	}
10800: 	$thisfn=$env{'request.filename'};
10801:     }
10802:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10803: # is that filename actually a symb? Verify, clean, and return
10804:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10805: 	if (&symbverify($thisfn,$1)) {
10806: 	    return $env{$cache_str}=&symbclean($thisfn);
10807: 	}
10808:     }
10809:     $thisfn=declutter($thisfn);
10810:     my %hash;
10811:     my %bighash;
10812:     my $syval='';
10813:     if (($env{'request.course.fn'}) && ($thisfn)) {
10814:         my $targetfn = $thisfn;
10815:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10816:             $targetfn = 'adm/wrapper/'.$thisfn;
10817:         }
10818: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10819: 	    $targetfn=$1;
10820: 	}
10821:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10822:                       &GDBM_READER(),0640)) {
10823: 	    $syval=$hash{$targetfn};
10824:             untie(%hash);
10825:         }
10826: # ---------------------------------------------------------- There was an entry
10827:         if ($syval) {
10828: 	    #unless ($syval=~/\_\d+$/) {
10829: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10830: 		    #&appenv({'request.ambiguous' => $thisfn});
10831: 		    #return $env{$cache_str}='';
10832: 		#}    
10833: 		#$syval.=$1;
10834: 	    #}
10835:         } else {
10836: # ------------------------------------------------------- Was not in symb table
10837:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10838:                             &GDBM_READER(),0640)) {
10839: # ---------------------------------------------- Get ID(s) for current resource
10840:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10841:               unless ($ids) { 
10842:                  $ids=$bighash{'ids_/'.$thisfn};
10843:               }
10844:               unless ($ids) {
10845: # alias?
10846: 		  $ids=$bighash{'mapalias_'.$thisfn};
10847:               }
10848:               if ($ids) {
10849: # ------------------------------------------------------------------- Has ID(s)
10850:                  my @possibilities=split(/\,/,$ids);
10851:                  if ($#possibilities==0) {
10852: # ----------------------------------------------- There is only one possibility
10853: 		     my ($mapid,$resid)=split(/\./,$ids);
10854: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10855: 						    $resid,$thisfn);
10856:                  } elsif (!$donotrecurse) {
10857: # ------------------------------------------ There is more than one possibility
10858:                      my $realpossible=0;
10859:                      foreach my $id (@possibilities) {
10860: 			 my $file=$bighash{'src_'.$id};
10861:                          if (&allowed('bre',$file)) {
10862:          		    my ($mapid,$resid)=split(/\./,$id);
10863:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10864: 				$realpossible++;
10865:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10866: 						    $resid,$thisfn);
10867:                             }
10868: 			 }
10869:                      }
10870: 		     if ($realpossible!=1) { $syval=''; }
10871:                  } else {
10872:                      $syval='';
10873:                  }
10874: 	      }
10875:               untie(%bighash)
10876:            }
10877:         }
10878:         if ($syval) {
10879: 	    return $env{$cache_str}=$syval;
10880:         }
10881:     }
10882:     &appenv({'request.ambiguous' => $thisfn});
10883:     return $env{$cache_str}='';
10884: }
10885: 
10886: # ---------------------------------------------------------- Return random seed
10887: 
10888: sub numval {
10889:     my $txt=shift;
10890:     $txt=~tr/A-J/0-9/;
10891:     $txt=~tr/a-j/0-9/;
10892:     $txt=~tr/K-T/0-9/;
10893:     $txt=~tr/k-t/0-9/;
10894:     $txt=~tr/U-Z/0-5/;
10895:     $txt=~tr/u-z/0-5/;
10896:     $txt=~s/\D//g;
10897:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10898:     return int($txt);
10899: }
10900: 
10901: sub numval2 {
10902:     my $txt=shift;
10903:     $txt=~tr/A-J/0-9/;
10904:     $txt=~tr/a-j/0-9/;
10905:     $txt=~tr/K-T/0-9/;
10906:     $txt=~tr/k-t/0-9/;
10907:     $txt=~tr/U-Z/0-5/;
10908:     $txt=~tr/u-z/0-5/;
10909:     $txt=~s/\D//g;
10910:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10911:     my $total;
10912:     foreach my $val (@txts) { $total+=$val; }
10913:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10914:     return int($total);
10915: }
10916: 
10917: sub numval3 {
10918:     use integer;
10919:     my $txt=shift;
10920:     $txt=~tr/A-J/0-9/;
10921:     $txt=~tr/a-j/0-9/;
10922:     $txt=~tr/K-T/0-9/;
10923:     $txt=~tr/k-t/0-9/;
10924:     $txt=~tr/U-Z/0-5/;
10925:     $txt=~tr/u-z/0-5/;
10926:     $txt=~s/\D//g;
10927:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10928:     my $total;
10929:     foreach my $val (@txts) { $total+=$val; }
10930:     if ($_64bit) { $total=(($total<<32)>>32); }
10931:     return $total;
10932: }
10933: 
10934: sub digest {
10935:     my ($data)=@_;
10936:     my $digest=&Digest::MD5::md5($data);
10937:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10938:     my ($e,$f);
10939:     {
10940:         use integer;
10941:         $e=($a+$b);
10942:         $f=($c+$d);
10943:         if ($_64bit) {
10944:             $e=(($e<<32)>>32);
10945:             $f=(($f<<32)>>32);
10946:         }
10947:     }
10948:     if (wantarray) {
10949: 	return ($e,$f);
10950:     } else {
10951: 	my $g;
10952: 	{
10953: 	    use integer;
10954: 	    $g=($e+$f);
10955: 	    if ($_64bit) {
10956: 		$g=(($g<<32)>>32);
10957: 	    }
10958: 	}
10959: 	return $g;
10960:     }
10961: }
10962: 
10963: sub latest_rnd_algorithm_id {
10964:     return '64bit5';
10965: }
10966: 
10967: sub get_rand_alg {
10968:     my ($courseid)=@_;
10969:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10970:     if ($courseid) {
10971: 	return $env{"course.$courseid.rndseed"};
10972:     }
10973:     return &latest_rnd_algorithm_id();
10974: }
10975: 
10976: sub validCODE {
10977:     my ($CODE)=@_;
10978:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10979:     return 0;
10980: }
10981: 
10982: sub getCODE {
10983:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10984:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10985: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10986: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10987: 	return $Apache::lonhomework::history{'resource.CODE'};
10988:     }
10989:     return undef;
10990: }
10991: #
10992: #  Determines the random seed for a specific context:
10993: #
10994: # parameters:
10995: #   symb      - in course context the symb for the seed.
10996: #   course_id - The course id of the form domain_coursenum.
10997: #   domain    - Domain for the user.
10998: #   course    - Course for the user.
10999: #   cenv      - environment of the course.
11000: #
11001: # NOTE:
11002: #   All parameters are picked out of the environment if missing
11003: #   or not defined.
11004: #   If a symb cannot be determined the current time is used instead.
11005: #
11006: #  For a given well defined symb, courside, domain, username,
11007: #  and course environment, the seed is reproducible.
11008: #
11009: sub rndseed {
11010:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11011:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11012:     if (!defined($symb)) {
11013: 	unless ($symb=$wsymb) { return time; }
11014:     }
11015:     if (!defined $courseid) { 
11016: 	$courseid=$wcourseid; 
11017:     }
11018:     if (!defined $domain) { $domain=$wdomain; }
11019:     if (!defined $username) { $username=$wusername }
11020: 
11021:     my $which;
11022:     if (defined($cenv->{'rndseed'})) {
11023: 	$which = $cenv->{'rndseed'};
11024:     } else {
11025: 	$which =&get_rand_alg($courseid);
11026:     }
11027:     if (defined(&getCODE())) {
11028: 
11029: 	if ($which eq '64bit5') {
11030: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11031: 	} elsif ($which eq '64bit4') {
11032: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11033: 	} else {
11034: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11035: 	}
11036:     } elsif ($which eq '64bit5') {
11037: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11038:     } elsif ($which eq '64bit4') {
11039: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11040:     } elsif ($which eq '64bit3') {
11041: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11042:     } elsif ($which eq '64bit2') {
11043: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11044:     } elsif ($which eq '64bit') {
11045: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11046:     }
11047:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11048: }
11049: 
11050: sub rndseed_32bit {
11051:     my ($symb,$courseid,$domain,$username)=@_;
11052:     {
11053: 	use integer;
11054: 	my $symbchck=unpack("%32C*",$symb) << 27;
11055: 	my $symbseed=numval($symb) << 22;
11056: 	my $namechck=unpack("%32C*",$username) << 17;
11057: 	my $nameseed=numval($username) << 12;
11058: 	my $domainseed=unpack("%32C*",$domain) << 7;
11059: 	my $courseseed=unpack("%32C*",$courseid);
11060: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11061: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11062: 	#&logthis("rndseed :$num:$symb");
11063: 	if ($_64bit) { $num=(($num<<32)>>32); }
11064: 	return $num;
11065:     }
11066: }
11067: 
11068: sub rndseed_64bit {
11069:     my ($symb,$courseid,$domain,$username)=@_;
11070:     {
11071: 	use integer;
11072: 	my $symbchck=unpack("%32S*",$symb) << 21;
11073: 	my $symbseed=numval($symb) << 10;
11074: 	my $namechck=unpack("%32S*",$username);
11075: 	
11076: 	my $nameseed=numval($username) << 21;
11077: 	my $domainseed=unpack("%32S*",$domain) << 10;
11078: 	my $courseseed=unpack("%32S*",$courseid);
11079: 	
11080: 	my $num1=$symbchck+$symbseed+$namechck;
11081: 	my $num2=$nameseed+$domainseed+$courseseed;
11082: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11083: 	#&logthis("rndseed :$num:$symb");
11084: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11085: 	return "$num1,$num2";
11086:     }
11087: }
11088: 
11089: sub rndseed_64bit2 {
11090:     my ($symb,$courseid,$domain,$username)=@_;
11091:     {
11092: 	use integer;
11093: 	# strings need to be an even # of cahracters long, it it is odd the
11094:         # last characters gets thrown away
11095: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11096: 	my $symbseed=numval($symb) << 10;
11097: 	my $namechck=unpack("%32S*",$username.' ');
11098: 	
11099: 	my $nameseed=numval($username) << 21;
11100: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11101: 	my $courseseed=unpack("%32S*",$courseid.' ');
11102: 	
11103: 	my $num1=$symbchck+$symbseed+$namechck;
11104: 	my $num2=$nameseed+$domainseed+$courseseed;
11105: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11106: 	#&logthis("rndseed :$num:$symb");
11107: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11108: 	return "$num1,$num2";
11109:     }
11110: }
11111: 
11112: sub rndseed_64bit3 {
11113:     my ($symb,$courseid,$domain,$username)=@_;
11114:     {
11115: 	use integer;
11116: 	# strings need to be an even # of cahracters long, it it is odd the
11117:         # last characters gets thrown away
11118: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11119: 	my $symbseed=numval2($symb) << 10;
11120: 	my $namechck=unpack("%32S*",$username.' ');
11121: 	
11122: 	my $nameseed=numval2($username) << 21;
11123: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11124: 	my $courseseed=unpack("%32S*",$courseid.' ');
11125: 	
11126: 	my $num1=$symbchck+$symbseed+$namechck;
11127: 	my $num2=$nameseed+$domainseed+$courseseed;
11128: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11129: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11130: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11131: 	
11132: 	return "$num1:$num2";
11133:     }
11134: }
11135: 
11136: sub rndseed_64bit4 {
11137:     my ($symb,$courseid,$domain,$username)=@_;
11138:     {
11139: 	use integer;
11140: 	# strings need to be an even # of cahracters long, it it is odd the
11141:         # last characters gets thrown away
11142: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11143: 	my $symbseed=numval3($symb) << 10;
11144: 	my $namechck=unpack("%32S*",$username.' ');
11145: 	
11146: 	my $nameseed=numval3($username) << 21;
11147: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11148: 	my $courseseed=unpack("%32S*",$courseid.' ');
11149: 	
11150: 	my $num1=$symbchck+$symbseed+$namechck;
11151: 	my $num2=$nameseed+$domainseed+$courseseed;
11152: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11153: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11154: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11155: 	
11156: 	return "$num1:$num2";
11157:     }
11158: }
11159: 
11160: sub rndseed_64bit5 {
11161:     my ($symb,$courseid,$domain,$username)=@_;
11162:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11163:     return "$num1:$num2";
11164: }
11165: 
11166: sub rndseed_CODE_64bit {
11167:     my ($symb,$courseid,$domain,$username)=@_;
11168:     {
11169: 	use integer;
11170: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11171: 	my $symbseed=numval2($symb);
11172: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11173: 	my $CODEseed=numval(&getCODE());
11174: 	my $courseseed=unpack("%32S*",$courseid.' ');
11175: 	my $num1=$symbseed+$CODEchck;
11176: 	my $num2=$CODEseed+$courseseed+$symbchck;
11177: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11178: 	#&logthis("rndseed :$num1:$num2:$symb");
11179: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11180: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11181: 	return "$num1:$num2";
11182:     }
11183: }
11184: 
11185: sub rndseed_CODE_64bit4 {
11186:     my ($symb,$courseid,$domain,$username)=@_;
11187:     {
11188: 	use integer;
11189: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11190: 	my $symbseed=numval3($symb);
11191: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11192: 	my $CODEseed=numval3(&getCODE());
11193: 	my $courseseed=unpack("%32S*",$courseid.' ');
11194: 	my $num1=$symbseed+$CODEchck;
11195: 	my $num2=$CODEseed+$courseseed+$symbchck;
11196: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11197: 	#&logthis("rndseed :$num1:$num2:$symb");
11198: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11199: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11200: 	return "$num1:$num2";
11201:     }
11202: }
11203: 
11204: sub rndseed_CODE_64bit5 {
11205:     my ($symb,$courseid,$domain,$username)=@_;
11206:     my $code = &getCODE();
11207:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11208:     return "$num1:$num2";
11209: }
11210: 
11211: sub setup_random_from_rndseed {
11212:     my ($rndseed)=@_;
11213:     if ($rndseed =~/([,:])/) {
11214: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11215: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11216:     } else {
11217: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11218:     }
11219: }
11220: 
11221: sub latest_receipt_algorithm_id {
11222:     return 'receipt3';
11223: }
11224: 
11225: sub recunique {
11226:     my $fucourseid=shift;
11227:     my $unique;
11228:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11229: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11230: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11231:     } else {
11232: 	$unique=$perlvar{'lonReceipt'};
11233:     }
11234:     return unpack("%32C*",$unique);
11235: }
11236: 
11237: sub recprefix {
11238:     my $fucourseid=shift;
11239:     my $prefix;
11240:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11241: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11242: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11243:     } else {
11244: 	$prefix=$perlvar{'lonHostID'};
11245:     }
11246:     return unpack("%32C*",$prefix);
11247: }
11248: 
11249: sub ireceipt {
11250:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11251: 
11252:     my $return =&recprefix($fucourseid).'-';
11253: 
11254:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11255: 	$env{'request.state'} eq 'construct') {
11256: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11257: 	return $return;
11258:     }
11259: 
11260:     my $cuname=unpack("%32C*",$funame);
11261:     my $cudom=unpack("%32C*",$fudom);
11262:     my $cucourseid=unpack("%32C*",$fucourseid);
11263:     my $cusymb=unpack("%32C*",$fusymb);
11264:     my $cunique=&recunique($fucourseid);
11265:     my $cpart=unpack("%32S*",$part);
11266:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11267: 
11268: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11269: 			       
11270: 	$return.= ($cunique%$cuname+
11271: 		   $cunique%$cudom+
11272: 		   $cusymb%$cuname+
11273: 		   $cusymb%$cudom+
11274: 		   $cucourseid%$cuname+
11275: 		   $cucourseid%$cudom+
11276: 		   $cpart%$cuname+
11277: 		   $cpart%$cudom);
11278:     } else {
11279: 	$return.= ($cunique%$cuname+
11280: 		   $cunique%$cudom+
11281: 		   $cusymb%$cuname+
11282: 		   $cusymb%$cudom+
11283: 		   $cucourseid%$cuname+
11284: 		   $cucourseid%$cudom);
11285:     }
11286:     return $return;
11287: }
11288: 
11289: sub receipt {
11290:     my ($part)=@_;
11291:     my ($symb,$courseid,$domain,$name) = &whichuser();
11292:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11293: }
11294: 
11295: sub whichuser {
11296:     my ($passedsymb)=@_;
11297:     my ($symb,$courseid,$domain,$name,$publicuser);
11298:     if (defined($env{'form.grade_symb'})) {
11299: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11300: 	my $allowed=&allowed('vgr',$tmp_courseid);
11301: 	if (!$allowed &&
11302: 	    exists($env{'request.course.sec'}) &&
11303: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11304: 	    $allowed=&allowed('vgr',$tmp_courseid.
11305: 			      '/'.$env{'request.course.sec'});
11306: 	}
11307: 	if ($allowed) {
11308: 	    ($symb)=&get_env_multiple('form.grade_symb');
11309: 	    $courseid=$tmp_courseid;
11310: 	    ($domain)=&get_env_multiple('form.grade_domain');
11311: 	    ($name)=&get_env_multiple('form.grade_username');
11312: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11313: 	}
11314:     }
11315:     if (!$passedsymb) {
11316: 	$symb=&symbread();
11317:     } else {
11318: 	$symb=$passedsymb;
11319:     }
11320:     $courseid=$env{'request.course.id'};
11321:     $domain=$env{'user.domain'};
11322:     $name=$env{'user.name'};
11323:     if ($name eq 'public' && $domain eq 'public') {
11324: 	if (!defined($env{'form.username'})) {
11325: 	    $env{'form.username'}.=time.rand(10000000);
11326: 	}
11327: 	$name.=$env{'form.username'};
11328:     }
11329:     return ($symb,$courseid,$domain,$name,$publicuser);
11330: 
11331: }
11332: 
11333: # ------------------------------------------------------------ Serves up a file
11334: # returns either the contents of the file or 
11335: # -1 if the file doesn't exist
11336: #
11337: # if the target is a file that was uploaded via DOCS, 
11338: # a check will be made to see if a current copy exists on the local server,
11339: # if it does this will be served, otherwise a copy will be retrieved from
11340: # the home server for the course and stored in /home/httpd/html/userfiles on
11341: # the local server.   
11342: 
11343: sub getfile {
11344:     my ($file) = @_;
11345:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11346:     &repcopy($file);
11347:     return &readfile($file);
11348: }
11349: 
11350: sub repcopy_userfile {
11351:     my ($file)=@_;
11352:     my $londocroot = $perlvar{'lonDocRoot'};
11353:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11354:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11355:     my ($cdom,$cnum,$filename) = 
11356: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11357:     my $uri="/uploaded/$cdom/$cnum/$filename";
11358:     if (-e "$file") {
11359: # we already have a local copy, check it out
11360: 	my @fileinfo = stat($file);
11361: 	my $rtncode;
11362: 	my $info;
11363: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11364: 	if ($lwpresp ne 'ok') {
11365: # there is no such file anymore, even though we had a local copy
11366: 	    if ($rtncode eq '404') {
11367: 		unlink($file);
11368: 	    }
11369: 	    return -1;
11370: 	}
11371: 	if ($info < $fileinfo[9]) {
11372: # nice, the file we have is up-to-date, just say okay
11373: 	    return 'ok';
11374: 	} else {
11375: # the file is outdated, get rid of it
11376: 	    unlink($file);
11377: 	}
11378:     }
11379: # one way or the other, at this point, we don't have the file
11380: # construct the correct path for the file
11381:     my @parts = ($cdom,$cnum); 
11382:     if ($filename =~ m|^(.+)/[^/]+$|) {
11383: 	push @parts, split(/\//,$1);
11384:     }
11385:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11386:     foreach my $part (@parts) {
11387: 	$path .= '/'.$part;
11388: 	if (!-e $path) {
11389: 	    mkdir($path,0770);
11390: 	}
11391:     }
11392: # now the path exists for sure
11393: # get a user agent
11394:     my $ua=new LWP::UserAgent;
11395:     my $transferfile=$file.'.in.transfer';
11396: # FIXME: this should flock
11397:     if (-e $transferfile) { return 'ok'; }
11398:     my $request;
11399:     $uri=~s/^\///;
11400:     my $homeserver = &homeserver($cnum,$cdom);
11401:     my $protocol = $protocol{$homeserver};
11402:     $protocol = 'http' if ($protocol ne 'https');
11403:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11404:     my $response=$ua->request($request,$transferfile);
11405: # did it work?
11406:     if ($response->is_error()) {
11407: 	unlink($transferfile);
11408: 	&logthis("Userfile repcopy failed for $uri");
11409: 	return -1;
11410:     }
11411: # worked, rename the transfer file
11412:     rename($transferfile,$file);
11413:     return 'ok';
11414: }
11415: 
11416: sub tokenwrapper {
11417:     my $uri=shift;
11418:     $uri=~s|^https?\://([^/]+)||;
11419:     $uri=~s|^/||;
11420:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11421:     my $token=$1;
11422:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11423:     if ($udom && $uname && $file) {
11424: 	$file=~s|(\?\.*)*$||;
11425:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11426:         my $homeserver = &homeserver($uname,$udom);
11427:         my $protocol = $protocol{$homeserver};
11428:         $protocol = 'http' if ($protocol ne 'https');
11429:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11430:                (($uri=~/\?/)?'&':'?').'token='.$token.
11431:                                '&tokenissued='.$perlvar{'lonHostID'};
11432:     } else {
11433:         return '/adm/notfound.html';
11434:     }
11435: }
11436: 
11437: # call with reqtype HEAD: get last modification time
11438: # call with reqtype GET: get the file contents
11439: # Do not call this with reqtype GET for large files! It loads everything into memory
11440: #
11441: sub getuploaded {
11442:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11443:     $uri=~s/^\///;
11444:     my $homeserver = &homeserver($cnum,$cdom);
11445:     my $protocol = $protocol{$homeserver};
11446:     $protocol = 'http' if ($protocol ne 'https');
11447:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11448:     my $ua=new LWP::UserAgent;
11449:     my $request=new HTTP::Request($reqtype,$uri);
11450:     my $response=$ua->request($request);
11451:     $$rtncode = $response->code;
11452:     if (! $response->is_success()) {
11453: 	return 'failed';
11454:     }      
11455:     if ($reqtype eq 'HEAD') {
11456: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11457:     } elsif ($reqtype eq 'GET') {
11458: 	$$info = $response->content;
11459:     }
11460:     return 'ok';
11461: }
11462: 
11463: sub readfile {
11464:     my $file = shift;
11465:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11466:     my $fh;
11467:     open($fh,"<$file");
11468:     my $a='';
11469:     while (my $line = <$fh>) { $a .= $line; }
11470:     return $a;
11471: }
11472: 
11473: sub filelocation {
11474:     my ($dir,$file) = @_;
11475:     my $location;
11476:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11477: 
11478:     if ($file =~ m-^/adm/-) {
11479: 	$file=~s-^/adm/wrapper/-/-;
11480: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11481:     }
11482: 
11483:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11484:         $location = $file;
11485:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11486:         my ($udom,$uname,$filename)=
11487:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11488:         my $home=&homeserver($uname,$udom);
11489:         my $is_me=0;
11490:         my @ids=&current_machine_ids();
11491:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11492:         if ($is_me) {
11493:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11494:         } else {
11495:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11496:   	      $udom.'/'.$uname.'/'.$filename;
11497:         }
11498:     } elsif ($file =~ m-^/adm/-) {
11499: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11500:     } else {
11501:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11502:         $file=~s:^/(res|priv)/:/:;
11503:         my $space=$1;
11504:         if ( !( $file =~ m:^/:) ) {
11505:             $location = $dir. '/'.$file;
11506:         } else {
11507:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11508:         }
11509:     }
11510:     $location=~s://+:/:g; # remove duplicate /
11511:     while ($location=~m{/\.\./}) {
11512: 	if ($location =~ m{/[^/]+/\.\./}) {
11513: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11514: 	} else {
11515: 	    $location=~ s{/\.\./}{/}g;
11516: 	}
11517:     } #remove dir/..
11518:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11519:     return $location;
11520: }
11521: 
11522: sub hreflocation {
11523:     my ($dir,$file)=@_;
11524:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11525: 	$file=filelocation($dir,$file);
11526:     } elsif ($file=~m-^/adm/-) {
11527: 	$file=~s-^/adm/wrapper/-/-;
11528: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11529:     }
11530:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11531: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11532:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11533: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11534: 	        {/uploaded/$1/$2/}x;
11535:     }
11536:     if ($file=~ m{^/userfiles/}) {
11537: 	$file =~ s{^/userfiles/}{/uploaded/};
11538:     }
11539:     return $file;
11540: }
11541: 
11542: 
11543: 
11544: 
11545: 
11546: sub current_machine_domains {
11547:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11548: }
11549: 
11550: sub machine_domains {
11551:     my ($hostname) = @_;
11552:     my @domains;
11553:     my %hostname = &all_hostnames();
11554:     while( my($id, $name) = each(%hostname)) {
11555: #	&logthis("-$id-$name-$hostname-");
11556: 	if ($hostname eq $name) {
11557: 	    push(@domains,&host_domain($id));
11558: 	}
11559:     }
11560:     return @domains;
11561: }
11562: 
11563: sub current_machine_ids {
11564:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11565: }
11566: 
11567: sub machine_ids {
11568:     my ($hostname) = @_;
11569:     $hostname ||= &hostname($perlvar{'lonHostID'});
11570:     my @ids;
11571:     my %name_to_host = &all_names();
11572:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11573: 	return @{ $name_to_host{$hostname} };
11574:     }
11575:     return;
11576: }
11577: 
11578: sub additional_machine_domains {
11579:     my @domains;
11580:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11581:     while( my $line = <$fh>) {
11582:         $line =~ s/\s//g;
11583:         push(@domains,$line);
11584:     }
11585:     return @domains;
11586: }
11587: 
11588: sub default_login_domain {
11589:     my $domain = $perlvar{'lonDefDomain'};
11590:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11591:     foreach my $posdom (&current_machine_domains(),
11592:                         &additional_machine_domains()) {
11593:         if (lc($posdom) eq lc($testdomain)) {
11594:             $domain=$posdom;
11595:             last;
11596:         }
11597:     }
11598:     return $domain;
11599: }
11600: 
11601: # ------------------------------------------------------------- Declutters URLs
11602: 
11603: sub declutter {
11604:     my $thisfn=shift;
11605:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11606:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11607:     $thisfn=~s/^\///;
11608:     $thisfn=~s|^adm/wrapper/||;
11609:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11610:     $thisfn=~s/^res\///;
11611:     $thisfn=~s/^priv\///;
11612:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11613:         $thisfn=~s/\?.+$//;
11614:     }
11615:     return $thisfn;
11616: }
11617: 
11618: # ------------------------------------------------------------- Clutter up URLs
11619: 
11620: sub clutter {
11621:     my $thisfn='/'.&declutter(shift);
11622:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11623: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11624:        $thisfn='/res'.$thisfn; 
11625:     }
11626:     if ($thisfn !~m|^/adm|) {
11627: 	if ($thisfn =~ m|^/ext/|) {
11628: 	    $thisfn='/adm/wrapper'.$thisfn;
11629: 	} else {
11630: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11631: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11632: 	    if ($embstyle eq 'ssi'
11633: 		|| ($embstyle eq 'hdn')
11634: 		|| ($embstyle eq 'rat')
11635: 		|| ($embstyle eq 'prv')
11636: 		|| ($embstyle eq 'ign')) {
11637: 		#do nothing with these
11638: 	    } elsif (($embstyle eq 'img') 
11639: 		|| ($embstyle eq 'emb')
11640: 		|| ($embstyle eq 'wrp')) {
11641: 		$thisfn='/adm/wrapper'.$thisfn;
11642: 	    } elsif ($embstyle eq 'unk'
11643: 		     && $thisfn!~/\.(sequence|page)$/) {
11644: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11645: 	    } else {
11646: #		&logthis("Got a blank emb style");
11647: 	    }
11648: 	}
11649:     }
11650:     return $thisfn;
11651: }
11652: 
11653: sub clutter_with_no_wrapper {
11654:     my $uri = &clutter(shift);
11655:     if ($uri =~ m-^/adm/-) {
11656: 	$uri =~ s-^/adm/wrapper/-/-;
11657: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11658:     }
11659:     return $uri;
11660: }
11661: 
11662: sub freeze_escape {
11663:     my ($value)=@_;
11664:     if (ref($value)) {
11665: 	$value=&nfreeze($value);
11666: 	return '__FROZEN__'.&escape($value);
11667:     }
11668:     return &escape($value);
11669: }
11670: 
11671: 
11672: sub thaw_unescape {
11673:     my ($value)=@_;
11674:     if ($value =~ /^__FROZEN__/) {
11675: 	substr($value,0,10,undef);
11676: 	$value=&unescape($value);
11677: 	return &thaw($value);
11678:     }
11679:     return &unescape($value);
11680: }
11681: 
11682: sub correct_line_ends {
11683:     my ($result)=@_;
11684:     $$result =~s/\r\n/\n/mg;
11685:     $$result =~s/\r/\n/mg;
11686: }
11687: # ================================================================ Main Program
11688: 
11689: sub goodbye {
11690:    &logthis("Starting Shut down");
11691: #not converted to using infrastruture and probably shouldn't be
11692:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11693: #converted
11694: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11695:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11696: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11697: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11698: #1.1 only
11699: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11700: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11701: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11702: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11703:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11704:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11705:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11706:    &flushcourselogs();
11707:    &logthis("Shutting down");
11708: }
11709: 
11710: sub get_dns {
11711:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11712:     if (!$ignore_cache) {
11713: 	my ($content,$cached)=
11714: 	    &Apache::lonnet::is_cached_new('dns',$url);
11715: 	if ($cached) {
11716: 	    &$func($content,$hashref);
11717: 	    return;
11718: 	}
11719:     }
11720: 
11721:     my %alldns;
11722:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11723:     foreach my $dns (<$config>) {
11724: 	next if ($dns !~ /^\^(\S*)/x);
11725:         my $line = $1;
11726:         my ($host,$protocol) = split(/:/,$line);
11727:         if ($protocol ne 'https') {
11728:             $protocol = 'http';
11729:         }
11730: 	$alldns{$host} = $protocol;
11731:     }
11732:     while (%alldns) {
11733: 	my ($dns) = keys(%alldns);
11734: 	my $ua=new LWP::UserAgent;
11735:         $ua->timeout(30);
11736: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11737: 	my $response=$ua->request($request);
11738:         delete($alldns{$dns});
11739: 	next if ($response->is_error());
11740: 	my @content = split("\n",$response->content);
11741: 	unless ($nocache) {
11742: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11743: 	}
11744: 	&$func(\@content,$hashref);
11745: 	return;
11746:     }
11747:     close($config);
11748:     my $which = (split('/',$url))[3];
11749:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11750:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11751:     my @content = <$config>;
11752:     &$func(\@content,$hashref);
11753:     return;
11754: }
11755: 
11756: # ------------------------------------------------------Get DNS checksums file
11757: sub parse_dns_checksums_tab {
11758:     my ($lines,$hashref) = @_;
11759:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11760:     my $loncaparev = &get_server_loncaparev($machine_dom);
11761:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11762:     my (%chksum,%revnum);
11763:     if (ref($lines) eq 'ARRAY') {
11764:         chomp(@{$lines});
11765:         my $version = shift(@{$lines});
11766:         if ($version eq $release) {  
11767:             foreach my $line (@{$lines}) {
11768:                 my ($file,$version,$shasum) = split(/,/,$line);
11769:                 $chksum{$file} = $shasum;
11770:                 $revnum{$file} = $version;
11771:             }
11772:             if (ref($hashref) eq 'HASH') {
11773:                 %{$hashref} = (
11774:                                 sums     => \%chksum,
11775:                                 versions => \%revnum,
11776:                               );
11777:             }
11778:         }
11779:     }
11780:     return;
11781: }
11782: 
11783: sub fetch_dns_checksums {
11784:     my %checksums;
11785:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11786:     my $loncaparev = &get_server_loncaparev($machine_dom);
11787:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11788:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11789:              \%checksums);
11790:     return \%checksums;
11791: }
11792: 
11793: # ------------------------------------------------------------ Read domain file
11794: {
11795:     my $loaded;
11796:     my %domain;
11797: 
11798:     sub parse_domain_tab {
11799: 	my ($lines) = @_;
11800: 	foreach my $line (@$lines) {
11801: 	    next if ($line =~ /^(\#|\s*$ )/x);
11802: 
11803: 	    chomp($line);
11804: 	    my ($name,@elements) = split(/:/,$line,9);
11805: 	    my %this_domain;
11806: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11807: 			       'lang_def', 'city', 'longi', 'lati',
11808: 			       'primary') {
11809: 		$this_domain{$field} = shift(@elements);
11810: 	    }
11811: 	    $domain{$name} = \%this_domain;
11812: 	}
11813:     }
11814: 
11815:     sub reset_domain_info {
11816: 	undef($loaded);
11817: 	undef(%domain);
11818:     }
11819: 
11820:     sub load_domain_tab {
11821: 	my ($ignore_cache) = @_;
11822: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11823: 	my $fh;
11824: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11825: 	    my @lines = <$fh>;
11826: 	    &parse_domain_tab(\@lines);
11827: 	}
11828: 	close($fh);
11829: 	$loaded = 1;
11830:     }
11831: 
11832:     sub domain {
11833: 	&load_domain_tab() if (!$loaded);
11834: 
11835: 	my ($name,$what) = @_;
11836: 	return if ( !exists($domain{$name}) );
11837: 
11838: 	if (!$what) {
11839: 	    return $domain{$name}{'description'};
11840: 	}
11841: 	return $domain{$name}{$what};
11842:     }
11843: 
11844:     sub domain_info {
11845:         &load_domain_tab() if (!$loaded);
11846:         return %domain;
11847:     }
11848: 
11849: }
11850: 
11851: 
11852: # ------------------------------------------------------------- Read hosts file
11853: {
11854:     my %hostname;
11855:     my %hostdom;
11856:     my %libserv;
11857:     my $loaded;
11858:     my %name_to_host;
11859:     my %internetdom;
11860:     my %LC_dns_serv;
11861: 
11862:     sub parse_hosts_tab {
11863: 	my ($file) = @_;
11864: 	foreach my $configline (@$file) {
11865: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11866:             chomp($configline);
11867: 	    if ($configline =~ /^\^/) {
11868:                 if ($configline =~ /^\^([\w.\-]+)/) {
11869:                     $LC_dns_serv{$1} = 1;
11870:                 }
11871:                 next;
11872:             }
11873: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11874: 	    $name=~s/\s//g;
11875: 	    if ($id && $domain && $role && $name) {
11876: 		$hostname{$id}=$name;
11877: 		push(@{$name_to_host{$name}}, $id);
11878: 		$hostdom{$id}=$domain;
11879: 		if ($role eq 'library') { $libserv{$id}=$name; }
11880:                 if (defined($protocol)) {
11881:                     if ($protocol eq 'https') {
11882:                         $protocol{$id} = $protocol;
11883:                     } else {
11884:                         $protocol{$id} = 'http'; 
11885:                     }
11886:                 } else {
11887:                     $protocol{$id} = 'http';
11888:                 }
11889:                 if (defined($intdom)) {
11890:                     $internetdom{$id} = $intdom;
11891:                 }
11892: 	    }
11893: 	}
11894:     }
11895:     
11896:     sub reset_hosts_info {
11897: 	&purge_remembered();
11898: 	&reset_domain_info();
11899: 	&reset_hosts_ip_info();
11900: 	undef(%name_to_host);
11901: 	undef(%hostname);
11902: 	undef(%hostdom);
11903: 	undef(%libserv);
11904: 	undef($loaded);
11905:     }
11906: 
11907:     sub load_hosts_tab {
11908: 	my ($ignore_cache) = @_;
11909: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11910: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11911: 	my @config = <$config>;
11912: 	&parse_hosts_tab(\@config);
11913: 	close($config);
11914: 	$loaded=1;
11915:     }
11916: 
11917:     sub hostname {
11918: 	&load_hosts_tab() if (!$loaded);
11919: 
11920: 	my ($lonid) = @_;
11921: 	return $hostname{$lonid};
11922:     }
11923: 
11924:     sub all_hostnames {
11925: 	&load_hosts_tab() if (!$loaded);
11926: 
11927: 	return %hostname;
11928:     }
11929: 
11930:     sub all_names {
11931: 	&load_hosts_tab() if (!$loaded);
11932: 
11933: 	return %name_to_host;
11934:     }
11935: 
11936:     sub all_host_domain {
11937:         &load_hosts_tab() if (!$loaded);
11938:         return %hostdom;
11939:     }
11940: 
11941:     sub is_library {
11942: 	&load_hosts_tab() if (!$loaded);
11943: 
11944: 	return exists($libserv{$_[0]});
11945:     }
11946: 
11947:     sub all_library {
11948: 	&load_hosts_tab() if (!$loaded);
11949: 
11950: 	return %libserv;
11951:     }
11952: 
11953:     sub unique_library {
11954: 	#2x reverse removes all hostnames that appear more than once
11955:         my %unique = reverse &all_library();
11956:         return reverse %unique;
11957:     }
11958: 
11959:     sub get_servers {
11960: 	&load_hosts_tab() if (!$loaded);
11961: 
11962: 	my ($domain,$type) = @_;
11963: 	my %possible_hosts = ($type eq 'library') ? %libserv
11964: 	                                          : %hostname;
11965: 	my %result;
11966: 	if (ref($domain) eq 'ARRAY') {
11967: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11968: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11969: 		    $result{$host} = $hostname;
11970: 		}
11971: 	    }
11972: 	} else {
11973: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11974: 		if ($hostdom{$host} eq $domain) {
11975: 		    $result{$host} = $hostname;
11976: 		}
11977: 	    }
11978: 	}
11979: 	return %result;
11980:     }
11981: 
11982:     sub get_unique_servers {
11983:         my %unique = reverse &get_servers(@_);
11984: 	return reverse %unique;
11985:     }
11986: 
11987:     sub host_domain {
11988: 	&load_hosts_tab() if (!$loaded);
11989: 
11990: 	my ($lonid) = @_;
11991: 	return $hostdom{$lonid};
11992:     }
11993: 
11994:     sub all_domains {
11995: 	&load_hosts_tab() if (!$loaded);
11996: 
11997: 	my %seen;
11998: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11999: 	return @uniq;
12000:     }
12001: 
12002:     sub internet_dom {
12003:         &load_hosts_tab() if (!$loaded);
12004: 
12005:         my ($lonid) = @_;
12006:         return $internetdom{$lonid};
12007:     }
12008: 
12009:     sub is_LC_dns {
12010:         &load_hosts_tab() if (!$loaded);
12011: 
12012:         my ($hostname) = @_;
12013:         return exists($LC_dns_serv{$hostname});
12014:     }
12015: 
12016: }
12017: 
12018: { 
12019:     my %iphost;
12020:     my %name_to_ip;
12021:     my %lonid_to_ip;
12022: 
12023:     sub get_hosts_from_ip {
12024: 	my ($ip) = @_;
12025: 	my %iphosts = &get_iphost();
12026: 	if (ref($iphosts{$ip})) {
12027: 	    return @{$iphosts{$ip}};
12028: 	}
12029: 	return;
12030:     }
12031:     
12032:     sub reset_hosts_ip_info {
12033: 	undef(%iphost);
12034: 	undef(%name_to_ip);
12035: 	undef(%lonid_to_ip);
12036:     }
12037: 
12038:     sub get_host_ip {
12039: 	my ($lonid) = @_;
12040: 	if (exists($lonid_to_ip{$lonid})) {
12041: 	    return $lonid_to_ip{$lonid};
12042: 	}
12043: 	my $name=&hostname($lonid);
12044:    	my $ip = gethostbyname($name);
12045: 	return if (!$ip || length($ip) ne 4);
12046: 	$ip=inet_ntoa($ip);
12047: 	$name_to_ip{$name}   = $ip;
12048: 	$lonid_to_ip{$lonid} = $ip;
12049: 	return $ip;
12050:     }
12051:     
12052:     sub get_iphost {
12053: 	my ($ignore_cache) = @_;
12054: 
12055: 	if (!$ignore_cache) {
12056: 	    if (%iphost) {
12057: 		return %iphost;
12058: 	    }
12059: 	    my ($ip_info,$cached)=
12060: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12061: 	    if ($cached) {
12062: 		%iphost      = %{$ip_info->[0]};
12063: 		%name_to_ip  = %{$ip_info->[1]};
12064: 		%lonid_to_ip = %{$ip_info->[2]};
12065: 		return %iphost;
12066: 	    }
12067: 	}
12068: 
12069: 	# get yesterday's info for fallback
12070: 	my %old_name_to_ip;
12071: 	my ($ip_info,$cached)=
12072: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12073: 	if ($cached) {
12074: 	    %old_name_to_ip = %{$ip_info->[1]};
12075: 	}
12076: 
12077: 	my %name_to_host = &all_names();
12078: 	foreach my $name (keys(%name_to_host)) {
12079: 	    my $ip;
12080: 	    if (!exists($name_to_ip{$name})) {
12081: 		$ip = gethostbyname($name);
12082: 		if (!$ip || length($ip) ne 4) {
12083: 		    if (defined($old_name_to_ip{$name})) {
12084: 			$ip = $old_name_to_ip{$name};
12085: 			&logthis("Can't find $name defaulting to old $ip");
12086: 		    } else {
12087: 			&logthis("Name $name no IP found");
12088: 			next;
12089: 		    }
12090: 		} else {
12091: 		    $ip=inet_ntoa($ip);
12092: 		}
12093: 		$name_to_ip{$name} = $ip;
12094: 	    } else {
12095: 		$ip = $name_to_ip{$name};
12096: 	    }
12097: 	    foreach my $id (@{ $name_to_host{$name} }) {
12098: 		$lonid_to_ip{$id} = $ip;
12099: 	    }
12100: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12101: 	}
12102: 	&do_cache_new('iphost','iphost',
12103: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12104: 		      48*60*60);
12105: 
12106: 	return %iphost;
12107:     }
12108: 
12109:     #
12110:     #  Given a DNS returns the loncapa host name for that DNS 
12111:     # 
12112:     sub host_from_dns {
12113:         my ($dns) = @_;
12114:         my @hosts;
12115:         my $ip;
12116: 
12117:         if (exists($name_to_ip{$dns})) {
12118:             $ip = $name_to_ip{$dns};
12119:         }
12120:         if (!$ip) {
12121:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12122:             if (length($ip) == 4) { 
12123: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12124:             }
12125:         }
12126:         if ($ip) {
12127: 	    @hosts = get_hosts_from_ip($ip);
12128: 	    return $hosts[0];
12129:         }
12130:         return undef;
12131:     }
12132: 
12133:     sub get_internet_names {
12134:         my ($lonid) = @_;
12135:         return if ($lonid eq '');
12136:         my ($idnref,$cached)=
12137:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12138:         if ($cached) {
12139:             return $idnref;
12140:         }
12141:         my $ip = &get_host_ip($lonid);
12142:         my @hosts = &get_hosts_from_ip($ip);
12143:         my %iphost = &get_iphost();
12144:         my (@idns,%seen);
12145:         foreach my $id (@hosts) {
12146:             my $dom = &host_domain($id);
12147:             my $prim_id = &domain($dom,'primary');
12148:             my $prim_ip = &get_host_ip($prim_id);
12149:             next if ($seen{$prim_ip});
12150:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12151:                 foreach my $id (@{$iphost{$prim_ip}}) {
12152:                     my $intdom = &internet_dom($id);
12153:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12154:                         push(@idns,$intdom);
12155:                     }
12156:                 }
12157:             }
12158:             $seen{$prim_ip} = 1;
12159:         }
12160:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12161:     }
12162: 
12163: }
12164: 
12165: sub all_loncaparevs {
12166:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
12167: }
12168: 
12169: # ---------------------------------------------------------- Read loncaparev table
12170: {
12171:     sub load_loncaparevs { 
12172:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12173:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12174:                 while (my $configline=<$config>) {
12175:                     chomp($configline);
12176:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12177:                     $loncaparevs{$hostid}=$loncaparev;
12178:                 }
12179:                 close($config);
12180:             }
12181:         }
12182:     }
12183: }
12184: 
12185: # ---------------------------------------------------------- Read serverhostID table
12186: {
12187:     sub load_serverhomeIDs {
12188:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12189:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12190:                 while (my $configline=<$config>) {
12191:                     chomp($configline);
12192:                     my ($name,$id)=split(/:/,$configline);
12193:                     $serverhomeIDs{$name}=$id;
12194:                 }
12195:                 close($config);
12196:             }
12197:         }
12198:     }
12199: }
12200: 
12201: 
12202: BEGIN {
12203: 
12204: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12205:     unless ($readit) {
12206: {
12207:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12208:     %perlvar = (%perlvar,%{$configvars});
12209: }
12210: 
12211: 
12212: # ------------------------------------------------------ Read spare server file
12213: {
12214:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12215: 
12216:     while (my $configline=<$config>) {
12217:        chomp($configline);
12218:        if ($configline) {
12219: 	   my ($host,$type) = split(':',$configline,2);
12220: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12221: 	   push(@{ $spareid{$type} }, $host);
12222:        }
12223:     }
12224:     close($config);
12225: }
12226: # ------------------------------------------------------------ Read permissions
12227: {
12228:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12229: 
12230:     while (my $configline=<$config>) {
12231: 	chomp($configline);
12232: 	if ($configline) {
12233: 	    my ($role,$perm)=split(/ /,$configline);
12234: 	    if ($perm ne '') { $pr{$role}=$perm; }
12235: 	}
12236:     }
12237:     close($config);
12238: }
12239: 
12240: # -------------------------------------------- Read plain texts for permissions
12241: {
12242:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12243: 
12244:     while (my $configline=<$config>) {
12245: 	chomp($configline);
12246: 	if ($configline) {
12247: 	    my ($short,@plain)=split(/:/,$configline);
12248:             %{$prp{$short}} = ();
12249: 	    if (@plain > 0) {
12250:                 $prp{$short}{'std'} = $plain[0];
12251:                 for (my $i=1; $i<@plain; $i++) {
12252:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12253:                 }
12254:             }
12255: 	}
12256:     }
12257:     close($config);
12258: }
12259: 
12260: # ---------------------------------------------------------- Read package table
12261: {
12262:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12263: 
12264:     while (my $configline=<$config>) {
12265: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12266: 	chomp($configline);
12267: 	my ($short,$plain)=split(/:/,$configline);
12268: 	my ($pack,$name)=split(/\&/,$short);
12269: 	if ($plain ne '') {
12270: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12271: 	    $packagetab{$short}=$plain; 
12272: 	}
12273:     }
12274:     close($config);
12275: }
12276: 
12277: # ---------------------------------------------------------- Read loncaparev table
12278: 
12279: &load_loncaparevs();
12280: 
12281: # ---------------------------------------------------------- Read serverhostID table
12282: 
12283: &load_serverhomeIDs();
12284: 
12285: # ---------------------------------------------------------- Read releaseslist XML
12286: {
12287:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12288:     if (-e $file) {
12289:         my $parser = HTML::LCParser->new($file);
12290:         while (my $token = $parser->get_token()) {
12291:             if ($token->[0] eq 'S') {
12292:                 my $item = $token->[1];
12293:                 my $name = $token->[2]{'name'};
12294:                 my $value = $token->[2]{'value'};
12295:                 if ($item ne '' && $name ne '' && $value ne '') {
12296:                     my $release = $parser->get_text();
12297:                     $release =~ s/(^\s*|\s*$ )//gx;
12298:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12299:                 }
12300:             }
12301:         }
12302:     }
12303: }
12304: 
12305: # ---------------------------------------------------------- Read managers table
12306: {
12307:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12308:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12309:             while (my $configline=<$config>) {
12310:                 chomp($configline);
12311:                 next if ($configline =~ /^\#/);
12312:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12313:                     $managerstab{$configline} = 1;
12314:                 }
12315:             }
12316:             close($config);
12317:         }
12318:     }
12319: }
12320: 
12321: # ------------- set up temporary directory
12322: {
12323:     $tmpdir = LONCAPA::tempdir();
12324: 
12325: }
12326: 
12327: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12328: 				'compress_threshold'=> 20_000,
12329:  			        });
12330: 
12331: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12332: $dumpcount=0;
12333: $locknum=0;
12334: 
12335: &logtouch();
12336: &logthis('<font color="yellow">INFO: Read configuration</font>');
12337: $readit=1;
12338:     {
12339: 	use integer;
12340: 	my $test=(2**32)+1;
12341: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12342: 	&logthis(" Detected 64bit platform ($_64bit)");
12343:     }
12344: }
12345: }
12346: 
12347: 1;
12348: __END__
12349: 
12350: =pod
12351: 
12352: =head1 NAME
12353: 
12354: Apache::lonnet - Subroutines to ask questions about things in the network.
12355: 
12356: =head1 SYNOPSIS
12357: 
12358: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12359: 
12360:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12361: 
12362: Common parameters:
12363: 
12364: =over 4
12365: 
12366: =item *
12367: 
12368: $uname : an internal username (if $cname expecting a course Id specifically)
12369: 
12370: =item *
12371: 
12372: $udom : a domain (if $cdom expecting a course's domain specifically)
12373: 
12374: =item *
12375: 
12376: $symb : a resource instance identifier
12377: 
12378: =item *
12379: 
12380: $namespace : the name of a .db file that contains the data needed or
12381: being set.
12382: 
12383: =back
12384: 
12385: =head1 OVERVIEW
12386: 
12387: lonnet provides subroutines which interact with the
12388: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12389: about classes, users, and resources.
12390: 
12391: For many of these objects you can also use this to store data about
12392: them or modify them in various ways.
12393: 
12394: =head2 Symbs
12395: 
12396: To identify a specific instance of a resource, LON-CAPA uses symbols
12397: or "symbs"X<symb>. These identifiers are built from the URL of the
12398: map, the resource number of the resource in the map, and the URL of
12399: the resource itself. The latter is somewhat redundant, but might help
12400: if maps change.
12401: 
12402: An example is
12403: 
12404:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12405: 
12406: The respective map entry is
12407: 
12408:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12409:   title="Problem 2">
12410:  </resource>
12411: 
12412: Symbs are used by the random number generator, as well as to store and
12413: restore data specific to a certain instance of for example a problem.
12414: 
12415: =head2 Storing And Retrieving Data
12416: 
12417: X<store()>X<cstore()>X<restore()>Three of the most important functions
12418: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12419: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12420: is is the non-critical message twin of cstore. These functions are for
12421: handlers to store a perl hash to a user's permanent data space in an
12422: easy manner, and to retrieve it again on another call. It is expected
12423: that a handler would use this once at the beginning to retrieve data,
12424: and then again once at the end to send only the new data back.
12425: 
12426: The data is stored in the user's data directory on the user's
12427: homeserver under the ID of the course.
12428: 
12429: The hash that is returned by restore will have all of the previous
12430: value for all of the elements of the hash.
12431: 
12432: Example:
12433: 
12434:  #creating a hash
12435:  my %hash;
12436:  $hash{'foo'}='bar';
12437: 
12438:  #storing it
12439:  &Apache::lonnet::cstore(\%hash);
12440: 
12441:  #changing a value
12442:  $hash{'foo'}='notbar';
12443: 
12444:  #adding a new value
12445:  $hash{'bar'}='foo';
12446:  &Apache::lonnet::cstore(\%hash);
12447: 
12448:  #retrieving the hash
12449:  my %history=&Apache::lonnet::restore();
12450: 
12451:  #print the hash
12452:  foreach my $key (sort(keys(%history))) {
12453:    print("\%history{$key} = $history{$key}");
12454:  }
12455: 
12456: Will print out:
12457: 
12458:  %history{1:foo} = bar
12459:  %history{1:keys} = foo:timestamp
12460:  %history{1:timestamp} = 990455579
12461:  %history{2:bar} = foo
12462:  %history{2:foo} = notbar
12463:  %history{2:keys} = foo:bar:timestamp
12464:  %history{2:timestamp} = 990455580
12465:  %history{bar} = foo
12466:  %history{foo} = notbar
12467:  %history{timestamp} = 990455580
12468:  %history{version} = 2
12469: 
12470: Note that the special hash entries C<keys>, C<version> and
12471: C<timestamp> were added to the hash. C<version> will be equal to the
12472: total number of versions of the data that have been stored. The
12473: C<timestamp> attribute will be the UNIX time the hash was
12474: stored. C<keys> is available in every historical section to list which
12475: keys were added or changed at a specific historical revision of a
12476: hash.
12477: 
12478: B<Warning>: do not store the hash that restore returns directly. This
12479: will cause a mess since it will restore the historical keys as if the
12480: were new keys. I.E. 1:foo will become 1:1:foo etc.
12481: 
12482: Calling convention:
12483: 
12484:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12485:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12486: 
12487: For more detailed information, see lonnet specific documentation.
12488: 
12489: =head1 RETURN MESSAGES
12490: 
12491: =over 4
12492: 
12493: =item * B<con_lost>: unable to contact remote host
12494: 
12495: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12496: when the connection is brought back up
12497: 
12498: =item * B<con_failed>: unable to contact remote host and unable to save message
12499: for later delivery
12500: 
12501: =item * B<error:>: an error a occurred, a description of the error follows the :
12502: 
12503: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12504: that was requested
12505: 
12506: =back
12507: 
12508: =head1 PUBLIC SUBROUTINES
12509: 
12510: =head2 Session Environment Functions
12511: 
12512: =over 4
12513: 
12514: =item * 
12515: X<appenv()>
12516: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12517: the user envirnoment file, and will be restored for each access this
12518: user makes during this session, also modifies the %env for the current
12519: process. Optional rolesarrayref - if defined contains a reference to an array
12520: of roles which are exempt from the restriction on modifying user.role entries 
12521: in the user's environment.db and in %env.    
12522: 
12523: =item *
12524: X<delenv()>
12525: B<delenv($delthis,$regexp)>: removes all items from the session
12526: environment file that begin with $delthis. If the 
12527: optional second arg - $regexp - is true, $delthis is treated as a 
12528: regular expression, otherwise \Q$delthis\E is used. 
12529: The values are also deleted from the current processes %env.
12530: 
12531: =item * get_env_multiple($name) 
12532: 
12533: gets $name from the %env hash, it seemlessly handles the cases where multiple
12534: values may be defined and end up as an array ref.
12535: 
12536: returns an array of values
12537: 
12538: =back
12539: 
12540: =head2 User Information
12541: 
12542: =over 4
12543: 
12544: =item *
12545: X<queryauthenticate()>
12546: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12547: authentication scheme
12548: 
12549: =item *
12550: X<authenticate()>
12551: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12552: authenticate user from domain's lib servers (first use the current
12553: one). C<$upass> should be the users password.
12554: $checkdefauth is optional (value is 1 if a check should be made to
12555:    authenticate user using default authentication method, and allow
12556:    account creation if username does not have account in the domain).
12557: $clientcancheckhost is optional (value is 1 if checking whether the
12558:    server can host will occur on the client side in lonauth.pm).   
12559: 
12560: =item *
12561: X<homeserver()>
12562: B<homeserver($uname,$udom)>: find the server which has
12563: the user's directory and files (there must be only one), this caches
12564: the answer, and also caches if there is a borken connection.
12565: 
12566: =item *
12567: X<idget()>
12568: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12569: (IDs are a unique resource in a domain, there must be only 1 ID per
12570: username, and only 1 username per ID in a specific domain) (returns
12571: hash: id=>name,id=>name)
12572: 
12573: =item *
12574: X<idrget()>
12575: B<idrget($udom,@unames)>: find the IDs behind a list of
12576: usernames (returns hash: name=>id,name=>id)
12577: 
12578: =item *
12579: X<idput()>
12580: B<idput($udom,%ids)>: store away a list of names and associated IDs
12581: 
12582: =item *
12583: X<rolesinit()>
12584: B<rolesinit($udom,$username)>: get user privileges.
12585: returns user role, first access and timer interval hashes
12586: 
12587: =item *
12588: X<privileged()>
12589: B<privileged($username,$domain)>: returns a true if user has a
12590: privileged and active role (i.e. su or dc), false otherwise.
12591: 
12592: =item *
12593: X<getsection()>
12594: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12595: course $cname, return section name/number or '' for "not in course"
12596: and '-1' for "no section"
12597: 
12598: =item *
12599: X<userenvironment()>
12600: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12601: passed in @what from the requested user's environment, returns a hash
12602: 
12603: =item * 
12604: X<userlog_query()>
12605: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12606: activity.log file. %filters defines filters applied when parsing the
12607: log file. These can be start or end timestamps, or the type of action
12608: - log to look for Login or Logout events, check for Checkin or
12609: Checkout, role for role selection. The response is in the form
12610: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12611: escaped strings of the action recorded in the activity.log file.
12612: 
12613: =back
12614: 
12615: =head2 User Roles
12616: 
12617: =over 4
12618: 
12619: =item *
12620: 
12621: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12622:  F: full access
12623:  U,I,K: authentication modes (cxx only)
12624:  '': forbidden
12625:  1: user needs to choose course
12626:  2: browse allowed
12627:  A: passphrase authentication needed
12628: 
12629: =item *
12630: 
12631: constructaccess($url,$setpriv) : check for access to construction space URL
12632: 
12633: See if the owner domain and name in the URL match those in the
12634: expected environment.  If so, return three element list
12635: ($ownername,$ownerdomain,$ownerhome).
12636: 
12637: Otherwise return the null string.
12638: 
12639: If second argument 'setpriv' is true, it assigns the privileges,
12640: and returns the same three element list, unless the owner has
12641: blocked "ad hoc" Domain Coordinator access to the Author Space,
12642: in which case the null string is returned.
12643: 
12644: =item *
12645: 
12646: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12647: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12648: and course level
12649: 
12650: =item *
12651: 
12652: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12653: (rolesplain.tab); plain text explanation of a user role term.
12654: $type is Course (default) or Community.
12655: If $forcedefault evaluates to true, text returned will be default 
12656: text for $type. Otherwise, if this is a course, the text returned 
12657: will be a custom name for the role (if defined in the course's 
12658: environment).  If no custom name is defined the default is returned.
12659:    
12660: =item *
12661: 
12662: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12663: All arguments are optional. Returns a hash of a roles, either for
12664: co-author/assistant author roles for a user's Construction Space
12665: (default), or if $context is 'userroles', roles for the user himself,
12666: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12667: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12668: For each key, value is set to colon-separated start and end times for
12669: the role.  If no username and domain are specified, will default to
12670: current user/domain. Types, roles, and roledoms are references to arrays
12671: of role statuses (active, future or previous), roles 
12672: (e.g., cc,in, st etc.) and domains of the roles which can be used
12673: to restrict the list of roles reported. If no array ref is 
12674: provided for types, will default to return only active roles.
12675: 
12676: =item *
12677: 
12678: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12679: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12680: 
12681: Additional optional arguments are: $type (if role checking is to be restricted 
12682: to certain user status types -- previous (expired roles), active (currently
12683: available roles) or future (roles available in the future), and
12684: $hideprivileged -- if true will not report course roles for users who
12685: have active Domain Coordinator role in course's domain or in additional
12686: domains (specified in 'Domains to check for privileged users' in course
12687: environment -- set via:  Course Settings -> Classlists and staff listing).
12688: 
12689: =item *
12690: 
12691: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12692: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12693: $possdomains and $possroles are optional array refs -- to domains to check and
12694: roles to check.  If $possdomains is not specified, a dump will be done of the
12695: users' roles.db to check for a dc or su role in any domain. This can be
12696: time consuming if &privileged is called repeatedly (e.g., when displaying a
12697: classlist), so in such cases, supplying a $possdomains array is preferred, as
12698: this then allows &privileged_by_domain() to be used, which caches the identity
12699: of privileged users, eliminating the need for repeated calls to &dump().
12700: 
12701: =item *
12702: 
12703: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12704: where the outer hash keys are domains specified in the $possdomains array ref,
12705: next inner hash keys are privileged roles specified in the $roles array ref,
12706: and the innermost hash contains key = value pairs for username:domain = end:start
12707: for active or future "privileged" users with that role in that domain. To avoid
12708: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12709: innerhash are cached using priv_$role and $dom as the identifiers.
12710: 
12711: =back
12712: 
12713: =head2 User Modification
12714: 
12715: =over 4
12716: 
12717: =item *
12718: 
12719: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12720: user for the level given by URL.  Optional start and end dates (leave empty
12721: string or zero for "no date")
12722: 
12723: =item *
12724: 
12725: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12726: change a users, password, possible return values are: ok,
12727: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12728: refused
12729: 
12730: =item *
12731: 
12732: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12733: 
12734: =item *
12735: 
12736: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12737:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12738: 
12739: will update user information (firstname,middlename,lastname,generation,
12740: permanentemail), and if forceid is true, student/employee ID also.
12741: A user's institutional affiliation(s) can also be updated.
12742: User information fields will not be overwritten with empty entries 
12743: unless the field is included in the $candelete array reference.
12744: This array is included when a single user is modified via "Manage Users",
12745: or when Autoupdate.pl is run by cron in a domain.
12746: 
12747: =item *
12748: 
12749: modifystudent
12750: 
12751: modify a student's enrollment and identification information.
12752: The course id is resolved based on the current user's environment.  
12753: This means the invoking user must be a course coordinator or otherwise
12754: associated with a course.
12755: 
12756: This call is essentially a wrapper for lonnet::modifyuser and
12757: lonnet::modify_student_enrollment
12758: 
12759: Inputs: 
12760: 
12761: =over 4
12762: 
12763: =item B<$udom> Student's loncapa domain
12764: 
12765: =item B<$uname> Student's loncapa login name
12766: 
12767: =item B<$uid> Student/Employee ID
12768: 
12769: =item B<$umode> Student's authentication mode
12770: 
12771: =item B<$upass> Student's password
12772: 
12773: =item B<$first> Student's first name
12774: 
12775: =item B<$middle> Student's middle name
12776: 
12777: =item B<$last> Student's last name
12778: 
12779: =item B<$gene> Student's generation
12780: 
12781: =item B<$usec> Student's section in course
12782: 
12783: =item B<$end> Unix time of the roles expiration
12784: 
12785: =item B<$start> Unix time of the roles start date
12786: 
12787: =item B<$forceid> If defined, allow $uid to be changed
12788: 
12789: =item B<$desiredhome> server to use as home server for student
12790: 
12791: =item B<$email> Student's permanent e-mail address
12792: 
12793: =item B<$type> Type of enrollment (auto or manual)
12794: 
12795: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12796: 
12797: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12798: 
12799: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12800: 
12801: =item B<$context> role change context (shown in User Management Logs display in a course)
12802: 
12803: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12804: 
12805: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
12806: 
12807: =back
12808: 
12809: =item *
12810: 
12811: modify_student_enrollment
12812: 
12813: Change a student's enrollment status in a class.  The environment variable
12814: 'role.request.course' must be defined for this function to proceed.
12815: 
12816: Inputs:
12817: 
12818: =over 4
12819: 
12820: =item $udom, student's domain
12821: 
12822: =item $uname, student's name
12823: 
12824: =item $uid, student's user id
12825: 
12826: =item $first, student's first name
12827: 
12828: =item $middle
12829: 
12830: =item $last
12831: 
12832: =item $gene
12833: 
12834: =item $usec
12835: 
12836: =item $end
12837: 
12838: =item $start
12839: 
12840: =item $type
12841: 
12842: =item $locktype
12843: 
12844: =item $cid
12845: 
12846: =item $selfenroll
12847: 
12848: =item $context
12849: 
12850: =item $credits, number of credits student will earn from this class
12851: 
12852: =back
12853: 
12854: 
12855: =item *
12856: 
12857: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12858: custom role; give a custom role to a user for the level given by URL.  Specify
12859: name and domain of role author, and role name
12860: 
12861: =item *
12862: 
12863: revokerole($udom,$uname,$url,$role) : revoke a role for url
12864: 
12865: =item *
12866: 
12867: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12868: 
12869: =back
12870: 
12871: =head2 Course Infomation
12872: 
12873: =over 4
12874: 
12875: =item *
12876: 
12877: coursedescription($courseid,$options) : returns a hash of information about the
12878: specified course id, including all environment settings for the
12879: course, the description of the course will be in the hash under the
12880: key 'description'
12881: 
12882: $options is an optional parameter that if supplied is a hash reference that controls
12883: what how this function works.  It has the following key/values:
12884: 
12885: =over 4
12886: 
12887: =item freshen_cache
12888: 
12889: If defined, and the environment cache for the course is valid, it is 
12890: returned in the returned hash.
12891: 
12892: =item one_time
12893: 
12894: If defined, the last cache time is set to _now_
12895: 
12896: =item user
12897: 
12898: If defined, the supplied username is used instead of the current user.
12899: 
12900: 
12901: =back
12902: 
12903: =item *
12904: 
12905: resdata($name,$domain,$type,@which) : request for current parameter
12906: setting for a specific $type, where $type is either 'course' or 'user',
12907: @what should be a list of parameters to ask about. This routine caches
12908: answers for 10 minutes.
12909: 
12910: =item *
12911: 
12912: get_courseresdata($courseid, $domain) : dump the entire course resource
12913: data base, returning a hash that is keyed by the resource name and has
12914: values that are the resource value.  I believe that the timestamps and
12915: versions are also returned.
12916: 
12917: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12918: supplemental content area. This routine caches the number of files for 
12919: 10 minutes.
12920: 
12921: =back
12922: 
12923: =head2 Course Modification
12924: 
12925: =over 4
12926: 
12927: =item *
12928: 
12929: writecoursepref($courseid,%prefs) : write preferences (environment
12930: database) for a course
12931: 
12932: =item *
12933: 
12934: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12935: 
12936: =item *
12937: 
12938: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12939: 
12940: =item *
12941: 
12942: is_course($courseid), is_course($cdom, $cnum)
12943: 
12944: Accepts either a combined $courseid (in the form of domain_courseid) or the
12945: two component version $cdom, $cnum. It checks if the specified course exists.
12946: 
12947: Returns:
12948:     undef if the course doesn't exist, otherwise
12949:     in scalar context the combined courseid.
12950:     in list context the two components of the course identifier, domain and 
12951:     courseid.    
12952: 
12953: =back
12954: 
12955: =head2 Resource Subroutines
12956: 
12957: =over 4
12958: 
12959: =item *
12960: 
12961: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12962: 
12963: =item *
12964: 
12965: repcopy($filename) : subscribes to the requested file, and attempts to
12966: replicate from the owning library server, Might return
12967: 'unavailable', 'not_found', 'forbidden', 'ok', or
12968: 'bad_request', also attempts to grab the metadata for the
12969: resource. Expects the local filesystem pathname
12970: (/home/httpd/html/res/....)
12971: 
12972: =back
12973: 
12974: =head2 Resource Information
12975: 
12976: =over 4
12977: 
12978: =item *
12979: 
12980: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
12981: and returns the value of a variety of different possible values,
12982: $varname should be a request string, and the other parameters can be
12983: used to specify who and what one is asking about. Ordinarily, $cid 
12984: does not need to be specified, as it is retrived from 
12985: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12986: within lonuserstate::loadmap() when initializing a course, before
12987: $env{'request.course.id'} has been set, so it needs to be provided
12988: in that one case.
12989: 
12990: Possible values for $varname are environment.lastname (or other item
12991: from the envirnment hash), user.name (or someother aspect about the
12992: user), resource.0.maxtries (or some other part and parameter of a
12993: resource)
12994: 
12995: =item *
12996: 
12997: directcondval($number) : get current value of a condition; reads from a state
12998: string
12999: 
13000: =item *
13001: 
13002: condval($condidx) : value of condition index based on state
13003: 
13004: =item *
13005: 
13006: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13007: resource's metadata, $what should be either a specific key, or either
13008: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13009: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13010: 
13011: this function automatically caches all requests
13012: 
13013: =item *
13014: 
13015: metadata_query($query,$custom,$customshow) : make a metadata query against the
13016: network of library servers; returns file handle of where SQL and regex results
13017: will be stored for query
13018: 
13019: =item *
13020: 
13021: symbread($filename) : return symbolic list entry (filename argument optional);
13022: returns the data handle
13023: 
13024: =item *
13025: 
13026: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13027: and is a possible symb for the URL in $thisfn, and if is an encrypted
13028: resource that the user accessed using /enc/ returns a 1 on success, 0
13029: on failure, user must be in a course, as it assumes the existence of
13030: the course initial hash, and uses $env('request.course.id'}.  The third
13031: arg is an optional reference to a scalar.  If this arg is passed in the 
13032: call to symbverify, it will be set to 1 if the symb has been set to be 
13033: encrypted; otherwise it will be null.  
13034: 
13035: =item *
13036: 
13037: symbclean($symb) : removes versions numbers from a symb, returns the
13038: cleaned symb
13039: 
13040: =item *
13041: 
13042: is_on_map($uri) : checks if the $uri is somewhere on the current
13043: course map, user must be in a course for it to work.
13044: 
13045: =item *
13046: 
13047: numval($salt) : return random seed value (addend for rndseed)
13048: 
13049: =item *
13050: 
13051: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13052: a random seed, all arguments are optional, if they aren't sent it uses the
13053: environment to derive them. Note: if symb isn't sent and it can't get one
13054: from &symbread it will use the current time as its return value
13055: 
13056: =item *
13057: 
13058: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13059: unfakeable, receipt
13060: 
13061: =item *
13062: 
13063: receipt() : API to ireceipt working off of env values; given out to users
13064: 
13065: =item *
13066: 
13067: countacc($url) : count the number of accesses to a given URL
13068: 
13069: =item *
13070: 
13071: 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
13072: 
13073: =item *
13074: 
13075: 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)
13076: 
13077: =item *
13078: 
13079: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13080: 
13081: =item *
13082: 
13083: devalidate($symb) : devalidate temporary spreadsheet calculations,
13084: forcing spreadsheet to reevaluate the resource scores next time.
13085: 
13086: =item * 
13087: 
13088: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13089: when viewing in course context.
13090: 
13091:  input: six args -- filename (decluttered), course number, course domain,
13092:                     url, symb (if registered) and group (if this is a 
13093:                     group item -- e.g., bulletin board, group page etc.).
13094: 
13095:  output: array of five scalars --
13096:          $cfile -- url for file editing if editable on current server
13097:          $home -- homeserver of resource (i.e., for author if published,
13098:                                           or course if uploaded.).
13099:          $switchserver --  1 if server switch will be needed.
13100:          $forceedit -- 1 if icon/link should be to go to edit mode 
13101:          $forceview -- 1 if icon/link should be to go to view mode
13102: 
13103: =item *
13104: 
13105: is_course_upload($file,$cnum,$cdom)
13106: 
13107: Used in course context to determine if current file was uploaded to 
13108: the course (i.e., would be found in /userfiles/docs on the course's 
13109: homeserver.
13110: 
13111:   input: 3 args -- filename (decluttered), course number and course domain.
13112:   output: boolean -- 1 if file was uploaded.
13113: 
13114: =back
13115: 
13116: =head2 Storing/Retreiving Data
13117: 
13118: =over 4
13119: 
13120: =item *
13121: 
13122: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13123: for this url; hashref needs to be given and should be a \%hashname; the
13124: remaining args aren't required and if they aren't passed or are '' they will
13125: be derived from the env
13126: 
13127: =item *
13128: 
13129: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13130: uses critical subroutine
13131: 
13132: =item *
13133: 
13134: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13135: all args are optional
13136: 
13137: =item *
13138: 
13139: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13140: dumps the complete (or key matching regexp) namespace into a hash
13141: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13142: normally &store()ed into
13143: 
13144: $range should be either an integer '100' (give me the first 100
13145:                                            matching records)
13146:               or be  two integers sperated by a - with no spaces
13147:                  '30-50' (give me the 30th through the 50th matching
13148:                           records)
13149: 
13150: 
13151: =item *
13152: 
13153: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13154: replaces a &store() version of data with a replacement set of data
13155: for a particular resource in a namespace passed in the $storehash hash 
13156: reference
13157: 
13158: =item *
13159: 
13160: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13161: works very similar to store/cstore, but all data is stored in a
13162: temporary location and can be reset using tmpreset, $storehash should
13163: be a hash reference, returns nothing on success
13164: 
13165: =item *
13166: 
13167: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13168: similar to restore, but all data is stored in a temporary location and
13169: can be reset using tmpreset. Returns a hash of values on success,
13170: error string otherwise.
13171: 
13172: =item *
13173: 
13174: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13175: deltes all keys for $symb form the temporary storage hash.
13176: 
13177: =item *
13178: 
13179: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13180: reference filled in from namesp ($udom and $uname are optional)
13181: 
13182: =item *
13183: 
13184: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13185: namesp ($udom and $uname are optional)
13186: 
13187: =item *
13188: 
13189: dump($namespace,$udom,$uname,$regexp,$range) : 
13190: dumps the complete (or key matching regexp) namespace into a hash
13191: ($udom, $uname, $regexp, $range are optional)
13192: 
13193: $range should be either an integer '100' (give me the first 100
13194:                                            matching records)
13195:               or be  two integers sperated by a - with no spaces
13196:                  '30-50' (give me the 30th through the 50th matching
13197:                           records)
13198: =item *
13199: 
13200: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13201: $store can be a scalar, an array reference, or if the amount to be 
13202: incremented is > 1, a hash reference.
13203: 
13204: ($udom and $uname are optional)
13205: 
13206: =item *
13207: 
13208: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13209: ($udom and $uname are optional)
13210: 
13211: =item *
13212: 
13213: cput($namespace,$storehash,$udom,$uname) : critical put
13214: ($udom and $uname are optional)
13215: 
13216: =item *
13217: 
13218: newput($namespace,$storehash,$udom,$uname) :
13219: 
13220: Attempts to store the items in the $storehash, but only if they don't
13221: currently exist, if this succeeds you can be certain that you have 
13222: successfully created a new key value pair in the $namespace db.
13223: 
13224: 
13225: Args:
13226:  $namespace: name of database to store values to
13227:  $storehash: hashref to store to the db
13228:  $udom: (optional) domain of user containing the db
13229:  $uname: (optional) name of user caontaining the db
13230: 
13231: Returns:
13232:  'ok' -> succeeded in storing all keys of $storehash
13233:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13234:                         least <key> already existed in the db (other
13235:                         requested keys may also already exist)
13236:  'error: <msg>' -> unable to tie the DB or other error occurred
13237:  'con_lost' -> unable to contact request server
13238:  'refused' -> action was not allowed by remote machine
13239: 
13240: 
13241: =item *
13242: 
13243: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13244: reference filled in from namesp (encrypts the return communication)
13245: ($udom and $uname are optional)
13246: 
13247: =item *
13248: 
13249: log($udom,$name,$home,$message) : write to permanent log for user; use
13250: critical subroutine
13251: 
13252: =item *
13253: 
13254: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13255: array reference filled in from namespace found in domain level on either
13256: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13257: 
13258: =item *
13259: 
13260: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13261: domain level either on specified domain server ($uhome) or primary domain 
13262: server ($udom and $uhome are optional)
13263: 
13264: =item * 
13265: 
13266: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13267: for: authentication, language, quotas, timezone, date locale, and portal URL in
13268: the target domain.
13269: 
13270: May also include additional key => value pairs for the following groups:
13271: 
13272: =over
13273: 
13274: =item
13275: disk quotas (MB allocated by default to portfolios and authoring spaces).
13276: 
13277: =over
13278: 
13279: =item defaultquota, authorquota
13280: 
13281: =back
13282: 
13283: =item
13284: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13285: portfolio for users).
13286: 
13287: =over
13288: 
13289: =item
13290: aboutme, blog, webdav, portfolio
13291: 
13292: =back
13293: 
13294: =item
13295: requestcourses: ability to request courses, and how requests are processed.
13296: 
13297: =over
13298: 
13299: =item
13300: official, unofficial, community, textbook
13301: 
13302: =back
13303: 
13304: =item
13305: inststatus: types of institutional affiliation, and order in which they are displayed.
13306: 
13307: =over
13308: 
13309: =item
13310: inststatustypes, inststatusorder
13311: 
13312: =back
13313: 
13314: =item
13315: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13316: for course's uploaded content.
13317: 
13318: =over
13319: 
13320: =item
13321: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
13322: communityquota, textbookquota
13323: 
13324: =back
13325: 
13326: =item
13327: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13328: on your servers.
13329: 
13330: =over
13331: 
13332: =item 
13333: remotesessions, hostedsessions
13334: 
13335: =back
13336: 
13337: =back
13338: 
13339: In cases where a domain coordinator has never used the "Set Domain Configuration"
13340: utility to create a configuration.db file on a domain's primary library server 
13341: only the following domain defaults: auth_def, auth_arg_def, lang_def
13342: -- corresponding values are authentication type (internal, krb4, krb5,
13343: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13344: will be available. Values are retrieved from cache (if current), unless the
13345: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13346: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13347: 
13348: Typical usage:
13349: 
13350: %domdefaults = &get_domain_defaults($target_domain);
13351: 
13352: =back
13353: 
13354: =head2 Network Status Functions
13355: 
13356: =over 4
13357: 
13358: =item *
13359: 
13360: dirlist() : return directory list based on URI (first arg).
13361: 
13362: Inputs: 1 required, 5 optional.
13363: 
13364: =over
13365: 
13366: =item 
13367: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13368: 
13369: =item
13370: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13371: 
13372: =item
13373: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13374: 
13375: =item
13376: $getpropath - boolean: 1 if prepend path using &propath(). 
13377: 
13378: =item
13379: $getuserdir - boolean: 1 if prepend path for "userfiles".
13380: 
13381: =item 
13382: $alternateRoot - path to prepend in place of path from $uri.
13383: 
13384: =back
13385: 
13386: Returns: Array of up to two items.
13387: 
13388: =over
13389: 
13390: a reference to an array of files/subdirectories
13391: 
13392: =over
13393: 
13394: Each element in the array of files/subdirectories is a & separated list of
13395: item name and the result of running stat on the item.  If dirlist was requested
13396: for a file instead of a directory, the item name will be ''. For a directory 
13397: listing, if the item is a metadata file, the element will end &N&M 
13398: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13399: default copyright set (1).  
13400: 
13401: =back
13402: 
13403: a scalar containing error condition (if encountered).
13404: 
13405: =over
13406: 
13407: =item 
13408: no_host (no homeserver identified for $username:$domain).
13409: 
13410: =item 
13411: no_such_host (server contacted for listing not identified as valid host).
13412: 
13413: =item 
13414: con_lost (connection to remote server failed).
13415: 
13416: =item 
13417: refused (invalid $username:$domain received on lond side).
13418: 
13419: =item 
13420: no_such_dir (directory at specified path on lond side does not exist). 
13421: 
13422: =item 
13423: empty (directory at specified path on lond side is empty).
13424: 
13425: =over
13426: 
13427: This is currently not encountered because the &ls3, &ls2, 
13428: &ls (_handler) routines on the lond side do not filter out
13429: . and .. from a directory listing. 
13430: 
13431: =back
13432: 
13433: =back
13434: 
13435: =back
13436: 
13437: =item *
13438: 
13439: spareserver() : find server with least workload from spare.tab
13440: 
13441: 
13442: =item *
13443: 
13444: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13445: if there is no corresponding loncapa host.
13446: 
13447: =back
13448: 
13449: 
13450: =head2 Apache Request
13451: 
13452: =over 4
13453: 
13454: =item *
13455: 
13456: ssi($url,%hash) : server side include, does a complete request cycle on url to
13457: localhost, posts hash
13458: 
13459: =back
13460: 
13461: =head2 Data to String to Data
13462: 
13463: =over 4
13464: 
13465: =item *
13466: 
13467: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13468: and '&' separators, supports elements that are arrayrefs and hashrefs
13469: 
13470: =item *
13471: 
13472: hashref2str($hashref) : convert a hashref into a string complete with
13473: escaping and '=' and '&' separators, supports elements that are
13474: arrayrefs and hashrefs
13475: 
13476: =item *
13477: 
13478: arrayref2str($arrayref) : convert an arrayref into a string complete
13479: with escaping and '&' separators, supports elements that are arrayrefs
13480: and hashrefs
13481: 
13482: =item *
13483: 
13484: str2hash($string) : convert string to hash using unescaping and
13485: splitting on '=' and '&', supports elements that are arrayrefs and
13486: hashrefs
13487: 
13488: =item *
13489: 
13490: str2array($string) : convert string to hash using unescaping and
13491: splitting on '&', supports elements that are arrayrefs and hashrefs
13492: 
13493: =back
13494: 
13495: =head2 Logging Routines
13496: 
13497: 
13498: These routines allow one to make log messages in the lonnet.log and
13499: lonnet.perm logfiles.
13500: 
13501: =over 4
13502: 
13503: =item *
13504: 
13505: logtouch() : make sure the logfile, lonnet.log, exists
13506: 
13507: =item *
13508: 
13509: logthis() : append message to the normal lonnet.log file, it gets
13510: preiodically rolled over and deleted.
13511: 
13512: =item *
13513: 
13514: logperm() : append a permanent message to lonnet.perm.log, this log
13515: file never gets deleted by any automated portion of the system, only
13516: messages of critical importance should go in here.
13517: 
13518: 
13519: =back
13520: 
13521: =head2 General File Helper Routines
13522: 
13523: =over 4
13524: 
13525: =item *
13526: 
13527: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13528: (a) files in /uploaded
13529:   (i) If a local copy of the file exists - 
13530:       compares modification date of local copy with last-modified date for 
13531:       definitive version stored on home server for course. If local copy is 
13532:       stale, requests a new version from the home server and stores it. 
13533:       If the original has been removed from the home server, then local copy 
13534:       is unlinked.
13535:   (ii) If local copy does not exist -
13536:       requests the file from the home server and stores it. 
13537:   
13538:   If $caller is 'uploadrep':  
13539:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13540:     for request for files originally uploaded via DOCS. 
13541:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13542:   
13543:   Otherwise:
13544:      This indicates a call from the content generation phase of the request.
13545:      -  returns the entire contents of the file or -1.
13546:      
13547: (b) files in /res
13548:    - returns the entire contents of a file or -1; 
13549:    it properly subscribes to and replicates the file if neccessary.
13550: 
13551: 
13552: =item *
13553: 
13554: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13555:                   reference
13556: 
13557: returns either a stat() list of data about the file or an empty list
13558: if the file doesn't exist or couldn't find out about it (connection
13559: problems or user unknown)
13560: 
13561: =item *
13562: 
13563: filelocation($dir,$file) : returns file system location of a file
13564: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13565: directory that relative $file lookups are to looked in ($dir of /a/dir
13566: and a file of ../bob will become /a/bob)
13567: 
13568: =item *
13569: 
13570: hreflocation($dir,$file) : returns file system location or a URL; same as
13571: filelocation except for hrefs
13572: 
13573: =item *
13574: 
13575: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13576: 
13577: =back
13578: 
13579: =head2 Usererfile file routines (/uploaded*)
13580: 
13581: =over 4
13582: 
13583: =item *
13584: 
13585: userfileupload(): main rotine for putting a file in a user or course's
13586:                   filespace, arguments are,
13587: 
13588:  formname - required - this is the name of the element in $env where the
13589:            filename, and the contents of the file to create/modifed exist
13590:            the filename is in $env{'form.'.$formname.'.filename'} and the
13591:            contents of the file is located in $env{'form.'.$formname}
13592:  context - if coursedoc, store the file in the course of the active role
13593:              of the current user; 
13594:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13595:            if 'canceloverwrite': delete file in tmp/overwrites directory
13596:  subdir - required - subdirectory to put the file in under ../userfiles/
13597:          if undefined, it will be placed in "unknown"
13598: 
13599:  (This routine calls clean_filename() to remove any dangerous
13600:  characters from the filename, and then calls finuserfileupload() to
13601:  complete the transaction)
13602: 
13603:  returns either the url of the uploaded file (/uploaded/....) if successful
13604:  and /adm/notfound.html if unsuccessful
13605: 
13606: =item *
13607: 
13608: clean_filename(): routine for cleaing a filename up for storage in
13609:                  userfile space, argument is:
13610: 
13611:  filename - proposed filename
13612: 
13613: returns: the new clean filename
13614: 
13615: =item *
13616: 
13617: finishuserfileupload(): routine that creates and sends the file to
13618: userspace, probably shouldn't be called directly
13619: 
13620:   docuname: username or courseid of destination for the file
13621:   docudom: domain of user/course of destination for the file
13622:   formname: same as for userfileupload()
13623:   fname: filename (including subdirectories) for the file
13624:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13625:   allfiles: reference to hash used to store objects found by parser
13626:   codebase: reference to hash used for codebases of java objects found by parser
13627:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13628:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13629:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13630:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13631:   context: if 'overwrite', will move the uploaded file from its temporary location to
13632:             userfiles to facilitate overwriting a previously uploaded file with same name.
13633:   mimetype: reference to scalar to accommodate mime type determined
13634:             from File::MMagic if $parser = parse.
13635: 
13636:  returns either the url of the uploaded file (/uploaded/....) if successful
13637:  and /adm/notfound.html if unsuccessful (or an error message if context 
13638:  was 'overwrite').
13639:  
13640: 
13641: =item *
13642: 
13643: renameuserfile(): renames an existing userfile to a new name
13644: 
13645:   Args:
13646:    docuname: username or courseid of destination for the file
13647:    docudom: domain of user/course of destination for the file
13648:    old: current file name (including any subdirs under userfiles)
13649:    new: desired file name (including any subdirs under userfiles)
13650: 
13651: =item *
13652: 
13653: mkdiruserfile(): creates a directory is a userfiles dir
13654: 
13655:   Args:
13656:    docuname: username or courseid of destination for the file
13657:    docudom: domain of user/course of destination for the file
13658:    dir: dir to create (including any subdirs under userfiles)
13659: 
13660: =item *
13661: 
13662: removeuserfile(): removes a file that exists in userfiles
13663: 
13664:   Args:
13665:    docuname: username or courseid of destination for the file
13666:    docudom: domain of user/course of destination for the file
13667:    fname: filname to delete (including any subdirs under userfiles)
13668: 
13669: =item *
13670: 
13671: removeuploadedurl(): convience function for removeuserfile()
13672: 
13673:   Args:
13674:    url:  a full /uploaded/... url to delete
13675: 
13676: =item * 
13677: 
13678: get_portfile_permissions():
13679:   Args:
13680:     domain: domain of user or course contain the portfolio files
13681:     user: name of user or num of course contain the portfolio files
13682:   Returns:
13683:     hashref of a dump of the proper file_permissions.db
13684:    
13685: 
13686: =item * 
13687: 
13688: get_access_controls():
13689: 
13690: Args:
13691:   current_permissions: the hash ref returned from get_portfile_permissions()
13692:   group: (optional) the group you want the files associated with
13693:   file: (optional) the file you want access info on
13694: 
13695: Returns:
13696:     a hash (keys are file names) of hashes containing
13697:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13698:         values are XML containing access control settings (see below) 
13699: 
13700: Internal notes:
13701: 
13702:  access controls are stored in file_permissions.db as key=value pairs.
13703:     key -> path to file/file_name\0uniqueID:scope_end_start
13704:         where scope -> public,guest,course,group,domains or users.
13705:               end -> UNIX time for end of access (0 -> no end date)
13706:               start -> UNIX time for start of access
13707: 
13708:     value -> XML description of access control
13709:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13710:             <start></start>
13711:             <end></end>
13712: 
13713:             <password></password>  for scope type = guest
13714: 
13715:             <domain></domain>     for scope type = course or group
13716:             <number></number>
13717:             <roles id="">
13718:              <role></role>
13719:              <access></access>
13720:              <section></section>
13721:              <group></group>
13722:             </roles>
13723: 
13724:             <dom></dom>         for scope type = domains
13725: 
13726:             <users>             for scope type = users
13727:              <user>
13728:               <uname></uname>
13729:               <udom></udom>
13730:              </user>
13731:             </users>
13732:            </scope> 
13733:               
13734:  Access data is also aggregated for each file in an additional key=value pair:
13735:  key -> path to file/file_name\0accesscontrol 
13736:  value -> reference to hash
13737:           hash contains key = value pairs
13738:           where key = uniqueID:scope_end_start
13739:                 value = UNIX time record was last updated
13740: 
13741:           Used to improve speed of look-ups of access controls for each file.  
13742:  
13743:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13744: 
13745: =item *
13746: 
13747: modify_access_controls():
13748: 
13749: Modifies access controls for a portfolio file
13750: Args
13751: 1. file name
13752: 2. reference to hash of required changes,
13753: 3. domain
13754: 4. username
13755:   where domain,username are the domain of the portfolio owner 
13756:   (either a user or a course) 
13757: 
13758: Returns:
13759: 1. result of additions or updates ('ok' or 'error', with error message). 
13760: 2. result of deletions ('ok' or 'error', with error message).
13761: 3. reference to hash of any new or updated access controls.
13762: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13763:    key = integer (inbound ID)
13764:    value = uniqueID
13765: 
13766: =item *
13767: 
13768: get_timebased_id():
13769: 
13770: Attempts to get a unique timestamp-based suffix for use with items added to a 
13771: course via the Course Editor (e.g., folders, composite pages, 
13772: group bulletin boards).
13773: 
13774: Args: (first three required; six others optional)
13775: 
13776: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13777:    docssequence, or name of group
13778: 
13779: 2. keyid (alphanumeric): name of temporary locking key in hash,
13780:    e.g., num, boardids
13781: 
13782: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13783:    file will be named nohist_namespace.db
13784: 
13785: 4. cdom: domain of course; default is current course domain from %env
13786: 
13787: 5. cnum: course number; default is current course number from %env
13788: 
13789: 6. idtype: set to concat if an additional digit is to be appended to the 
13790:    unix timestamp to form the suffix, if the plain timestamp is already
13791:    in use.  Default is to not do this, but simply increment the unix 
13792:    timestamp by 1 until a unique key is obtained.
13793: 
13794: 7. who: holder of locking key; defaults to user:domain for user.
13795: 
13796: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13797:    retrying); default is 3.
13798: 
13799: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13800: 
13801: Returns:
13802: 
13803: 1. suffix obtained (numeric)
13804: 
13805: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13806: 
13807: 3. error: contains (localized) error message if an error occurred.
13808: 
13809: 
13810: =back
13811: 
13812: =head2 HTTP Helper Routines
13813: 
13814: =over 4
13815: 
13816: =item *
13817: 
13818: escape() : unpack non-word characters into CGI-compatible hex codes
13819: 
13820: =item *
13821: 
13822: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13823: 
13824: =back
13825: 
13826: =head1 PRIVATE SUBROUTINES
13827: 
13828: =head2 Underlying communication routines (Shouldn't call)
13829: 
13830: =over 4
13831: 
13832: =item *
13833: 
13834: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13835: 
13836: =item *
13837: 
13838: reply() : uses subreply to send a message to remote machine, logs all failures
13839: 
13840: =item *
13841: 
13842: critical() : passes a critical message to another server; if cannot
13843: get through then place message in connection buffer directory and
13844: returns con_delayed, if incapable of saving message, returns
13845: con_failed
13846: 
13847: =item *
13848: 
13849: reconlonc() : tries to reconnect lonc client processes.
13850: 
13851: =back
13852: 
13853: =head2 Resource Access Logging
13854: 
13855: =over 4
13856: 
13857: =item *
13858: 
13859: flushcourselogs() : flush (save) buffer logs and access logs
13860: 
13861: =item *
13862: 
13863: courselog($what) : save message for course in hash
13864: 
13865: =item *
13866: 
13867: courseacclog($what) : save message for course using &courselog().  Perform
13868: special processing for specific resource types (problems, exams, quizzes, etc).
13869: 
13870: =item *
13871: 
13872: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13873: as a PerlChildExitHandler
13874: 
13875: =back
13876: 
13877: =head2 Other
13878: 
13879: =over 4
13880: 
13881: =item *
13882: 
13883: symblist($mapname,%newhash) : update symbolic storage links
13884: 
13885: =back
13886: 
13887: =cut
13888: 

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